Code

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