Code

Updated check for boolean config values
[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     restore_error_handler();
213     /* Parse release out of object dn */
214     $release = preg_replace("/".preg_quote(get_ou("applicationRDN").$this->base, '/')."$/i","",$this->dn);
215     $release = preg_replace("/^cn=[^,]+,/","",$release);
217     /* Get a list of all groups 
218      */
219     $groups = array();
220     $ldap= $this->config->get_ldap_link();
221     $ldap->cd($this->config->current['BASE']);
222     $ldap->search("(objectClass=posixGroup)",array("dn"));
223     while($attrs = $ldap->fetch()){
224       $groups[$attrs['dn']] = array();
225     }
226     
227     /* Check if there are groups, useing this application 
228      */
229     $found = array();
230     foreach($groups as $group => $data){
231       $ldap->cd($release.$group);
232       $ldap->search("(objectClass=gotoMenuEntry)",array("dn"));
233       while($attrs = $ldap->fetch()){
234         $info = preg_replace("/".preg_quote($release.$group, '/')."$/","",$attrs['dn']); 
235         if(preg_match("/^cn=".$this->cn."/",$info) && !preg_match("/ou=[^,]+,/",$info)){
236           $found[] = $attrs['dn'];
237         }
238       }
239     }
241     /* Create an error message an skip remove, if 
242         this application is still in use. 
243      */
244     if(count($found)){
245       msg_dialog::display(_("Error"), sprintf(_("Cannot remove application - it is still in use by these objects: %s"), "<br>".msgPool::buildList($found)), ERROR_DIALOG);
246       return(FALSE);
247     }
249     $ldap->rmDir($this->dn);
250     new log("remove","application/".get_class($this),$this->dn,array_keys($this->attrs),$ldap->get_error());
251     if (!$ldap->success()){
252       msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $this->dn, LDAP_DEL, get_class()), ERROR_DIALOG);
253     }
255     /* Optionally execute a command after we're done */
256     $this->handle_post_events("remove");
258     /* Delete references to object groups */
259     $ldap->cd ($this->config->current['BASE']);
260     $ldap->search ("(&(objectClass=gosaGroupOfNames)(member=".LDAP::prepare4filter($this->dn)."))", array("cn"));
261     while ($ldap->fetch()){
262       $og= new ogroup($this->config, $ldap->getDN());
263       unset($og->member[$this->dn]);
264       $og->save ();
265       if (!$ldap->success()){
266         msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $this->dn, 0, get_class()), ERROR_DIALOG);
267       }
268     }
269   }
272   /* Save data to object */
273   function save_object()
274   {
275     if(preg_match("/freeze/i",$this->FAIstate)){
276       return;
277     }
279     if (isset($_POST['cn'])){
281       /* Create a base backup and reset the
282          base directly after calling plugin::save_object();
283          Base will be set seperatly a few lines below */
284       $base_tmp = $this->base;
285       plugin::save_object();
286       $this->base = $base_tmp;
288       /* Refresh base */
289       if(!$this->is_release()){
290         if ($this->acl_is_moveable($this->base)){
291           if (!$this->baseSelector->update()) {
292             msg_dialog::display(_("Error"), msgPool::permMove(), ERROR_DIALOG);
293           }
294           if ($this->base != $this->baseSelector->getBase()) {
295             $this->base= $this->baseSelector->getBase();
296             $this->is_modified= TRUE;
297           }
298         }
299       }
302       /* Save attributes */
303       parent::save_object();
305       $checks = array("execForGroupmembers" => "G",
306                       "placeOnDesktop"      => "D",
307                       "placeOnKicker"       => "L",
308                       "placeInStartmenu"    => "M",
309                       "overwriteConfig"     => "O");
312       /* Save application flags */
313       foreach($checks as $name => $flag){
314         if($this->acl_is_writeable($name)){
315           $set = isset($_POST[$name]) && $_POST[$name] == 1;
316           if(!$set && strstr($this->gosaApplicationFlags,$flag)){
317             $this->gosaApplicationFlags = str_replace($flag,"",$this->gosaApplicationFlags);  
318           }elseif($set && !preg_match("/".$flag."/",$this->gosaApplicationFlags)){
319             $this->gosaApplicationFlags .= $flag;
320           }
321         }  
322       }
324       /* Remove current picture */
325       if(isset($_POST['remove_picture'])){
326         $this->set_picture("");
327       }
329       /* Check for picture upload */
330       if (isset($_FILES['picture_file']['name']) && $_FILES['picture_file']['name'] != ""){
332         if (!is_uploaded_file($_FILES['picture_file']['tmp_name'])) {
333           msg_dialog::display(_("Error"), msgPool::incorrectUpload(), ERROR_DIALOG);
334         }
336         if (!function_exists("imagick_blob2image")){
337           /* Get temporary file name for conversation */
338           $fname = tempnam (TEMP_DIR, "GOsa");
340           /* Open file and write out photoData */
341           $fp = fopen ($fname, "w");
342           fwrite ($fp, $_FILES['picture_file']['tmp_name']);
343           fclose ($fp);
345           /* Build conversation query. Filename is generated automatically, so
346              we do not need any special security checks. Exec command and save
347              output. For PHP safe mode, you'll need a configuration which respects
348              image magick as executable... */
349           $query= "convert -size 48x48 $fname -resize 48x48 +profile \"*\" -";
350           @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__, $query, "Execute");
352           /* Read data written by convert */
353           $output= "";
354           $sh= popen($query, 'r');
355           while (!feof($sh)){
356             $output.= fread($sh, 4096);
357           }
358           pclose($sh);
360           unlink($fname);       
361         } else {
363           /* Load the new uploaded Photo */
364           if(!$handle  =  imagick_ReadImage($_FILES['picture_file']['tmp_name'])){
365             msg_dialog::display(_("Error"), msgPool::incorrectUpload(_("no read permission")), ERROR_DIALOG);
366           }
368           /* Resizing image to 147x200 and blur */
369           if(!imagick_resize($handle,48,48,IMAGICK_FILTER_GAUSSIAN,0)){
370             msg_dialog::display(_("Error"), msgPool::incorrectUpload(_("cannot resize image")), ERROR_DIALOG);
371           }
373           /* Converting image to JPEG */
374           if(!imagick_convert($handle,"PNG")) {
375             msg_dialog::display(_("Error"), msgPool::incorrectUpload(_("cannot convert image")), ERROR_DIALOG);
376           }
378           if(!imagick_writeimage($handle,$_FILES['picture_file']['tmp_name'])){
379             msg_dialog::display(_("Error"), msgPool::incorrectUpload(sprintf(_("cannot save image to '%s'"), $_FILES['picture_file']['tmp_name'])), ERROR_DIALOG);
380           }
382           imagick_free($handle);
383         }
385         /* Activate new picture */
386         $this->set_picture($_FILES['picture_file']['tmp_name']);
387       } 
388     }
389   }
392   /* Check values */
393   function check()
394   {
395     /* Call common method to give check the hook */
396     $message= plugin::check();
398     if(!preg_match("#^/#",$this->gosaApplicationExecute)){
399       $message[]=msgPool::invalid(_("Execute path"),"","","/some/path");
400     }
402     // Check if a wrong base was supplied
403     if(!$this->baseSelector->checkLastBaseUpdate()){
404       $message[]= msgPool::check_base();;
405     }
407     /* Permissions for that base? */
408     if ($this->base != ""){
409       $new_dn= "cn=".$this->cn.",".get_ou('applicationRDN').$this->base;
410     } else {
411       $new_dn= $this->dn;
412     }
415     if($this->dn == "new"){
416       $this->set_acl_base($this->base);
417     }
419     /* All required fields are set? */
420     if ($this->cn == ""){
421       $message[]= msgPool::required(_("Name"));
422     }
424     if(preg_match("/[^a-z0-9_-]/",$this->cn))   {
425       $message[]=msgPool::invalid(_("Name"),$this->cn,"/^[a-z0-9_-]*$/");
426     }
428     if ($this->gosaApplicationExecute == ""){
429       $message[]= msgPool::required(_("Execute"));
430     }
432     /* Check for existing application */
433     $ldap= $this->config->get_ldap_link();
434     $ldap->cd($this->config->current["BASE"]);
436     $tmp = $this->config->search("faiManagement", "CLASS",array('menu','tabs'));
438     if($this->is_release()){
439       $base = $this->parent->parent->app_release;
440     }else{
441       $base = get_ou('applicationRDN').$this->base;
442     }
444     $ldap->ls("(&(objectClass=gosaApplication)(cn=".$this->cn."))",$base,array("cn"));
445     if($ldap->count()){
446       $attrs = $ldap->fetch();
447       if($this->dn != $attrs['dn']) {
448         $message[]= msgPool::duplicated("cn");
449       }
450     }
452     /* Check if we are allowed to create or move this object 
453      */
454     if($this->orig_dn == "new" && !$this->acl_is_createable($this->base)){
455       $message[] = msgPool::permCreate();
456     }elseif($this->orig_dn != "new" && $this->base != $this->orig_base && !$this->acl_is_moveable($this->base)){
457       $message[] = msgPool::permMove();
458     }
460     return $message;
461   }
464   /* Save to LDAP */
465   function save()
466   {
467     /* Get application script without header part, to check if we must save the script itself */
468     $script = preg_replace('/.*### END HEADER ###/s', '', $this->gotoLogonScript);
470     $this->gosaApplicationFlags ="[{$this->gosaApplicationFlags}]";
471     plugin::save();
472     $this->attrs["gosaApplicationIcon"]= $this->gosaApplicationIcon;
474     /* Write back to ldap */
475     $ldap= $this->config->get_ldap_link();
476     $ldap->cat($this->dn, array('dn'));
478     $a= $ldap->fetch();
479     if (count($a)){
481       /* Remove gotoLogonScript if it is empty */
482       if(empty($script))    {
483         $this->attrs['gotoLogonScript'] = array();
484       }
486       $ldap->cd($this->dn);
487       $this->cleanup();
488       $ldap->modify ($this->attrs); 
489       $this->handle_post_events("modify");
490       new log("modify","application/".get_class($this),$this->dn,array_keys($this->attrs),$ldap->get_error());
491     } else {
492       
493       /* Remove gotoLogonScript if it is empty */
494       if(empty($script))    {
495         unset($this->attrs['gotoLogonScript']);
496       }
498       $ldap->cd($this->config->current['BASE']);
499       $ldap->create_missing_trees(preg_replace('/^[^,]+,/', '', $this->dn));
500       $ldap->cd($this->dn);
501       $ldap->add($this->attrs);
502       new log("create","application/".get_class($this),$this->dn,array_keys($this->attrs),$ldap->get_error());
503       $this->handle_post_events("add");
504     }
505     if (!$ldap->success()){
506       msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $this->dn, 0, get_class()), ERROR_DIALOG);
507     }
508   }
510   
511   function is_release()
512   {
513     if(isset($this->parent->parent)){
514       return($this->parent->parent->IsReleaseManagementActivated());
515     }else{
516       /* Check if we should enable the release selection */
517       $tmp = $this->config->search("faiManagement", "CLASS",array('menu','tabs'));
518       if(!empty($tmp)){
519         return(true);
520       }
521     }
522     return(FALSE);
523   }
526   function set_picture($filename)
527   {
528     if (!is_file($filename)){
529       $filename= "./plugins/goto/images/default_icon.png";
530       $this->gosaApplicationIcon= "*removed*";
531     }
533     if (file_exists($filename)){
534       $fd = fopen ($filename, "rb");
535       $this->iconData= fread ($fd, filesize ($filename));
536       session::set('binary',$this->iconData);
537       session::set('binarytype',"image/jpeg");
538       $this->gosaApplicationIcon= $this->iconData;
540       fclose ($fd);
541     }
542   }
544   function getCopyDialog()
545   {
546     $vars = array("cn");
548     $str ="<h3>"._("Application settings")."</h3>
549       <table summary=\""._("Application settings")."\">
550       <tr>
551       <td>".
552       _("Application name"). 
553       "</td>  
554       <td>
555       <input id='gosaApplicationName' name='cn' size='35' maxlength='60' 
556       value='".$this->cn."' 
557       title='"._("Application name to be displayed (i.e. below icons)")."'>                     
558       </td>
559       </tr>
560       </table>";
561     $ret = array();
562     $ret['status'] = "";
563     $ret['string'] = $str;
564     return($ret);
565   }
567   function saveCopyDialog()
568   {
569     if(isset($_POST['cn'])){
570       $this->cn = $_POST['cn'];
571     }
572   }
575   function PrepareForCopyPaste($source)
576   {
577     plugin::PrepareForCopyPaste($source);
578     $source_o = new application($this->config,$source['dn']);
579     $this->gosaApplicationIcon = $source_o->gosaApplicationIcon;     
580   }
583   /* Return plugin informations for acl handling
584       #FIXME FAIscript seams to ununsed within this class... */
585   static function plInfo()
586   {
587     return (array(
588           "plShortName"   => _("Generic"),
589           "plDescription" => _("Application generic"),
590           "plSelfModify"  => FALSE,
591           "plDepends"     => array(),
592           "plPriority"    => 0,
593           "plSection"     => array("administration"),
594           "plCategory"    => array("application" => array("description"  => _("Application"),
595                                                           "objectClass"  => "gosaApplication")),
596           "plProvidedAcls"=> array(
597             "cn"                => _("Name"),
598             "base"              => _("Base"),
599             "description"       => _("Description"),
600             "gosaApplicationExecute"  => _("Execute"),
601             "gosaApplicationName"     => _("Name"),
602             "gosaApplicationIcon"     => _("Icon"),
603             "gotoLogonScript"         => _("Script content"),
605             "execForGroupmembers" => _("Only executable for members"),              // G
606             "placeOnDesktop"      => _("Place icon on members desktop"),            // D
607             "placeOnKicker"       => _("Place entry in members launch bar"),        // L
608             "placeInStartmenu"    => _("Place entry in members startmenu"),         // M
609             "overwriteConfig"      => _("Replace user configuration on startup"))  // O
610             ));
611   }
613 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
614 ?>