Code

Update acl stuff
[gosa.git] / gosa-core / include / class_ldap.inc
1 <?php
2 /*
3  * This code is part of GOsa (http://www.gosa-project.org)
4  * Copyright (C) 2003-2008 GONICUS GmbH
5  * Copyright (C) 2003 Alejandro Escanero Blanco <aescanero@chaosdimension.org>
6  * Copyright (C) 1998  Eric Kilfoil <eric@ipass.net>
7  *
8  * ID: $$Id$$
9  *
10  * This program is free software; you can redistribute it and/or modify
11  * it under the terms of the GNU General Public License as published by
12  * the Free Software Foundation; either version 2 of the License, or
13  * (at your option) any later version.
14  *
15  * This program is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18  * GNU General Public License for more details.
19  *
20  * You should have received a copy of the GNU General Public License
21  * along with this program; if not, write to the Free Software
22  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
23  */
25 define("ALREADY_EXISTING_ENTRY",-10001);
26 define("UNKNOWN_TOKEN_IN_LDIF_FILE",-10002);
27 define("NO_FILE_UPLOADED",10003);
28 define("INSERT_OK",10000);
29 define("SPECIALS_OVERRIDE", TRUE);
31 class LDAP{
33   var $hascon   =false;
34   var $reconnect=false;
35   var $tls      = false;
36   var $cid;
37   var $hasres   = array();
38   var $sr       = array();
39   var $re       = array();
40   var $basedn   ="";
41   var $start    = array(); // 0 if we are fetching the first entry, otherwise 1
42   var $error    = ""; // Any error messages to be returned can be put here
43   var $srp      = 0;
44   var $objectClasses = array(); // Information read from slapd.oc.conf
45   var $binddn   = "";
46   var $bindpw   = "";
47   var $hostname = "";
48   var $follow_referral = FALSE;
49   var $referrals= array();
50   var $max_ldap_query_time = 0;   // 0, empty or negative values will disable this check 
52   function LDAP($binddn,$bindpw, $hostname, $follow_referral= FALSE, $tls= FALSE)
53   {
54     global $config;
55     $this->follow_referral= $follow_referral;
56     $this->tls=$tls;
57     $this->binddn=LDAP::convert($binddn);
59     $this->bindpw=$bindpw;
60     $this->hostname=$hostname;
62     /* Check if MAX_LDAP_QUERY_TIME is defined */ 
63     if(is_object($config) && $config->get_cfg_value("ldapMaxQueryTime") != ""){
64       $str = $config->get_cfg_value("ldapMaxQueryTime");
65       $this->max_ldap_query_time = (float)($str);
66     }
68     $this->connect();
69   }
72   function getSearchResource()
73   {
74     $this->sr[$this->srp]= NULL;
75     $this->start[$this->srp]= 0;
76     $this->hasres[$this->srp]= false;
77     return $this->srp++;
78   }
81   /* Function to replace all problematic characters inside a DN by \001XX, where
82      \001 is decoded to chr(1) [ctrl+a]. It is not impossible, but very unlikely
83      that this character is inside a DN.
85      Currently used codes:
86      ,   => CO
87      \2C => CO
88      (   => OB
89      )   => CB
90      /   => SL                                                                  
91      \22 => DQ                                                                  */
92   static function convert($dn)
93   {
94     if (SPECIALS_OVERRIDE == TRUE){
95       $tmp= preg_replace(array("/\\\\,/", "/\\\\2C/", "/\(/", "/\)/", "/\//", "/\\\\22/", '/\\\\"/'),
96           array("\001CO", "\001CO", "\001OB", "\001CB", "\001SL", "\001DQ", "\001DQ"),
97           $dn);
98       return (preg_replace('/,\s+/', ',', $tmp));
99     } else {
100       return ($dn);
101     }
102   }
105   /* Function to fix all problematic characters inside a DN by replacing \001XX
106      codes to their original values. See "convert" for mor information. 
107      ',' characters are always expanded to \, (not \2C), since all tested LDAP
108      servers seem to take it the correct way.                                  */
109   static function fix($dn)
110   {
111     if (SPECIALS_OVERRIDE == TRUE){
112       return (preg_replace(array("/\001CO/", "/\001OB/", "/\001CB/", "/\001SL/", "/\001DQ/"),
113             array("\,", "(", ")", "/", '\"'),
114             $dn));
115     } else {
116       return ($dn);
117     }
118   }
120   /* Function to fix problematic characters in DN's that are used for search
121      requests. I.e. member=....                                               */
122   static function prepare4filter($dn)
123   {
124     $fixed= normalizeLdap(str_replace('\\\\', '\\\\\\', LDAP::fix($dn)));
125     return str_replace('\\,', '\\\\,', $fixed);
126   }
129   function connect()
130   {
131     $this->hascon=false;
132     $this->reconnect=false;
133     if ($this->cid= @ldap_connect($this->hostname)) {
134       @ldap_set_option($this->cid, LDAP_OPT_PROTOCOL_VERSION, 3);
135       if (function_exists("ldap_set_rebind_proc") && $this->follow_referral) {
136         @ldap_set_option($this->cid, LDAP_OPT_REFERRALS, 1);
137         @ldap_set_rebind_proc($this->cid, array(&$this, "rebind"));
138       }
139       if (function_exists("ldap_start_tls") && $this->tls){
140         @ldap_start_tls($this->cid);
141       }
143       $this->error = "No Error";
144       if ($bid = @ldap_bind($this->cid, LDAP::fix($this->binddn), $this->bindpw)) {
145         $this->error = "Success";
146         $this->hascon=true;
147       } else {
148         if ($this->reconnect){
149           if ($this->error != "Success"){
150             $this->error = "Could not rebind to " . $this->binddn;
151           }
152         } else {
153           $this->error = "Could not bind to " . $this->binddn;
154         }
155       }
156     } else {
157       $this->error = "Could not connect to LDAP server";
158     }
159   }
161   function rebind($ldap, $referral)
162   {
163     $credentials= $this->get_credentials($referral);
164     if (@ldap_bind($ldap, LDAP::fix($credentials['ADMINDN']), $credentials['ADMINPASSWORD'])) {
165       $this->error = "Success";
166       $this->hascon=true;
167       $this->reconnect= true;
168       return (0);
169     } else {
170       $this->error = "Could not bind to " . $credentials['ADMINDN'];
171       return NULL;
172     }
173   }
175   function reconnect()
176   {
177     if ($this->reconnect){
178       @ldap_unbind($this->cid);
179       $this->cid = NULL;
180     }
181   }
183   function unbind()
184   {
185     @ldap_unbind($this->cid);
186     $this->cid = NULL;
187   }
189   function disconnect()
190   {
191     if($this->hascon){
192       @ldap_close($this->cid);
193       $this->hascon=false;
194     }
195   }
197   function cd($dir)
198   {
199     if ($dir == ".."){
200       $this->basedn = $this->getParentDir();
201     } else {
202       $this->basedn = LDAP::convert($dir);
203     }
204   }
206   function getParentDir($basedn = "")
207   {
208     if ($basedn==""){
209       $basedn = $this->basedn;
210     } else {
211       $basedn = LDAP::convert($basedn);
212     }
213     return(ereg_replace("[^,]*[,]*[ ]*(.*)", "\\1", $basedn));
214   }
216   
217   function search($srp, $filter, $attrs= array())
218   {
219     if($this->hascon){
220       if ($this->reconnect) $this->connect();
222       $start = microtime(true);
223       $this->clearResult($srp);
224       $this->sr[$srp] = @ldap_search($this->cid, LDAP::fix($this->basedn), $filter, $attrs);
225       $this->error = @ldap_error($this->cid);
226       $this->resetResult($srp);
227       $this->hasres[$srp]=true;
228    
229       /* Check if query took longer as specified in max_ldap_query_time */
230       if($this->max_ldap_query_time){
231         $diff = microtime(true) - $start;
232         if($diff > $this->max_ldap_query_time){
233           msg_dialog::display(_("Performance warning"), sprintf(_("LDAP performance is poor: last query took about %.2fs!"), $diff), WARNING_DIALOG);
234         }
235       }
237       $this->log("LDAP operation: time=".(microtime(true)-$start)." operation=search('".LDAP::fix($this->basedn)."', '$filter')");
238       return($this->sr[$srp]);
239     }else{
240       $this->error = "Could not connect to LDAP server";
241       return("");
242     }
243   }
245   function ls($srp, $filter = "(objectclass=*)", $basedn = "",$attrs = array("*"))
246   {
247     if($this->hascon){
248       if ($this->reconnect) $this->connect();
250       $this->clearResult($srp);
251       if ($basedn == "")
252         $basedn = $this->basedn;
253       else
254         $basedn= LDAP::convert($basedn);
255   
256       $start = microtime(true);
257       $this->sr[$srp] = @ldap_list($this->cid, LDAP::fix($basedn), $filter,$attrs);
258       $this->error = @ldap_error($this->cid);
259       $this->resetResult($srp);
260       $this->hasres[$srp]=true;
262        /* Check if query took longer as specified in max_ldap_query_time */
263       if($this->max_ldap_query_time){
264         $diff = microtime(true) - $start;
265         if($diff > $this->max_ldap_query_time){
266           msg_dialog::display(_("Performance warning"), sprintf(_("LDAP performance is poor: last query took about %.2fs!"), $diff), WARNING_DIALOG);
267         }
268       }
270       $this->log("LDAP operation: time=".(microtime(true) - $start)." operation=ls('".LDAP::fix($basedn)."', '$filter')");
272       return($this->sr[$srp]);
273     }else{
274       $this->error = "Could not connect to LDAP server";
275       return("");
276     }
277   }
279   function cat($srp, $dn,$attrs= array("*"), $filter = "(objectclass=*)")
280   {
281     if($this->hascon){
282       if ($this->reconnect) $this->connect();
284       $this->clearResult($srp);
285       $this->sr[$srp] = @ldap_read($this->cid, LDAP::fix($dn), $filter,$attrs);
286       $this->error = @ldap_error($this->cid);
287       $this->resetResult($srp);
288       $this->hasres[$srp]=true;
289       return($this->sr[$srp]);
290     }else{
291       $this->error = "Could not connect to LDAP server";
292       return("");
293     }
294   }
296   function object_match_filter($dn,$filter)
297   {
298     if($this->hascon){
299       if ($this->reconnect) $this->connect();
300       $res =  @ldap_read($this->cid, LDAP::fix($dn), $filter, array("objectClass"));
301       $rv =   @ldap_count_entries($this->cid, $res);
302       return($rv);
303     }else{
304       $this->error = "Could not connect to LDAP server";
305       return(FALSE);
306     }
307   }
309   function set_size_limit($size)
310   {
311     /* Ignore zero settings */
312     if ($size == 0){
313       @ldap_set_option($this->cid, LDAP_OPT_SIZELIMIT, 10000000);
314     }
315     if($this->hascon){
316       @ldap_set_option($this->cid, LDAP_OPT_SIZELIMIT, $size);
317     } else {
318       $this->error = "Could not connect to LDAP server";
319     }
320   }
322   function fetch($srp)
323   {
324     $att= array();
325     if($this->hascon){
326       if($this->hasres[$srp]){
327         if ($this->start[$srp] == 0)
328         {
329           if ($this->sr[$srp]){
330             $this->start[$srp] = 1;
331             $this->re[$srp]= @ldap_first_entry($this->cid, $this->sr[$srp]);
332           } else {
333             return array();
334           }
335         } else {
336           $this->re[$srp]= @ldap_next_entry($this->cid, $this->re[$srp]);
337         }
338         if ($this->re[$srp])
339         {
340           $att= @ldap_get_attributes($this->cid, $this->re[$srp]);
341           $att['dn']= trim(LDAP::convert(@ldap_get_dn($this->cid, $this->re[$srp])));
342         }
343         $this->error = @ldap_error($this->cid);
344         if (!isset($att)){
345           $att= array();
346         }
347         return($att);
348       }else{
349         $this->error = "Perform a fetch with no search";
350         return("");
351       }
352     }else{
353       $this->error = "Could not connect to LDAP server";
354       return("");
355     }
356   }
358   function resetResult($srp)
359   {
360     $this->start[$srp] = 0;
361   }
363   function clearResult($srp)
364   {
365     if($this->hasres[$srp]){
366       $this->hasres[$srp] = false;
367       @ldap_free_result($this->sr[$srp]);
368     }
369   }
371   function getDN($srp)
372   {
373     if($this->hascon){
374       if($this->hasres[$srp]){
376         if(!$this->re[$srp])
377           {
378           $this->error = "Perform a Fetch with no valid Result";
379           }
380           else
381           {
382           $rv = @ldap_get_dn($this->cid, $this->re[$srp]);
383         
384           $this->error = @ldap_error($this->cid);
385           return(trim(LDAP::convert($rv)));
386            }
387       }else{
388         $this->error = "Perform a Fetch with no Search";
389         return("");
390       }
391     }else{
392       $this->error = "Could not connect to LDAP server";
393       return("");
394     }
395   }
397   function count($srp)
398   {
399     if($this->hascon){
400       if($this->hasres[$srp]){
401         $rv = @ldap_count_entries($this->cid, $this->sr[$srp]);
402         $this->error = @ldap_error($this->cid);
403         return($rv);
404       }else{
405         $this->error = "Perform a Fetch with no Search";
406         return("");
407       }
408     }else{
409       $this->error = "Could not connect to LDAP server";
410       return("");
411     }
412   }
414   function rm($attrs = "", $dn = "")
415   {
416     if($this->hascon){
417       if ($this->reconnect) $this->connect();
418       if ($dn == "")
419         $dn = $this->basedn;
421       $r = ldap_mod_del($this->cid, LDAP::fix($dn), $attrs);
422       $this->error = @ldap_error($this->cid);
423       return($r);
424     }else{
425       $this->error = "Could not connect to LDAP server";
426       return("");
427     }
428   }
430   function mod_add($attrs = "", $dn = "")
431   {
432     if($this->hascon){
433       if ($this->reconnect) $this->connect();
434       if ($dn == "")
435         $dn = $this->basedn;
437       $r = @ldap_mod_add($this->cid, LDAP::fix($dn), $attrs);
438       $this->error = @ldap_error($this->cid);
439       return($r);
440     }else{
441       $this->error = "Could not connect to LDAP server";
442       return("");
443     }
444   }
446   function rename($attrs, $dn = "")
447   {
448     if($this->hascon){
449       if ($this->reconnect) $this->connect();
450       if ($dn == "")
451         $dn = $this->basedn;
453       $r = @ldap_mod_replace($this->cid, LDAP::fix($dn), $attrs);
454       $this->error = @ldap_error($this->cid);
455       return($r);
456     }else{
457       $this->error = "Could not connect to LDAP server";
458       return("");
459     }
460   }
462   function rmdir($deletedn)
463   {
464     if($this->hascon){
465       if ($this->reconnect) $this->connect();
466       $r = @ldap_delete($this->cid, LDAP::fix($deletedn));
467       $this->error = @ldap_error($this->cid);
468       return($r ? $r : 0);
469     }else{
470       $this->error = "Could not connect to LDAP server";
471       return("");
472     }
473   }
476   /*! \brief Move the given Ldap entry from $source to $dest
477       @param  String  $source The source dn.
478       @param  String  $dest   The destination dn.
479       @return Boolean TRUE on success else FALSE.
480    */
481   function rename_dn($source,$dest)
482   {
483     /* Check if source and destination are the same entry */
484     if(strtolower($source) == strtolower($dest)){
485       trigger_error("Source and destination can't be the same entry.");
486       $this->error = "Source and destination can't be the same entry.";
487       return(FALSE);
488     }
490     /* Check if destination entry exists */    
491     if($this->dn_exists($dest)){
492       trigger_error("Destination '$dest' already exists.");
493       $this->error = "Destination '$dest' already exists.";
494       return(FALSE);
495     }
497     /* Extract the name and the parent part out ouf source dn.
498         e.g.  cn=herbert,ou=department,dc=... 
499          parent   =>  ou=department,dc=...
500          dest_rdn =>  cn=herbert
501      */
502     $parent   = preg_replace("/^[^,]+,/","", $dest);
503     $dest_rdn = preg_replace("/,.*$/","",$dest);
505     if($this->hascon){
506       if ($this->reconnect) $this->connect();
507       $r= ldap_rename($this->cid,@LDAP::fix($source), @LDAP::fix($dest_rdn),@LDAP::fix($parent),TRUE); 
508       $this->error = ldap_error($this->cid);
510       /* Check if destination dn exists, if not the 
511           server may not support this operation */
512       $r &= is_resource($this->dn_exists($dest));
513       return($r);
514     }else{
515       $this->error = "Could not connect to LDAP server";
516       return(FALSE);
517     }
518   }
521   /**
522   *  Function rmdir_recursive
523   *
524   *  Description: Based in recursive_remove, adding two thing: full subtree remove, and delete own node.
525   *  Parameters:  The dn to delete
526   *  GiveBack:    True on sucessfull , 0 in error, and "" when we don't get a ldap conection
527   *
528   */
529   function rmdir_recursive($srp, $deletedn)
530   {
531     if($this->hascon){
532       if ($this->reconnect) $this->connect();
533       $delarray= array();
534         
535       /* Get sorted list of dn's to delete */
536       $this->ls ($srp, "(objectClass=*)",$deletedn);
537       while ($this->fetch($srp)){
538         $deldn= $this->getDN($srp);
539         $delarray[$deldn]= strlen($deldn);
540       }
541       arsort ($delarray);
542       reset ($delarray);
544       /* Really Delete ALL dn's in subtree */
545       foreach ($delarray as $key => $value){
546         $this->rmdir_recursive($srp, $key);
547       }
548       
549       /* Finally Delete own Node */
550       $r = @ldap_delete($this->cid, LDAP::fix($deletedn));
551       $this->error = @ldap_error($this->cid);
552       return($r ? $r : 0);
553     }else{
554       $this->error = "Could not connect to LDAP server";
555       return("");
556     }
557   }
559   function makeReadableErrors($error,$attrs)
560   { 
561     global $config;
563     if($this->success()) return("");
565     $str = "";
566     if(preg_match("/^objectClass: value #([0-9]*) invalid per syntax$/", $this->get_additional_error())){
567       $oc = preg_replace("/^objectClass: value #([0-9]*) invalid per syntax$/","\\1", $this->get_additional_error());
568       if(isset($attrs['objectClass'][$oc])){
569         $str.= " - <b>objectClass: ".$attrs['objectClass'][$oc]."</b>";
570       }
571     }
572     if($error == "Undefined attribute type"){
573       $str = " - <b>attribute: ".preg_replace("/:.*$/","",$this->get_additional_error())."</b>";
574     } 
576     @DEBUG(DEBUG_LDAP,__LINE__,__FUNCTION__,__FILE__,$attrs,"Erroneous data");
578     return($str);
579   }
581   function modify($attrs)
582   {
583     if(count($attrs) == 0){
584       return (0);
585     }
586     if($this->hascon){
587       if ($this->reconnect) $this->connect();
588       $r = @ldap_modify($this->cid, LDAP::fix($this->basedn), $attrs);
589       $this->error = @ldap_error($this->cid);
590       if(!$this->success()){
591         $this->error.= $this->makeReadableErrors($this->error,$attrs);
592       }
593       return($r ? $r : 0);
594     }else{
595       $this->error = "Could not connect to LDAP server";
596       return("");
597     }
598   }
600   function add($attrs)
601   {
602     if($this->hascon){
603       if ($this->reconnect) $this->connect();
604       $r = @ldap_add($this->cid, LDAP::fix($this->basedn), $attrs);
605       $this->error = @ldap_error($this->cid);
606       if(!$this->success()){
607         $this->error.= $this->makeReadableErrors($this->error,$attrs);
608       }
609       return($r ? $r : 0);
610     }else{
611       $this->error = "Could not connect to LDAP server";
612       return("");
613     }
614   }
616   function create_missing_trees($srp, $target)
617   {
618     global $config;
620     $real_path= substr($target, 0, strlen($target) - strlen($this->basedn) -1 );
622     if ($target == $this->basedn){
623       $l= array("dummy");
624     } else {
625       $l= array_reverse(gosa_ldap_explode_dn($real_path));
626     }
627     unset($l['count']);
628     $cdn= $this->basedn;
629     $tag= "";
631     /* Load schema if available... */
632     $classes= $this->get_objectclasses();
634     foreach ($l as $part){
635       if ($part != "dummy"){
636         $cdn= "$part,$cdn";
637       }
639       /* Ignore referrals */
640       $found= false;
641       foreach($this->referrals as $ref){
642         $base= preg_replace('!^[^:]+://[^/]+/([^?]+).*$!', '\\1', $ref['URI']);
643         if ($base == $cdn){
644           $found= true;
645           break;
646         }
647       }
648       if ($found){
649         continue;
650       }
652       $this->cat ($srp, $cdn);
653       $attrs= $this->fetch($srp);
655       /* Create missing entry? */
656       if (count ($attrs)){
657       
658         /* Catch the tag - if present */
659         if (isset($attrs['gosaUnitTag'][0])){
660           $tag= $attrs['gosaUnitTag'][0];
661         }
663       } else {
664         $type= preg_replace('/^([^=]+)=.*$/', '\\1', $cdn);
665         $param= preg_replace('/^[^=]+=([^,]+).*$/', '\\1', $cdn);
667         $na= array();
669         /* Automatic or traditional? */
670         if(count($classes)){
672           /* Get name of first matching objectClass */
673           $ocname= "";
674           foreach($classes as $class){
675             if (isset($class['MUST']) && $class['MUST'] == "$type"){
677               /* Look for first classes that is structural... */
678               if (isset($class['STRUCTURAL'])){
679                 $ocname= $class['NAME'];
680                 break;
681               }
683               /* Look for classes that are auxiliary... */
684               if (isset($class['AUXILIARY'])){
685                 $ocname= $class['NAME'];
686               }
687             }
688           }
690           /* Bail out, if we've nothing to do... */
691           if ($ocname == ""){
692             msg_dialog::display(_("Internal error"), sprintf(_("Cannot automatically create subtrees with RDN '%s': no object class found!"),$type), FATAL_ERROR_DIALOG);
693             exit();
694           }
696           /* Assemble_entry */
697           if ($tag != ""){
698             $na['objectClass']= array($ocname, "gosaAdministrativeUnitTag");
699             $na["gosaUnitTag"]= $tag;
700           } else {
701             $na['objectClass']= array($ocname);
702           }
703           if (isset($classes[$ocname]['AUXILIARY'])){
704             $na['objectClass'][]= $classes[$ocname]['SUP'];
705           }
706           if ($type == "dc"){
707             /* This is bad actually, but - tell me a better way? */
708             $na['objectClass'][]= 'locality';
709           }
710           $na[$type]= $param;
711           if (is_array($classes[$ocname]['MUST'])){
712             foreach($classes[$ocname]['MUST'] as $attr){
713               $na[$attr]= "filled";
714             }
715           }
717         } else {
719           /* Use alternative add... */
720           switch ($type){
721             case 'ou':
722               if ($tag != ""){
723                 $na["objectClass"]= array("organizationalUnit", "gosaAdministrativeUnitTag");
724                 $na["gosaUnitTag"]= $tag;
725               } else {
726                 $na["objectClass"]= "organizationalUnit";
727               }
728               $na["ou"]= $param;
729               break;
730             case 'dc':
731               if ($tag != ""){
732                 $na["objectClass"]= array("dcObject", "top", "locality", "gosaAdministrativeUnitTag");
733                 $na["gosaUnitTag"]= $tag;
734               } else {
735                 $na["objectClass"]= array("dcObject", "top", "locality");
736               }
737               $na["dc"]= $param;
738               break;
739             default:
740               msg_dialog::display(_("Internal error"), sprintf(_("Cannot automatically create subtrees with RDN '%s': not supported"),$type), FATAL_ERROR_DIALOG);
741               exit();
742           }
744         }
745         $this->cd($cdn);
746         $this->add($na);
747     
748         if (!$this->success()){
750           print_a(array($cdn,$na));
752           msg_dialog::display(_("LDAP error"), msgPool::ldaperror($this->get_error(), $cdn, LDAP_ADD, get_class()));
753           return FALSE;
754         }
755       }
756     }
758     return TRUE;
759   }
762   function recursive_remove($srp)
763   {
764     $delarray= array();
766     /* Get sorted list of dn's to delete */
767     $this->search ($srp, "(objectClass=*)");
768     while ($this->fetch($srp)){
769       $deldn= $this->getDN($srp);
770       $delarray[$deldn]= strlen($deldn);
771     }
772     arsort ($delarray);
773     reset ($delarray);
775     /* Delete all dn's in subtree */
776     foreach ($delarray as $key => $value){
777       $this->rmdir($key);
778     }
779   }
782   function get_attribute($dn, $name,$r_array=0)
783   {
784     $data= "";
785     if ($this->reconnect) $this->connect();
786     $sr= @ldap_read($this->cid, LDAP::fix($dn), "objectClass=*", array("$name"));
788     /* fill data from LDAP */
789     if ($sr) {
790       $ei= @ldap_first_entry($this->cid, $sr);
791       if ($ei) {
792         if ($info= @ldap_get_values_len($this->cid, $ei, "$name")){
793           $data= $info[0];
794         }
795       }
796     }
797     if($r_array==0) {
798       return ($data);
799     } else {
800       return ($info);
801     }
802   }
803  
806   function get_additional_error()
807   {
808     $error= "";
809     @ldap_get_option ($this->cid, LDAP_OPT_ERROR_STRING, $error);
810     return ($error);
811   }
814   function success()
815   {
816     return (preg_match('/Success/i', $this->error));
817   }
820   function get_error()
821   {
822     if ($this->error == 'Success'){
823       return $this->error;
824     } else {
825       $adderror= $this->get_additional_error();
826       if ($adderror != ""){
827         $error= $this->error." (".$this->get_additional_error().", ".sprintf(_("while operating on '%s' using LDAP server '%s'"), $this->basedn, $this->hostname).")";
828       } else {
829         $error= $this->error." (".sprintf(_("while operating on LDAP server %s"), $this->hostname).")";
830       }
831       return $error;
832     }
833   }
835   function get_credentials($url, $referrals= NULL)
836   {
837     $ret= array();
838     $url= preg_replace('!\?\?.*$!', '', $url);
839     $server= preg_replace('!^([^:]+://[^/]+)/.*$!', '\\1', $url);
841     if ($referrals === NULL){
842       $referrals= $this->referrals;
843     }
845     if (isset($referrals[$server])){
846       return ($referrals[$server]);
847     } else {
848       $ret['ADMINDN']= LDAP::fix($this->binddn);
849       $ret['ADMINPASSWORD']= $this->bindpw;
850     }
852     return ($ret);
853   }
856   function gen_ldif ($srp, $dn, $filter= "(objectClass=*)", $attributes= array('*'), $recursive= TRUE)
857   {
858     $display= "";
860     if ($recursive){
861       $this->cd($dn);
862       $this->ls($srp, $filter,$dn, array('dn','objectClass'));
863       $deps = array();
865       $display .= $this->gen_one_entry($dn)."\n";
867       while ($attrs= $this->fetch($srp)){
868         $deps[] = $attrs['dn'];
869       }
870       foreach($deps as $dn){
871         $display .= $this->gen_ldif($srp, $dn, $filter,$attributes,$recursive);
872       }
873     } else {
874       $display.= $this->gen_one_entry($dn);
875     }
876     return ($display);
877   }
880   function gen_xls ($srp, $dn, $filter= "(objectClass=*)", $attributes= array('*'), $recursive= TRUE,$r_array=0)
881   {
882     $display= array();
884       $this->cd($dn);
885       $this->search($srp, "$filter");
887       $i=0;
888       while ($attrs= $this->fetch($srp)){
889         $j=0;
891         foreach ($attributes as $at){
892           $display[$i][$j]= $this->get_attribute($attrs['dn'], $at,$r_array);
893           $j++;
894         }
896         $i++;
897       }
899     return ($display);
900   }
903   function gen_one_entry($dn, $filter= "(objectClass=*)" , $name= array("*"))
904   {
905     $ret = "";
906     $data = "";
907     if($this->reconnect){
908       $this->connect();
909     }
911     /* Searching Ldap Tree */
912     $sr= @ldap_read($this->cid, LDAP::fix($dn), $filter, $name);
914     /* Get the first entry */   
915     $entry= @ldap_first_entry($this->cid, $sr);
917     /* Get all attributes related to that Objekt */
918     $atts = array();
919     
920     /* Assemble dn */
921     $atts[0]['name']  = "dn";
922     $atts[0]['value'] = array('count' => 1, 0 => $dn);
924     /* Reset index */
925     $i = 1 ; 
926   $identifier = array();
927     $attribute= @ldap_first_attribute($this->cid,$entry,$identifier);
928     while ($attribute) {
929       $i++;
930       $atts[$i]['name']  = $attribute;
931       $atts[$i]['value'] = @ldap_get_values_len($this->cid, $entry, "$attribute");
933       /* Next one */
934       $attribute= @ldap_next_attribute($this->cid,$entry,$identifier);
935     }
937     foreach($atts as $at)
938     {
939       for ($i= 0; $i<$at['value']['count']; $i++){
941         /* Check if we must encode the data */
942         if(!preg_match('/^[a-z0-9+@#.=, \/ -]+$/i', $at['value'][$i])) {
943           $ret .= $at['name'].":: ".base64_encode($at['value'][$i])."\n";
944         } else {
945           $ret .= $at['name'].": ".$at['value'][$i]."\n";
946         }
947       }
948     }
950     return($ret);
951   }
954   function dn_exists($dn)
955   {
956     return @ldap_list($this->cid, LDAP::fix($dn), "(objectClass=*)", array("objectClass"));
957   }
958   
961   /*  This funktion imports ldifs 
962         
963       If DeleteOldEntries is true, the destination entry will be deleted first. 
964       If JustModify is true the destination entry will only be touched by the attributes specified in the ldif.
965       if JustMofify id false the destination dn will be overwritten by the new ldif. 
966     */
968   function import_complete_ldif($srp, $str_attr,$error,$JustModify,$DeleteOldEntries)
969   {
970     if($this->reconnect) $this->connect();
972     /* First we have to splitt the string ito detect empty lines
973        An empty line indicates an new Entry */
974     $entries = split("\n",$str_attr);
976     $data = "";
977     $cnt = 0; 
978     $current_line = 0;
980     /* FIX ldif */
981     $last = "";
982     $tmp  = "";
983     $i = 0;
984     foreach($entries as $entry){
985       if(preg_match("/^ /",$entry)){
986         $tmp[$i] .= trim($entry);
987       }else{
988         $i ++;
989         $tmp[$i] = trim($entry);
990       }
991     }
993     /* Every single line ... */
994     foreach($tmp as $entry) {
995       $current_line ++;
997       /* Removing Spaces to .. 
998          .. test if a new entry begins */
999       $tmp  = str_replace(" ","",$data );
1001       /* .. prevent empty lines in an entry */
1002       $tmp2 = str_replace(" ","",$entry);
1004       /* If the Block ends (Empty Line) */
1005       if((empty($entry))&&(!empty($tmp))) {
1006         /* Add collected lines as a complete block */
1007         $all[$cnt] = $data;
1008         $cnt ++;
1009         $data ="";
1010       } else {
1012         /* Append lines ... */
1013         if(!empty($tmp2)) {
1014           /* check if we need base64_decode for this line */
1015           if(ereg("::",$tmp2))
1016           {
1017             $encoded = split("::",$entry);
1018             $attr  = trim($encoded[0]);
1019             $value = base64_decode(trim($encoded[1]));
1020             /* Add linenumber */
1021             $data .= $current_line."#".base64_encode($attr.":".$value)."\n";
1022           }
1023           else
1024           {
1025             /* Add Linenumber */ 
1026             $data .= $current_line."#".base64_encode($entry)."\n";
1027           }
1028         }
1029       }
1030     }
1032     /* The Data we collected is not in the array all[];
1033        For example the Data is stored like this..
1035        all[0] = "1#dn : .... \n 
1036        2#ObjectType: person \n ...."
1037        
1038        Now we check every insertblock and try to insert */
1039     foreach ( $all as $single) {
1040       $lineone = split("\n",$single);  
1041       $ndn = split("#", $lineone[0]);
1042       $line = base64_decode($ndn[1]);
1044       $dnn = split (":",$line,2);
1045       $current_line = $ndn[0];
1046       $dn    = $dnn[0];
1047       $value = $dnn[1];
1049       /* Every block must begin with a dn */
1050       if($dn != "dn") {
1051         $error= sprintf(_("This is not a valid DN: '%s'. A block for import should begin with 'dn: ...' in line %s"), $line, $current_line);
1052         return -2;  
1053       }
1055       /* Should we use Modify instead of Add */
1056       $usemodify= false;
1058       /* Delete before insert */
1059       $usermdir= false;
1060     
1061       /* The dn address already exists, Don't delete destination entry, overwrite it */
1062       if (($this->dn_exists($value))&&((!$JustModify)&&(!$DeleteOldEntries))) {
1064         $usermdir = $usemodify = false;
1066       /* Delete old entry first, then add new */
1067       } elseif(($this->dn_exists($value))&&($DeleteOldEntries)){
1069         /* Delete first, then add */
1070         $usermdir = true;        
1072       } elseif(($this->dn_exists($value))&&($JustModify)) {
1073         
1074         /* Modify instead of Add */
1075         $usemodify = true;
1076       }
1077      
1078       /* If we can't Import, return with a file error */
1079       if(!$this->import_single_entry($srp, $single,$usemodify,$usermdir) ) {
1080         $error= sprintf(_("Error while importing dn: '%s', please check your LDIF from line %s on!"), $line,
1081                         $current_line);
1082         return UNKNOWN_TOKEN_IN_LDIF_FILE;      }
1083     }
1085     return (INSERT_OK);
1086   }
1089   /* Imports a single entry 
1090       If $delete is true;  The old entry will be deleted if it exists.
1091       if $modify is true;  All variables that are not touched by the new ldif will be kept.
1092       if $modify is false; The new ldif overwrites the old entry, and all untouched attributes get lost.
1093   */
1094   function import_single_entry($srp, $str_attr,$modify,$delete)
1095   {
1096     global $config;
1098     if(!$config){
1099       trigger_error("Can't import ldif, can't read config object.");
1100     }
1101   
1103     if($this->reconnect) $this->connect();
1105     $ret = false;
1106     $rows= split("\n",$str_attr);
1107     $data= false;
1109     foreach($rows as $row) {
1110       
1111       /* Check if we use Linenumbers (when import_complete_ldif is called we use
1112          Linenumbers) Linenumbers are use like this 123#attribute : value */
1113       if(!empty($row)) {
1114         if(strpos($row,"#")!=FALSE) {
1116           /* We are using line numbers 
1117              Because there is a # before a : */
1118           $tmp1= split("#",$row);
1119           $current_line= $tmp1[0];
1120           $row= base64_decode($tmp1[1]);
1121         }
1123         /* Split the line into  attribute  and value */
1124         $attr   = split(":", $row,2);
1125         $attr[0]= trim($attr[0]);  /* attribute */
1126         $attr[1]= $attr[1];  /* value */
1128         /* Check :: was used to indicate base64_encoded strings */
1129         if($attr[1][0] == ":"){
1130           $attr[1]=trim(preg_replace("/^:/","",$attr[1]));
1131           $attr[1]=base64_decode($attr[1]);
1132         }
1134         $attr[1] = trim($attr[1]);
1136         /* Check for attributes that are used more than once */
1137         if(!isset($data[$attr[0]])) {
1138           $data[$attr[0]]=$attr[1];
1139         } else {
1140           $tmp = $data[$attr[0]];
1142           if(!is_array($tmp)) {
1143             $new[0]=$tmp;
1144             $new[1]=$attr[1];
1145             $datas[$attr[0]]['count']=1;             
1146             $data[$attr[0]]=$new;
1147           } else {
1148             $cnt = $datas[$attr[0]]['count'];           
1149             $cnt ++;
1150             $data[$attr[0]][$cnt]=$attr[1];
1151             $datas[$attr[0]]['count'] = $cnt;
1152           }
1153         }
1154       }
1155     }
1157     /* If dn is an index of data, we should try to insert the data */
1158     if(isset($data['dn'])) {
1160       /* Fix dn */
1161       $tmp = gosa_ldap_explode_dn($data['dn']);
1162       unset($tmp['count']);
1163       $newdn ="";
1164       foreach($tmp as $tm){
1165         $newdn.= trim($tm).",";
1166       }
1167       $newdn = preg_replace("/,$/","",$newdn);
1168       $data['dn'] = $newdn;
1169    
1170       /* Creating Entry */
1171       $this->cd($data['dn']);
1173       /* Delete existing entry */
1174       if($delete){
1175         $this->rmdir_recursive($srp, $data['dn']);
1176       }
1177      
1178       /* Create missing trees */
1179       $this->cd ($this->basedn);
1180       $this->cd($config->current['BASE']);
1181       $this->create_missing_trees($srp, preg_replace("/^[^,]+,/","",$data['dn']));
1182       $this->cd($data['dn']);
1184       $dn = $data['dn'];
1185       unset($data['dn']);
1186       
1187       if(!$modify){
1189         $this->cat($srp, $dn);
1190         if($this->count($srp)){
1191         
1192           /* The destination entry exists, overwrite it with the new entry */
1193           $attrs = $this->fetch($srp);
1194           foreach($attrs as $name => $value ){
1195             if(!is_numeric($name)){
1196               if(in_array($name,array("dn","count"))) continue;
1197               if(!isset($data[$name])){
1198                 $data[$name] = array();
1199               }
1200             }
1201           }
1202           $ret = $this->modify($data);
1203     
1204         }else{
1205     
1206           /* The destination entry doesn't exists, create it */
1207           $ret = $this->add($data);
1208         }
1210       } else {
1211         
1212         /* Keep all vars that aren't touched by this ldif */
1213         $ret = $this->modify($data);
1214       }
1215     }
1217     if (!$this->success()){
1218       msg_dialog::display(_("LDAP error"), msgPool::ldaperror($this->get_error(), $dn, "", get_class()));
1219     }
1221     return($ret);
1222   }
1224   
1225   function importcsv($str)
1226   {
1227     $lines = split("\n",$str);
1228     foreach($lines as $line)
1229     {
1230       /* continue if theres a comment */
1231       if(substr(trim($line),0,1)=="#"){
1232         continue;
1233       }
1235       $line= str_replace ("\t\t","\t",$line);
1236       $line= str_replace ("\t"  ,"," ,$line);
1237       echo $line;
1239       $cells = split(",",$line )  ;
1240       $linet= str_replace ("\t\t",",",$line);
1241       $cells = split("\t",$line);
1242       $count = count($cells);  
1243     }
1245   }
1246   
1247   function get_objectclasses( $force_reload = FALSE)
1248   {
1249     $objectclasses = array();
1250     global $config;
1252     /* Only read schema if it is allowed */
1253     if(isset($config) && preg_match("/config/i",get_class($config))){
1254       if ($config->get_cfg_value("schemaCheck") != "true"){
1255         return($objectclasses);
1256       } 
1257     }
1259     /* Return the cached results. */
1260     if(class_available('session') && session::global_is_set("LDAP_CACHE::get_objectclasses") && !$force_reload){
1261       $objectclasses = session::global_get("LDAP_CACHE::get_objectclasses");
1262       return($objectclasses);
1263     }
1264         
1265           # Get base to look for schema 
1266           $sr = @ldap_read ($this->cid, "", "objectClass=*", array("subschemaSubentry"));
1267           $attr = @ldap_get_entries($this->cid,$sr);
1268           if (!isset($attr[0]['subschemasubentry'][0])){
1269             return array();
1270           }
1271         
1272           /* Get list of objectclasses and fill array */
1273           $nb= $attr[0]['subschemasubentry'][0];
1274           $objectclasses= array();
1275           $sr= ldap_read ($this->cid, $nb, "objectClass=*", array("objectclasses"));
1276           $attrs= ldap_get_entries($this->cid,$sr);
1277           if (!isset($attrs[0])){
1278             return array();
1279           }
1280           foreach ($attrs[0]['objectclasses'] as $val){
1281       if (preg_match('/^[0-9]+$/', $val)){
1282         continue;
1283       }
1284       $name= "OID";
1285       $pattern= split(' ', $val);
1286       $ocname= preg_replace("/^.* NAME\s+\(*\s*'([^']+)'\s*\)*.*$/", '\\1', $val);
1287       $objectclasses[$ocname]= array();
1289       foreach($pattern as $chunk){
1290         switch($chunk){
1292           case '(':
1293                     $value= "";
1294                     break;
1296           case ')': if ($name != ""){
1297                       $objectclasses[$ocname][$name]= $this->value2container($value);
1298                     }
1299                     $name= "";
1300                     $value= "";
1301                     break;
1303           case 'NAME':
1304           case 'DESC':
1305           case 'SUP':
1306           case 'STRUCTURAL':
1307           case 'ABSTRACT':
1308           case 'AUXILIARY':
1309           case 'MUST':
1310           case 'MAY':
1311                     if ($name != ""){
1312                       $objectclasses[$ocname][$name]= $this->value2container($value);
1313                     }
1314                     $name= $chunk;
1315                     $value= "";
1316                     break;
1318           default:  $value.= $chunk." ";
1319         }
1320       }
1322           }
1323     if(class_available("session")){
1324       session::global_set("LDAP_CACHE::get_objectclasses",$objectclasses);
1325     }
1327           return $objectclasses;
1328   }
1331   function value2container($value)
1332   {
1333     /* Set emtpy values to "true" only */
1334     if (preg_match('/^\s*$/', $value)){
1335       return true;
1336     }
1338     /* Remove ' and " if needed */
1339     $value= preg_replace('/^[\'"]/', '', $value);
1340     $value= preg_replace('/[\'"] *$/', '', $value);
1342     /* Convert to array if $ is inside... */
1343     if (preg_match('/\$/', $value)){
1344       $container= preg_split('/\s*\$\s*/', $value);
1345     } else {
1346       $container= chop($value);
1347     }
1349     return ($container);
1350   }
1353   function log($string)
1354   {
1355     if (session::global_is_set('config')){
1356       $cfg = session::global_get('config');
1357       if (isset($cfg->current['LDAPSTATS']) && preg_match('/true/i', $cfg->current['LDAPSTATS'])){
1358         syslog (LOG_INFO, $string);
1359       }
1360     }
1361   }
1363   /* added by Guido Serra aka Zeph <zeph@purotesto.it> */
1364   function getCn($dn){
1365     $simple= split(",", $dn);
1367     foreach($simple as $piece) {
1368       $partial= split("=", $piece);
1370       if($partial[0] == "cn"){
1371         return $partial[1];
1372       }
1373     }
1374   }
1377   function get_naming_contexts($server, $admin= "", $password= "")
1378   {
1379     /* Build LDAP connection */
1380     $ds= ldap_connect ($server);
1381     if (!$ds) {
1382       die ("Can't bind to LDAP. No check possible!");
1383     }
1384     ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
1385     $r= ldap_bind ($ds, $admin, $password);
1387     /* Get base to look for naming contexts */
1388     $sr  = @ldap_read ($ds, "", "objectClass=*", array("+"));
1389     $attr= @ldap_get_entries($ds,$sr);
1391     return ($attr[0]['namingcontexts']);
1392   }
1395   function get_root_dse($server, $admin= "", $password= "")
1396   {
1397     /* Build LDAP connection */
1398     $ds= ldap_connect ($server);
1399     if (!$ds) {
1400       die ("Can't bind to LDAP. No check possible!");
1401     }
1402     ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
1403     $r= ldap_bind ($ds, $admin, $password);
1405     /* Get base to look for naming contexts */
1406     $sr  = @ldap_read ($ds, "", "objectClass=*", array("+"));
1407     $attr= @ldap_get_entries($ds,$sr);
1408    
1409     /* Return empty array, if nothing was set */
1410     if (!isset($attr[0])){
1411       return array();
1412     }
1414     /* Rework array... */
1415     $result= array();
1416     for ($i= 0; $i<$attr[0]['count']; $i++){
1417       $result[$attr[0][$i]]= $attr[0][$attr[0][$i]];
1418       unset($result[$attr[0][$i]]['count']);
1419     }
1421     return ($result);
1422   }
1425 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
1426 ?>