Code

Updated ACL check. - Very strange, see diff.
[gosa.git] / gosa-core / include / class_userinfo.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$$
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  */
23 class userinfo
24 {
25   var $dn;
26   var $ip;
27   var $username;
28   var $cn;
29   var $uid;
30   var $gidNumber= -1;
31   var $language= "";
32   var $config;
33   var $gosaUnitTag= "";
34   var $subtreeACL= array();
35   var $ACL= array();
36   var $ocMapping= array();
37   var $groups= array();
38   var $result_cache =array();
40   /* get acl's an put them into the userinfo object
41      attr subtreeACL (userdn:components, userdn:component1#sub1#sub2,component2,...) */
42   function userinfo(&$config, $userdn){
43     $this->config= &$config;
44     $ldap= $this->config->get_ldap_link();
45     $ldap->cat($userdn,array('sn', 'givenName', 'uid', 'gidNumber', 'preferredLanguage', 'gosaUnitTag'));
46     $attrs= $ldap->fetch();
48     if (isset($attrs['givenName'][0]) && isset($attrs['sn'][0])){
49       $this->cn= $attrs['givenName'][0]." ".$attrs['sn'][0];
50     } else {
51       $this->cn= $attrs['uid'][0];
52     }
53     if (isset($attrs['gidNumber'][0])){
54       $this->gidNumber= $attrs['gidNumber'][0];
55     }
57     /* Assign user language */
58     if (isset($attrs['preferredLanguage'][0])){
59       $this->language= $attrs['preferredLanguage'][0];
60     }
62     if (isset($attrs['gosaUnitTag'][0])){
63       $this->gosaUnitTag= $attrs['gosaUnitTag'][0];
64     }
66     $this->dn= $userdn;
67     $this->uid= $attrs['uid'][0];
68     $this->ip= $_SERVER['REMOTE_ADDR'];
70     /* Initialize ACL_CACHE */
71     session::set('ACL_CACHE',array());
72     $this->reset_acl_cache();
73   }
76   public function reset_acl_cache()
77   {
78     /* Initialize ACL_CACHE */
79     session::set('ACL_CACHE',array());
80   }
82   function loadACL()
83   {
84     $this->ACL= array();    
85     $this->groups= array();    
86     $this->result_cache =array();
87     $this->reset_acl_cache();
88     $ldap= $this->config->get_ldap_link();
89     $ldap->cd($this->config->current['BASE']);
91     /* Get member groups... */
92     $ldap->search("(&(objectClass=posixGroup)(memberUid=".$this->uid."))", array('dn'));
93     while ($attrs= $ldap->fetch()){
94       $this->groups[$attrs['dn']]= $attrs['dn'];
95     }
97     /* Crawl through ACLs and move relevant to the tree */
98     $ldap->search("(objectClass=gosaACL)", array('dn', 'gosaAclEntry'));
99     $aclp= array();
100     $aclc= array();
101     while ($attrs= $ldap->fetch()){
103       /* Insert links in ACL array */
104       $aclp[$attrs['dn']]= substr_count($attrs['dn'], ',');
105       $aclc[$attrs['dn']]= array();
106       $ol= array();
107       for($i= 0; $i<$attrs['gosaAclEntry']['count']; $i++){
108         $ol= array_merge($ol, @acl::explodeAcl($attrs['gosaAclEntry'][$i]));
109       }
110       $aclc[$attrs['dn']]= $ol;
111     }
113     /* Resolve roles here. 
114      */
115     foreach($aclc as $dn => $data){
116       foreach($data as $prio => $aclc_value)  {
117         if($aclc_value['type'] == "role"){
119           unset($aclc[$dn][$prio]);
121           $ldap->cat($aclc_value['acl'],array("gosaAclTemplate"));
122           $attrs = $ldap->fetch();
124           if(isset($attrs['gosaAclTemplate'])){
125             for($i= 0; $i<$attrs['gosaAclTemplate']['count']; $i++){
126               $tmp = @acl::explodeAcl($attrs['gosaAclTemplate'][$i]);  
128               foreach($tmp as $new_acl){
129                 $new_acl['members'] = $aclc_value['members'];
130                 $aclc[$dn][] =$new_acl;
131               }
132             }      
133           }
134         }
135       }
136     }
138     /* ACL's read, sort for tree depth */
139     asort($aclp);
141     /* Sort in tree order */
142     foreach ($aclp as $dn => $acl){
143       /* Check if we need to keep this ACL */
144       foreach($aclc[$dn] as $idx => $type){
145         $interresting= FALSE;
146         
147         /* No members? This is good for all users... */
148         if (!count($type['members'])){
149           $interresting= TRUE;
150         } else {
152           /* Inspect members... */
153           foreach ($type['members'] as $grp => $grpdsc){
154             /* Some group inside the members that is relevant for us? */
155             if (in_array_ics(preg_replace('/^G:/', '', $grp), $this->groups)){
156               $interresting= TRUE;
157             }
159             /* User inside the members? */
160             if (preg_replace('/^U:/', '', $grp) == $this->dn){
161               $interresting= TRUE;
162             }
163           }
164         }
166         if ($interresting){
167           if (!isset($this->ACL[$dn])){
168             $this->ACL[$dn]= array();
169           }
170           $this->ACL[$dn][$idx]= $type;
171         }
172       }
174     }
176   }
179   function get_category_permissions($dn, $category)
180   {
181     /* If we are forced to skip ACLs checks for the current user 
182         then return all permissions.
183      */
184     if($this->ignore_acl_for_current_user()){
185       return("rwcdm");
186     }
188     /* Get list of objectClasses and get the permissions for it */
189     $acl= "";
190     if (isset($this->ocMapping[$category])){
191       foreach($this->ocMapping[$category] as $oc){
192         $acl.= $this->get_permissions($dn, $category."/".$oc);
193       }
194     }else{
195       trigger_error("ACL request for an invalid category (".$category.").");
196     }
198     return ($acl);
199   }
202   function get_permissions($dn, $object, $attribute= "", $skip_write= FALSE)
203   {
204     /* If we are forced to skip ACLs checks for the current user 
205         then return all permissions.
206      */
207     if($this->ignore_acl_for_current_user()){
208       return("rwcdm");
209     }
211     /* Push cache answer? */
212     $ACL_CACHE = &session::get('ACL_CACHE');
213     if (isset($ACL_CACHE["$dn+$object+$attribute"])){
215       /* Remove write if needed */
216       if ($skip_write){
217         $ret = preg_replace('/w/', '', $ACL_CACHE["$dn+$object+$attribute"]);
218       }else{
219         $ret = $ACL_CACHE["$dn+$object+$attribute"];
220       } 
221       return($ret);
222     }
224     /* Get ldap object, for later filter checks 
225      */
226     $ldap = $this->config->get_ldap_link();
228     $acl= array("r" => "", "w" => "", "c" => "", "d" => "", "m" => "", "a" => "");
230     /* Build dn array */
231     $path= split(',', $dn);
232     $path= array_reverse($path);
234     /* Walk along the path to evaluate the acl */
235     $cpath= "";
236     foreach ($path as $element){
238       /* Clean potential ACLs for each level */
239       $acl= $this->cleanACL($acl);
241       if ($cpath == ""){
242         $cpath= $element;
243       } else {
244         $cpath= $element.','.$cpath;
245       }
246       if (isset($this->ACL[$cpath])){
248         /* Inspect this ACL, place the result into ACL */
249         foreach ($this->ACL[$cpath] as $subacl){
251           /* Reset? Just clean the ACL and turn over to the next one... */
252           if ($subacl['type'] == 'reset'){
253             $acl= $this->cleanACL($acl, TRUE);
254             continue;
255           }
257           if($subacl['type'] == "role") {
258             echo "role skipped";
259             continue;
260           }
262          /* With user filter */
263          if (isset($subacl['filter']) && !empty($subacl['filter'])){
264            $sdn = preg_replace("/^[^,]*+,/","",$dn);
265            $ldap->cd($sdn);
266            $ldap->ls($subacl['filter'],$sdn);
267            if(!$ldap->count()){
268              continue;
269            }else{
270              $found = FALSE; 
271              while($attrs = $ldap->fetch()){
272                if($attrs['dn'] == $dn){
273                  $found = TRUE;
274                  break;
275                }
276              }
277              if(!$found){
278                continue;
279              }
280            }
281          }
283           /* Per attribute ACL? */
284           if (isset($subacl['acl'][$object][$attribute])){
285             $acl= $this->mergeACL($acl, $subacl['type'], $subacl['acl'][$object][$attribute]);
286             continue;
287           }
289           /* Per object ACL? */
290           if (isset($subacl['acl'][$object][0])){
291             $acl= $this->mergeACL($acl, $subacl['type'], $subacl['acl'][$object][0]);
292             continue;
293           }
295           /* Global ACL? */
296           if (isset($subacl['acl']['all'][0])){
297             $acl= $this->mergeACL($acl, $subacl['type'], $subacl['acl']['all'][0]);
298             continue;
299           }
301           /* If attribute is "", we want to know, if we've *any* permissions here... */
302           if ($attribute == "" && isset($subacl['acl'][$object])){
303             foreach($subacl['acl'][$object] as $attr => $dummy){
304               $acl= $this->mergeACL($acl, $subacl['type'], $subacl['acl'][$object][$attr]);
305             }
306             continue;
307           }
309         }
310       }
311     }
313     /* Assemble string */
314     $ret= "";
315     foreach ($acl as $key => $value){
316       /*  Why doesn't 
317             if($value !=""){ 
318           work here??? It skips 0 too.
319        */
320       if (!preg_match("/^$/",$value)){ 
321         $ret.= $key;
322       }
323     }
325     $ACL_CACHE["$dn+$object+$attribute"]= $ret;
327     /* Remove write if needed */
328     if ($skip_write){
329       $ret= preg_replace('/w/', '', $ret);
330     }
331     return ($ret);
332   }
335   /* Extract all departments that are accessible (direct or 'on the way' to an
336      accessible department) */
337   function get_module_departments($module)
338   {
339     
340     /* If we are forced to skip ACLs checks for the current user 
341         then return all departments as valid.
342      */
343     if($this->ignore_acl_for_current_user()){
344       return(array_keys($this->config->idepartments));
345     }
347     /* Use cached results if possilbe */
348     $ACL_CACHE = session::get('ACL_CACHE');
349     if(isset($ACL_CACHE['MODULE_DEPARTMENTS'][serialize($module)])){
350       return($ACL_CACHE['MODULE_DEPARTMENTS'][serialize($module)]);
351     }
353     global $plist;
355     $objects= array();
356     $deps= array();
358     /* Extract all relevant objects for this module from plist */
359     foreach ($plist->info as $object => $info){
360       if (!isset($info['plCategory'])){
361         continue;
362       }
363       foreach ($info['plCategory'] as $idx => $data){
364         if (preg_match('/^[0-9]+$/', $idx)){
365           if ($data == $module){
366             $objects[$object]= $object;
367           }
368         } else {
369           if ($idx == $module){
370             $objects[$object]= $object;
371           }
372         }
373       }
374     }
376     /* For all gosaDepartments */
377     foreach ($this->config->departments as $dn){
378       $acl= array("r" => "", "w" => "", "c" => "", "d" => "", "m" => "", "a" => "");
380       /* Build dn array */
381       $path= split(',', $dn);
382       $path= array_reverse($path);
384       /* Walk along the path to evaluate the acl */
385       $cpath= "";
386       foreach ($path as $element){
388         /* Clean potential ACLs for each level */
389         $acl= $this->cleanACL($acl);
391         if ($cpath == ""){
392           $cpath= $element;
393         } else {
394           $cpath= $element.','.$cpath;
395         }
396         if (isset($this->ACL[$cpath])){
398           /* Inspect this ACL, place the result into ACL */
399           foreach ($this->ACL[$cpath] as $subacl){
401             /* Reset? Just clean the ACL and turn over to the next one... */
402             if ($subacl['type'] == 'reset'){
403               $acl= $this->cleanACL($acl, TRUE);
404               continue;
405             }
406     
407             if($subacl['type'] == 'role'){
408               echo "role skipped";
409               continue;
410             }
412             /* Per object ACL? */
413             foreach ($objects as $object){
414               if (isset($subacl['acl']["$module/$object"])){
415                 foreach($subacl['acl']["$module/$object"] as $attribute => $dcl){
416                   $acl= $this->mergeACL($acl, $subacl['type'], $subacl['acl']["$module/$object"][$attribute]);
417                 }
418               }
419             }
421             /* Global ACL? */
422             if (isset($subacl['acl']["$module/all"][0])){
423               $acl= $this->mergeACL($acl, $subacl['type'], $subacl['acl']["$module/all"][0]);
424               continue;
425             }
427             /* Global ACL? */
428             if (isset($subacl['acl']["all"][0])){
429               $acl= $this->mergeACL($acl, $subacl['type'], $subacl['acl']["all"][0]);
430               continue;
431             }
432           }
433         }
434       }
436       /* Add department, if we have (some) permissions for the required module */
437       foreach ($acl as $val){
438         if ($val != ""){
439           $deps[]= $dn;
440           break;
441         }
442       }
443     }
445     $ACL_CACHE = &session::get('ACL_CACHE');
446     $ACL_CACHE['MODULE_DEPARTMENTS'][serialize($module)] = $deps;
447     return ($deps);
448   }
451   function mergeACL($acl, $type, $newACL)
452   {
453     if (strpos($newACL, 'w') !== FALSE && strpos($newACL, 'r') === FALSE){
454       $newACL .= "r";
455     }
457     foreach(str_split($newACL) as $char){
459       /* Ignore invalid characters */
460       if (!preg_match('/[rwcdm]/', $char)){
461         continue;
462       }
464       /* Skip permanent and subtree entries */
465       if (preg_match('/[sp]/', $acl[$char])){
466         continue;
467       }
469       switch ($type){
470         case 'psub':
471           $acl[$char]= 'p';
472           break;
474         case 'sub':
475           $acl[$char]= 's';
476           break;
478         case 'one':
479           $acl[$char]= 1;
480           break;
482         case 'base':
483           if ($acl[$char] != 1){
484             $acl[$char]= 0;
485           }
486           break;
487       }
488     }
490     return ($acl);
491   }
494   function cleanACL($acl, $reset= FALSE)
495   {
496     foreach ($acl as &$value){
498       /* Reset removes everything but 'p' */
499       if ($reset && $value != 'p'){
500         $value= "";
501         continue;
502       }
504       /* Decrease tree level */
505       if (is_int($value)){
506         if ($value){
507           $value--;
508         } else {
509           $value= "";
510         }
511       }
512     }
514     return ($acl);
515   }
518   /* #FIXME This could be logical wrong or could be optimized in the future
519      Return combined acls for a given category. 
520      All acls will be combined like boolean AND 
521       As example ('rwcdm' + 'rcd' + 'wrm'= 'r') 
522     
523      Results will be cached in $this->result_cache.
524       $this->result_cache will be resetted if load_acls is called.
525   */
526   function has_complete_category_acls($dn,$category)
527   {
528     $acl    = "rwcdm";
529     $types  = "rwcdm";
531     if(!is_string($category)){
532       trigger_error("category must be string");   
533       $acl = "";
534     }else{
535       if(!isset($this->result_cache['has_complete_category_acls'][$dn][$category]))   {
536         if (isset($this->ocMapping[$category])){
537           foreach($this->ocMapping[$category] as $oc){
539             /* Skip objectClass '0' (e.g. users/0) get_permissions will ever return '' ??  */
540             if($oc == "0") continue;
541             $tmp =  $this->get_permissions($dn, $category."/".$oc);
542             for($i = 0 ; $i < strlen($types); $i++) {
543               if(!preg_match("/".$types[$i]."/",$tmp)){ 
544                 $acl = preg_replace("/".$types[$i]."/","",$acl);
545               }
546             }
547           }
548         }else{
549           trigger_error("Invalid type of category ".$category);
550           $acl = "";
551         }
552         $this->result_cache['has_complete_category_acls'][$dn][$category] = $acl;
553       }else{
554         $acl = $this->result_cache['has_complete_category_acls'][$dn][$category];
555       }
556     }
557     return($acl);
558   }
560  
561   /*! \brief  Returns TRUE if the current user is configured in IGNORE_ACL=".." in your gosa.conf 
562       @param  Return Boolean TRUE if we have to skip ACL checks else FALSE.
563    */ 
564   function ignore_acl_for_current_user()
565   {
566     return(isset($this->config->current['IGNORE_ACL']) && $this->config->current['IGNORE_ACL'] == $this->dn);
567   }
571 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
572 ?>