Code

Updated check for activated faiManagement
[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   var $orig_base = "";
21   var $orig_cn = "";
22   var $orig_dn = "";
24   /* attribute list for save action */
25   var $attributes= array("cn", "description", "gosaApplicationExecute", "gosaApplicationName","gosaApplicationIcon",
26       "gosaApplicationFlags","gotoLogonScript");
28   var $objectclasses= array("top", "gosaApplication");
29   var $FAIstate ="";
31   var $baseSelector;
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 ("/^[^,]+,".preg_quote(get_ou('applicationRDN'), '/')."/i", "", $this->dn);
63     }
65     $this->orig_cn = $this->cn;
66     $this->orig_base = $this->base;
67     $this->gosaApplicationFlags = preg_replace("/[^GDLMO]/","",$this->gosaApplicationFlags);
69     /* Instanciate base selector */
70     $this->baseSelector= new baseSelector($this->get_allowed_bases(), $this->base);
71     $this->baseSelector->setSubmitButton(false);
72     $this->baseSelector->setHeight(300);
73     $this->baseSelector->update(true);
74   }
77   function generateTemplate()
78   {
79     $str= "# This code is part of GOsa (https://gosa.gonicus.de)\n#\n";
81     $values = array();
82     $names      = array();
83     if($this->parent->by_object['applicationParameters']->is_account){
84       $names = $this->parent->by_object['applicationParameters']->option_name;
85       $values = $this->parent->by_object['applicationParameters']->option_value;
86     }
88     if (count($names)){
89       $str .="# This plugin handles these environment variables:\n";
90     } else {
91       $str .="# This plugin handles no environment variables.\n";
92     }
94     foreach($names as $index => $name){
96       // Fix length
97       for($i = strlen($name) ; $i < 30 ; $i++){
98         $name= $name." ";
99       }
100       if((isset($values[$index]))&&(!empty($values[$index]))){
101         $str.= "# ".$name."\t(e.g. '".$values[$index]."')\n";
102       }else{
103         $str.= "# ".$name."\t("._("no example").")\n";
104       }
105     }
106     $str .= "#\n".
107       "# Don't remove the following tag, it is used for header update.\n".
108       "### END HEADER ###";
110     return($str);
111   }
113   function execute()
114   {
115     /* Call parent execute */
116     plugin::execute();
118     /* Log view */
119     if($this->is_account && !$this->view_logged){
120       $this->view_logged = TRUE;
121       new log("view","application/".get_class($this),$this->dn);
122     }
124     $smarty= get_smarty();
126     /* Assign base ACL */
127     $smarty->assign("base", $this->baseSelector->render());
129     $tmp = $this->plInfo();
130     foreach($tmp['plProvidedAcls'] as $name => $translation){
131       $smarty->assign($name."ACL",$this->getacl($name, preg_match("/freeze/i",$this->FAIstate)));
132     }
133     $smarty->assign("IconReadable", $this->acl_is_readable("gosaApplicationIcon"));
134  
135     /* Do we represent a valid group? */
136     if (!$this->is_account && $this->parent === NULL){
137       $display= "<img alt=\"\" src=\"images/small-error.png\" align=\"middle\">&nbsp;<b>".
138         msgPool::noValidExtension(_("application"))."</b>";
139       return ($display);
140     }
142     /* Download requested */
143     foreach($_POST as $name => $value){
144       if(preg_match("/^downloadScript/",$name)){
145         session::set('binary',$this->gotoLogonScript);
146         session::set('binarytype',"octet-stream");
147         session::set('binaryfile',$this->cn.".gosaApplication");
148         header("location: getbin.php ");
149         exit();
150       }
151     }
153     /* Reassign picture data, sometimes its corrupt cause we started a download of application scripts */
154     session::set('binary',$this->iconData);
155     session::set('binarytype',"image/jpeg");
156     
157     $smarty->assign("rand", rand(0, 10000));
158     $head = $this->generateTemplate();
159     $this->gotoLogonScript= $this->generateTemplate().preg_replace('/.*### END HEADER ###/s', '', $this->gotoLogonScript);
161     if((isset($_POST['upLoad']))&&(isset($_FILES['ScriptFile'])) && !preg_match("/freeze/i",$this->FAIstate)){
162       $str = file_get_contents($_FILES['ScriptFile']['tmp_name']);
163       $this->gotoLogonScript = $str;
164     }
166     /* Fill templating stuff */
167     $smarty->assign("cn", $this->cn);
168     if(!$this->is_release()){
169       $smarty->assign("bases", $this->get_allowed_bases());
170     }else{
171       $smarty->assign("bases", array());
172     }
173     if ($this->dn == "new"){
174       $smarty->assign("selectmode", "");
175       $smarty->assign("namemode", "");
176     } else {
177       $smarty->assign("namemode", "readonly");
178       $smarty->assign("selectmode", "disabled");
179     }
180     
181     /* Get random number for pictures */
182     srand((double)microtime()*1000000);
183     $smarty->assign("rand", rand(0, 10000));
185     /* Variables */
186     foreach(array("description", "gosaApplicationExecute", "gosaApplicationName","cn") as $val){
187       $smarty->assign($val, $this->$val);
188     }
190     /* Checkboxes */
191     foreach (array("G" => "execForGroupmembers", "O" => "overwriteConfig",
192           "L" => "placeOnKicker",
193           "D" => "placeOnDesktop", "M" => "placeInStartmenu") as $key => $val){
194       if (preg_match("/$key/", $this->gosaApplicationFlags) && $this->acl_is_readable("$val")){
195         $smarty->assign("$val", "checked");
196       } else {
197         $smarty->assign("$val", "");
198       }
199     }
201     $smarty->assign("isReleaseApplikation" ,$this->is_release());
202     $smarty->assign("gotoLogonScript",htmlentities($this->gotoLogonScript, ENT_COMPAT, 'UTF-8'));
203     $smarty->assign("base_select", $this->base);
204     /* Show main page */
205     return($smarty->fetch (get_template_path('generic.tpl', TRUE)));
206   }
209   function remove_from_parent()
210   {
211     /* Parse release out of object dn */
212     $release = preg_replace("/".preg_quote(get_ou("applicationRDN").$this->base, '/')."$/i","",$this->dn);
213     $release = preg_replace("/^cn=[^,]+,/","",$release);
215     /* Get a list of all groups 
216      */
217     $groups = array();
218     $ldap= $this->config->get_ldap_link();
219     $ldap->cd($this->config->current['BASE']);
220     $ldap->search("(objectClass=posixGroup)",array("dn"));
221     while($attrs = $ldap->fetch()){
222       $groups[$attrs['dn']] = array();
223     }
224     
225     /* Check if there are groups, useing this application 
226      */
227     $found = array();
228     foreach($groups as $group => $data){
229       $ldap->cd($release.$group);
230       $ldap->search("(objectClass=gotoMenuEntry)",array("dn"));
231       while($attrs = $ldap->fetch()){
232         $info = preg_replace("/".preg_quote($release.$group, '/')."$/","",$attrs['dn']); 
233         if(preg_match("/^cn=".$this->cn."/",$info) && !preg_match("/ou=[^,]+,/",$info)){
234           $found[] = $attrs['dn'];
235         }
236       }
237     }
239     /* Create an error message an skip remove, if 
240         this application is still in use. 
241      */
242     if(count($found)){
243       msg_dialog::display(_("Error"), sprintf(_("Cannot remove application - it is still in use by these objects: %s"), "<br>".msgPool::buildList($found)), ERROR_DIALOG);
244       return(FALSE);
245     }
247     $ldap->rmDir($this->dn);
248     new log("remove","application/".get_class($this),$this->dn,array_keys($this->attrs),$ldap->get_error());
249     if (!$ldap->success()){
250       msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $this->dn, LDAP_DEL, get_class()), ERROR_DIALOG);
251     }
253     /* Optionally execute a command after we're done */
254     $this->handle_post_events("remove");
256     /* Delete references to object groups */
257     $ldap->cd ($this->config->current['BASE']);
258     $ldap->search ("(&(objectClass=gosaGroupOfNames)(member=".LDAP::prepare4filter($this->dn)."))", array("cn"));
259     while ($ldap->fetch()){
260       $og= new ogroup($this->config, $ldap->getDN());
261       unset($og->member[$this->dn]);
262       $og->save ();
263       if (!$ldap->success()){
264         msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $this->dn, 0, get_class()), ERROR_DIALOG);
265       }
266     }
267   }
270   /* Save data to object */
271   function save_object()
272   {
273     if(preg_match("/freeze/i",$this->FAIstate)){
274       return;
275     }
277     if (isset($_POST['cn'])){
279       /* Create a base backup and reset the
280          base directly after calling plugin::save_object();
281          Base will be set seperatly a few lines below */
282       $base_tmp = $this->base;
283       plugin::save_object();
284       $this->base = $base_tmp;
286       /* Refresh base */
287       if(!$this->is_release()){
288         if ($this->acl_is_moveable($this->base)){
289           if (!$this->baseSelector->update()) {
290             msg_dialog::display(_("Error"), msgPool::permMove(), ERROR_DIALOG);
291           }
292           if ($this->base != $this->baseSelector->getBase()) {
293             $this->base= $this->baseSelector->getBase();
294             $this->is_modified= TRUE;
295           }
296         }
297       }
300       /* Save attributes */
301       parent::save_object();
303       $checks = array("execForGroupmembers" => "G",
304                       "placeOnDesktop"      => "D",
305                       "placeOnKicker"       => "L",
306                       "placeInStartmenu"    => "M",
307                       "overwriteConfig"     => "O");
310       /* Save application flags */
311       foreach($checks as $name => $flag){
312         if($this->acl_is_writeable($name)){
313           $set = isset($_POST[$name]) && $_POST[$name] == 1;
314           if(!$set && strstr($this->gosaApplicationFlags,$flag)){
315             $this->gosaApplicationFlags = str_replace($flag,"",$this->gosaApplicationFlags);  
316           }elseif($set && !preg_match("/".$flag."/",$this->gosaApplicationFlags)){
317             $this->gosaApplicationFlags .= $flag;
318           }
319         }  
320       }
322       /* Remove current picture */
323       if(isset($_POST['remove_picture'])){
324         $this->set_picture("");
325       }
327       /* Check for picture upload */
328       if (isset($_FILES['picture_file']['name']) && $_FILES['picture_file']['name'] != ""){
330         if (!is_uploaded_file($_FILES['picture_file']['tmp_name'])) {
331           msg_dialog::display(_("Error"), msgPool::incorrectUpload(), ERROR_DIALOG);
332         }
334         if (!function_exists("imagick_blob2image")){
335           /* Get temporary file name for conversation */
336           $fname = tempnam (TEMP_DIR, "GOsa");
338           /* Open file and write out photoData */
339           $fp = fopen ($fname, "w");
340           fwrite ($fp, $_FILES['picture_file']['tmp_name']);
341           fclose ($fp);
343           /* Build conversation query. Filename is generated automatically, so
344              we do not need any special security checks. Exec command and save
345              output. For PHP safe mode, you'll need a configuration which respects
346              image magick as executable... */
347           $query= "convert -size 48x48 $fname -resize 48x48 +profile \"*\" -";
348           @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__, $query, "Execute");
350           /* Read data written by convert */
351           $output= "";
352           $sh= popen($query, 'r');
353           while (!feof($sh)){
354             $output.= fread($sh, 4096);
355           }
356           pclose($sh);
358           unlink($fname);       
359         } else {
361           /* Load the new uploaded Photo */
362           if(!$handle  =  imagick_ReadImage($_FILES['picture_file']['tmp_name'])){
363             msg_dialog::display(_("Error"), msgPool::incorrectUpload(_("no read permission")), ERROR_DIALOG);
364           }
366           /* Resizing image to 147x200 and blur */
367           if(!imagick_resize($handle,48,48,IMAGICK_FILTER_GAUSSIAN,0)){
368             msg_dialog::display(_("Error"), msgPool::incorrectUpload(_("cannot resize image")), ERROR_DIALOG);
369           }
371           /* Converting image to JPEG */
372           if(!imagick_convert($handle,"PNG")) {
373             msg_dialog::display(_("Error"), msgPool::incorrectUpload(_("cannot convert image")), ERROR_DIALOG);
374           }
376           if(!imagick_writeimage($handle,$_FILES['picture_file']['tmp_name'])){
377             msg_dialog::display(_("Error"), msgPool::incorrectUpload(sprintf(_("cannot save image to '%s'"), $_FILES['picture_file']['tmp_name'])), ERROR_DIALOG);
378           }
380           imagick_free($handle);
381         }
383         /* Activate new picture */
384         $this->set_picture($_FILES['picture_file']['tmp_name']);
385       } 
386     }
387   }
390   /* Check values */
391   function check()
392   {
393     /* Call common method to give check the hook */
394     $message= plugin::check();
396     if(!preg_match("#^/#",$this->gosaApplicationExecute)){
397       $message[]=msgPool::invalid(_("Execute path"),"","","/some/path");
398     }
400     // Check if a wrong base was supplied
401     if(!$this->baseSelector->checkLastBaseUpdate()){
402       $message[]= msgPool::check_base();;
403     }
405     /* Permissions for that base? */
406     if ($this->base != ""){
407       $new_dn= "cn=".$this->cn.",".get_ou('applicationRDN').$this->base;
408     } else {
409       $new_dn= $this->dn;
410     }
413     if($this->dn == "new"){
414       $this->set_acl_base($this->base);
415     }
417     /* All required fields are set? */
418     if ($this->cn == ""){
419       $message[]= msgPool::required(_("Name"));
420     }
422     if(preg_match("/[^a-z0-9_-]/",$this->cn))   {
423       $message[]=msgPool::invalid(_("Name"),$this->cn,"/^[a-z0-9_-]*$/");
424     }
426     if ($this->gosaApplicationExecute == ""){
427       $message[]= msgPool::required(_("Execute"));
428     }
430     /* Check for existing application */
431     $ldap= $this->config->get_ldap_link();
432     $ldap->cd($this->config->current["BASE"]);
433     if($this->is_release()){
434       $base = $this->parent->parent->app_release;
435     }else{
436       $base = get_ou('applicationRDN').$this->base;
437     }
439     $ldap->ls("(&(objectClass=gosaApplication)(cn=".$this->cn."))",$base,array("cn"));
440     if($ldap->count()){
441       $attrs = $ldap->fetch();
442       if($this->dn != $attrs['dn']) {
443         $message[]= msgPool::duplicated("cn");
444       }
445     }
447     /* Check if we are allowed to create or move this object 
448      */
449     if($this->orig_dn == "new" && !$this->acl_is_createable($this->base)){
450       $message[] = msgPool::permCreate();
451     }elseif($this->orig_dn != "new" && $this->base != $this->orig_base && !$this->acl_is_moveable($this->base)){
452       $message[] = msgPool::permMove();
453     }
455     return $message;
456   }
459   /* Save to LDAP */
460   function save()
461   {
462     /* Get application script without header part, to check if we must save the script itself */
463     $script = preg_replace('/.*### END HEADER ###/s', '', $this->gotoLogonScript);
465     $this->gosaApplicationFlags ="[{$this->gosaApplicationFlags}]";
466     plugin::save();
467     $this->attrs["gosaApplicationIcon"]= $this->gosaApplicationIcon;
469     /* Write back to ldap */
470     $ldap= $this->config->get_ldap_link();
471     $ldap->cat($this->dn, array('dn'));
473     $a= $ldap->fetch();
474     if (count($a)){
476       /* Remove gotoLogonScript if it is empty */
477       if(empty($script))    {
478         $this->attrs['gotoLogonScript'] = array();
479       }
481       $ldap->cd($this->dn);
482       $this->cleanup();
483       $ldap->modify ($this->attrs); 
484       $this->handle_post_events("modify");
485       new log("modify","application/".get_class($this),$this->dn,array_keys($this->attrs),$ldap->get_error());
486     } else {
487       
488       /* Remove gotoLogonScript if it is empty */
489       if(empty($script))    {
490         unset($this->attrs['gotoLogonScript']);
491       }
493       $ldap->cd($this->config->current['BASE']);
494       $ldap->create_missing_trees(preg_replace('/^[^,]+,/', '', $this->dn));
495       $ldap->cd($this->dn);
496       $ldap->add($this->attrs);
497       new log("create","application/".get_class($this),$this->dn,array_keys($this->attrs),$ldap->get_error());
498       $this->handle_post_events("add");
499     }
500     if (!$ldap->success()){
501       msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $this->dn, 0, get_class()), ERROR_DIALOG);
502     }
503   }
505   
506   function is_release()
507   {
508     if(isset($this->parent->parent)){
509       return($this->parent->parent->IsReleaseManagementActivated());
510     }else{
512       /* Check if we should enable the release selection */
513       return($this->config->pluginEnabled("faiManagement"));
514     }
515     return(FALSE);
516   }
519   function set_picture($filename)
520   {
521     if (!is_file($filename)){
522       $filename= "./plugins/goto/images/default_icon.png";
523       $this->gosaApplicationIcon= "*removed*";
524     }
526     if (file_exists($filename)){
527       $fd = fopen ($filename, "rb");
528       $this->iconData= fread ($fd, filesize ($filename));
529       session::set('binary',$this->iconData);
530       session::set('binarytype',"image/jpeg");
531       $this->gosaApplicationIcon= $this->iconData;
533       fclose ($fd);
534     }
535   }
537   function getCopyDialog()
538   {
539     $vars = array("cn");
541     $str ="<h3>"._("Application settings")."</h3>
542       <table summary=\""._("Application settings")."\">
543       <tr>
544       <td>".
545       _("Application name"). 
546       "</td>  
547       <td>
548       <input id='gosaApplicationName' name='cn' size='35' maxlength='60' 
549       value='".$this->cn."' 
550       title='"._("Application name to be displayed (i.e. below icons)")."'>                     
551       </td>
552       </tr>
553       </table>";
554     $ret = array();
555     $ret['status'] = "";
556     $ret['string'] = $str;
557     return($ret);
558   }
560   function saveCopyDialog()
561   {
562     if(isset($_POST['cn'])){
563       $this->cn = $_POST['cn'];
564     }
565   }
568   function PrepareForCopyPaste($source)
569   {
570     plugin::PrepareForCopyPaste($source);
571     $source_o = new application($this->config,$source['dn']);
572     $this->gosaApplicationIcon = $source_o->gosaApplicationIcon;     
573   }
576   /* Return plugin informations for acl handling
577       #FIXME FAIscript seams to ununsed within this class... */
578   static function plInfo()
579   {
580     return (array(
581           "plShortName"   => _("Generic"),
582           "plDescription" => _("Application generic"),
583           "plSelfModify"  => FALSE,
584           "plDepends"     => array(),
585           "plPriority"    => 0,
586           "plSection"     => array("administration"),
587           "plCategory"    => array("application" => array("description"  => _("Application"),
588                                                           "objectClass"  => "gosaApplication")),
589           "plProvidedAcls"=> array(
590             "cn"                => _("Name"),
591             "base"              => _("Base"),
592             "description"       => _("Description"),
593             "gosaApplicationExecute"  => _("Execute"),
594             "gosaApplicationName"     => _("Name"),
595             "gosaApplicationIcon"     => _("Icon"),
596             "gotoLogonScript"         => _("Script content"),
598             "execForGroupmembers" => _("Only executable for members"),              // G
599             "placeOnDesktop"      => _("Place icon on members desktop"),            // D
600             "placeOnKicker"       => _("Place entry in members launch bar"),        // L
601             "placeInStartmenu"    => _("Place entry in members startmenu"),         // M
602             "overwriteConfig"      => _("Replace user configuration on startup"))  // O
603             ));
604   }
606 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
607 ?>