Code

f292c1bb9de613fbcdea0f172d006ab452962922
[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(isset($object_acls[0])){
218                 if(strpos($object_acls[0],"s")){
219                   unset($without_self_acl[$sdn][$dn][$acl_id]['acl'][$object]);
220                 }
221               }
222             }
223           }
224         }
225         $dn = preg_replace("/^[^,]*+,/","",$dn);
226       }
227     } 
228     $this->ACLperPath =$without_self_acl;
230     /* Append Self entry */
231     $dn = $this->dn;
232     while(strpos($dn,",") && !isset($all_acl[$dn])){
233       $dn = preg_replace("/^[^,]*+,/","",$dn);
234     }
235     if(isset($all_acl[$dn])){
236       $this->ACLperPath[$this->dn] = $all_acl[$dn];
237     }
238   }
241   function get_category_permissions($dn, $category, $any_acl = FALSE)
242   {
243     return(@$this->get_permissions($dn,$category.'/0',""));
244   }
246   
247   /*! \brief Check if the given object (dn) is copyable
248       @param  String The object dn 
249       @param  String The acl  category (e.g. users) 
250       @param  String The acl  class (e.g. user) 
251       @return Boolean   TRUE if the given object is copyable else FALSE 
252   */
253   function is_copyable($dn, $object, $class)
254   {
255     return(preg_match("/r/",$this->has_complete_category_acls($dn, $object)));
256   }
259   /*! \brief Check if the given object (dn) is cutable
260       @param  String The object dn 
261       @param  String The acl  category (e.g. users) 
262       @param  String The acl  class (e.g. user) 
263       @return Boolean   TRUE if the given object is cutable else FALSE 
264   */
265   function is_cutable($dn, $object, $class)
266   {
267     $remove = preg_match("/d/",$this->get_permissions($dn,$object."/".$class));
268     $read   = preg_match("/r/",$this->has_complete_category_acls($dn, $object));
269     return($remove && $read);
270   }
273   /*! \brief  Checks if we are allowed to paste an object to the given destination ($dn)
274       @param  String The destination dn 
275       @param  String The acl  category (e.g. users) 
276       @param  String The acl  class (e.g. user) 
277       @return Boolean   TRUE if we are allowed to paste an object.
278   */
279   function is_pasteable($dn, $object)
280   {
281     return(preg_match("/w/",$this->has_complete_category_acls($dn, $object)));
282   }
285   /*! \brief  Checks if we are allowed to restore a snapshot for the given dn.
286       @param  String The destination dn 
287       @param  String The acl  category (e.g. users) 
288       @return Boolean   TRUE if we are allowed to restore a snapshot.
289   */
290   function allow_snapshot_restore($dn, $object)
291   {
292     if(!is_array($object)){
293       $object = array($object);
294     }
295     $r = $w = TRUE;
296     foreach($object as $category){
297       $w &= preg_match("/w/",$this->has_complete_category_acls($dn, $category));
298       $r &= preg_match("/r/",$this->has_complete_category_acls($dn, $category));
299     }
300     return($r && $w ); 
301   }  
304   /*! \brief  Checks if we are allowed to create a snapshot of the given dn.
305       @param  String The source dn 
306       @param  String The acl category (e.g. users) 
307       @return Boolean   TRUE if we are allowed to restore a snapshot.
308   */
309   function allow_snapshot_create($dn, $object)
310   {
311     if(!is_array($object)){
312       $object = array($object);
313     }
314     $r = TRUE;
315     foreach($object as $category){
316       $r &= preg_match("/r/",$this->has_complete_category_acls($dn, $category));
317     }
318     return($r) ; 
319   }  
322   function get_permissions($dn, $object, $attribute= "", $skip_write= FALSE)
323   {
324     /* If we are forced to skip ACLs checks for the current user 
325         then return all permissions.
326      */
327     if($this->ignore_acl_for_current_user()){
328       if($skip_write){
329         return("rcdm");
330       }
331       return("rwcdm");
332     }
334     /* Push cache answer? */
335     $ACL_CACHE = &session::global_get('ACL_CACHE');
336     if (isset($ACL_CACHE["$dn+$object+$attribute"])){
337       $ret = $ACL_CACHE["$dn+$object+$attribute"];
338       if($skip_write){
339         $ret = str_replace(array('w','c','d','m'), '',$ret);
340       }
341       return($ret);
342     }
344     /* Detect the set of ACLs we have to check for this object 
345      */
346     $adn = $dn;
347     while(!isset($this->ACLperPath[$adn]) && strpos($adn,",") !== FALSE){
348       $adn = preg_replace("/^[^,]*+,/","",$adn);
349     }
350     if(isset($this->ACLperPath[$adn])){
351       $ACL = $this->ACLperPath[$adn];
352     }else{
353       $ACL_CACHE["$dn+$object+$attribute"] = "";
354       return("");
355     }
356  
357     /* If we do not need to respect any user-filter settings 
358         we can skip the per object ACL checks.
359      */
360     $orig_dn= $dn;
361     if(!isset($this->ACLperPath_usesFilter[$adn])){
362       $dn = $adn;
363       if (isset($ACL_CACHE["$dn+$object+$attribute"])){
364         $ret = $ACL_CACHE["$dn+$object+$attribute"];
365         if(!isset($ACL_CACHE["$orig_dn+$object+$attribute"])){
366           $ACL_CACHE["$orig_dn+$object+$attribute"] = $ACL_CACHE["$dn+$object+$attribute"];
367         }
368         if($skip_write){
369           $ret = str_replace('w','',$ret);
370         }
371         return($ret);
372       }
373     }
374  
375     /* Get ldap object, for later filter checks 
376      */
377     $ldap = $this->config->get_ldap_link();
379     $acl= array("r" => "", "w" => "", "c" => "", "d" => "", "m" => "", "a" => "");
381     /* Build dn array */
382     $path= split(',', $dn);
383     $path= array_reverse($path);
385     /* Walk along the path to evaluate the acl */
386     $cpath= "";
387     foreach ($path as $element){
389       /* Clean potential ACLs for each level */
390                         if(isset($this->config->idepartments[$cpath])){
391         $acl= $this->cleanACL($acl);
392       }
394       if ($cpath == ""){
395         $cpath= $element;
396       } else {
397         $cpath= $element.','.$cpath;
398       }
400       if (isset($ACL[$cpath])){
402         /* Inspect this ACL, place the result into ACL */
403         foreach ($ACL[$cpath] as $subacl){
405           /* Reset? Just clean the ACL and turn over to the next one... */
406           if ($subacl['type'] == 'reset'){
407             $acl= $this->cleanACL($acl, TRUE);
408             continue;
409           }
411           if($subacl['type'] == "role") {
412             echo "role skipped";
413             continue;
414           }
416           /* With user filter */
417           if (isset($subacl['filter']) && !empty($subacl['filter'])){
418             $id = $dn."-".$subacl['filter'];
419             if(!isset($ACL_CACHE['FILTER'][$id])){
420               $ACL_CACHE['FILTER'][$id] = $ldap->object_match_filter($dn,$subacl['filter']);
421             }
422             if(!$ACL_CACHE['FILTER'][$id]){
423               continue;
424             }
425           }
427           /* Self ACLs? 
428            */
429           if($dn != $this->dn && isset($subacl['acl'][$object][0]) && (strpos($subacl['acl'][$object][0],"s") !== FALSE)){
430             continue;
431           }
433           /* If attribute is "", we want to know, if we've *any* permissions here... 
434               Merge global class ACLs [0] with attributes specific ACLs [attribute].
435            */
436           if ($attribute == "" && isset($subacl['acl'][$object])){
437             foreach($subacl['acl'][$object] as $attr => $dummy){
438               $acl= $this->mergeACL($acl, $subacl['type'], $subacl['acl'][$object][$attr]);
439             }
440             continue;
441           }
443           /* Per attribute ACL? */
444           if (isset($subacl['acl'][$object][$attribute])){
445             $acl= $this->mergeACL($acl, $subacl['type'], $subacl['acl'][$object][$attribute]);
446             continue;
447           }
449           /* Per object ACL? */
450           if (isset($subacl['acl'][$object][0])){
451             $acl= $this->mergeACL($acl, $subacl['type'], $subacl['acl'][$object][0]);
452             continue;
453           }
455           /* Global ACL? */
456           if (isset($subacl['acl']['all'][0])){
457             $acl= $this->mergeACL($acl, $subacl['type'], $subacl['acl']['all'][0]);
458             continue;
459           }
461           /* Category ACLs    (e.g. $object = "user/0")
462            */
463           if(strstr($object,"/0")){
464             $ocs = preg_replace("/\/0$/","",$object);
465             if(isset($this->ocMapping[$ocs])){
467               /* if $attribute is "", then check every single attribute for this object.
468                  if it is 0, then just check the object category ACL.
469                */
470               if($attribute == ""){    
471                 foreach($this->ocMapping[$ocs] as $oc){
472                   if (isset($subacl['acl'][$ocs.'/'.$oc])){
474                     if($dn != $this->dn && strpos($subacl['acl'][$ocs.'/'.$oc][0],"s") !== FALSE) continue;
476                     foreach($subacl['acl'][$ocs.'/'.$oc] as $attr => $dummy){
477                       $acl= $this->mergeACL($acl, $subacl['type'], $subacl['acl'][$ocs.'/'.$oc][$attr]);
478                     }
479                     continue;
480                   }
481                 }
482               }else{
483                 if(isset($subacl['acl'][$ocs.'/'.$oc][0])){
484                   if($dn != $this->dn && strpos($subacl['acl'][$ocs.'/'.$oc][0],"s") !== FALSE) continue;
485                   $acl= $this->mergeACL($acl, $subacl['type'], $subacl['acl'][$ocs.'/'.$oc][0]);
486                 }
487               }
488             }
489             continue;
490           }
491         }
492       }
493     }
495     /* If the requested ACL is for a container object, then alter 
496         ACLs by applying cleanACL a last time.
497      */
498     if(isset($this->config->idepartments[$dn])){
499       $acl = $this->cleanACL($acl);
500     }
502     /* Assemble string */
503     $ret= "";
504     foreach ($acl as $key => $value){
505       if ($value !== ""){
506         $ret.= $key;
507       }
508     }
510     $ACL_CACHE["$dn+$object+$attribute"]= $ret;
511     $ACL_CACHE["$orig_dn+$object+$attribute"]= $ret;
513     /* Remove write if needed */
514     if ($skip_write){
515       $ret = str_replace(array('w','c','d','m'), '',$ret);
516     }
517     return ($ret);
518   }
521   /* Extract all departments that are accessible (direct or 'on the way' to an
522      accessible department) */
523   function get_module_departments($module, $skip_self_acls = FALSE )
524   {
525     /* If we are forced to skip ACLs checks for the current user 
526         then return all departments as valid.
527      */
528     if($this->ignore_acl_for_current_user()){
529       return(array_keys($this->config->idepartments));
530     }
532     /* Use cached results if possilbe */
533     $ACL_CACHE = &session::global_get('ACL_CACHE');
535     if(!is_array($module)){
536       $module = array($module);
537     }
539     global $plist;
540     $res = array();
541     foreach($module as $mod){
542       if(isset($ACL_CACHE['MODULE_DEPARTMENTS'][$mod])){
543         $res = array_merge($res,$ACL_CACHE['MODULE_DEPARTMENTS'][$mod]);
544         continue;
545       }
547       $deps = array();
549       /* Search for per object ACLs */
550       foreach($this->ACL as $dn => $infos){
551         foreach($infos as $info){
552           $found = FALSE;
553           foreach($info['acl'] as $cat => $data){
555             /* Skip self acls? */
556             if($skip_self_acls && isset($data['0']) && (strpos($data['0'], "s") !== FALSE)) continue;
557             if(preg_match("/^".preg_quote($mod, '/')."/",$cat)){
558               $found =TRUE;
559               break;
560             }
561           } 
563           if($found && !isset($this->config->idepartments[$dn])){
564             while(!isset($this->config->idepartments[$dn]) && strpos($dn, ",")){
565               $dn = preg_replace("/^[^,]+,/","",$dn);
566             }
567             if(isset($this->config->idepartments[$dn])){
568               $deps[$dn] = $dn;
569             }
570           }
571         }
572       }
574       /* For all gosaDepartments */
575       foreach ($this->config->departments as $dn){
576         if(isset($deps[$dn])) continue;
577         $acl = "";
578         if(strpos($mod, '/')){
579           $acl.=  $this->get_permissions($dn,$mod);
580         }else{
581           $acl.=  $this->get_category_permissions($dn,$mod,TRUE);
582         }
583         if(!empty($acl)) {
584           $deps[$dn] = $dn;
585         }
586       }
588       $ACL_CACHE['MODULE_DEPARTMENTS'][$mod] = $deps;
589       $res = array_merge($res,$deps);
590     }
592     return (array_values($res));
593   }
596   function mergeACL($acl, $type, $newACL)
597   {
598                 $at= array("psub" => "p", "sub" => "s", "one" => "1");
600     if (strpos($newACL, 'w') !== FALSE && strpos($newACL, 'r') === FALSE){
601       $newACL .= "r";
602     }
604                 /* Ignore invalid characters */
605                 $newACL= preg_replace('/[^rwcdm]/', '', $newACL);
607     foreach(str_split($newACL) as $char){
609       /* Skip "self" ACLs without combination of rwcdm, they have no effect.
610          -self flag without read/write/create/...
611        */
612       if(empty($char)) continue;
614       /* Skip permanent and subtree entries */
615       if (preg_match('/[sp]/', $acl[$char])){
616         continue;
617       }
619                         if ($type == "base" && $acl[$char] != 1) {
620                                 $acl[$char]= 0;
621                         } else {
622         $acl[$char]= $at[$type];
623                         }
624     }
626     return ($acl);
627   }
630   function cleanACL($acl, $reset= FALSE)
631   {
632     foreach ($acl as $key => $value){
634       /* Continue, if value is empty or permanent */
635       if ($value == "" || $value == "p") {
636             continue;
637       }
639       /* Reset removes everything but 'p' */
640       if ($reset && $value != 'p'){
641         $acl[$key]= "";
642         continue;
643       }
645       /* Decrease tree level */
646       if (is_int($value)){
647         if ($value){
648           $acl[$key]--;
649         } else {
650           $acl[$key]= "";
651         }
652       }
653     }
655     return ($acl);
656   }
659   /* #FIXME This could be logical wrong or could be optimized in the future
660      Return combined acls for a given category. 
661      All acls will be combined like boolean AND 
662       As example ('rwcdm' + 'rcd' + 'wrm'= 'r') 
663     
664      Results will be cached in $this->result_cache.
665       $this->result_cache will be resetted if load_acls is called.
666   */
667   function has_complete_category_acls($dn,$category)
668   {
669     $acl    = "rwcdm";
670     $types  = "rwcdm";
672     if(!is_string($category)){
673       trigger_error("category must be string");   
674       $acl = "";
675     }else{
676       if(!isset($this->result_cache['has_complete_category_acls'][$dn][$category]))   {
677         if (isset($this->ocMapping[$category])){
678           foreach($this->ocMapping[$category] as $oc){
680             /* Skip objectClass '0' (e.g. users/0) get_permissions will ever return '' ??  */
681             if($oc == "0") continue;
682             $tmp =  $this->get_permissions($dn, $category."/".$oc);
683             for($i = 0, $l= strlen($types); $i < $l; $i++) {
684               if(!preg_match("/".$types[$i]."/",$tmp)){ 
685                 $acl = preg_replace("/".$types[$i]."/","",$acl);
686               }
687             }
688           }
689         }else{
690           trigger_error("Invalid type of category ".$category);
691           $acl = "";
692         }
693         $this->result_cache['has_complete_category_acls'][$dn][$category] = $acl;
694       }else{
695         $acl = $this->result_cache['has_complete_category_acls'][$dn][$category];
696       }
697     }
698     return($acl);
699   }
701  
702   /*! \brief  Returns TRUE if the current user is configured in IGNORE_ACL=".." in your gosa.conf 
703       @param  Return Boolean TRUE if we have to skip ACL checks else FALSE.
704    */ 
705   function ignore_acl_for_current_user()
706   {
707     return($this->ignoreACL);
708   }
712 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
713 ?>