Code

Created trunk inside of 2.6-lhm
[gosa.git] / trunk / 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();
39   var $ignoreACl = FALSE;
40   var $ACLperPath = array();
41   var $ACLperPath_usesFilter = array();
43   /* get acl's an put them into the userinfo object
44      attr subtreeACL (userdn:components, userdn:component1#sub1#sub2,component2,...) */
45   function userinfo(&$config, $userdn){
46     $this->config= &$config;
47     $ldap= $this->config->get_ldap_link();
48     $ldap->cat($userdn,array('sn', 'givenName', 'uid', 'gidNumber', 'preferredLanguage', 'gosaUnitTag'));
49     $attrs= $ldap->fetch();
51     if (isset($attrs['givenName'][0]) && isset($attrs['sn'][0])){
52       $this->cn= $attrs['givenName'][0]." ".$attrs['sn'][0];
53     } else {
54       $this->cn= $attrs['uid'][0];
55     }
56     if (isset($attrs['gidNumber'][0])){
57       $this->gidNumber= $attrs['gidNumber'][0];
58     }
60     /* Assign user language */
61     if (isset($attrs['preferredLanguage'][0])){
62       $this->language= $attrs['preferredLanguage'][0];
63     }
65     if (isset($attrs['gosaUnitTag'][0])){
66       $this->gosaUnitTag= $attrs['gosaUnitTag'][0];
67     }
69     $this->dn= $userdn;
70     $this->uid= $attrs['uid'][0];
71     $this->ip= $_SERVER['REMOTE_ADDR'];
73     $this->ignoreACL = ($this->config->get_cfg_value("ignoreAcl") == $this->dn);
75     /* Initialize ACL_CACHE */
76     $this->reset_acl_cache();
77   }
80   public function reset_acl_cache()
81   {
82     /* Initialize ACL_CACHE */
83     session::global_set('ACL_CACHE',array());
84   }
86   function loadACL()
87   {
88     $this->ACL= array();    
89     $this->groups= array();    
90     $this->result_cache =array();
91     $this->reset_acl_cache();
92     $ldap= $this->config->get_ldap_link();
93     $ldap->cd($this->config->current['BASE']);
95     /* Get member groups... */
96     $ldap->search("(&(objectClass=posixGroup)(memberUid=".$this->uid."))", array('dn'));
97     while ($attrs= $ldap->fetch()){
98       $this->groups[$attrs['dn']]= $attrs['dn'];
99     }
101     /* Crawl through ACLs and move relevant to the tree */
102     $ldap->search("(objectClass=gosaACL)", array('dn', 'gosaAclEntry'));
103     $aclp= array();
104     $aclc= array();
105     while ($attrs= $ldap->fetch()){
107       /* Insert links in ACL array */
108       $aclp[$attrs['dn']]= substr_count($attrs['dn'], ',');
109       $aclc[$attrs['dn']]= array();
110       $ol= array();
111       for($i= 0; $i<$attrs['gosaAclEntry']['count']; $i++){
112         $ol= array_merge($ol, @acl::explodeAcl($attrs['gosaAclEntry'][$i]));
113       }
114       $aclc[$attrs['dn']]= $ol;
115     }
117     /* Resolve roles here. 
118      */
119     foreach($aclc as $dn => $data){
120       foreach($data as $prio => $aclc_value)  {
121         if($aclc_value['type'] == "role"){
123           unset($aclc[$dn][$prio]);
125           $ldap->cat($aclc_value['acl'],array("gosaAclTemplate"));
126           $attrs = $ldap->fetch();
128           if(isset($attrs['gosaAclTemplate'])){
129             for($i= 0; $i<$attrs['gosaAclTemplate']['count']; $i++){
130               $tmp = @acl::explodeAcl($attrs['gosaAclTemplate'][$i]);  
132               foreach($tmp as $new_acl){
134                 /* Keep non role attributes here! */
135                 $new_acl['filter'] = $aclc_value['filter'];
136                 $new_acl['members'] = $aclc_value['members'];
137                 $aclc[$dn][] =$new_acl;
138               }
139             }      
140           }
141         }
142       }
143     }
145     /* ACL's read, sort for tree depth */
146     asort($aclp);
148     /* Sort in tree order */
149     foreach ($aclp as $dn => $acl){
150       /* Check if we need to keep this ACL */
151       foreach($aclc[$dn] as $idx => $type){
152         $interresting= FALSE;
153         
154         /* No members? This is good for all users... */
155         if (!count($type['members'])){
156           $interresting= TRUE;
157         } else {
159           /* Inspect members... */
160           foreach ($type['members'] as $grp => $grpdsc){
162             /* Some group inside the members that is relevant for us? */
163             if (in_array_ics(@LDAP::convert(preg_replace('/^G:/', '', $grp)), $this->groups)){
164               $interresting= TRUE;
165             }
167             /* User inside the members? */
168             if (preg_replace('/^U:/', '', $grp) == $this->dn){
169               $interresting= TRUE;
170             }
171           }
172         }
174         if ($interresting){
175           if (!isset($this->ACL[$dn])){
176             $this->ACL[$dn]= array();
177           }
178           $this->ACL[$dn][$idx]= $type;
179         }
180       }
181     }
183     /* Create an array which represenet all relevant permissions settings 
184         per dn.
186       The array will look like this:
187       
188       .     ['ou=base']        ['ou=base']          = array(ACLs);
189       .     
190       .     ['ou=dep1,ou=base']['ou=dep1,ou=base']  = array(ACLs);
191       .                        ['ou=base']          = array(ACLs);
194       For object located in 'ou=dep1,ou=base' we have to both ACLs,
195        for objects in 'ou=base' we only have to apply on ACL.
196      */
197     $without_self_acl = $all_acl = array();
198     foreach($this->ACL as $dn => $acl){
199       $sdn =$dn;
200       $first= TRUE; // Run at least once 
201       while(strpos($dn,",") !== FALSE || $first){
202         $first = FALSE;
203         if(isset($this->ACL[$dn])){
204           $all_acl[$sdn][$dn] = $this->ACL[$dn];
205           $without_self_acl[$sdn][$dn] = $this->ACL[$dn]; 
206           foreach($without_self_acl[$sdn][$dn] as $acl_id => $acl_set){
207   
208             /* Remember which ACL set has speicial user filter 
209              */
210             if(isset($acl_set['filter']{1})){
211               $this->ACLperPath_usesFilter[$sdn] = TRUE;
212             }
213           
214             /* Remove all acl entries which are especially for the current user (self acl)
215              */
216             foreach($acl_set['acl'] as $object => $object_acls){
217               if(strpos($object_acls[0],"s")){
218                 unset($without_self_acl[$sdn][$dn][$acl_id]['acl'][$object]);
219               }
220             }
221           }
222         }
223         $dn = preg_replace("/^[^,]*+,/","",$dn);
224       }
225     } 
226     $this->ACLperPath =$without_self_acl;
228     /* Append Self entry */
229     $dn = $this->dn;
230     while(strpos($dn,",") && !isset($all_acl[$dn])){
231       $dn = preg_replace("/^[^,]*+,/","",$dn);
232     }
233     if(isset($all_acl[$dn])){
234       $this->ACLperPath[$this->dn] = $all_acl[$dn];
235     }
236   }
239   function get_category_permissions($dn, $category, $any_acl = FALSE)
240   {
241     return(@$this->get_permissions($dn,$category.'/0',""));
242   }
244   
245   /*! \brief Check if the given object (dn) is copyable
246       @param  String The object dn 
247       @param  String The acl  category (e.g. users) 
248       @param  String The acl  class (e.g. user) 
249       @return Boolean   TRUE if the given object is copyable else FALSE 
250   */
251   function is_copyable($dn, $object, $class)
252   {
253     return(preg_match("/r/",$this->has_complete_category_acls($dn, $object)));
254   }
257   /*! \brief Check if the given object (dn) is cutable
258       @param  String The object dn 
259       @param  String The acl  category (e.g. users) 
260       @param  String The acl  class (e.g. user) 
261       @return Boolean   TRUE if the given object is cutable else FALSE 
262   */
263   function is_cutable($dn, $object, $class)
264   {
265     $remove = preg_match("/d/",$this->get_permissions($dn,$object."/".$class));
266     $read   = preg_match("/r/",$this->has_complete_category_acls($dn, $object));
267     return($remove && $read);
268   }
271   /*! \brief  Checks if we are allowed to paste an object to the given destination ($dn)
272       @param  String The destination dn 
273       @param  String The acl  category (e.g. users) 
274       @param  String The acl  class (e.g. user) 
275       @return Boolean   TRUE if we are allowed to paste an object.
276   */
277   function is_pasteable($dn, $object)
278   {
279     return(preg_match("/w/",$this->has_complete_category_acls($dn, $object)));
280   }
283   /*! \brief  Checks if we are allowed to restore a snapshot for the given dn.
284       @param  String The destination dn 
285       @param  String The acl  category (e.g. users) 
286       @return Boolean   TRUE if we are allowed to restore a snapshot.
287   */
288   function allow_snapshot_restore($dn, $object)
289   {
290     if(!is_array($object)){
291       $object = array($object);
292     }
293     $r = $w = TRUE;
294     foreach($object as $category){
295       $w &= preg_match("/w/",$this->has_complete_category_acls($dn, $category));
296       $r &= preg_match("/r/",$this->has_complete_category_acls($dn, $category));
297     }
298     return($r && $w ); 
299   }  
302   /*! \brief  Checks if we are allowed to create a snapshot of the given dn.
303       @param  String The source dn 
304       @param  String The acl category (e.g. users) 
305       @return Boolean   TRUE if we are allowed to restore a snapshot.
306   */
307   function allow_snapshot_create($dn, $object)
308   {
309     if(!is_array($object)){
310       $object = array($object);
311     }
312     $r = TRUE;
313     foreach($object as $category){
314       $r &= preg_match("/r/",$this->has_complete_category_acls($dn, $category));
315     }
316     return($r) ; 
317   }  
320   function get_permissions($dn, $object, $attribute= "", $skip_write= FALSE)
321   {
322     /* If we are forced to skip ACLs checks for the current user 
323         then return all permissions.
324      */
325     if($this->ignore_acl_for_current_user()){
326       if($skip_write){
327         return("rcdm");
328       }
329       return("rwcdm");
330     }
332     /* Push cache answer? */
333     $ACL_CACHE = &session::global_get('ACL_CACHE');
334     if (isset($ACL_CACHE["$dn+$object+$attribute"])){
335       $ret = $ACL_CACHE["$dn+$object+$attribute"];
336       if($skip_write){
337         $ret = str_replace(array('w','c','d','m'), '',$ret);
338       }
339       return($ret);
340     }
342     /* Detect the set of ACLs we have to check for this object 
343      */
344     $adn = $dn;
345     while(!isset($this->ACLperPath[$adn]) && strpos($adn,",") !== FALSE){
346       $adn = preg_replace("/^[^,]*+,/","",$adn);
347     }
348     if(isset($this->ACLperPath[$adn])){
349       $ACL = $this->ACLperPath[$adn];
350     }else{
351       $ACL_CACHE["$dn+$object+$attribute"] = "";
352       return("");
353     }
354  
355     /* If we do not need to respect any user-filter settings 
356         we can skip the per object ACL checks.
357      */
358     $orig_dn= $dn;
359     if(!isset($this->ACLperPath_usesFilter[$adn])){
360       $dn = $adn;
361       if (isset($ACL_CACHE["$dn+$object+$attribute"])){
362         $ret = $ACL_CACHE["$dn+$object+$attribute"];
363         if(!isset($ACL_CACHE["$orig_dn+$object+$attribute"])){
364           $ACL_CACHE["$orig_dn+$object+$attribute"] = $ACL_CACHE["$dn+$object+$attribute"];
365         }
366         if($skip_write){
367           $ret = str_replace('w','',$ret);
368         }
369         return($ret);
370       }
371     }
372  
373     /* Get ldap object, for later filter checks 
374      */
375     $ldap = $this->config->get_ldap_link();
377     $acl= array("r" => "", "w" => "", "c" => "", "d" => "", "m" => "", "a" => "");
379     /* Build dn array */
380     $path= split(',', $dn);
381     $path= array_reverse($path);
383     /* Walk along the path to evaluate the acl */
384     $cpath= "";
385     foreach ($path as $element){
387       /* Clean potential ACLs for each level */
388                         if(isset($this->config->idepartments[$cpath])){
389         $acl= $this->cleanACL($acl);
390       }
392       if ($cpath == ""){
393         $cpath= $element;
394       } else {
395         $cpath= $element.','.$cpath;
396       }
398       if (isset($ACL[$cpath])){
400         /* Inspect this ACL, place the result into ACL */
401         foreach ($ACL[$cpath] as $subacl){
403           /* Reset? Just clean the ACL and turn over to the next one... */
404           if ($subacl['type'] == 'reset'){
405             $acl= $this->cleanACL($acl, TRUE);
406             continue;
407           }
409           if($subacl['type'] == "role") {
410             echo "role skipped";
411             continue;
412           }
414           /* With user filter */
415           if (isset($subacl['filter']) && !empty($subacl['filter'])){
416             $id = $dn."-".$subacl['filter'];
417             if(!isset($ACL_CACHE['FILTER'][$id])){
418               $ACL_CACHE['FILTER'][$id] = $ldap->object_match_filter($dn,$subacl['filter']);
419             }
420             if(!$ACL_CACHE['FILTER'][$id]){
421               continue;
422             }
423           }
425           /* Self ACLs? 
426            */
427           if($dn != $this->dn && isset($subacl['acl'][$object][0]) && (strpos($subacl['acl'][$object][0],"s") !== FALSE)){
428             continue;
429           }
431           /* If attribute is "", we want to know, if we've *any* permissions here... 
432               Merge global class ACLs [0] with attributes specific ACLs [attribute].
433            */
434           if ($attribute == "" && isset($subacl['acl'][$object])){
435             foreach($subacl['acl'][$object] as $attr => $dummy){
436               $acl= $this->mergeACL($acl, $subacl['type'], $subacl['acl'][$object][$attr]);
437             }
438             continue;
439           }
441           /* Per attribute ACL? */
442           if (isset($subacl['acl'][$object][$attribute])){
443             $acl= $this->mergeACL($acl, $subacl['type'], $subacl['acl'][$object][$attribute]);
444             continue;
445           }
447           /* Per object ACL? */
448           if (isset($subacl['acl'][$object][0])){
449             $acl= $this->mergeACL($acl, $subacl['type'], $subacl['acl'][$object][0]);
450             continue;
451           }
453           /* Global ACL? */
454           if (isset($subacl['acl']['all'][0])){
455             $acl= $this->mergeACL($acl, $subacl['type'], $subacl['acl']['all'][0]);
456             continue;
457           }
459           /* Category ACLs    (e.g. $object = "user/0")
460            */
461           if(strstr($object,"/0")){
462             $ocs = preg_replace("/\/0$/","",$object);
463             if(isset($this->ocMapping[$ocs])){
465               /* if $attribute is "", then check every single attribute for this object.
466                  if it is 0, then just check the object category ACL.
467                */
468               if($attribute == ""){    
469                 foreach($this->ocMapping[$ocs] as $oc){
470                   if (isset($subacl['acl'][$ocs.'/'.$oc])){
472                     if($dn != $this->dn && strpos($subacl['acl'][$ocs.'/'.$oc][0],"s") !== FALSE) continue;
474                     foreach($subacl['acl'][$ocs.'/'.$oc] as $attr => $dummy){
475                       $acl= $this->mergeACL($acl, $subacl['type'], $subacl['acl'][$ocs.'/'.$oc][$attr]);
476                     }
477                     continue;
478                   }
479                 }
480               }else{
481                 if(isset($subacl['acl'][$ocs.'/'.$oc][0])){
482                   if($dn != $this->dn && strpos($subacl['acl'][$ocs.'/'.$oc][0],"s") !== FALSE) continue;
483                   $acl= $this->mergeACL($acl, $subacl['type'], $subacl['acl'][$ocs.'/'.$oc][0]);
484                 }
485               }
486             }
487             continue;
488           }
489         }
490       }
491     }
493     /* If the requested ACL is for a container object, then alter 
494         ACLs by applying cleanACL a last time.
495      */
496     if(isset($this->config->idepartments[$dn])){
497       $acl = $this->cleanACL($acl);
498     }
500     /* Assemble string */
501     $ret= "";
502     foreach ($acl as $key => $value){
503       if ($value !== ""){
504         $ret.= $key;
505       }
506     }
508     $ACL_CACHE["$dn+$object+$attribute"]= $ret;
509     $ACL_CACHE["$orig_dn+$object+$attribute"]= $ret;
511     /* Remove write if needed */
512     if ($skip_write){
513       $ret = str_replace(array('w','c','d','m'), '',$ret);
514     }
515     return ($ret);
516   }
519   /* Extract all departments that are accessible (direct or 'on the way' to an
520      accessible department) */
521   function get_module_departments($module, $skip_self_acls = FALSE )
522   {
523     /* If we are forced to skip ACLs checks for the current user 
524         then return all departments as valid.
525      */
526     if($this->ignore_acl_for_current_user()){
527       return(array_keys($this->config->idepartments));
528     }
530     /* Use cached results if possilbe */
531     $ACL_CACHE = &session::global_get('ACL_CACHE');
533     if(!is_array($module)){
534       $module = array($module);
535     }
537     global $plist;
538     $res = array();
539     foreach($module as $mod){
540       if(isset($ACL_CACHE['MODULE_DEPARTMENTS'][$mod])){
541         $res = array_merge($res,$ACL_CACHE['MODULE_DEPARTMENTS'][$mod]);
542         continue;
543       }
545       $deps = array();
547       /* Search for per object ACLs */
548       foreach($this->ACL as $dn => $infos){
549         foreach($infos as $info){
550           $found = FALSE;
551           foreach($info['acl'] as $cat => $data){
553             /* Skip self acls? */
554             if($skip_self_acls && isset($data['0']) && (strpos($data['0'], "s") !== FALSE)) continue;
555             if(preg_match("/^".preg_quote($mod, '/')."/",$cat)){
556               $found =TRUE;
557               break;
558             }
559           } 
561           if($found && !isset($this->config->idepartments[$dn])){
562             while(!isset($this->config->idepartments[$dn]) && strpos($dn, ",")){
563               $dn = preg_replace("/^[^,]+,/","",$dn);
564             }
565             if(isset($this->config->idepartments[$dn])){
566               $deps[$dn] = $dn;
567             }
568           }
569         }
570       }
572       /* For all gosaDepartments */
573       foreach ($this->config->departments as $dn){
574         if(isset($deps[$dn])) continue;
575         $acl = "";
576         if(strpos($mod, '/')){
577           $acl.=  $this->get_permissions($dn,$mod);
578         }else{
579           $acl.=  $this->get_category_permissions($dn,$mod,TRUE);
580         }
581         if(!empty($acl)) {
582           $deps[$dn] = $dn;
583         }
584       }
586       $ACL_CACHE['MODULE_DEPARTMENTS'][$mod] = $deps;
587       $res = array_merge($res,$deps);
588     }
590     return (array_values($res));
591   }
594   function mergeACL($acl, $type, $newACL)
595   {
596                 $at= array("psub" => "p", "sub" => "s", "one" => "1");
598     if (strpos($newACL, 'w') !== FALSE && strpos($newACL, 'r') === FALSE){
599       $newACL .= "r";
600     }
602                 /* Ignore invalid characters */
603                 $newACL= preg_replace('/[^rwcdm]/', '', $newACL);
605     foreach(str_split($newACL) as $char){
607       /* Skip "self" ACLs without combination of rwcdm, they have no effect.
608          -self flag without read/write/create/...
609        */
610       if(empty($char)) continue;
612       /* Skip permanent and subtree entries */
613       if (preg_match('/[sp]/', $acl[$char])){
614         continue;
615       }
617                         if ($type == "base" && $acl[$char] != 1) {
618                                 $acl[$char]= 0;
619                         } else {
620         $acl[$char]= $at[$type];
621                         }
622     }
624     return ($acl);
625   }
628   function cleanACL($acl, $reset= FALSE)
629   {
630     foreach ($acl as $key => $value){
632       /* Continue, if value is empty or permanent */
633       if ($value == "" || $value == "p") {
634             continue;
635       }
637       /* Reset removes everything but 'p' */
638       if ($reset && $value != 'p'){
639         $acl[$key]= "";
640         continue;
641       }
643       /* Decrease tree level */
644       if (is_int($value)){
645         if ($value){
646           $acl[$key]--;
647         } else {
648           $acl[$key]= "";
649         }
650       }
651     }
653     return ($acl);
654   }
657   /* #FIXME This could be logical wrong or could be optimized in the future
658      Return combined acls for a given category. 
659      All acls will be combined like boolean AND 
660       As example ('rwcdm' + 'rcd' + 'wrm'= 'r') 
661     
662      Results will be cached in $this->result_cache.
663       $this->result_cache will be resetted if load_acls is called.
664   */
665   function has_complete_category_acls($dn,$category)
666   {
667     $acl    = "rwcdm";
668     $types  = "rwcdm";
670     if(!is_string($category)){
671       trigger_error("category must be string");   
672       $acl = "";
673     }else{
674       if(!isset($this->result_cache['has_complete_category_acls'][$dn][$category]))   {
675         if (isset($this->ocMapping[$category])){
676           foreach($this->ocMapping[$category] as $oc){
678             /* Skip objectClass '0' (e.g. users/0) get_permissions will ever return '' ??  */
679             if($oc == "0") continue;
680             $tmp =  $this->get_permissions($dn, $category."/".$oc);
681             for($i = 0, $l= strlen($types); $i < $l; $i++) {
682               if(!preg_match("/".$types[$i]."/",$tmp)){ 
683                 $acl = preg_replace("/".$types[$i]."/","",$acl);
684               }
685             }
686           }
687         }else{
688           trigger_error("Invalid type of category ".$category);
689           $acl = "";
690         }
691         $this->result_cache['has_complete_category_acls'][$dn][$category] = $acl;
692       }else{
693         $acl = $this->result_cache['has_complete_category_acls'][$dn][$category];
694       }
695     }
696     return($acl);
697   }
699  
700   /*! \brief  Returns TRUE if the current user is configured in IGNORE_ACL=".." in your gosa.conf 
701       @param  Return Boolean TRUE if we have to skip ACL checks else FALSE.
702    */ 
703   function ignore_acl_for_current_user()
704   {
705     return($this->ignoreACL);
706   }
710 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
711 ?>