Code

Yes. Really makes sense. Thanks for reporting.
[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("*"))
280   {
281     if($this->hascon){
282       if ($this->reconnect) $this->connect();
284       $this->clearResult($srp);
285       $filter = "(objectclass=*)";
286       $this->sr[$srp] = @ldap_read($this->cid, LDAP::fix($dn), $filter,$attrs);
287       $this->error = @ldap_error($this->cid);
288       $this->resetResult($srp);
289       $this->hasres[$srp]=true;
290       return($this->sr[$srp]);
291     }else{
292       $this->error = "Could not connect to LDAP server";
293       return("");
294     }
295   }
297   function object_match_filter($dn,$filter)
298   {
299     if($this->hascon){
300       if ($this->reconnect) $this->connect();
301       $res =  @ldap_read($this->cid, LDAP::fix($dn), $filter, array("objectClass"));
302       $rv =   @ldap_count_entries($this->cid, $res);
303       return($rv);
304     }else{
305       $this->error = "Could not connect to LDAP server";
306       return(FALSE);
307     }
308   }
310   function set_size_limit($size)
311   {
312     /* Ignore zero settings */
313     if ($size == 0){
314       @ldap_set_option($this->cid, LDAP_OPT_SIZELIMIT, 10000000);
315     }
316     if($this->hascon){
317       @ldap_set_option($this->cid, LDAP_OPT_SIZELIMIT, $size);
318     } else {
319       $this->error = "Could not connect to LDAP server";
320     }
321   }
323   function fetch($srp)
324   {
325     $att= array();
326     if($this->hascon){
327       if($this->hasres[$srp]){
328         if ($this->start[$srp] == 0)
329         {
330           if ($this->sr[$srp]){
331             $this->start[$srp] = 1;
332             $this->re[$srp]= @ldap_first_entry($this->cid, $this->sr[$srp]);
333           } else {
334             return array();
335           }
336         } else {
337           $this->re[$srp]= @ldap_next_entry($this->cid, $this->re[$srp]);
338         }
339         if ($this->re[$srp])
340         {
341           $att= @ldap_get_attributes($this->cid, $this->re[$srp]);
342           $att['dn']= trim(LDAP::convert(@ldap_get_dn($this->cid, $this->re[$srp])));
343         }
344         $this->error = @ldap_error($this->cid);
345         if (!isset($att)){
346           $att= array();
347         }
348         return($att);
349       }else{
350         $this->error = "Perform a fetch with no search";
351         return("");
352       }
353     }else{
354       $this->error = "Could not connect to LDAP server";
355       return("");
356     }
357   }
359   function resetResult($srp)
360   {
361     $this->start[$srp] = 0;
362   }
364   function clearResult($srp)
365   {
366     if($this->hasres[$srp]){
367       $this->hasres[$srp] = false;
368       @ldap_free_result($this->sr[$srp]);
369     }
370   }
372   function getDN($srp)
373   {
374     if($this->hascon){
375       if($this->hasres[$srp]){
377         if(!$this->re[$srp])
378           {
379           $this->error = "Perform a Fetch with no valid Result";
380           }
381           else
382           {
383           $rv = @ldap_get_dn($this->cid, $this->re[$srp]);
384         
385           $this->error = @ldap_error($this->cid);
386           return(trim(LDAP::convert($rv)));
387            }
388       }else{
389         $this->error = "Perform a Fetch with no Search";
390         return("");
391       }
392     }else{
393       $this->error = "Could not connect to LDAP server";
394       return("");
395     }
396   }
398   function count($srp)
399   {
400     if($this->hascon){
401       if($this->hasres[$srp]){
402         $rv = @ldap_count_entries($this->cid, $this->sr[$srp]);
403         $this->error = @ldap_error($this->cid);
404         return($rv);
405       }else{
406         $this->error = "Perform a Fetch with no Search";
407         return("");
408       }
409     }else{
410       $this->error = "Could not connect to LDAP server";
411       return("");
412     }
413   }
415   function rm($attrs = "", $dn = "")
416   {
417     if($this->hascon){
418       if ($this->reconnect) $this->connect();
419       if ($dn == "")
420         $dn = $this->basedn;
422       $r = ldap_mod_del($this->cid, LDAP::fix($dn), $attrs);
423       $this->error = @ldap_error($this->cid);
424       return($r);
425     }else{
426       $this->error = "Could not connect to LDAP server";
427       return("");
428     }
429   }
431   function mod_add($attrs = "", $dn = "")
432   {
433     if($this->hascon){
434       if ($this->reconnect) $this->connect();
435       if ($dn == "")
436         $dn = $this->basedn;
438       $r = @ldap_mod_add($this->cid, LDAP::fix($dn), $attrs);
439       $this->error = @ldap_error($this->cid);
440       return($r);
441     }else{
442       $this->error = "Could not connect to LDAP server";
443       return("");
444     }
445   }
447   function rename($attrs, $dn = "")
448   {
449     if($this->hascon){
450       if ($this->reconnect) $this->connect();
451       if ($dn == "")
452         $dn = $this->basedn;
454       $r = @ldap_mod_replace($this->cid, LDAP::fix($dn), $attrs);
455       $this->error = @ldap_error($this->cid);
456       return($r);
457     }else{
458       $this->error = "Could not connect to LDAP server";
459       return("");
460     }
461   }
463   function rmdir($deletedn)
464   {
465     if($this->hascon){
466       if ($this->reconnect) $this->connect();
467       $r = @ldap_delete($this->cid, LDAP::fix($deletedn));
468       $this->error = @ldap_error($this->cid);
469       return($r ? $r : 0);
470     }else{
471       $this->error = "Could not connect to LDAP server";
472       return("");
473     }
474   }
477   /*! \brief Move the given Ldap entry from $source to $dest
478       @param  String  $source The source dn.
479       @param  String  $dest   The destination dn.
480       @return Boolean TRUE on success else FALSE.
481    */
482   function rename_dn($source,$dest)
483   {
484     /* Check if source and destination are the same entry */
485     if(strtolower($source) == strtolower($dest)){
486       trigger_error("Source and destination can't be the same entry.");
487       $this->error = "Source and destination can't be the same entry.";
488       return(FALSE);
489     }
491     /* Check if destination entry exists */    
492     if($this->dn_exists($dest)){
493       trigger_error("Destination '$dest' already exists.");
494       $this->error = "Destination '$dest' already exists.";
495       return(FALSE);
496     }
498     /* Extract the name and the parent part out ouf source dn.
499         e.g.  cn=herbert,ou=department,dc=... 
500          parent   =>  ou=department,dc=...
501          dest_rdn =>  cn=herbert
502      */
503     $parent   = preg_replace("/^[^,]+,/","", $dest);
504     $dest_rdn = preg_replace("/,.*$/","",$dest);
506     if($this->hascon){
507       if ($this->reconnect) $this->connect();
508       $r= ldap_rename($this->cid,@LDAP::fix($source), @LDAP::fix($dest_rdn),@LDAP::fix($parent),TRUE); 
509       $this->error = ldap_error($this->cid);
511       /* Check if destination dn exists, if not the 
512           server may not support this operation */
513       $r &= is_resource($this->dn_exists($dest));
514       return($r);
515     }else{
516       $this->error = "Could not connect to LDAP server";
517       return(FALSE);
518     }
519   }
522   /**
523   *  Function rmdir_recursive
524   *
525   *  Description: Based in recursive_remove, adding two thing: full subtree remove, and delete own node.
526   *  Parameters:  The dn to delete
527   *  GiveBack:    True on sucessfull , 0 in error, and "" when we don't get a ldap conection
528   *
529   */
530   function rmdir_recursive($srp, $deletedn)
531   {
532     if($this->hascon){
533       if ($this->reconnect) $this->connect();
534       $delarray= array();
535         
536       /* Get sorted list of dn's to delete */
537       $this->ls ($srp, "(objectClass=*)",$deletedn);
538       while ($this->fetch($srp)){
539         $deldn= $this->getDN($srp);
540         $delarray[$deldn]= strlen($deldn);
541       }
542       arsort ($delarray);
543       reset ($delarray);
545       /* Really Delete ALL dn's in subtree */
546       foreach ($delarray as $key => $value){
547         $this->rmdir_recursive($srp, $key);
548       }
549       
550       /* Finally Delete own Node */
551       $r = @ldap_delete($this->cid, LDAP::fix($deletedn));
552       $this->error = @ldap_error($this->cid);
553       return($r ? $r : 0);
554     }else{
555       $this->error = "Could not connect to LDAP server";
556       return("");
557     }
558   }
560   function makeReadableErrors($error,$attrs)
561   { 
562     global $config;
564     if($this->success()) return("");
566     $str = "";
567     if(preg_match("/^objectClass: value #([0-9]*) invalid per syntax$/", $this->get_additional_error())){
568       $oc = preg_replace("/^objectClass: value #([0-9]*) invalid per syntax$/","\\1", $this->get_additional_error());
569       if(isset($attrs['objectClass'][$oc])){
570         $str.= " - <b>objectClass: ".$attrs['objectClass'][$oc]."</b>";
571       }
572     }
573     if($error == "Undefined attribute type"){
574       $str = " - <b>attribute: ".preg_replace("/:.*$/","",$this->get_additional_error())."</b>";
575     } 
577     @DEBUG(DEBUG_LDAP,__LINE__,__FUNCTION__,__FILE__,$attrs,"Erroneous data");
579     return($str);
580   }
582   function modify($attrs)
583   {
584     if(count($attrs) == 0){
585       return (0);
586     }
587     if($this->hascon){
588       if ($this->reconnect) $this->connect();
589       $r = @ldap_modify($this->cid, LDAP::fix($this->basedn), $attrs);
590       $this->error = @ldap_error($this->cid);
591       if(!$this->success()){
592         $this->error.= $this->makeReadableErrors($this->error,$attrs);
593       }
594       return($r ? $r : 0);
595     }else{
596       $this->error = "Could not connect to LDAP server";
597       return("");
598     }
599   }
601   function add($attrs)
602   {
603     if($this->hascon){
604       if ($this->reconnect) $this->connect();
605       $r = @ldap_add($this->cid, LDAP::fix($this->basedn), $attrs);
606       $this->error = @ldap_error($this->cid);
607       if(!$this->success()){
608         $this->error.= $this->makeReadableErrors($this->error,$attrs);
609       }
610       return($r ? $r : 0);
611     }else{
612       $this->error = "Could not connect to LDAP server";
613       return("");
614     }
615   }
617   function create_missing_trees($srp, $target)
618   {
619     global $config;
621     $real_path= substr($target, 0, strlen($target) - strlen($this->basedn) -1 );
623     if ($target == $this->basedn){
624       $l= array("dummy");
625     } else {
626       $l= array_reverse(gosa_ldap_explode_dn($real_path));
627     }
628     unset($l['count']);
629     $cdn= $this->basedn;
630     $tag= "";
632     /* Load schema if available... */
633     $classes= $this->get_objectclasses();
635     foreach ($l as $part){
636       if ($part != "dummy"){
637         $cdn= "$part,$cdn";
638       }
640       /* Ignore referrals */
641       $found= false;
642       foreach($this->referrals as $ref){
643         $base= preg_replace('!^[^:]+://[^/]+/([^?]+).*$!', '\\1', $ref['URI']);
644         if ($base == $cdn){
645           $found= true;
646           break;
647         }
648       }
649       if ($found){
650         continue;
651       }
653       $this->cat ($srp, $cdn);
654       $attrs= $this->fetch($srp);
656       /* Create missing entry? */
657       if (count ($attrs)){
658       
659         /* Catch the tag - if present */
660         if (isset($attrs['gosaUnitTag'][0])){
661           $tag= $attrs['gosaUnitTag'][0];
662         }
664       } else {
665         $type= preg_replace('/^([^=]+)=.*$/', '\\1', $cdn);
666         $param= preg_replace('/^[^=]+=([^,]+).*$/', '\\1', $cdn);
668         $na= array();
670         /* Automatic or traditional? */
671         if(count($classes)){
673           /* Get name of first matching objectClass */
674           $ocname= "";
675           foreach($classes as $class){
676             if (isset($class['MUST']) && $class['MUST'] == "$type"){
678               /* Look for first classes that is structural... */
679               if (isset($class['STRUCTURAL'])){
680                 $ocname= $class['NAME'];
681                 break;
682               }
684               /* Look for classes that are auxiliary... */
685               if (isset($class['AUXILIARY'])){
686                 $ocname= $class['NAME'];
687               }
688             }
689           }
691           /* Bail out, if we've nothing to do... */
692           if ($ocname == ""){
693             msg_dialog::display(_("Internal error"), sprintf(_("Cannot automatically create subtrees with RDN '%s': no object class found!"),$type), FATAL_ERROR_DIALOG);
694             exit();
695           }
697           /* Assemble_entry */
698           if ($tag != ""){
699             $na['objectClass']= array($ocname, "gosaAdministrativeUnitTag");
700             $na["gosaUnitTag"]= $tag;
701           } else {
702             $na['objectClass']= array($ocname);
703           }
704           if (isset($classes[$ocname]['AUXILIARY'])){
705             $na['objectClass'][]= $classes[$ocname]['SUP'];
706           }
707           if ($type == "dc"){
708             /* This is bad actually, but - tell me a better way? */
709             $na['objectClass'][]= 'locality';
710           }
711           $na[$type]= $param;
712           if (is_array($classes[$ocname]['MUST'])){
713             foreach($classes[$ocname]['MUST'] as $attr){
714               $na[$attr]= "filled";
715             }
716           }
718         } else {
720           /* Use alternative add... */
721           switch ($type){
722             case 'ou':
723               if ($tag != ""){
724                 $na["objectClass"]= array("organizationalUnit", "gosaAdministrativeUnitTag");
725                 $na["gosaUnitTag"]= $tag;
726               } else {
727                 $na["objectClass"]= "organizationalUnit";
728               }
729               $na["ou"]= $param;
730               break;
731             case 'dc':
732               if ($tag != ""){
733                 $na["objectClass"]= array("dcObject", "top", "locality", "gosaAdministrativeUnitTag");
734                 $na["gosaUnitTag"]= $tag;
735               } else {
736                 $na["objectClass"]= array("dcObject", "top", "locality");
737               }
738               $na["dc"]= $param;
739               break;
740             default:
741               msg_dialog::display(_("Internal error"), sprintf(_("Cannot automatically create subtrees with RDN '%s': not supported"),$type), FATAL_ERROR_DIALOG);
742               exit();
743           }
745         }
746         $this->cd($cdn);
747         $this->add($na);
748     
749         if (!$this->success()){
751           print_a(array($cdn,$na));
753           msg_dialog::display(_("LDAP error"), msgPool::ldaperror($this->get_error(), $cdn, LDAP_ADD, get_class()));
754           return FALSE;
755         }
756       }
757     }
759     return TRUE;
760   }
763   function recursive_remove($srp)
764   {
765     $delarray= array();
767     /* Get sorted list of dn's to delete */
768     $this->search ($srp, "(objectClass=*)");
769     while ($this->fetch($srp)){
770       $deldn= $this->getDN($srp);
771       $delarray[$deldn]= strlen($deldn);
772     }
773     arsort ($delarray);
774     reset ($delarray);
776     /* Delete all dn's in subtree */
777     foreach ($delarray as $key => $value){
778       $this->rmdir($key);
779     }
780   }
783   function get_attribute($dn, $name,$r_array=0)
784   {
785     $data= "";
786     if ($this->reconnect) $this->connect();
787     $sr= @ldap_read($this->cid, LDAP::fix($dn), "objectClass=*", array("$name"));
789     /* fill data from LDAP */
790     if ($sr) {
791       $ei= @ldap_first_entry($this->cid, $sr);
792       if ($ei) {
793         if ($info= @ldap_get_values_len($this->cid, $ei, "$name")){
794           $data= $info[0];
795         }
796       }
797     }
798     if($r_array==0) {
799       return ($data);
800     } else {
801       return ($info);
802     }
803   }
804  
807   function get_additional_error()
808   {
809     $error= "";
810     @ldap_get_option ($this->cid, LDAP_OPT_ERROR_STRING, $error);
811     return ($error);
812   }
815   function success()
816   {
817     return (preg_match('/Success/i', $this->error));
818   }
821   function get_error()
822   {
823     if ($this->error == 'Success'){
824       return $this->error;
825     } else {
826       $adderror= $this->get_additional_error();
827       if ($adderror != ""){
828         $error= $this->error." (".$this->get_additional_error().", ".sprintf(_("while operating on '%s' using LDAP server '%s'"), $this->basedn, $this->hostname).")";
829       } else {
830         $error= $this->error." (".sprintf(_("while operating on LDAP server %s"), $this->hostname).")";
831       }
832       return $error;
833     }
834   }
836   function get_credentials($url, $referrals= NULL)
837   {
838     $ret= array();
839     $url= preg_replace('!\?\?.*$!', '', $url);
840     $server= preg_replace('!^([^:]+://[^/]+)/.*$!', '\\1', $url);
842     if ($referrals === NULL){
843       $referrals= $this->referrals;
844     }
846     if (isset($referrals[$server])){
847       return ($referrals[$server]);
848     } else {
849       $ret['ADMINDN']= LDAP::fix($this->binddn);
850       $ret['ADMINPASSWORD']= $this->bindpw;
851     }
853     return ($ret);
854   }
857   function gen_ldif ($srp, $dn, $filter= "(objectClass=*)", $attributes= array('*'), $recursive= TRUE)
858   {
859     $display= "";
861     if ($recursive){
862       $this->cd($dn);
863       $this->ls($srp, $filter,$dn, array('dn','objectClass'));
864       $deps = array();
866       $display .= $this->gen_one_entry($dn)."\n";
868       while ($attrs= $this->fetch($srp)){
869         $deps[] = $attrs['dn'];
870       }
871       foreach($deps as $dn){
872         $display .= $this->gen_ldif($srp, $dn, $filter,$attributes,$recursive);
873       }
874     } else {
875       $display.= $this->gen_one_entry($dn);
876     }
877     return ($display);
878   }
881   function gen_xls ($srp, $dn, $filter= "(objectClass=*)", $attributes= array('*'), $recursive= TRUE,$r_array=0)
882   {
883     $display= array();
885       $this->cd($dn);
886       $this->search($srp, "$filter");
888       $i=0;
889       while ($attrs= $this->fetch($srp)){
890         $j=0;
892         foreach ($attributes as $at){
893           $display[$i][$j]= $this->get_attribute($attrs['dn'], $at,$r_array);
894           $j++;
895         }
897         $i++;
898       }
900     return ($display);
901   }
904   function gen_one_entry($dn, $filter= "(objectClass=*)" , $name= array("*"))
905   {
906     $ret = "";
907     $data = "";
908     if($this->reconnect){
909       $this->connect();
910     }
912     /* Searching Ldap Tree */
913     $sr= @ldap_read($this->cid, LDAP::fix($dn), $filter, $name);
915     /* Get the first entry */   
916     $entry= @ldap_first_entry($this->cid, $sr);
918     /* Get all attributes related to that Objekt */
919     $atts = array();
920     
921     /* Assemble dn */
922     $atts[0]['name']  = "dn";
923     $atts[0]['value'] = array('count' => 1, 0 => $dn);
925     /* Reset index */
926     $i = 1 ; 
927   $identifier = array();
928     $attribute= @ldap_first_attribute($this->cid,$entry,$identifier);
929     while ($attribute) {
930       $i++;
931       $atts[$i]['name']  = $attribute;
932       $atts[$i]['value'] = @ldap_get_values_len($this->cid, $entry, "$attribute");
934       /* Next one */
935       $attribute= @ldap_next_attribute($this->cid,$entry,$identifier);
936     }
938     foreach($atts as $at)
939     {
940       for ($i= 0; $i<$at['value']['count']; $i++){
942         /* Check if we must encode the data */
943         if(!preg_match('/^[a-z0-9+@#.=, \/ -]+$/i', $at['value'][$i])) {
944           $ret .= $at['name'].":: ".base64_encode($at['value'][$i])."\n";
945         } else {
946           $ret .= $at['name'].": ".$at['value'][$i]."\n";
947         }
948       }
949     }
951     return($ret);
952   }
955   function dn_exists($dn)
956   {
957     return @ldap_list($this->cid, LDAP::fix($dn), "(objectClass=*)", array("objectClass"));
958   }
959   
962   /*  This funktion imports ldifs 
963         
964       If DeleteOldEntries is true, the destination entry will be deleted first. 
965       If JustModify is true the destination entry will only be touched by the attributes specified in the ldif.
966       if JustMofify id false the destination dn will be overwritten by the new ldif. 
967     */
969   function import_complete_ldif($srp, $str_attr,$error,$JustModify,$DeleteOldEntries)
970   {
971     if($this->reconnect) $this->connect();
973     /* First we have to splitt the string ito detect empty lines
974        An empty line indicates an new Entry */
975     $entries = split("\n",$str_attr);
977     $data = "";
978     $cnt = 0; 
979     $current_line = 0;
981     /* FIX ldif */
982     $last = "";
983     $tmp  = "";
984     $i = 0;
985     foreach($entries as $entry){
986       if(preg_match("/^ /",$entry)){
987         $tmp[$i] .= trim($entry);
988       }else{
989         $i ++;
990         $tmp[$i] = trim($entry);
991       }
992     }
994     /* Every single line ... */
995     foreach($tmp as $entry) {
996       $current_line ++;
998       /* Removing Spaces to .. 
999          .. test if a new entry begins */
1000       $tmp  = str_replace(" ","",$data );
1002       /* .. prevent empty lines in an entry */
1003       $tmp2 = str_replace(" ","",$entry);
1005       /* If the Block ends (Empty Line) */
1006       if((empty($entry))&&(!empty($tmp))) {
1007         /* Add collected lines as a complete block */
1008         $all[$cnt] = $data;
1009         $cnt ++;
1010         $data ="";
1011       } else {
1013         /* Append lines ... */
1014         if(!empty($tmp2)) {
1015           /* check if we need base64_decode for this line */
1016           if(ereg("::",$tmp2))
1017           {
1018             $encoded = split("::",$entry);
1019             $attr  = trim($encoded[0]);
1020             $value = base64_decode(trim($encoded[1]));
1021             /* Add linenumber */
1022             $data .= $current_line."#".base64_encode($attr.":".$value)."\n";
1023           }
1024           else
1025           {
1026             /* Add Linenumber */ 
1027             $data .= $current_line."#".base64_encode($entry)."\n";
1028           }
1029         }
1030       }
1031     }
1033     /* The Data we collected is not in the array all[];
1034        For example the Data is stored like this..
1036        all[0] = "1#dn : .... \n 
1037        2#ObjectType: person \n ...."
1038        
1039        Now we check every insertblock and try to insert */
1040     foreach ( $all as $single) {
1041       $lineone = split("\n",$single);  
1042       $ndn = split("#", $lineone[0]);
1043       $line = base64_decode($ndn[1]);
1045       $dnn = split (":",$line,2);
1046       $current_line = $ndn[0];
1047       $dn    = $dnn[0];
1048       $value = $dnn[1];
1050       /* Every block must begin with a dn */
1051       if($dn != "dn") {
1052         $error= sprintf(_("This is not a valid DN: '%s'. A block for import should begin with 'dn: ...' in line %s"), $line, $current_line);
1053         return -2;  
1054       }
1056       /* Should we use Modify instead of Add */
1057       $usemodify= false;
1059       /* Delete before insert */
1060       $usermdir= false;
1061     
1062       /* The dn address already exists, Don't delete destination entry, overwrite it */
1063       if (($this->dn_exists($value))&&((!$JustModify)&&(!$DeleteOldEntries))) {
1065         $usermdir = $usemodify = false;
1067       /* Delete old entry first, then add new */
1068       } elseif(($this->dn_exists($value))&&($DeleteOldEntries)){
1070         /* Delete first, then add */
1071         $usermdir = true;        
1073       } elseif(($this->dn_exists($value))&&($JustModify)) {
1074         
1075         /* Modify instead of Add */
1076         $usemodify = true;
1077       }
1078      
1079       /* If we can't Import, return with a file error */
1080       if(!$this->import_single_entry($srp, $single,$usemodify,$usermdir) ) {
1081         $error= sprintf(_("Error while importing dn: '%s', please check your LDIF from line %s on!"), $line,
1082                         $current_line);
1083         return UNKNOWN_TOKEN_IN_LDIF_FILE;      }
1084     }
1086     return (INSERT_OK);
1087   }
1090   /* Imports a single entry 
1091       If $delete is true;  The old entry will be deleted if it exists.
1092       if $modify is true;  All variables that are not touched by the new ldif will be kept.
1093       if $modify is false; The new ldif overwrites the old entry, and all untouched attributes get lost.
1094   */
1095   function import_single_entry($srp, $str_attr,$modify,$delete)
1096   {
1097     global $config;
1099     if(!$config){
1100       trigger_error("Can't import ldif, can't read config object.");
1101     }
1102   
1104     if($this->reconnect) $this->connect();
1106     $ret = false;
1107     $rows= split("\n",$str_attr);
1108     $data= false;
1110     foreach($rows as $row) {
1111       
1112       /* Check if we use Linenumbers (when import_complete_ldif is called we use
1113          Linenumbers) Linenumbers are use like this 123#attribute : value */
1114       if(!empty($row)) {
1115         if(strpos($row,"#")!=FALSE) {
1117           /* We are using line numbers 
1118              Because there is a # before a : */
1119           $tmp1= split("#",$row);
1120           $current_line= $tmp1[0];
1121           $row= base64_decode($tmp1[1]);
1122         }
1124         /* Split the line into  attribute  and value */
1125         $attr   = split(":", $row,2);
1126         $attr[0]= trim($attr[0]);  /* attribute */
1127         $attr[1]= $attr[1];  /* value */
1129         /* Check :: was used to indicate base64_encoded strings */
1130         if($attr[1][0] == ":"){
1131           $attr[1]=trim(preg_replace("/^:/","",$attr[1]));
1132           $attr[1]=base64_decode($attr[1]);
1133         }
1135         $attr[1] = trim($attr[1]);
1137         /* Check for attributes that are used more than once */
1138         if(!isset($data[$attr[0]])) {
1139           $data[$attr[0]]=$attr[1];
1140         } else {
1141           $tmp = $data[$attr[0]];
1143           if(!is_array($tmp)) {
1144             $new[0]=$tmp;
1145             $new[1]=$attr[1];
1146             $datas[$attr[0]]['count']=1;             
1147             $data[$attr[0]]=$new;
1148           } else {
1149             $cnt = $datas[$attr[0]]['count'];           
1150             $cnt ++;
1151             $data[$attr[0]][$cnt]=$attr[1];
1152             $datas[$attr[0]]['count'] = $cnt;
1153           }
1154         }
1155       }
1156     }
1158     /* If dn is an index of data, we should try to insert the data */
1159     if(isset($data['dn'])) {
1161       /* Fix dn */
1162       $tmp = gosa_ldap_explode_dn($data['dn']);
1163       unset($tmp['count']);
1164       $newdn ="";
1165       foreach($tmp as $tm){
1166         $newdn.= trim($tm).",";
1167       }
1168       $newdn = preg_replace("/,$/","",$newdn);
1169       $data['dn'] = $newdn;
1170    
1171       /* Creating Entry */
1172       $this->cd($data['dn']);
1174       /* Delete existing entry */
1175       if($delete){
1176         $this->rmdir_recursive($srp, $data['dn']);
1177       }
1178      
1179       /* Create missing trees */
1180       $this->cd ($this->basedn);
1181       $this->cd($config->current['BASE']);
1182       $this->create_missing_trees($srp, preg_replace("/^[^,]+,/","",$data['dn']));
1183       $this->cd($data['dn']);
1185       $dn = $data['dn'];
1186       unset($data['dn']);
1187       
1188       if(!$modify){
1190         $this->cat($srp, $dn);
1191         if($this->count($srp)){
1192         
1193           /* The destination entry exists, overwrite it with the new entry */
1194           $attrs = $this->fetch($srp);
1195           foreach($attrs as $name => $value ){
1196             if(!is_numeric($name)){
1197               if(in_array($name,array("dn","count"))) continue;
1198               if(!isset($data[$name])){
1199                 $data[$name] = array();
1200               }
1201             }
1202           }
1203           $ret = $this->modify($data);
1204     
1205         }else{
1206     
1207           /* The destination entry doesn't exists, create it */
1208           $ret = $this->add($data);
1209         }
1211       } else {
1212         
1213         /* Keep all vars that aren't touched by this ldif */
1214         $ret = $this->modify($data);
1215       }
1216     }
1218     if (!$this->success()){
1219       msg_dialog::display(_("LDAP error"), msgPool::ldaperror($this->get_error(), $dn, "", get_class()));
1220     }
1222     return($ret);
1223   }
1225   
1226   function importcsv($str)
1227   {
1228     $lines = split("\n",$str);
1229     foreach($lines as $line)
1230     {
1231       /* continue if theres a comment */
1232       if(substr(trim($line),0,1)=="#"){
1233         continue;
1234       }
1236       $line= str_replace ("\t\t","\t",$line);
1237       $line= str_replace ("\t"  ,"," ,$line);
1238       echo $line;
1240       $cells = split(",",$line )  ;
1241       $linet= str_replace ("\t\t",",",$line);
1242       $cells = split("\t",$line);
1243       $count = count($cells);  
1244     }
1246   }
1247   
1248   function get_objectclasses( $force_reload = FALSE)
1249   {
1250     $objectclasses = array();
1251     global $config;
1253     /* Only read schema if it is allowed */
1254     if(isset($config) && preg_match("/config/i",get_class($config))){
1255       if ($config->get_cfg_value("schemaCheck") != "true"){
1256         return($objectclasses);
1257       } 
1258     }
1260     /* Return the cached results. */
1261     if(class_available('session') && session::global_is_set("LDAP_CACHE::get_objectclasses") && !$force_reload){
1262       $objectclasses = session::global_get("LDAP_CACHE::get_objectclasses");
1263       return($objectclasses);
1264     }
1265         
1266           # Get base to look for schema 
1267           $sr = @ldap_read ($this->cid, "", "objectClass=*", array("subschemaSubentry"));
1268           $attr = @ldap_get_entries($this->cid,$sr);
1269           if (!isset($attr[0]['subschemasubentry'][0])){
1270             return array();
1271           }
1272         
1273           /* Get list of objectclasses and fill array */
1274           $nb= $attr[0]['subschemasubentry'][0];
1275           $objectclasses= array();
1276           $sr= ldap_read ($this->cid, $nb, "objectClass=*", array("objectclasses"));
1277           $attrs= ldap_get_entries($this->cid,$sr);
1278           if (!isset($attrs[0])){
1279             return array();
1280           }
1281           foreach ($attrs[0]['objectclasses'] as $val){
1282       if (preg_match('/^[0-9]+$/', $val)){
1283         continue;
1284       }
1285       $name= "OID";
1286       $pattern= split(' ', $val);
1287       $ocname= preg_replace("/^.* NAME\s+\(*\s*'([^']+)'\s*\)*.*$/", '\\1', $val);
1288       $objectclasses[$ocname]= array();
1290       foreach($pattern as $chunk){
1291         switch($chunk){
1293           case '(':
1294                     $value= "";
1295                     break;
1297           case ')': if ($name != ""){
1298                       $objectclasses[$ocname][$name]= $this->value2container($value);
1299                     }
1300                     $name= "";
1301                     $value= "";
1302                     break;
1304           case 'NAME':
1305           case 'DESC':
1306           case 'SUP':
1307           case 'STRUCTURAL':
1308           case 'ABSTRACT':
1309           case 'AUXILIARY':
1310           case 'MUST':
1311           case 'MAY':
1312                     if ($name != ""){
1313                       $objectclasses[$ocname][$name]= $this->value2container($value);
1314                     }
1315                     $name= $chunk;
1316                     $value= "";
1317                     break;
1319           default:  $value.= $chunk." ";
1320         }
1321       }
1323           }
1324     if(class_available("session")){
1325       session::global_set("LDAP_CACHE::get_objectclasses",$objectclasses);
1326     }
1328           return $objectclasses;
1329   }
1332   function value2container($value)
1333   {
1334     /* Set emtpy values to "true" only */
1335     if (preg_match('/^\s*$/', $value)){
1336       return true;
1337     }
1339     /* Remove ' and " if needed */
1340     $value= preg_replace('/^[\'"]/', '', $value);
1341     $value= preg_replace('/[\'"] *$/', '', $value);
1343     /* Convert to array if $ is inside... */
1344     if (preg_match('/\$/', $value)){
1345       $container= preg_split('/\s*\$\s*/', $value);
1346     } else {
1347       $container= chop($value);
1348     }
1350     return ($container);
1351   }
1354   function log($string)
1355   {
1356     if (session::global_is_set('config')){
1357       $cfg = session::global_get('config');
1358       if (isset($cfg->current['LDAPSTATS']) && preg_match('/true/i', $cfg->current['LDAPSTATS'])){
1359         syslog (LOG_INFO, $string);
1360       }
1361     }
1362   }
1364   /* added by Guido Serra aka Zeph <zeph@purotesto.it> */
1365   function getCn($dn){
1366     $simple= split(",", $dn);
1368     foreach($simple as $piece) {
1369       $partial= split("=", $piece);
1371       if($partial[0] == "cn"){
1372         return $partial[1];
1373       }
1374     }
1375   }
1378   function get_naming_contexts($server, $admin= "", $password= "")
1379   {
1380     /* Build LDAP connection */
1381     $ds= ldap_connect ($server);
1382     if (!$ds) {
1383       die ("Can't bind to LDAP. No check possible!");
1384     }
1385     ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
1386     $r= ldap_bind ($ds, $admin, $password);
1388     /* Get base to look for naming contexts */
1389     $sr  = @ldap_read ($ds, "", "objectClass=*", array("+"));
1390     $attr= @ldap_get_entries($ds,$sr);
1392     return ($attr[0]['namingcontexts']);
1393   }
1396   function get_root_dse($server, $admin= "", $password= "")
1397   {
1398     /* Build LDAP connection */
1399     $ds= ldap_connect ($server);
1400     if (!$ds) {
1401       die ("Can't bind to LDAP. No check possible!");
1402     }
1403     ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
1404     $r= ldap_bind ($ds, $admin, $password);
1406     /* Get base to look for naming contexts */
1407     $sr  = @ldap_read ($ds, "", "objectClass=*", array("+"));
1408     $attr= @ldap_get_entries($ds,$sr);
1409    
1410     /* Return empty array, if nothing was set */
1411     if (!isset($attr[0])){
1412       return array();
1413     }
1415     /* Rework array... */
1416     $result= array();
1417     for ($i= 0; $i<$attr[0]['count']; $i++){
1418       $result[$attr[0][$i]]= $attr[0][$attr[0][$i]];
1419       unset($result[$attr[0][$i]]['count']);
1420     }
1422     return ($result);
1423   }
1426 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
1427 ?>