Code

Updated partition handling
[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("application", "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(gosa_file_name($_FILES['ScriptFile']['tmp_name']));
163       $this->gotoLogonScript = $str;
164     }
166     /* Fill templating stuff */
167     $smarty->assign("cn", set_post($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, set_post($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",set_post($this->gotoLogonScript));
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("application", "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         $filename = gosa_file_name($_FILES['picture_file']['tmp_name']);
331         if (!is_readable($filename)) {
332           msg_dialog::display(_("Error"), msgPool::incorrectUpload(), ERROR_DIALOG);
333         }
335         if (!function_exists("imagick_blob2image")){
336           /* Get temporary file name for conversation */
337           $fname = tempnam (TEMP_DIR, "GOsa");
339           /* Open file and write out photoData */
340           $fp = fopen ($fname, "w");
341           fwrite ($fp, $filename);
342           fclose ($fp);
344           /* Build conversation query. Filename is generated automatically, so
345              we do not need any special security checks. Exec command and save
346              output. For PHP safe mode, you'll need a configuration which respects
347              image magick as executable... */
348           $query= "convert -size 48x48 $fname -resize 48x48 +profile \"*\" -";
349           @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__, $query, "Execute");
351           /* Read data written by convert */
352           $output= "";
353           $sh= popen($query, 'r');
354           while (!feof($sh)){
355             $output.= fread($sh, 4096);
356           }
357           pclose($sh);
359           unlink($fname);       
360         } else {
362           /* Load the new uploaded Photo */
363           if(!$handle  =  imagick_ReadImage($filename)){
364             msg_dialog::display(_("Error"), msgPool::incorrectUpload(_("no read permission")), ERROR_DIALOG);
365           }
367           /* Resizing image to 147x200 and blur */
368           if(!imagick_resize($handle,48,48,IMAGICK_FILTER_GAUSSIAN,0)){
369             msg_dialog::display(_("Error"), msgPool::incorrectUpload(_("cannot resize image")), ERROR_DIALOG);
370           }
372           /* Converting image to JPEG */
373           if(!imagick_convert($handle,"PNG")) {
374             msg_dialog::display(_("Error"), msgPool::incorrectUpload(_("cannot convert image")), ERROR_DIALOG);
375           }
377           if(!imagick_writeimage($handle,$filename)){
378             msg_dialog::display(_("Error"), msgPool::incorrectUpload(sprintf(_("cannot save image to '%s'"), $filename)), ERROR_DIALOG);
379           }
381           imagick_free($handle);
382         }
384         /* Activate new picture */
385         $this->set_picture($filename);
386       } 
387     }
388   }
391   /* Check values */
392   function check()
393   {
394     /* Call common method to give check the hook */
395     $message= plugin::check();
397     if(!preg_match("#^/#",$this->gosaApplicationExecute)){
398       $message[]=msgPool::invalid(_("Execute path"),"","","/some/path");
399     }
401     // Check if a wrong base was supplied
402     if(!$this->baseSelector->checkLastBaseUpdate()){
403       $message[]= msgPool::check_base();;
404     }
406     /* Permissions for that base? */
407     if ($this->base != ""){
408       $new_dn= "cn=".$this->cn.",".get_ou("application", "applicationRDN").$this->base;
409     } else {
410       $new_dn= $this->dn;
411     }
414     if($this->dn == "new"){
415       $this->set_acl_base($this->base);
416     }
418     /* All required fields are set? */
419     if ($this->cn == ""){
420       $message[]= msgPool::required(_("Name"));
421     }
423     if(preg_match("/[^a-z0-9_-]/",$this->cn))   {
424       $message[]=msgPool::invalid(_("Name"),$this->cn,"/^[a-z0-9_-]*$/");
425     }
427     if ($this->gosaApplicationExecute == ""){
428       $message[]= msgPool::required(_("Execute"));
429     }
431     /* Check for existing application */
432     $ldap= $this->config->get_ldap_link();
433     $ldap->cd($this->config->current["BASE"]);
434     if($this->is_release()){
435       $base = $this->parent->parent->app_release;
436     }else{
437       $base = get_ou("application", "applicationRDN").$this->base;
438     }
440     $ldap->ls("(&(objectClass=gosaApplication)(cn=".$this->cn."))",$base,array("cn"));
441     if($ldap->count()){
442       $attrs = $ldap->fetch();
443       if($this->dn != $attrs['dn']) {
444         $message[]= msgPool::duplicated("cn");
445       }
446     }
448     /* Check if we are allowed to create or move this object 
449      */
450     if($this->orig_dn == "new" && !$this->acl_is_createable($this->base)){
451       $message[] = msgPool::permCreate();
452     }elseif($this->orig_dn != "new" && $this->base != $this->orig_base && !$this->acl_is_moveable($this->base)){
453       $message[] = msgPool::permMove();
454     }
456     return $message;
457   }
460   /* Save to LDAP */
461   function save()
462   {
463     /* Get application script without header part, to check if we must save the script itself */
464     $script = preg_replace('/.*### END HEADER ###/s', '', $this->gotoLogonScript);
466     $this->gosaApplicationFlags ="[{$this->gosaApplicationFlags}]";
467     plugin::save();
468     $this->attrs["gosaApplicationIcon"]= $this->gosaApplicationIcon;
470     /* Write back to ldap */
471     $ldap= $this->config->get_ldap_link();
472     $ldap->cat($this->dn, array('dn'));
474     $a= $ldap->fetch();
475     if (count($a)){
477       /* Remove gotoLogonScript if it is empty */
478       if(empty($script))    {
479         $this->attrs['gotoLogonScript'] = array();
480       }
482       $ldap->cd($this->dn);
483       $this->cleanup();
484       $ldap->modify ($this->attrs); 
485       $this->handle_post_events("modify");
486       new log("modify","application/".get_class($this),$this->dn,array_keys($this->attrs),$ldap->get_error());
487     } else {
488       
489       /* Remove gotoLogonScript if it is empty */
490       if(empty($script))    {
491         unset($this->attrs['gotoLogonScript']);
492       }
494       $ldap->cd($this->config->current['BASE']);
495       $ldap->create_missing_trees(preg_replace('/^[^,]+,/', '', $this->dn));
496       $ldap->cd($this->dn);
497       $ldap->add($this->attrs);
498       new log("create","application/".get_class($this),$this->dn,array_keys($this->attrs),$ldap->get_error());
499       $this->handle_post_events("add");
500     }
501     if (!$ldap->success()){
502       msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $this->dn, 0, get_class()), ERROR_DIALOG);
503     }
504   }
506   
507   function is_release()
508   {
509     if(isset($this->parent->parent)){
510       return($this->parent->parent->IsReleaseManagementActivated());
511     }else{
513       /* Check if we should enable the release selection */
514       return($this->config->pluginEnabled("faiManagement"));
515     }
516     return(FALSE);
517   }
520   function set_picture($filename)
521   {
522     if (!is_file($filename)){
523       $filename= "./plugins/goto/images/default_icon.png";
524       $this->gosaApplicationIcon= "*removed*";
525     }
527     if (file_exists($filename)){
528       $fd = fopen ($filename, "rb");
529       $this->iconData= fread ($fd, filesize ($filename));
530       session::set('binary',$this->iconData);
531       session::set('binarytype',"image/jpeg");
532       $this->gosaApplicationIcon= $this->iconData;
534       fclose ($fd);
535     }
536   }
538   function getCopyDialog()
539   {
540     $vars = array("cn");
542     $str ="<h3>"._("Application settings")."</h3>
543       <table summary=\""._("Application settings")."\">
544       <tr>
545       <td>".
546       _("Application name"). 
547       "</td>  
548       <td>
549       <input id='gosaApplicationName' name='cn' size='35' maxlength='60' 
550       value='".$this->cn."' 
551       title='"._("Application name to be displayed (i.e. below icons)")."'>                     
552       </td>
553       </tr>
554       </table>";
555     $ret = array();
556     $ret['status'] = "";
557     $ret['string'] = $str;
558     return($ret);
559   }
561   function saveCopyDialog()
562   {
563     if(isset($_POST['cn'])){
564       $this->cn = set_post($_POST['cn']);
565     }
566   }
569   function PrepareForCopyPaste($source)
570   {
571     plugin::PrepareForCopyPaste($source);
572     $source_o = new application($this->config,$source['dn']);
573     $this->gosaApplicationIcon = $source_o->gosaApplicationIcon;     
574   }
577   /* Return plugin informations for acl handling
578       #FIXME FAIscript seams to ununsed within this class... */
579   static function plInfo()
580   {
581       return (array(
582                   "plShortName"   => _("Generic"),
583                   "plDescription" => _("Application generic"),
584                   "plSelfModify"  => FALSE,
585                   "plDepends"     => array(),
586                   "plPriority"    => 0,
587                   "plSection"     => array("administration"),
588                   "plCategory"    => array("application" => array("description"  => _("Application"),
589                           "objectClass"  => "gosaApplication")),
590                   "plRequirements"=> array(
591                       'ldapSchema' => array('gosaApplication' => '>=2.7'),
592                       'onFailureDisablePlugin' => array(get_class(),'applicationManagement','appgroup')
593                       ),
594                   "plProperties" =>
595                   array(
596                       array(
597                           "name"          => "applicationRDN",
598                           "type"          => "rdn",
599                           "default"       => "ou=apps,",
600                           "description"   => _("RDN for application storage."),
601                           "check"         => "gosaProperty::isRdn",
602                           "migrate"       => "migrate_applicationRDN",
603                           "group"         => "plugin",
604                           "mandatory"     => FALSE)),
606           "plProvidedAcls"=> array(
607                   "cn"                => _("Name"),
608                   "base"              => _("Base"),
609                   "description"       => _("Description"),
610                   "gosaApplicationExecute"  => _("Execute"),
611                   "gosaApplicationName"     => _("Name"),
612                   "gosaApplicationIcon"     => _("Icon"),
613                   "gotoLogonScript"         => _("Script content"),
615                   "execForGroupmembers" => _("Only executable for members"),              // G
616                   "placeOnDesktop"      => _("Place icon on members desktop"),            // D
617                   "placeOnKicker"       => _("Place entry in members launch bar"),        // L
618                   "placeInStartmenu"    => _("Place entry in members start menu"),         // M
619                   "overwriteConfig"      => _("Replace user configuration on startup"))  // O
620               ));
621   }
623 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
624 ?>