Code

Recent changes in win2003sp1 required some fixes (backward compatible).
[gosa.git] / plugins / admin / applications / class_applicationGeneric.inc
1 <?php
2 class application extends plugin
3 {
4   /* CLI vars */
5   var $cli_summary= "Handling of GOsa's application object";
6   var $cli_description= "Some longer text\nfor help";
7   var $cli_parameters= array("eins" => "Eins ist toll", "zwei" => "Zwei ist noch besser");
9   /* application attributes */
10   var $cn= "";
11   var $description= "";
12   var $base= "";
13   var $gosaApplicationExecute= "";
14   var $gosaApplicationName= "";
15   var $gosaApplicationFlags= "";
16   var $gosaApplicationIcon= "";
17   var $gotoLogonScript  ="";
18   var $iconData;
20   /* Headpage attributes */
21   var $last_sorting= "invalid";
22   var $applications= array();
24   /* attribute list for save action */
25   var $attributes= array("cn", "description", "gosaApplicationExecute", "gosaApplicationName","gosaApplicationIcon",
26       "gosaApplicationFlags","gotoLogonScript");
27   var $objectclasses= array("top", "gosaApplication");
29   var $isReleaseApplikation = false;
31   function application ($config, $dn= NULL, $parent= NULL)
32   {
33     plugin::plugin ($config, $dn, $parent);
35     $tmp = search_config($this->config->data,"faiManagement","CLASS");
36     if(!empty($tmp)) {
37       if(!preg_match("/^ou=apps,/",$_SESSION['appfilter']['release'])){
38         $this->isReleaseApplikation = true;  
39       }
40     }
42     /* Load icon */
43     $ldap= $config->get_ldap_link();
44     if ($dn != 'new'){
45       $this->iconData= $ldap->get_attribute($dn, "gosaApplicationIcon");
46       $this->saved_attributes['gosaApplicationIcon'] = $this->iconData;
47     }
48     if ($this->iconData == ""){
49       $this->set_picture("");
50     }
51     $_SESSION['binary']= $this->iconData;
52     $_SESSION['binarytype']= "image/jpeg";
53     $this->gosaApplicationIcon= $this->iconData;
55     /* This is always an account */
56     $this->is_account= TRUE;
58     if ($this->dn == "new"){
59       if(isset($_SESSION['CurrentMainBase'])){
60         $this->base= $_SESSION['CurrentMainBase'];
61       }else{
62         $ui= get_userinfo();
63         $this->base= dn2base($ui->dn);
64       }
65     } else {
67       if($this->isReleaseApplikation){
68         $this->base = preg_replace("/^.*,ou=apps,/","",$this->dn);
69       }else{
70         $this->base= preg_replace ("/^[^,]+,[^,]+,/", "", $this->dn);
71       }
72     }
73   }
76   function generateTemplate(){
77     $str= "# This code is part of GOsa (https://gosa.gonicus.de)\n#\n";
79     $values = array();
80     $names      = array();
81     if($this->parent->by_object['applicationParameters']->is_account){
82       $names = $this->parent->by_object['applicationParameters']->option_name;
83       $values = $this->parent->by_object['applicationParameters']->option_value;
84     }
86     if (count($names)){
87       $str .="# This plugin handles these environment variables:\n";
88     } else {
89       $str .="# This plugin handles no environment variables.\n";
90     }
92     foreach($names as $index => $name){
94       // Fix length
95       for($i = strlen($name) ; $i < 30 ; $i++){
96         $name= $name." ";
97       }
98       if((isset($values[$index]))&&(!empty($values[$index]))){
99         $str.= "# ".$name."\t(e.g. '".$values[$index]."')\n";
100       }else{
101         $str.= "# ".$name."\t("._("no example").")\n";
102       }
103     }
104     $str .= "#\n".
105       "# Don't remove the following tag, it is used for header update.\n".
106       "### END HEADER ###";
108     return($str);
109   }
111   function execute()
112   {
113     /* Call parent execute */
114     plugin::execute();
116     $smarty= get_smarty();
118     $tmp = $this->plInfo();
119     foreach($tmp['plProvidedAcls'] as $name => $translation){
120       $smarty->assign($name."ACL",$this->getacl($name));
121     }
122  
123     $baseACL = $this->getacl("base");
124     if(!$this->acl_is_moveable()) {
125       $baseACL = preg_replace("/w/","",$baseACL);
126     }
127     $smarty->assign("baseACL",          $baseACL);
129     /* Do we represent a valid group? */
130     if (!$this->is_account && $this->parent == NULL){
131       $display= "<img alt=\"\" src=\"images/stop.png\" align=\"middle\">&nbsp;<b>".
132         _("This 'dn' is no application.")."</b>";
133       return ($display);
134     }
136     /* Download requested */
137     foreach($_POST as $name => $value){
138       if(preg_match("/^downloadScript/",$name)){
139         $_SESSION['binary']       = $this->gotoLogonScript;
140         $_SESSION['binarytype']   = "octet-stream";
141         $_SESSION['binaryfile']   = $this->cn.".gosaApplication";
142         header("location: getbin.php ");
143         exit();
144       }
145     }
147     /* Reassign picture data, sometimes its corrupt cause we started a download of application scripts */
148     $_SESSION['binary']     = $this->iconData;
149     $_SESSION['binarytype'] = "image/jpeg";
150     
151     $smarty->assign("rand", rand(0, 10000));
152     $head = $this->generateTemplate();
153     $this->gotoLogonScript= $this->generateTemplate().preg_replace('/.*### END HEADER ###/s', '', $this->gotoLogonScript);
155     if((isset($_POST['upLoad']))&&(isset($_FILES['ScriptFile']))){
156       $str = file_get_contents($_FILES['ScriptFile']['tmp_name']);
157       $this->gotoLogonScript = $str;
158     }
160     /* Fill templating stuff */
161     $smarty->assign("cn", $this->cn);
162     $smarty->assign("bases", $this->get_allowed_bases());
163     if ($this->dn == "new"){
164       $smarty->assign("selectmode", "");
165       $smarty->assign("namemode", "");
166     } else {
167       $smarty->assign("namemode", "readonly");
168       $smarty->assign("selectmode", "disabled");
169     }
170     
171     /* Base select dialog */
172     $once = true;
173     foreach($_POST as $name => $value){
174       if(preg_match("/^chooseBase/",$name) && $once){
175         $once = false;
176         $this->dialog = new baseSelectDialog($this->config,$this,$this->get_allowed_bases());
177         $this->dialog->setCurrentBase($this->base);
178       }
179     }
181     /* Dialog handling */
182     if(is_object($this->dialog)){
183       /* Must be called before save_object */
184       $this->dialog->save_object();
186       if($this->dialog->isClosed()){
187         $this->dialog = false;
188       }elseif($this->dialog->isSelected()){
189         $this->base = $this->dialog->isSelected();
190         $this->dialog= false;
191       }else{
192         return($this->dialog->execute());
193       }
194     }
196     /* Get random number for pictures */
197     srand((double)microtime()*1000000);
198     $smarty->assign("rand", rand(0, 10000));
200     /* Variables */
201     foreach(array("description", "gosaApplicationExecute", "gosaApplicationName","cn") as $val){
202       $smarty->assign($val, $this->$val);
203     }
205     /* Checkboxes */
206     foreach (array("G" => "exec_for_groupmembers", "O" => "overwrite_config",
207           "L" => "place_on_kicker",
208           "D" => "place_on_desktop", "M" => "place_in_startmenu") as $key => $val){
209       if (preg_match("/$key/", $this->gosaApplicationFlags)){
210         $smarty->assign("$val", "checked");
211       } else {
212         $smarty->assign("$val", "");
213       }
214     }
216     $smarty->assign("isReleaseApplikation" , $this->isReleaseApplikation);
217     $smarty->assign("gotoLogonScript",htmlentities($this->gotoLogonScript, ENT_COMPAT, 'UTF-8'));
218     $smarty->assign("base_select", $this->base);
219     /* Show main page */
220     return($smarty->fetch (get_template_path('generic.tpl', TRUE)));
221   }
224   function remove_from_parent()
225   {
226     $ldap= $this->config->get_ldap_link();
227     $ldap->rmDir($this->dn);
228     show_ldap_error($ldap->get_error(), sprintf(_("Removing of application with dn '%s' failed."),$this->dn));
230     /* Optionally execute a command after we're done */
231     $this->handle_post_events("remove");
233     /* Delete references to object groups */
234     $ldap->cd ($this->config->current['BASE']);
235     $ldap->search ("(&(objectClass=gosaGroupOfNames)(member=".$this->dn."))", array("cn"));
236     while ($ldap->fetch()){
237       $og= new ogroup($this->config, $ldap->getDN());
238       unset($og->member[$this->dn]);
239       $og->save ();
240       show_ldap_error($ldap->get_error(), sprintf(_("Removing application from objectgroup '%s' failed"), $og->dn));
241     }
242     $ldap->search ("(&(objectClass=posixGroup)(gosaMemberApplication=".$this->cn."))", array("cn"));
243     while ($attrs= $ldap->fetch()){
244       $ag= new appgroup($this->config, $ldap->getDN());
245       $ag->removeApp($this->cn);
246       $ag->save ();
247       show_ldap_error($ldap->get_error(), sprintf(_("Removing application from group '%s' failed"), $ag->dn));
248     }
250   }
253   /* Save data to object */
254   function save_object()
255   {
256     if($this->isReleaseApplikation){
257       $tmpBase = $this->base;
258     } 
259  
260     if (isset($_POST['cn'])){
262       /* Save attributes */
263       parent::save_object();
265       /* Save application flags */
266       $flag= "";
267       if (isset($_POST['exec_for_groupmembers']) && $_POST['exec_for_groupmembers'] == 1){
268         $flag.= "G";
269       }
270       if (isset($_POST['place_on_desktop']) && $_POST['place_on_desktop'] == 1){
271         $flag.= "D";
272       }
273       if (isset($_POST['place_on_kicker']) && $_POST['place_on_kicker'] == 1){
274         $flag.= "L";
275       }
276       if (isset($_POST['place_in_startmenu']) && $_POST['place_in_startmenu'] == 1){
277         $flag.= "M";
278       }
279       if (isset($_POST['overwrite_config']) && $_POST['overwrite_config'] == 1){
280         $flag.= "O";
281       }
282       if ($this->acl_is_writeable("gosaApplicationFlags")){
283         $this->gosaApplicationFlags= "[$flag]";
284       }
286       /* Check for picture upload */
287       if (isset($_FILES['picture_file']['name']) && $_FILES['picture_file']['name'] != ""){
288         if (!is_uploaded_file($_FILES['picture_file']['tmp_name'])) {
289           print_red (_("The specified picture has not been uploaded correctly."));
290         }
292         if (!function_exists("imagick_blob2image")){
293           /* Get temporary file name for conversation */
294           $fname = tempnam ("/tmp", "GOsa");
296           /* Open file and write out photoData */
297           $fp = fopen ($fname, "w");
298           fwrite ($fp, $_FILES['picture_file']['tmp_name']);
299           fclose ($fp);
301           /* Build conversation query. Filename is generated automatically, so
302              we do not need any special security checks. Exec command and save
303              output. For PHP safe mode, you'll need a configuration which respects
304              image magick as executable... */
305           $query= "convert -size 48x48 $fname -resize 48x48 +profile \"*\" -";
306           @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__, $query, "Execute");
308           /* Read data written by convert */
309           $output= "";
310           $sh= popen($query, 'r');
311           while (!feof($sh)){
312             $output.= fread($sh, 4096);
313           }
314           pclose($sh);
316           unlink($fname);       
317         } else {
319           /* Load the new uploaded Photo */
320           if(!$handle  =  imagick_ReadImage($_FILES['picture_file']['tmp_name'])){
321             gosa_log("Can't Load image");
322           }
324           /* Resizing image to 147x200 and blur */
325           if(!imagick_resize($handle,48,48,IMAGICK_FILTER_GAUSSIAN,0)){
326             gosa_log("imagick_resize failed");
327           }
329           /* Converting image to JPEG */
330           if(!imagick_convert($handle,"PNG")) {
331             gosa_log("Can't Convert to PNG");
332           }
334           if(imagick_writeimage($handle,$_FILES['picture_file']['tmp_name'])){
335             gosa_log("can't write to specified folder");
336           }
338           imagick_free($handle);
339         }
341         /* Activate new picture */
342         $this->set_picture($_FILES['picture_file']['tmp_name']);
343       } 
345       if(isset($_POST['base'])){
346         $this->base= $_POST['base'];
347       }
348     }
350     if($this->isReleaseApplikation){
351       $this->base = $tmpBase;
352     }
353   }
356   /* Check values */
357   function check()
358   {
359     /* Call common method to give check the hook */
360     $message= plugin::check();
362     if(!preg_match("#^/#",$this->gosaApplicationExecute)){
363       $message[]=(_("Specified execute path must start with '/'."));
364     }
366     /* Permissions for that base? */
367     if ($this->base != ""){
368       $new_dn= "cn=".$this->cn.",ou=apps,".$this->base;
369     } else {
370       $new_dn= $this->dn;
371     }
373     $ui= get_userinfo();
374     if (!$this->acl_is_createable() && $this->dn == "new"){
375       $message[]= _("You have no permissions to create a application on this 'Base'.");
376     }
378     /* All required fields are set? */
379     if ($this->cn == ""){
380       $message[]= _("Required field 'Name' is not filled.");
381     }
383     if(preg_match("/[^a-z0-9]/",$this->cn))     {
384       $message[]=_("Invalid character in application name. Only a-z 0-9 are allowed.");
385     }
387     if ($this->gosaApplicationExecute == ""){
388       $message[]= _("Required field 'Execute' is not filled.");
389     }
391     /* Check for existing application */
392     $ldap= $this->config->get_ldap_link();
393     $ldap->cd($this->config->current["BASE"]);
395     $tmp = search_config($this->config->data,"faiManagement","CLASS");
396     if((!empty($tmp)) && (isset($_SESSION['appfilter']['release']))){
397       $baseDn = str_replace($this->config->current['BASE'],$this->base,$_SESSION['appfilter']['release']);
398       $baseDn = preg_replace("/ou=apps,.*/","ou=apps,".$this->base,$_SESSION['appfilter']['release']);
399       $ldap->ls("(&(objectClass=gosaApplication)(cn=".$this->cn."))",$baseDn,array("cn"));
400       if($ldap->count()){
401         $attrs = $ldap->fetch();
402         if($this->dn != $attrs['dn']) {
403           $message[]= _("There's already an application with this 'Name'.");
404         }
405       }
406     }else{
407       $ldap->ls("(&(objectClass=gosaApplication)(cn=".$this->cn."))","ou=apps,".$this->base,array("cn"));
408       if ($ldap->count()){
409         $attrs = $ldap->fetch();
410         if($this->dn != $attrs['dn']) {
411           $message[]= _("There's already an application with this 'Name'.");
412         }
413       }
414     }
415     return $message;
416   }
419   /* Save to LDAP */
420   function save()
421   {
422     /* Get application script without header part, to check if we must save the script itself */
423     $script = preg_replace('/.*### END HEADER ###/s', '', $this->gotoLogonScript);
425     plugin::save();
426     $this->attrs["gosaApplicationIcon"]= $this->gosaApplicationIcon;
428     /* Write back to ldap */
429     $ldap= $this->config->get_ldap_link();
430     $ldap->cat($this->dn, array('dn'));
432     $a= $ldap->fetch();
433     if (count($a)){
435       /* Remove gotoLogonScript if it is empty */
436       if(empty($script))    {
437         $this->attrs['gotoLogonScript'] = array();
438       }
440       $ldap->cd($this->dn);
441       $this->cleanup();
442       $ldap->modify ($this->attrs); 
443       $this->handle_post_events("modify");
444     } else {
445       
446       /* Remove gotoLogonScript if it is empty */
447       if(empty($script))    {
448         unset($this->attrs['gotoLogonScript']);
449       }
451       $ldap->cd($this->config->current['BASE']);
452       $ldap->create_missing_trees(preg_replace('/^[^,]+,/', '', $this->dn));
453       $ldap->cd($this->dn);
454       $ldap->add($this->attrs);
455       $this->handle_post_events("add");
456     }
457     show_ldap_error($ldap->get_error(), sprintf(_("Saving of application with dn '%s' failed."),$this->dn));
458   }
460   function set_picture($filename)
461   {
462     if (!is_file($filename)){
463       $filename= "./images/default_icon.png";
464       $this->gosaApplicationIcon= "*removed*";
465     }
467     if (file_exists($filename)){
468       $fd = fopen ($filename, "rb");
469       $this->iconData= fread ($fd, filesize ($filename));
470       $_SESSION['binary']= $this->iconData;
471       $_SESSION['binarytype']= "image/jpeg";
472       $this->gosaApplicationIcon= $this->iconData;
474       fclose ($fd);
475     }
476   }
478   function getCopyDialog()
479   {
480     $vars = array("cn");
482     $str ="<h2>"._("Application settings")."</h2>
483       <table>
484       <tr>
485       <td>".
486       _("Application name"). 
487       "</td>  
488       <td>
489       <input id='gosaApplicationName' name='cn' size='35' maxlength='60' 
490       value='".$this->cn."' 
491       title='"._("Application name to be displayed (i.e. below icons)")."'>                     
492       </td>
493       </tr>
494       </table>";
495     $ret = array();
496     $ret['status'] = "";
497     $ret['string'] = $str;
498     return($ret);
499   }
501   function saveCopyDialog()
502   {
503     if(isset($_POST['cn'])){
504       $this->cn = $_POST['cn'];
505     }
506   }
509   /* Return plugin informations for acl handling
510       #FIXME FAIscript seams to ununsed within this class... */
511   function plInfo()
512   {
513     return (array(
514           "plShortName"   => _("Generic"),
515           "plDescription" => _("Application generic"),
516           "plSelfModify"  => FALSE,
517           "plDepends"     => array(),
518           "plPriority"    => 0,
519           "plSection"     => array("administration"),
520           "plCategory"    => array("application" => array("description"  => _("Application"),
521                                                           "objectClass"  => "gosaApplication")),
522           "plProvidedAcls"=> array(
523             "cn"                => _("Name"),
524             "base"              => _("Base"),
525             "description"       => _("Description"),
526             "gosaApplicationExecute"  => _("Execute"),
527             "gosaApplicationName"     => _("Name"),
528             "gosaApplicationIcon"     => _("Icon"),
529             "gosaApplicationFlags"    => _("Flag"),
530             "gotoLogonScript"         => _("Script content"),
532             "exec_for_groupmembers" => _("Only executable for members"),              // G
533             "place_on_desktop"      => _("Place icon on members desktop"),            // D
534             "place_on_kicker"       => _("Place entry in members launch bar"),        // L
535             "place_in_startmenu"    => _("Place entry in members startmenu"),         // M
536             "overwrite_config"      => _("Replace user configuration on startup"))  // O
537             ));
538   }
540 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
541 ?>