Code

Updated sudo to use the generic user/group select dialogs
[gosa.git] / gosa-plugins / sudo / admin / sudo / class_sudoGeneric.inc
1 <?php
2 /*
3  * This code is part of GOsa (http://www.gosa-project.org)
4  * Copyright (C) 2003-2008 GONICUS GmbH
5  *
6  * ID: $$Id: class_sudo.inc 9975 2008-03-25 14:09:30Z hickert $$
7  *
8  * This program is free software; you can redistribute it and/or modify
9  * it under the terms of the GNU General Public License as published by
10  * the Free Software Foundation; either version 2 of the License, or
11  * (at your option) any later version.
12  *
13  * This program is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License
19  * along with this program; if not, write to the Free Software
20  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
21  */
24 /*! \brief Sudo generic class. Allow setting User/Host/Command/Runas
25            for a sudo role object.
26  */
27 class sudo extends plugin
28 {
30   protected $cn= "";
31   protected $description= "";
33   protected $sudoUser   = array("ALL");
34   protected $sudoCommand= array();
35   protected $sudoHost   = array("ALL");
36   protected $sudoRunAs  = array("ALL");
37   protected $accessTo         = array();
38   protected $trustModel       = "";
40   private $is_default = FALSE;
41   private $was_trust_account= FALSE;
43   public $objectclasses = array("top","sudoRole");
44   public $attributes    = array("cn","description","sudoUser","sudoCommand","sudoHost","sudoRunAs","accessTo","trustModel");
46   public $ignore_account = TRUE;
48   public $orig_dn;
50   protected $trustSelect;
52   /*! \brief  Returns to the base department for sudo roles.
53               This department is then used to store new roles.
54       @param  Object  GOsa configuration object.
55       @return String sudo store department
56    */
57   public static function get_sudoers_ou($config)
58   {
59     return(get_ou("sudoRDN").$config->current['BASE']);
60   }
62   /*! \brief  Initializes this sudo class, with all required attributes.
63       @param  Object $config  GOsa configuration object.
64       @param  String $db      "new" or the sudo role dn.
65       @return .
66    */
67   function sudo(&$config, $dn= NULL)
68   {
69     plugin::plugin ($config, $dn);
71     if($this->initially_was_account){
72       foreach(array("sudoUser","sudoCommand","sudoHost","sudoRunAs") as $attr){
73         $this->$attr = array();
74         if(isset($this->attrs[$attr])){
75           $tmp = array();
76           for($i = 0 ; $i < $this->attrs[$attr]['count']; $i++){
77             $tmp[] = $this->attrs[$attr][$i];
78           }
79           $this->$attr = $tmp;
80         }
81       }
83       /* Is this account a trustAccount? */
84       if (isset($this->attrs['trustModel'])){
85         $this->trustModel= $this->attrs['trustModel'][0];
86         $this->was_trust_account= TRUE;
87       } else {
88         $this->was_trust_account= FALSE;
89         $this->trustModel= "";
90       }
92       $this->accessTo = array();
93       if (isset($this->attrs['accessTo'])){
94         for ($i= 0; $i<$this->attrs['accessTo']['count']; $i++){
95           $tmp= $this->attrs['accessTo'][$i];
96           $this->accessTo[$tmp]= $tmp;
97         }
98       }
100     }
102     if(preg_match("/^defaults$/i",$this->cn)){
103       $this->is_default = TRUE;
104     }
106     /* Get global filter config */
107     if (!session::is_set("sysfilter")){
108       $ui= get_userinfo();
109       $base= get_base_from_people($ui->dn);
110       $sysfilter= array( "depselect"       => $base,
111           "regex"           => "*");
112       session::set("sysfilter", $sysfilter);
113     }
115     $this->orig_dn = $this->dn;
116   }
119   /*! \brief  Creates the sudo generic ui. 
120       @return String  The generated HTML content for this plugin. 
121    */
122   function execute()
123   {
124     /* Call parent execute */
125     plugin::execute();
127     /*********************
128        Access control list / trust mode 
129      *********************/ 
131     /* Add user workstation? */
132     if (isset($_POST["add_ws"])){
133       $this->trustSelect= new trustSelect($this->config,get_userinfo());
134       $this->dialog= TRUE;
135     }
137     // Add selected machines to trusted ones.
138     if (isset($_POST["add_ws_finish"]) &&  $this->trustSelect){
139       $trusts = $this->trustSelect->detectPostActions();
140       if(isset($trusts['targets'])){
142         $headpage = $this->trustSelect->getHeadpage();
143         foreach($trusts['targets'] as $id){
144           $attrs = $headpage->getEntry($id);
145           $this->accessTo[$attrs['cn'][0]]= $attrs['cn'][0];
146         }
147         ksort($this->accessTo);
148         $this->is_modified= TRUE;
149       }
150       $this->trustSelect= NULL;
151       $this->dialog= FALSE;
152     }
155     /* Remove user workstations? */
156     if (isset($_POST["delete_ws"]) && isset($_POST['workstation_list'])){
157       foreach($_POST['workstation_list'] as $name){
158         unset ($this->accessTo[$name]);
159       }
160       $this->is_modified= TRUE;
161     }
163     /* Add user workstation finished? */
164     if (isset($_POST["add_ws_finish"]) || isset($_POST["add_ws_cancel"])){
165       $this->trustSelect= NULL;
166       $this->dialog= FALSE;
167     }
169     /* Show ws dialog */
170     if ($this->trustSelect){
172       // Build up blocklist
173       session::set('filterBlacklist', array('cn' => array_values($this->accessTo)));
174       return($this->trustSelect->execute());
175     }
178     /*********************
179        Add users 
180      *********************/ 
181  
182     if(isset($_POST['list_sudoUser']) && !is_object($this->dialog) && $this->acl_is_writeable("sudoUser")){
183       $this->dialog =new userGroupSelect($this->config,get_userinfo());
184     }
185    
186     /* Add selected hosts  to the sudoUser list */ 
187     if(isset($_POST['userGroupSelect_save']) && $this->dialog instanceof userGroupSelect){
188       if($this->acl_is_writeable("sudoUser")){
189         foreach($this->dialog->save() as $entry){
190           if(in_array("posixGroup",$entry['objectClass'])){
191             $name = trim("%".$entry['cn'][0]);
192           }elseif(isset($entry['uid'][0])){
193             $name = trim($entry['uid'][0]);
194           }
195           if(!in_array($name,$this->sudoUser) && !in_array("!".$name,$this->sudoUser)){
196             $this->sudoUser[] = $name;
197           }
198         }   
199       }
200       unset($this->dialog);
201       $this->dialog = NULL;
202     }    
204     if(isset($_POST['userGroupSelect_cancel']) && $this->dialog instanceOf userGroupSelect){
205       unset($this->dialog);
206       $this->dialog = NULL;
207     }    
209     if($this->dialog instanceOf userGroupSelect){
210       $used = array();
211       foreach($this->sudoUser as $name){
212         $str = preg_replace("/^!/","",$name);
213         if(preg_match("/^%/", $str)){
214           $used['cn'][] = preg_replace("/^%/","",$str);
215         }else{
216           $used['uid'][] = $str;
217         }
218       }
220       // Build up blocklist
221       session::set('filterBlacklist', $used);
222       return($this->dialog->execute());
223     }
224  
227     /*********************
228        Add systems 
229      *********************/ 
230   
231     if(isset($_POST['list_sudoHost']) && !is_object($this->dialog) && $this->acl_is_writeable("sudoHost")){
232       $used = array();
233       foreach($this->sudoHost as $name){
234         $used[] = preg_replace("/^!/","",$name);
235       }
236       $this->dialog =new target_list_systems($this->config,$used);
237     }
238    
239     /* Add selected hosts  to the sudoHost list */ 
240     if(isset($_POST['SavetargetSelectDialog']) && $this->dialog instanceof target_list_systems){
241       if($this->acl_is_writeable("sudoHost")){
242         foreach($this->dialog->save() as $entry){
243           $cn = trim($entry['cn'][0]);
244           if(!in_array($cn,$this->sudoHost) && !in_array("!".$cn,$this->sudoHost)){
245             $this->sudoHost[] = $cn;
246           }
247         }   
248       }   
249       unset($this->dialog);
250       $this->dialog = NULL;
251     }    
254     /*********************
255        Dialog handling / display / close  
256      *********************/ 
257   
258     if(isset($_POST['userGroupSelect_cancel']) && is_object($this->dialog)){
259       unset($this->dialog);
260       $this->dialog = NULL;
261     }    
263     if(is_object($this->dialog)){
264       return($this->dialog->execute());
265     }
267  
268     /*********************
269        NEGATE values 
270      *********************/ 
271     foreach($_POST as $name => $value){
272       if(preg_match("/^neg_/",$name)){
273         $attr = preg_replace("/^neg_([^_]*)_.*$/","\\1",$name);
274         $value= preg_replace("/^neg_[^_]*_([0-9]*)_.*$/","\\1",$name);
275  
276         if($this->acl_is_writeable($attr)){
277           $attrs = $this->$attr;
278           if(isset( $attrs[$value])){
279             $v =  $attrs[$value];
280             if(preg_match("/^!/",$v)){
281               $attrs[$value] = preg_replace("/^!/","",$v);
282             }else{
283               $attrs[$value] = "!".$v;
284             }
285             $this->$attr = $attrs;  
286           }
287         }
288         break; // Do it once, image inputs will be posted twice
289       }
290     }
291   
292     /*********************
293        Delete values 
294      *********************/ 
295     foreach($_POST as $name => $value){
296       if(preg_match("/^del_/",$name)){
297         $attr = preg_replace("/^del_([^_]*)_.*$/","\\1",$name);
298         $value= preg_replace("/^del_[^_]*_([0-9]*)_.*$/","\\1",$name);
299         if($this->acl_is_writeable($attr)){
300           $attrs = $this->$attr;
301           if(isset( $attrs[$value])){
302             unset($attrs[$value]);
303             $this->$attr = $attrs;  
304           }
305         }
306         break; // Do it once, image inputs will be posted twice
307       }
308     }
311     /*********************
312        ADD values 
313      *********************/
315     /* User / Host / Runas */ 
316     foreach(array("sudoUser","sudoHost","sudoRunAs") as $attr){
317       if($this->acl_is_writeable($attr) && 
318           isset($_POST["add_".$attr]) && 
319           isset($_POST['new_'.$attr]) && 
320           !empty($_POST['new_'.$attr])){
321         if(preg_match("/^[a-z\.0-9]*$/i",$_POST['new_'.$attr])){
322           $attrs = $this->$attr;
323           $attrs[] =  trim($_POST['new_'.$attr]); 
324           $this->$attr = $attrs;
325         }else{
326           msg_dialog::display(_("Error"),msgPool::invalid($attr,$_POST['new_'.$attr],"/[a-z0-9]/"));
327         }
328       }
329     }
331     /* Command */
332     foreach(array("sudoCommand") as $attr){
333       if($this->acl_is_writeable($attr) && isset($_POST["add_".$attr]) && isset($_POST['new_'.$attr])){
334         $attrs = $this->$attr;
335         $attrs[] =  trim($_POST['new_'.$attr]); 
336         $this->$attr = $attrs;
337       }
338     }
340     
341     /*********************
342        SMARTY assignments 
343      *********************/
345     $smarty = get_smarty();
346     $smarty->assign("is_default",$this->is_default);
347     foreach($this->attributes as $attr){
348       if(is_string($this->$attr)){
349         $smarty->assign($attr,htmlentities($this->$attr));
350       }else{
351         $smarty->assign($attr,$this->$attr);
352       }
353       $smarty->assign($attr."ACL",$this->getacl($attr));
354     }
356     /* Work on trust modes */
357     $smarty->assign("trusthide", " disabled ");
358     if ($this->trustModel == "fullaccess"){
359       $trustmode= 1;
360     } elseif ($this->trustModel == "byhost"){
361       $trustmode= 2;
362       $smarty->assign("trusthide", "");
363     } else {
364       $trustmode= 0;
365     }
366     $smarty->assign("trustmode", $trustmode);
367     $smarty->assign("trustmodes", array( 
368           0 => _("disabled"), 
369           1 => _("full access"),
370           2 => _("allow access to these hosts")));
372     if((count($this->accessTo))==0){
373       $smarty->assign("emptyArrAccess",true);
374     }else{
375       $smarty->assign("emptyArrAccess",false);
376     }
377     $smarty->assign("workstations", $this->accessTo);
378     
379     /* Create lists 
380      */
381     $divlist_sudoUser = new divSelectBox("divlist_sudoUser");
382     $divlist_sudoUser->SetHeight("90");
383     $divlist_sudoHost = new divSelectBox("divlist_sudoHost");
384     $divlist_sudoHost->Setheight("90");
385     $divlist_sudoRunAs = new divSelectBox("divlist_sudoRunAs");
386     $divlist_sudoRunAs->Setheight("90");
387     $divlist_sudoCommand = new divSelectBox("divlist_sudoCommand");
388     $divlist_sudoCommand->Setheight("90");
390     /* Fill divlists
391      */
392     $neg_img= "<img src='plugins/sudo/images/negate.png' alt='!' class='center'>"; 
393     $option = "<input type='image' src='plugins/sudo/images/negate.png'     name='neg_%ATTR%_%KEY%' class='center'>"; 
394     $option.= "<input type='image' src='images/lists/trash.png'  name='del_%ATTR%_%KEY%' class='center'>"; 
395     foreach(array("sudoCommand","sudoHost","sudoRunAs") as $attr){
396       if($this->acl_is_readable($attr)){
397         foreach($this->$attr as $key => $entry){
398           $neg = "";
399           if(preg_match("/^!/",$entry)){
400             $neg = $neg_img;
401           }
402           $entry = preg_replace("/^!/","",$entry);
403           $list_name = "divlist_".$attr;
404           $$list_name->AddEntry(
405               array(
406                 array("string" => $neg,"attach" => "style='width:18px;'"),
407                 array("string" => $entry),
408                 array("string" => preg_replace(array("/%KEY%/","/%ATTR%/"),array($key,$attr),$option),
409                   "attach" => "style='width:40px; border-right: 0px;'")));
410         }
411       }
412     }
414     foreach(array("sudoUser") as $attr){
415       $img1 = "<img src='plugins/users/images/select_user.png'   alt='"._("User")."' class='center'>";
416       $img2 = "<img src='plugins/groups/images/groups.png' alt='"._("Group")."' class='center'>";
417       if($this->acl_is_readable($attr)){
418         foreach($this->$attr as $key => $entry){
419           $neg = "";
420           if(preg_match("/^!/",$entry)){
421             $neg = $neg_img;
422           }
423           $entry = preg_replace("/^!/","",$entry);
425           $img = $img1;
426           if(preg_match("/^%/",$entry)){
427             $img = $img2;
428           }
429           $entry = preg_replace("/^%/","",$entry);
430   
431           $list_name = "divlist_".$attr;
432           $$list_name->AddEntry(
433               array(
434                 array("string" => $neg,"attach" => "style='width:18px;'"),
435                 array("string" => $img,"attach" => "style='width:18px;'"),
436                 array("string" => $entry),
437                 array("string" => preg_replace(array("/%KEY%/","/%ATTR%/"),array($key,$attr),$option),
438                   "attach" => "style='width:40px; border-right: 0px;'")));
439         }
440       }
441     }
446     /* Tell smarty about our divlists 
447      */
448     $smarty->assign("divlist_sudoUser",   $divlist_sudoUser->DrawList());
449     $smarty->assign("divlist_sudoHost",   $divlist_sudoHost->DrawList());
450     $smarty->assign("divlist_sudoRunAs",  $divlist_sudoRunAs->DrawList());
451     $smarty->assign("divlist_sudoCommand",$divlist_sudoCommand->DrawList());
452     return($smarty->fetch(get_template_path('generic.tpl', TRUE)));
453   }
456   /*! \brief  Remove this sudo role from the ldap server 
457    */
458   function remove_from_parent()
459   {
460     plugin::remove_from_parent();
462     $ldap = $this->config->get_ldap_link();
463     $ldap->cd($this->dn);
464     $ldap->rmdir($this->dn);
466     /* Send signal to the world that we've done */
467     $this->handle_post_events("remove");
468   }
471   /*! \brief  Save all relevant HTML posts. 
472    */
473   function save_object()
474   {
475     plugin::save_object();
476     
477     if($this->is_default){
478       $this->cn = "defaults";
479     }  
481     /* Trust mode - special handling */
482     if($this->acl_is_writeable("trustModel")){
483       if (isset($_POST['trustmode'])){
484         $saved= $this->trustModel;
485         if ($_POST['trustmode'] == "1"){
486           $this->trustModel= "fullaccess";
487         } elseif ($_POST['trustmode'] == "2"){
488           $this->trustModel= "byhost";
489         } else {
490           $this->trustModel= "";
491         }
492         if ($this->trustModel != $saved){
493           $this->is_modified= TRUE;
494         }
495       }
496     }
497   }
500   /*! \brief  Save changes into the ldap database.
501    */
502   function save()
503   {
504     plugin::save();
505    /* Trust accounts */
506     $objectclasses= array();
507     foreach ($this->attrs['objectClass'] as $key => $class){
508       if (preg_match('/trustAccount/i', $class)){
509         continue;
510       }
511       $objectclasses[]= $this->attrs['objectClass'][$key];
512     }
514     $this->attrs['objectClass']= $objectclasses;
515     if ($this->trustModel != ""){
516       $this->attrs['objectClass'][]= "trustAccount";
517       $this->attrs['trustModel']= $this->trustModel;
518       $this->attrs['accessTo']= array();
519       if ($this->trustModel == "byhost"){
520         foreach ($this->accessTo as $host){
521           $this->attrs['accessTo'][]= $host;
522         }
523       }
524     } else {
525       if ($this->was_trust_account){
526         $this->attrs['accessTo']= array();
527         $this->attrs['trustModel']= array();
528       }
529     }
532     /* Ensure a correct array index 
533      */ 
534     $this->attrs['sudoHost']    = array_values($this->attrs['sudoHost']);
535     $this->attrs['sudoRunAs']   = array_values($this->attrs['sudoRunAs']);
536     $this->attrs['sudoUser']    = array_values($this->attrs['sudoUser']);
537     $this->attrs['sudoCommand'] = array_values($this->attrs['sudoCommand']);
539     $this->cleanup();
541     $ldap = $this->config->get_ldap_link();
542     $ldap->cd($this->config->current['BASE']);
544     if($this->is_new){
545       $ldap->create_missing_trees(preg_replace('/^[^,]+,/', '', $this->dn));
546       $ldap->cd($this->dn);
547       $ldap->add($this->attrs);
549       /* Send signal to the world that we've done */
550       $this->handle_post_events("create");
551     }else{
552       $ldap->cd($this->dn);
553       $ldap->modify($this->attrs);;
555       /* Send signal to the world that we've done */
556       $this->handle_post_events("modify");
557     }
559     if (!$ldap->success()){
560       msg_dialog::display(_("LDAP error"), msgPool::ldaperror($ldap->get_error(), $this->dn, LDAP_DEL, get_class()));
561     }
562   }
565   /*! \brief  Check the given input.
566       @return Array   All error messages in an array();
567    */
568   function check()
569   {
570     $message = plugin::check();
572     /* Is a name given? */
573     if($this->cn == ""){
574       $message[] = msgPool::required(_("Name"));
575     }
577     /* Check if name is reserved */
578     if(!$this->is_default && preg_match("/^defaults$/i",$this->cn)){
579       $message[] = msgPool::reserved(_("Name"));
580     }
582     /* Check name */
583     if(!preg_match("/^[0-9a-z\@]*$/i",$this->cn)){
584       $message[] = msgPool::invalid(_("Name"),$this->cn,"/[0-9a-z\@]/i");
585     }
587     /* Check if this entry will cause duplicated ldap entries */
588     $ldap = $this->config->get_ldap_link();
589     $ldap->cd($this->get_sudoers_ou($this->config));
590     $ldap->search("(&(objectClass=sudoRole)(cn=".$this->cn."))");
591     while($attrs = $ldap->fetch()){
592       if($attrs['dn'] != $this->dn){
593         $message[] = msgPool::duplicated(_("Name"));
594       }
595     }
597     /* Check if we are allowed to create or move this object
598      */
599     if($this->orig_dn == "new" && !$this->acl_is_createable($this->get_sudoers_ou($this->config))){
600       $message[] = msgPool::permCreate();
601     }
603     return ($message);
604   }
607   /*! \brief Force this entry to be handled and saved as 'default'
608       @param  BOOL  TRUE -force defaults   FALSE -normal
609    */
610   public function set_default($state)
611   {
612     $this->is_default = TRUE;
613     $this->cn = "defaults";
614   }
617   /*! \brief  Add ACL object
618       @return Returns the ACL object.
619    */
620   static function plInfo()
621   {
622     return (array(  
623           "plShortName" => _("Sudo"),
624           "plDescription" => _("Sudo role"),
625           "plSelfModify"  => FALSE,
626           "plDepends"     => array(),
627           "plPriority"    => 0,
628           "plSection"     => array("administration"),
629           "plCategory"    => array("sudo" => array("objectClass" => "sudoRole", "description" => _("Sudo role"))),
631           "plProvidedAcls"    => array(
632             "cn"                => _("Name"),
633             "description"       => _("Description"),
634             "sudoUser"          => _("Users"),
635             "sudoHost"          => _("Host"),
636             "sudoCommand"       => _("Command"),
637             "sudoRunAs"         => _("Run as user"),
638             "trustModel"        => _("Access control list"))
639         ));
640   }
643   /*! \brief  This function will be called if an object gets copied.
644               This function adapts attributes from the source object.
645       @param  Array The source object.
646    */
647   function PrepareForCopyPaste($source)
648   {
649     plugin::PrepareForCopyPaste($source);
650     foreach(array("sudoUser","sudoCommand","sudoHost","sudoRunAs") as $attr){
651       $this->$attr = array();
652       if(isset($source[$attr])){
653         $tmp = array();
654         for($i = 0 ; $i < $source[$attr]['count']; $i++){
655           $tmp[] = $source[$attr][$i];
656         }
657         $this->$attr = $tmp;
658       }
659     }
661     /* Is this account a trustAccount? */
662     if (isset($source['trustModel'])){
663       $this->trustModel= $source['trustModel'][0];
664       $this->was_trust_account= TRUE;
665     } else {
666       $this->was_trust_account= FALSE;
667       $this->trustModel= "";
668     }
670     $this->accessTo = array();
671     if (isset($source['accessTo'])){
672       for ($i= 0; $i<$source['accessTo']['count']; $i++){
673         $tmp= $source['accessTo'][$i];
674         $this->accessTo[$tmp]= $tmp;
675       }
676     }
677   }
680   /*! \brief  Used for copy & paste.
681               Returns a HTML input mask, which allows to change the cn of this entry.
682       @param  Array   Array containing current status && a HTML template.              
683    */
684   function getCopyDialog()
685   {
686     $vars = array("cn");
687     $smarty = get_smarty();
688     $smarty->assign("cn", htmlentities($this->cn));
689     $str = $smarty->fetch(get_template_path("paste_generic.tpl",TRUE));
690     $ret = array();
691     $ret['string'] = $str;
692     $ret['status'] = "";
693     return($ret);
694   }
697   public function get_cn()
698   {
699     return($this->cn);
700   }
703   /*! \brief  Used for copy & paste.
704               Some entries must be renamed to avaoid duplicate entries.
705    */
706   function saveCopyDialog()
707   {
708     if(isset($_POST['cn'])){
709       $this->cn = get_post('cn');
710     }
711   }
713 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
714 ?>