Code

Removed a couple of normalize_preg calls
[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('applicationRDN')."/", "", $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     $smarty->assign("IconReadable", $this->acl_is_readable("gosaApplicationIcon"));
122  
123     /* Do we represent a valid group? */
124     if (!$this->is_account && $this->parent === NULL){
125       $display= "<img alt=\"\" src=\"images/small-error.png\" align=\"middle\">&nbsp;<b>".
126         msgPool::noValidExtension(_("application"))."</b>";
127       return ($display);
128     }
130     /* Download requested */
131     foreach($_POST as $name => $value){
132       if(preg_match("/^downloadScript/",$name)){
133         session::set('binary',$this->gotoLogonScript);
134         session::set('binarytype',"octet-stream");
135         session::set('binaryfile',$this->cn.".gosaApplication");
136         header("location: getbin.php ");
137         exit();
138       }
139     }
141     /* Reassign picture data, sometimes its corrupt cause we started a download of application scripts */
142     session::set('binary',$this->iconData);
143     session::set('binarytype',"image/jpeg");
144     
145     $smarty->assign("rand", rand(0, 10000));
146     $head = $this->generateTemplate();
147     $this->gotoLogonScript= $this->generateTemplate().preg_replace('/.*### END HEADER ###/s', '', $this->gotoLogonScript);
149     if((isset($_POST['upLoad']))&&(isset($_FILES['ScriptFile'])) && !preg_match("/freeze/i",$this->FAIstate)){
150       $str = file_get_contents($_FILES['ScriptFile']['tmp_name']);
151       $this->gotoLogonScript = $str;
152     }
154     /* Fill templating stuff */
155     $smarty->assign("cn", $this->cn);
156     if(!$this->is_release()){
157       $smarty->assign("bases", $this->get_allowed_bases());
158     }else{
159       $smarty->assign("bases", array());
160     }
161     if ($this->dn == "new"){
162       $smarty->assign("selectmode", "");
163       $smarty->assign("namemode", "");
164     } else {
165       $smarty->assign("namemode", "readonly");
166       $smarty->assign("selectmode", "disabled");
167     }
168     
169     /* Base select dialog */
170     $once = true;
171     foreach($_POST as $name => $value){
172       if(preg_match("/^chooseBase/",$name) && $once && !preg_match("/freeze/i",$this->FAIstate)){
173         $once = false;
174         $this->dialog = new baseSelectDialog($this->config,$this,$this->get_allowed_bases());
175         $this->dialog->setCurrentBase($this->base);
176       }
177     }
179     /* Dialog handling */
180     if(is_object($this->dialog)){
181       /* Must be called before save_object */
182       $this->dialog->save_object();
184       if($this->dialog->isClosed()){
185         $this->dialog = false;
186       }elseif($this->dialog->isSelected()){
187  
188         /* Just allow selection valid bases */ 
189         $tmp = $this->get_allowed_bases();
190         if(isset($tmp[$this->dialog->isSelected()])){
191           $this->base = $this->dialog->isSelected();
192         }
193         $this->dialog= false;
194       }else{
195         return($this->dialog->execute());
196       }
197     }
199     /* Get random number for pictures */
200     srand((double)microtime()*1000000);
201     $smarty->assign("rand", rand(0, 10000));
203     /* Variables */
204     foreach(array("description", "gosaApplicationExecute", "gosaApplicationName","cn") as $val){
205       $smarty->assign($val, $this->$val);
206     }
208     /* Checkboxes */
209     foreach (array("G" => "execForGroupmembers", "O" => "overwriteConfig",
210           "L" => "placeOnKicker",
211           "D" => "placeOnDesktop", "M" => "placeInStartmenu") as $key => $val){
212       if (preg_match("/$key/", $this->gosaApplicationFlags) && $this->acl_is_readable("$val")){
213         $smarty->assign("$val", "checked");
214       } else {
215         $smarty->assign("$val", "");
216       }
217     }
219     $smarty->assign("isReleaseApplikation" ,$this->is_release());
220     $smarty->assign("gotoLogonScript",htmlentities($this->gotoLogonScript, ENT_COMPAT, 'UTF-8'));
221     $smarty->assign("base_select", $this->base);
222     /* Show main page */
223     return($smarty->fetch (get_template_path('generic.tpl', TRUE)));
224   }
227   function remove_from_parent()
228   {
229     restore_error_handler();
231     /* Parse release out of object dn */
232     $release = preg_replace("/".get_ou("applicationRDN").preg_quote($this->base)."$/","",$this->dn);
233     $release = preg_replace("/^cn=[^,]+,/","",$release);
235     /* Get a list of all groups 
236      */
237     $groups = array();
238     $ldap= $this->config->get_ldap_link();
239     $ldap->cd($this->config->current['BASE']);
240     $ldap->search("(objectClass=posixGroup)",array("dn"));
241     while($attrs = $ldap->fetch()){
242       $groups[$attrs['dn']] = array();
243     }
244     
245     /* Check if there are groups, useing this application 
246      */
247     $found = array();
248     foreach($groups as $group => $data){
249       $ldap->cd($release.$group);
250       $ldap->search("(objectClass=gotoMenuEntry)",array("dn"));
251       while($attrs = $ldap->fetch()){
252         $info = preg_replace("/".preg_quote($release.$group)."$/","",$attrs['dn']); 
253         if(preg_match("/^cn=".$this->cn."/",$info) && !preg_match("/ou=[^,]+,/",$info)){
254           $found[] = $attrs['dn'];
255         }
256       }
257     }
259     /* Create an error message an skip remove, if 
260         this application is still in use. 
261      */
262     if(count($found)){
263       msg_dialog::display(_("Error"), sprintf(_("Cannot remove application - it is still in use by these objects: %s"), "<br>".msgPool::buildList($found)), ERROR_DIALOG);
264       return(FALSE);
265     }
267     $ldap->rmDir($this->dn);
268     new log("remove","application/".get_class($this),$this->dn,array_keys($this->attrs),$ldap->get_error());
269     if (!$ldap->success()){
270       msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $this->dn, LDAP_DEL, get_class()), ERROR_DIALOG);
271     }
273     /* Optionally execute a command after we're done */
274     $this->handle_post_events("remove");
276     /* Delete references to object groups */
277     $ldap->cd ($this->config->current['BASE']);
278     $ldap->search ("(&(objectClass=gosaGroupOfNames)(member=".LDAP::prepare4filter($this->dn)."))", array("cn"));
279     while ($ldap->fetch()){
280       $og= new ogroup($this->config, $ldap->getDN());
281       unset($og->member[$this->dn]);
282       $og->save ();
283       if (!$ldap->success()){
284         msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $this->dn, 0, get_class()), ERROR_DIALOG);
285       }
286     }
287   }
290   /* Save data to object */
291   function save_object()
292   {
293     if(preg_match("/freeze/i",$this->FAIstate)){
294       return;
295     }
297     if (isset($_POST['cn'])){
299       /* Create a base backup and reset the
300          base directly after calling plugin::save_object();
301          Base will be set seperatly a few lines below */
302       $base_tmp = $this->base;
303       plugin::save_object();
304       $this->base = $base_tmp;
306       /* Save attributes */
307       parent::save_object();
309       $checks = array("execForGroupmembers" => "G",
310                       "placeOnDesktop"      => "D",
311                       "placeOnKicker"       => "L",
312                       "placeInStartmenu"    => "M",
313                       "overwriteConfig"     => "O");
315       /* Save application flags */
316       foreach($checks as $name => $flag){
317         if($this->acl_is_writeable($name)){
318           $set = isset($_POST[$name]) && $_POST[$name] == 1;
319           if(!$set && preg_match("/".$flag."/",$this->gosaApplicationFlags)){
320             $this->gosaApplicationFlags = preg_replace("/".$flag."/","",$this->gosaApplicationFlags);  
321           }elseif($set && !preg_match("/".$flag."/",$this->gosaApplicationFlags)){
322             $this->gosaApplicationFlags = preg_replace("/]/",$flag."]",$this->gosaApplicationFlags); 
323           }
324         }  
325       }
327       /* Remove current picture */
328       if(isset($_POST['remove_picture'])){
329         $this->set_picture("");
330       }
332       /* Check for picture upload */
333       if (isset($_FILES['picture_file']['name']) && $_FILES['picture_file']['name'] != ""){
335         if (!is_uploaded_file($_FILES['picture_file']['tmp_name'])) {
336           msg_dialog::display(_("Error"), msgPool::incorrectUpload(), ERROR_DIALOG);
337         }
339         if (!function_exists("imagick_blob2image")){
340           /* Get temporary file name for conversation */
341           $fname = tempnam (TEMP_DIR, "GOsa");
343           /* Open file and write out photoData */
344           $fp = fopen ($fname, "w");
345           fwrite ($fp, $_FILES['picture_file']['tmp_name']);
346           fclose ($fp);
348           /* Build conversation query. Filename is generated automatically, so
349              we do not need any special security checks. Exec command and save
350              output. For PHP safe mode, you'll need a configuration which respects
351              image magick as executable... */
352           $query= "convert -size 48x48 $fname -resize 48x48 +profile \"*\" -";
353           @DEBUG (DEBUG_SHELL, __LINE__, __FUNCTION__, __FILE__, $query, "Execute");
355           /* Read data written by convert */
356           $output= "";
357           $sh= popen($query, 'r');
358           while (!feof($sh)){
359             $output.= fread($sh, 4096);
360           }
361           pclose($sh);
363           unlink($fname);       
364         } else {
366           /* Load the new uploaded Photo */
367           if(!$handle  =  imagick_ReadImage($_FILES['picture_file']['tmp_name'])){
368             msg_dialog::display(_("Error"), msgPool::incorrectUpload(_("no read permission")), ERROR_DIALOG);
369           }
371           /* Resizing image to 147x200 and blur */
372           if(!imagick_resize($handle,48,48,IMAGICK_FILTER_GAUSSIAN,0)){
373             msg_dialog::display(_("Error"), msgPool::incorrectUpload(_("cannot resize image")), ERROR_DIALOG);
374           }
376           /* Converting image to JPEG */
377           if(!imagick_convert($handle,"PNG")) {
378             msg_dialog::display(_("Error"), msgPool::incorrectUpload(_("cannot convert image")), ERROR_DIALOG);
379           }
381           if(!imagick_writeimage($handle,$_FILES['picture_file']['tmp_name'])){
382             msg_dialog::display(_("Error"), msgPool::incorrectUpload(sprintf(_("cannot save image to '%s'"), $_FILES['picture_file']['tmp_name'])), ERROR_DIALOG);
383           }
385           imagick_free($handle);
386         }
388         /* Activate new picture */
389         $this->set_picture($_FILES['picture_file']['tmp_name']);
390       } 
392       if(!$this->is_release()){
393         $tmp = $this->get_allowed_bases();
394         if(isset($_POST['base'])){
395           if(isset($tmp[$_POST['base']])){
396             $this->base= $_POST['base'];
397           }
398         }
399       }
400     }
401   }
404   /* Check values */
405   function check()
406   {
407     /* Call common method to give check the hook */
408     $message= plugin::check();
410     if(!preg_match("#^/#",$this->gosaApplicationExecute)){
411       $message[]=msgPool::invalid(_("Execute path"),"","","/some/path");
412     }
414     /* Permissions for that base? */
415     if ($this->base != ""){
416       $new_dn= "cn=".$this->cn.",".get_ou('applicationRDN').$this->base;
417     } else {
418       $new_dn= $this->dn;
419     }
422     if($this->dn == "new"){
423       $this->set_acl_base($this->base);
424     }
426     /* All required fields are set? */
427     if ($this->cn == ""){
428       $message[]= msgPool::required(_("Name"));
429     }
431     if(preg_match("/[^a-z0-9_-]/",$this->cn))   {
432       $message[]=msgPool::invalid(_("Name"),$this->cn,"/^[a-z0-9_-]*$/");
433     }
435     if ($this->gosaApplicationExecute == ""){
436       $message[]= msgPool::required(_("Execute"));
437     }
439     /* Check for existing application */
440     $ldap= $this->config->get_ldap_link();
441     $ldap->cd($this->config->current["BASE"]);
443     $tmp = $this->config->search("faiManagement", "CLASS",array('menu','tabs'));
445     if($this->is_release()){
446       $base = $this->parent->parent->app_release;
447     }else{
448       $base = get_ou('applicationRDN').$this->base;
449     }
451     $ldap->ls("(&(objectClass=gosaApplication)(cn=".$this->cn."))",$base,array("cn"));
452     if($ldap->count()){
453       $attrs = $ldap->fetch();
454       if($this->dn != $attrs['dn']) {
455         $message[]= msgPool::duplicated("cn");
456       }
457     }
459     /* Check if we are allowed to create or move this object 
460      */
461     if($this->orig_dn == "new" && !$this->acl_is_createable($this->base)){
462       $message[] = msgPool::permCreate();
463     }elseif($this->orig_dn != "new" && $this->base != $this->orig_base && !$this->acl_is_moveable($this->base)){
464       $message[] = msgPool::permMove();
465     }
467     return $message;
468   }
471   /* Save to LDAP */
472   function save()
473   {
474     /* Get application script without header part, to check if we must save the script itself */
475     $script = preg_replace('/.*### END HEADER ###/s', '', $this->gotoLogonScript);
477     plugin::save();
478     $this->attrs["gosaApplicationIcon"]= $this->gosaApplicationIcon;
480     /* Write back to ldap */
481     $ldap= $this->config->get_ldap_link();
482     $ldap->cat($this->dn, array('dn'));
484     $a= $ldap->fetch();
485     if (count($a)){
487       /* Remove gotoLogonScript if it is empty */
488       if(empty($script))    {
489         $this->attrs['gotoLogonScript'] = array();
490       }
492       $ldap->cd($this->dn);
493       $this->cleanup();
494       $ldap->modify ($this->attrs); 
495       $this->handle_post_events("modify");
496       new log("modify","application/".get_class($this),$this->dn,array_keys($this->attrs),$ldap->get_error());
497     } else {
498       
499       /* Remove gotoLogonScript if it is empty */
500       if(empty($script))    {
501         unset($this->attrs['gotoLogonScript']);
502       }
504       $ldap->cd($this->config->current['BASE']);
505       $ldap->create_missing_trees(preg_replace('/^[^,]+,/', '', $this->dn));
506       $ldap->cd($this->dn);
507       $ldap->add($this->attrs);
508       new log("create","application/".get_class($this),$this->dn,array_keys($this->attrs),$ldap->get_error());
509       $this->handle_post_events("add");
510     }
511     if (!$ldap->success()){
512       msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $this->dn, 0, get_class()), ERROR_DIALOG);
513     }
514   }
516   
517   function is_release()
518   {
519     if(isset($this->parent->parent)){
520       return($this->parent->parent->IsReleaseManagementActivated());
521     }else{
522       /* Check if we should enable the release selection */
523       $tmp = $this->config->search("faiManagement", "CLASS",array('menu','tabs'));
524       if(!empty($tmp)){
525         return(true);
526       }
527     }
528     return(FALSE);
529   }
532   function set_picture($filename)
533   {
534     if (!is_file($filename)){
535       $filename= "./plugins/goto/images/default_icon.png";
536       $this->gosaApplicationIcon= "*removed*";
537     }
539     if (file_exists($filename)){
540       $fd = fopen ($filename, "rb");
541       $this->iconData= fread ($fd, filesize ($filename));
542       session::set('binary',$this->iconData);
543       session::set('binarytype',"image/jpeg");
544       $this->gosaApplicationIcon= $this->iconData;
546       fclose ($fd);
547     }
548   }
550   function getCopyDialog()
551   {
552     $vars = array("cn");
554     $str ="<h2>"._("Application settings")."</h2>
555       <table>
556       <tr>
557       <td>".
558       _("Application name"). 
559       "</td>  
560       <td>
561       <input id='gosaApplicationName' name='cn' size='35' maxlength='60' 
562       value='".$this->cn."' 
563       title='"._("Application name to be displayed (i.e. below icons)")."'>                     
564       </td>
565       </tr>
566       </table>";
567     $ret = array();
568     $ret['status'] = "";
569     $ret['string'] = $str;
570     return($ret);
571   }
573   function saveCopyDialog()
574   {
575     if(isset($_POST['cn'])){
576       $this->cn = $_POST['cn'];
577     }
578   }
581   function PrepareForCopyPaste($source)
582   {
583     plugin::PrepareForCopyPaste($source);
584     $source_o = new application($this->config,$source['dn']);
585     $this->gosaApplicationIcon = $source_o->gosaApplicationIcon;     
586   }
589   /* Return plugin informations for acl handling
590       #FIXME FAIscript seams to ununsed within this class... */
591   static function plInfo()
592   {
593     return (array(
594           "plShortName"   => _("Generic"),
595           "plDescription" => _("Application generic"),
596           "plSelfModify"  => FALSE,
597           "plDepends"     => array(),
598           "plPriority"    => 0,
599           "plSection"     => array("administration"),
600           "plCategory"    => array("application" => array("description"  => _("Application"),
601                                                           "objectClass"  => "gosaApplication")),
602           "plProvidedAcls"=> array(
603             "cn"                => _("Name"),
604             "base"              => _("Base"),
605             "description"       => _("Description"),
606             "gosaApplicationExecute"  => _("Execute"),
607             "gosaApplicationName"     => _("Name"),
608             "gosaApplicationIcon"     => _("Icon"),
609             "gotoLogonScript"         => _("Script content"),
611             "execForGroupmembers" => _("Only executable for members"),              // G
612             "placeOnDesktop"      => _("Place icon on members desktop"),            // D
613             "placeOnKicker"       => _("Place entry in members launch bar"),        // L
614             "placeInStartmenu"    => _("Place entry in members startmenu"),         // M
615             "overwriteConfig"      => _("Replace user configuration on startup"))  // O
616             ));
617   }
619 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
620 ?>