Code

Added base display to lists. Make it react on bases.
[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   static function convert($dn)
92   {
93     if (SPECIALS_OVERRIDE == TRUE){
94       $tmp= preg_replace(array("/\\\\,/", "/\\\\2C/", "/\(/", "/\)/", "/\//"),
95           array("\001CO", "\001CO", "\001OB", "\001CB", "\001SL"),
96           $dn);
97       return (preg_replace('/,\s+/', ',', $tmp));
98     } else {
99       return ($dn);
100     }
101   }
104   /* Function to fix all problematic characters inside a DN by replacing \001XX
105      codes to their original values. See "convert" for mor information. 
106      ',' characters are always expanded to \, (not \2C), since all tested LDAP
107      servers seem to take it the correct way.                                  */
108   static function fix($dn)
109   {
110     if (SPECIALS_OVERRIDE == TRUE){
111       return (preg_replace(array("/\001CO/", "/\001OB/", "/\001CB/", "/\001SL/"),
112             array("\,", "(", ")", "/"),
113             $dn));
114     } else {
115       return ($dn);
116     }
117   }
119   /* Function to fix problematic characters in DN's that are used for search
120      requests. I.e. member=....                                               */
121   static function prepare4filter($dn)
122   {
123     return normalizeLdap(str_replace('\\\\', '\\\\\\', LDAP::fix($dn)));
124   }
127   function connect()
128   {
129     $this->hascon=false;
130     $this->reconnect=false;
131     if ($this->cid= @ldap_connect($this->hostname)) {
132       @ldap_set_option($this->cid, LDAP_OPT_PROTOCOL_VERSION, 3);
133       if (function_exists("ldap_set_rebind_proc") && $this->follow_referral) {
134         @ldap_set_option($this->cid, LDAP_OPT_REFERRALS, 1);
135         @ldap_set_rebind_proc($this->cid, array(&$this, "rebind"));
136       }
137       if (function_exists("ldap_start_tls") && $this->tls){
138         @ldap_start_tls($this->cid);
139       }
141       $this->error = "No Error";
142       if ($bid = @ldap_bind($this->cid, LDAP::fix($this->binddn), $this->bindpw)) {
143         $this->error = "Success";
144         $this->hascon=true;
145       } else {
146         if ($this->reconnect){
147           if ($this->error != "Success"){
148             $this->error = "Could not rebind to " . $this->binddn;
149           }
150         } else {
151           $this->error = "Could not bind to " . $this->binddn;
152         }
153       }
154     } else {
155       $this->error = "Could not connect to LDAP server";
156     }
157   }
159   function rebind($ldap, $referral)
160   {
161     $credentials= $this->get_credentials($referral);
162     if (@ldap_bind($ldap, LDAP::fix($credentials['ADMINDN']), $credentials['ADMINPASSWORD'])) {
163       $this->error = "Success";
164       $this->hascon=true;
165       $this->reconnect= true;
166       return (0);
167     } else {
168       $this->error = "Could not bind to " . $credentials['ADMINDN'];
169       return NULL;
170     }
171   }
173   function reconnect()
174   {
175     if ($this->reconnect){
176       @ldap_unbind($this->cid);
177       $this->cid = NULL;
178     }
179   }
181   function unbind()
182   {
183     @ldap_unbind($this->cid);
184     $this->cid = NULL;
185   }
187   function disconnect()
188   {
189     if($this->hascon){
190       @ldap_close($this->cid);
191       $this->hascon=false;
192     }
193   }
195   function cd($dir)
196   {
197     if ($dir == ".."){
198       $this->basedn = $this->getParentDir();
199     } else {
200       $this->basedn = LDAP::convert($dir);
201     }
202   }
204   function getParentDir($basedn = "")
205   {
206     if ($basedn==""){
207       $basedn = $this->basedn;
208     } else {
209       $basedn = LDAP::convert($this->basedn);
210     }
211     return(ereg_replace("[^,]*[,]*[ ]*(.*)", "\\1", $basedn));
212   }
214   
215   function search($srp, $filter, $attrs= array())
216   {
217     if($this->hascon){
218       if ($this->reconnect) $this->connect();
220       $start = microtime();
221       $this->clearResult($srp);
222       $this->sr[$srp] = @ldap_search($this->cid, LDAP::fix($this->basedn), $filter, $attrs);
223       $this->error = @ldap_error($this->cid);
224       $this->resetResult($srp);
225       $this->hasres[$srp]=true;
226    
227       /* Check if query took longer as specified in max_ldap_query_time */
228       if($this->max_ldap_query_time){
229         $diff = get_MicroTimeDiff($start,microtime());
230         if($diff > $this->max_ldap_query_time){
231           msg_dialog::display(_("Performance warning"), sprintf(_("LDAP performance is poor: last query took about %.2fs!"), $diff), WARNING_DIALOG);
232         }
233       }
235       $this->log("LDAP operation: time=".get_MicroTimeDiff($start,microtime())." operation=search('".LDAP::fix($this->basedn)."', '$filter')");
236       return($this->sr[$srp]);
237     }else{
238       $this->error = "Could not connect to LDAP server";
239       return("");
240     }
241   }
243   function ls($srp, $filter = "(objectclass=*)", $basedn = "",$attrs = array("*"))
244   {
245     if($this->hascon){
246       if ($this->reconnect) $this->connect();
248       $this->clearResult($srp);
249       if ($basedn == "")
250         $basedn = $this->basedn;
251       else
252         $basedn= LDAP::convert($basedn);
253   
254       $start = microtime();
255       $this->sr[$srp] = @ldap_list($this->cid, LDAP::fix($basedn), $filter,$attrs);
256       $this->error = @ldap_error($this->cid);
257       $this->resetResult($srp);
258       $this->hasres[$srp]=true;
260        /* Check if query took longer as specified in max_ldap_query_time */
261       if($this->max_ldap_query_time){
262         $diff = get_MicroTimeDiff($start,microtime());
263         if($diff > $this->max_ldap_query_time){
264           msg_dialog::display(_("Performance warning"), sprintf(_("LDAP performance is poor: last query took about %.2fs!"), $diff), WARNING_DIALOG);
265         }
266       }
268       $this->log("LDAP operation: time=".get_MicroTimeDiff($start,microtime())." operation=ls('".LDAP::fix($basedn)."', '$filter')");
270       return($this->sr[$srp]);
271     }else{
272       $this->error = "Could not connect to LDAP server";
273       return("");
274     }
275   }
277   function cat($srp, $dn,$attrs= array("*"))
278   {
279     if($this->hascon){
280       if ($this->reconnect) $this->connect();
282       $this->clearResult($srp);
283       $filter = "(objectclass=*)";
284       $this->sr[$srp] = @ldap_read($this->cid, LDAP::fix($dn), $filter,$attrs);
285       $this->error = @ldap_error($this->cid);
286       $this->resetResult($srp);
287       $this->hasres[$srp]=true;
288       return($this->sr[$srp]);
289     }else{
290       $this->error = "Could not connect to LDAP server";
291       return("");
292     }
293   }
295   function object_match_filter($dn,$filter)
296   {
297     if($this->hascon){
298       if ($this->reconnect) $this->connect();
299       $res =  @ldap_read($this->cid, LDAP::fix($dn), $filter, array("objectClass"));
300       $rv =   @ldap_count_entries($this->cid, $res);
301       return($rv);
302     }else{
303       $this->error = "Could not connect to LDAP server";
304       return(FALSE);
305     }
306   }
308   function set_size_limit($size)
309   {
310     /* Ignore zero settings */
311     if ($size == 0){
312       @ldap_set_option($this->cid, LDAP_OPT_SIZELIMIT, 10000000);
313     }
314     if($this->hascon){
315       @ldap_set_option($this->cid, LDAP_OPT_SIZELIMIT, $size);
316     } else {
317       $this->error = "Could not connect to LDAP server";
318     }
319   }
321   function fetch($srp)
322   {
323     $att= array();
324     if($this->hascon){
325       if($this->hasres[$srp]){
326         if ($this->start[$srp] == 0)
327         {
328           if ($this->sr[$srp]){
329             $this->start[$srp] = 1;
330             $this->re[$srp]= @ldap_first_entry($this->cid, $this->sr[$srp]);
331           } else {
332             return array();
333           }
334         } else {
335           $this->re[$srp]= @ldap_next_entry($this->cid, $this->re[$srp]);
336         }
337         if ($this->re[$srp])
338         {
339           $att= @ldap_get_attributes($this->cid, $this->re[$srp]);
340           $att['dn']= trim(LDAP::convert(@ldap_get_dn($this->cid, $this->re[$srp])));
341         }
342         $this->error = @ldap_error($this->cid);
343         if (!isset($att)){
344           $att= array();
345         }
346         return($att);
347       }else{
348         $this->error = "Perform a fetch with no search";
349         return("");
350       }
351     }else{
352       $this->error = "Could not connect to LDAP server";
353       return("");
354     }
355   }
357   function resetResult($srp)
358   {
359     $this->start[$srp] = 0;
360   }
362   function clearResult($srp)
363   {
364     if($this->hasres[$srp]){
365       $this->hasres[$srp] = false;
366       @ldap_free_result($this->sr[$srp]);
367     }
368   }
370   function getDN($srp)
371   {
372     if($this->hascon){
373       if($this->hasres[$srp]){
375         if(!$this->re[$srp])
376           {
377           $this->error = "Perform a Fetch with no valid Result";
378           }
379           else
380           {
381           $rv = @ldap_get_dn($this->cid, $this->re[$srp]);
382         
383           $this->error = @ldap_error($this->cid);
384           return(trim(LDAP::convert($rv)));
385            }
386       }else{
387         $this->error = "Perform a Fetch with no Search";
388         return("");
389       }
390     }else{
391       $this->error = "Could not connect to LDAP server";
392       return("");
393     }
394   }
396   function count($srp)
397   {
398     if($this->hascon){
399       if($this->hasres[$srp]){
400         $rv = @ldap_count_entries($this->cid, $this->sr[$srp]);
401         $this->error = @ldap_error($this->cid);
402         return($rv);
403       }else{
404         $this->error = "Perform a Fetch with no Search";
405         return("");
406       }
407     }else{
408       $this->error = "Could not connect to LDAP server";
409       return("");
410     }
411   }
413   function rm($attrs = "", $dn = "")
414   {
415     if($this->hascon){
416       if ($this->reconnect) $this->connect();
417       if ($dn == "")
418         $dn = $this->basedn;
420       $r = @ldap_mod_del($this->cid, LDAP::fix($dn), $attrs);
421       $this->error = @ldap_error($this->cid);
422       return($r);
423     }else{
424       $this->error = "Could not connect to LDAP server";
425       return("");
426     }
427   }
429   function rename($attrs, $dn = "")
430   {
431     if($this->hascon){
432       if ($this->reconnect) $this->connect();
433       if ($dn == "")
434         $dn = $this->basedn;
436       $r = @ldap_mod_replace($this->cid, LDAP::fix($dn), $attrs);
437       $this->error = @ldap_error($this->cid);
438       return($r);
439     }else{
440       $this->error = "Could not connect to LDAP server";
441       return("");
442     }
443   }
445   function rmdir($deletedn)
446   {
447     if($this->hascon){
448       if ($this->reconnect) $this->connect();
449       $r = @ldap_delete($this->cid, LDAP::fix($deletedn));
450       $this->error = @ldap_error($this->cid);
451       return($r ? $r : 0);
452     }else{
453       $this->error = "Could not connect to LDAP server";
454       return("");
455     }
456   }
459   /*! \brief Move the given Ldap entry from $source to $dest
460       @param  String  $source The source dn.
461       @param  String  $dest   The destination dn.
462       @return Boolean TRUE on success else FALSE.
463    */
464   function rename_dn($source,$dest)
465   {
466     /* Check if source and destination are the same entry */
467     if(strtolower($source) == strtolower($dest)){
468       trigger_error("Source and destination can't be the same entry.");
469       $this->error = "Source and destination can't be the same entry.";
470       return(FALSE);
471     }
473     /* Check if destination entry exists */    
474     if($this->dn_exists($dest)){
475       trigger_error("Destination '$dest' already exists.");
476       $this->error = "Destination '$dest' already exists.";
477       return(FALSE);
478     }
480     /* Extract the name and the parent part out ouf source dn.
481         e.g.  cn=herbert,ou=department,dc=... 
482          parent   =>  ou=department,dc=...
483          dest_rdn =>  cn=herbert
484      */
485     $parent   = preg_replace("/^[^,]+,/","", $dest);
486     $dest_rdn = preg_replace("/,.*$/","",$dest);
488     if($this->hascon){
489       if ($this->reconnect) $this->connect();
490       $r= ldap_rename($this->cid,@LDAP::fix($source), @LDAP::fix($dest_rdn),@LDAP::fix($parent),TRUE); 
491       $this->error = ldap_error($this->cid);
493       /* Check if destination dn exists, if not the 
494           server may not support this operation */
495       $r &= is_resource($this->dn_exists($dest));
496       return($r);
497     }else{
498       $this->error = "Could not connect to LDAP server";
499       return(FALSE);
500     }
501   }
504   /**
505   *  Function rmdir_recursive
506   *
507   *  Description: Based in recursive_remove, adding two thing: full subtree remove, and delete own node.
508   *  Parameters:  The dn to delete
509   *  GiveBack:    True on sucessfull , 0 in error, and "" when we don't get a ldap conection
510   *
511   */
512   function rmdir_recursive($srp, $deletedn)
513   {
514     if($this->hascon){
515       if ($this->reconnect) $this->connect();
516       $delarray= array();
517         
518       /* Get sorted list of dn's to delete */
519       $this->ls ($srp, "(objectClass=*)",$deletedn);
520       while ($this->fetch($srp)){
521         $deldn= $this->getDN($srp);
522         $delarray[$deldn]= strlen($deldn);
523       }
524       arsort ($delarray);
525       reset ($delarray);
527       /* Really Delete ALL dn's in subtree */
528       foreach ($delarray as $key => $value){
529         $this->rmdir_recursive($srp, $key);
530       }
531       
532       /* Finally Delete own Node */
533       $r = @ldap_delete($this->cid, LDAP::fix($deletedn));
534       $this->error = @ldap_error($this->cid);
535       return($r ? $r : 0);
536     }else{
537       $this->error = "Could not connect to LDAP server";
538       return("");
539     }
540   }
543   function modify($attrs)
544   {
545     if(count($attrs) == 0){
546       return (0);
547     }
548     if($this->hascon){
549       if ($this->reconnect) $this->connect();
550       $r = @ldap_modify($this->cid, LDAP::fix($this->basedn), $attrs);
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 add($attrs)
560   {
561     if($this->hascon){
562       if ($this->reconnect) $this->connect();
563       $r = @ldap_add($this->cid, LDAP::fix($this->basedn), $attrs);
564       $this->error = @ldap_error($this->cid);
565       return($r ? $r : 0);
566     }else{
567       $this->error = "Could not connect to LDAP server";
568       return("");
569     }
570   }
572   function create_missing_trees($srp, $target)
573   {
574     global $config;
576     $real_path= substr($target, 0, strlen($target) - strlen($this->basedn) -1 );
578     if ($target == $this->basedn){
579       $l= array("dummy");
580     } else {
581       $l= array_reverse(gosa_ldap_explode_dn($real_path));
582     }
583     unset($l['count']);
584     $cdn= $this->basedn;
585     $tag= "";
587     /* Load schema if available... */
588     $classes= $this->get_objectclasses();
590     foreach ($l as $part){
591       if ($part != "dummy"){
592         $cdn= "$part,$cdn";
593       }
595       /* Ignore referrals */
596       $found= false;
597       foreach($this->referrals as $ref){
598         $base= preg_replace('!^[^:]+://[^/]+/([^?]+).*$!', '\\1', $ref['URI']);
599         if ($base == $cdn){
600           $found= true;
601           break;
602         }
603       }
604       if ($found){
605         continue;
606       }
608       $this->cat ($srp, $cdn);
609       $attrs= $this->fetch($srp);
611       /* Create missing entry? */
612       if (count ($attrs)){
613       
614         /* Catch the tag - if present */
615         if (isset($attrs['gosaUnitTag'][0])){
616           $tag= $attrs['gosaUnitTag'][0];
617         }
619       } else {
620         $type= preg_replace('/^([^=]+)=.*$/', '\\1', $cdn);
621         $param= preg_replace('/^[^=]+=([^,]+).*$/', '\\1', $cdn);
623         $na= array();
625         /* Automatic or traditional? */
626         if(count($classes)){
628           /* Get name of first matching objectClass */
629           $ocname= "";
630           foreach($classes as $class){
631             if (isset($class['MUST']) && $class['MUST'] == "$type"){
633               /* Look for first classes that is structural... */
634               if (isset($class['STRUCTURAL'])){
635                 $ocname= $class['NAME'];
636                 break;
637               }
639               /* Look for classes that are auxiliary... */
640               if (isset($class['AUXILIARY'])){
641                 $ocname= $class['NAME'];
642               }
643             }
644           }
646           /* Bail out, if we've nothing to do... */
647           if ($ocname == ""){
648             msg_dialog::display(_("Internal error"), sprintf(_("Cannot automatically create subtrees with RDN '%s': no object class found!"),$type), FATAL_ERROR_DIALOG);
649             exit();
650           }
652           /* Assemble_entry */
653           if ($tag != ""){
654             $na['objectClass']= array($ocname, "gosaAdministrativeUnitTag");
655             $na["gosaUnitTag"]= $tag;
656           } else {
657             $na['objectClass']= array($ocname);
658           }
659           if (isset($classes[$ocname]['AUXILIARY'])){
660             $na['objectClass'][]= $classes[$ocname]['SUP'];
661           }
662           if ($type == "dc"){
663             /* This is bad actually, but - tell me a better way? */
664             $na['objectClass'][]= 'locality';
665           }
666           $na[$type]= $param;
667           if (is_array($classes[$ocname]['MUST'])){
668             foreach($classes[$ocname]['MUST'] as $attr){
669               $na[$attr]= "filled";
670             }
671           }
673         } else {
675           /* Use alternative add... */
676           switch ($type){
677             case 'ou':
678               if ($tag != ""){
679                 $na["objectClass"]= array("organizationalUnit", "gosaAdministrativeUnitTag");
680                 $na["gosaUnitTag"]= $tag;
681               } else {
682                 $na["objectClass"]= "organizationalUnit";
683               }
684               $na["ou"]= $param;
685               break;
686             case 'dc':
687               if ($tag != ""){
688                 $na["objectClass"]= array("dcObject", "top", "locality", "gosaAdministrativeUnitTag");
689                 $na["gosaUnitTag"]= $tag;
690               } else {
691                 $na["objectClass"]= array("dcObject", "top", "locality");
692               }
693               $na["dc"]= $param;
694               break;
695             default:
696               msg_dialog::display(_("Internal error"), sprintf(_("Cannot automatically create subtrees with RDN '%s': not supported"),$type), FATAL_ERROR_DIALOG);
697               exit();
698           }
700         }
701         $this->cd($cdn);
702         $this->add($na);
703     
704         if (!$this->success()){
706           print_a(array($cdn,$na));
708           msg_dialog::display(_("LDAP error"), msgPool::ldaperror($this->get_error(), $cdn, LDAP_ADD, get_class()));
709           return FALSE;
710         }
711       }
712     }
714     return TRUE;
715   }
718   function recursive_remove($srp)
719   {
720     $delarray= array();
722     /* Get sorted list of dn's to delete */
723     $this->search ($srp, "(objectClass=*)");
724     while ($this->fetch($srp)){
725       $deldn= $this->getDN($srp);
726       $delarray[$deldn]= strlen($deldn);
727     }
728     arsort ($delarray);
729     reset ($delarray);
731     /* Delete all dn's in subtree */
732     foreach ($delarray as $key => $value){
733       $this->rmdir($key);
734     }
735   }
737   function get_attribute($dn, $name,$r_array=0)
738   {
739     $data= "";
740     if ($this->reconnect) $this->connect();
741     $sr= @ldap_read($this->cid, LDAP::fix($dn), "objectClass=*", array("$name"));
743     /* fill data from LDAP */
744     if ($sr) {
745       $ei= @ldap_first_entry($this->cid, $sr);
746       if ($ei) {
747         if ($info= @ldap_get_values_len($this->cid, $ei, "$name")){
748           $data= $info[0];
749         }
750       }
751     }
752     if($r_array==0)
753     return ($data);
754     else
755     return ($info);
756   
757   
758   }
759  
762   function get_additional_error()
763   {
764     $error= "";
765     @ldap_get_option ($this->cid, LDAP_OPT_ERROR_STRING, $error);
766     return ($error);
767   }
770   function success()
771   {
772     return (preg_match('/Success/i', $this->error));
773   }
776   function get_error()
777   {
778     if ($this->error == 'Success'){
779       return $this->error;
780     } else {
781       $adderror= $this->get_additional_error();
782       if ($adderror != ""){
783         $error= $this->error." (".$this->get_additional_error().", ".sprintf(_("while operating on '%s' using LDAP server '%s'"), $this->basedn, $this->hostname).")";
784       } else {
785         $error= $this->error." (".sprintf(_("while operating on LDAP server %s"), $this->hostname).")";
786       }
787       return $error;
788     }
789   }
791   function get_credentials($url, $referrals= NULL)
792   {
793     $ret= array();
794     $url= preg_replace('!\?\?.*$!', '', $url);
795     $server= preg_replace('!^([^:]+://[^/]+)/.*$!', '\\1', $url);
797     if ($referrals === NULL){
798       $referrals= $this->referrals;
799     }
801     if (isset($referrals[$server])){
802       return ($referrals[$server]);
803     } else {
804       $ret['ADMINDN']= LDAP::fix($this->binddn);
805       $ret['ADMINPASSWORD']= $this->bindpw;
806     }
808     return ($ret);
809   }
812   function gen_ldif ($srp, $dn, $filter= "(objectClass=*)", $attributes= array('*'), $recursive= TRUE)
813   {
814     $display= "";
816     if ($recursive){
817       $this->cd($dn);
818       $this->ls($srp, $filter,$dn, array('dn','objectClass'));
819       $deps = array();
821       $display .= $this->gen_one_entry($dn)."\n";
823       while ($attrs= $this->fetch($srp)){
824         $deps[] = $attrs['dn'];
825       }
826       foreach($deps as $dn){
827         $display .= $this->gen_ldif($srp, $dn, $filter,$attributes,$recursive);
828       }
829     } else {
830       $display.= $this->gen_one_entry($dn);
831     }
832     return ($display);
833   }
836   function gen_xls ($srp, $dn, $filter= "(objectClass=*)", $attributes= array('*'), $recursive= TRUE,$r_array=0)
837   {
838     $display= array();
840       $this->cd($dn);
841       $this->search($srp, "$filter");
843       $i=0;
844       while ($attrs= $this->fetch($srp)){
845         $j=0;
847         foreach ($attributes as $at){
848           $display[$i][$j]= $this->get_attribute($attrs['dn'], $at,$r_array);
849           $j++;
850         }
852         $i++;
853       }
855     return ($display);
856   }
859   function gen_one_entry($dn, $filter= "(objectClass=*)" , $name= array("*"))
860   {
861     $ret = "";
862     $data = "";
863     if($this->reconnect){
864       $this->connect();
865     }
867     /* Searching Ldap Tree */
868     $sr= @ldap_read($this->cid, LDAP::fix($dn), $filter, $name);
870     /* Get the first entry */   
871     $entry= @ldap_first_entry($this->cid, $sr);
873     /* Get all attributes related to that Objekt */
874     $atts = array();
875     
876     /* Assemble dn */
877     $atts[0]['name']  = "dn";
878     $atts[0]['value'] = array('count' => 1, 0 => $dn);
880     /* Reset index */
881     $i = 1 ; 
882   $identifier = array();
883     $attribute= @ldap_first_attribute($this->cid,$entry,$identifier);
884     while ($attribute) {
885       $i++;
886       $atts[$i]['name']  = $attribute;
887       $atts[$i]['value'] = @ldap_get_values_len($this->cid, $entry, "$attribute");
889       /* Next one */
890       $attribute= @ldap_next_attribute($this->cid,$entry,$identifier);
891     }
893     foreach($atts as $at)
894     {
895       for ($i= 0; $i<$at['value']['count']; $i++){
897         /* Check if we must encode the data */
898         if(!preg_match('/^[a-z0-9+@#.=, \/ -]+$/i', $at['value'][$i])) {
899           $ret .= $at['name'].":: ".base64_encode($at['value'][$i])."\n";
900         } else {
901           $ret .= $at['name'].": ".$at['value'][$i]."\n";
902         }
903       }
904     }
906     return($ret);
907   }
910   function dn_exists($dn)
911   {
912     return @ldap_list($this->cid, LDAP::fix($dn), "(objectClass=*)", array("objectClass"));
913   }
914   
917   /*  This funktion imports ldifs 
918         
919       If DeleteOldEntries is true, the destination entry will be deleted first. 
920       If JustModify is true the destination entry will only be touched by the attributes specified in the ldif.
921       if JustMofify id false the destination dn will be overwritten by the new ldif. 
922     */
924   function import_complete_ldif($srp, $str_attr,$error,$JustModify,$DeleteOldEntries)
925   {
926     if($this->reconnect) $this->connect();
928     /* First we have to splitt the string ito detect empty lines
929        An empty line indicates an new Entry */
930     $entries = split("\n",$str_attr);
932     $data = "";
933     $cnt = 0; 
934     $current_line = 0;
936     /* FIX ldif */
937     $last = "";
938     $tmp  = "";
939     $i = 0;
940     foreach($entries as $entry){
941       if(preg_match("/^ /",$entry)){
942         $tmp[$i] .= trim($entry);
943       }else{
944         $i ++;
945         $tmp[$i] = trim($entry);
946       }
947     }
949     /* Every single line ... */
950     foreach($tmp as $entry) {
951       $current_line ++;
953       /* Removing Spaces to .. 
954          .. test if a new entry begins */
955       $tmp  = str_replace(" ","",$data );
957       /* .. prevent empty lines in an entry */
958       $tmp2 = str_replace(" ","",$entry);
960       /* If the Block ends (Empty Line) */
961       if((empty($entry))&&(!empty($tmp))) {
962         /* Add collected lines as a complete block */
963         $all[$cnt] = $data;
964         $cnt ++;
965         $data ="";
966       } else {
968         /* Append lines ... */
969         if(!empty($tmp2)) {
970           /* check if we need base64_decode for this line */
971           if(ereg("::",$tmp2))
972           {
973             $encoded = split("::",$entry);
974             $attr  = trim($encoded[0]);
975             $value = base64_decode(trim($encoded[1]));
976             /* Add linenumber */
977             $data .= $current_line."#".base64_encode($attr.":".$value)."\n";
978           }
979           else
980           {
981             /* Add Linenumber */ 
982             $data .= $current_line."#".base64_encode($entry)."\n";
983           }
984         }
985       }
986     }
988     /* The Data we collected is not in the array all[];
989        For example the Data is stored like this..
991        all[0] = "1#dn : .... \n 
992        2#ObjectType: person \n ...."
993        
994        Now we check every insertblock and try to insert */
995     foreach ( $all as $single) {
996       $lineone = split("\n",$single);  
997       $ndn = split("#", $lineone[0]);
998       $line = base64_decode($ndn[1]);
1000       $dnn = split (":",$line,2);
1001       $current_line = $ndn[0];
1002       $dn    = $dnn[0];
1003       $value = $dnn[1];
1005       /* Every block must begin with a dn */
1006       if($dn != "dn") {
1007         $error= sprintf(_("This is not a valid DN: '%s'. A block for import should begin with 'dn: ...' in line %s"), $line, $current_line);
1008         return -2;  
1009       }
1011       /* Should we use Modify instead of Add */
1012       $usemodify= false;
1014       /* Delete before insert */
1015       $usermdir= false;
1016     
1017       /* The dn address already exists, Don't delete destination entry, overwrite it */
1018       if (($this->dn_exists($value))&&((!$JustModify)&&(!$DeleteOldEntries))) {
1020         $usermdir = $usemodify = false;
1022       /* Delete old entry first, then add new */
1023       } elseif(($this->dn_exists($value))&&($DeleteOldEntries)){
1025         /* Delete first, then add */
1026         $usermdir = true;        
1028       } elseif(($this->dn_exists($value))&&($JustModify)) {
1029         
1030         /* Modify instead of Add */
1031         $usemodify = true;
1032       }
1033      
1034       /* If we can't Import, return with a file error */
1035       if(!$this->import_single_entry($srp, $single,$usemodify,$usermdir) ) {
1036         $error= sprintf(_("Error while importing dn: '%s', please check your LDIF from line %s on!"), $line,
1037                         $current_line);
1038         return UNKNOWN_TOKEN_IN_LDIF_FILE;      }
1039     }
1041     return (INSERT_OK);
1042   }
1045   /* Imports a single entry 
1046       If $delete is true;  The old entry will be deleted if it exists.
1047       if $modify is true;  All variables that are not touched by the new ldif will be kept.
1048       if $modify is false; The new ldif overwrites the old entry, and all untouched attributes get lost.
1049   */
1050   function import_single_entry($srp, $str_attr,$modify,$delete)
1051   {
1052     global $config;
1054     if(!$config){
1055       trigger_error("Can't import ldif, can't read config object.");
1056     }
1057   
1059     if($this->reconnect) $this->connect();
1061     $ret = false;
1062     $rows= split("\n",$str_attr);
1063     $data= false;
1065     foreach($rows as $row) {
1066       
1067       /* Check if we use Linenumbers (when import_complete_ldif is called we use
1068          Linenumbers) Linenumbers are use like this 123#attribute : value */
1069       if(!empty($row)) {
1070         if(strpos($row,"#")!=FALSE) {
1072           /* We are using line numbers 
1073              Because there is a # before a : */
1074           $tmp1= split("#",$row);
1075           $current_line= $tmp1[0];
1076           $row= base64_decode($tmp1[1]);
1077         }
1079         /* Split the line into  attribute  and value */
1080         $attr   = split(":", $row,2);
1081         $attr[0]= trim($attr[0]);  /* attribute */
1082         $attr[1]= $attr[1];  /* value */
1084         /* Check :: was used to indicate base64_encoded strings */
1085         if($attr[1][0] == ":"){
1086           $attr[1]=trim(preg_replace("/^:/","",$attr[1]));
1087           $attr[1]=base64_decode($attr[1]);
1088         }
1090         $attr[1] = trim($attr[1]);
1092         /* Check for attributes that are used more than once */
1093         if(!isset($data[$attr[0]])) {
1094           $data[$attr[0]]=$attr[1];
1095         } else {
1096           $tmp = $data[$attr[0]];
1098           if(!is_array($tmp)) {
1099             $new[0]=$tmp;
1100             $new[1]=$attr[1];
1101             $datas[$attr[0]]['count']=1;             
1102             $data[$attr[0]]=$new;
1103           } else {
1104             $cnt = $datas[$attr[0]]['count'];           
1105             $cnt ++;
1106             $data[$attr[0]][$cnt]=$attr[1];
1107             $datas[$attr[0]]['count'] = $cnt;
1108           }
1109         }
1110       }
1111     }
1113     /* If dn is an index of data, we should try to insert the data */
1114     if(isset($data['dn'])) {
1116       /* Fix dn */
1117       $tmp = gosa_ldap_explode_dn($data['dn']);
1118       unset($tmp['count']);
1119       $newdn ="";
1120       foreach($tmp as $tm){
1121         $newdn.= trim($tm).",";
1122       }
1123       $newdn = preg_replace("/,$/","",$newdn);
1124       $data['dn'] = $newdn;
1125    
1126       /* Creating Entry */
1127       $this->cd($data['dn']);
1129       /* Delete existing entry */
1130       if($delete){
1131         $this->rmdir_recursive($srp, $data['dn']);
1132       }
1133      
1134       /* Create missing trees */
1135       $this->cd ($this->basedn);
1136       $this->cd($config->current['BASE']);
1137       $this->create_missing_trees($srp, preg_replace("/^[^,]+,/","",$data['dn']));
1138       $this->cd($data['dn']);
1140       $dn = $data['dn'];
1141       unset($data['dn']);
1142       
1143       if(!$modify){
1145         $this->cat($srp, $dn);
1146         if($this->count($srp)){
1147         
1148           /* The destination entry exists, overwrite it with the new entry */
1149           $attrs = $this->fetch($srp);
1150           foreach($attrs as $name => $value ){
1151             if(!is_numeric($name)){
1152               if(in_array($name,array("dn","count"))) continue;
1153               if(!isset($data[$name])){
1154                 $data[$name] = array();
1155               }
1156             }
1157           }
1158           $ret = $this->modify($data);
1159     
1160         }else{
1161     
1162           /* The destination entry doesn't exists, create it */
1163           $ret = $this->add($data);
1164         }
1166       } else {
1167         
1168         /* Keep all vars that aren't touched by this ldif */
1169         $ret = $this->modify($data);
1170       }
1171     }
1173     if (!$this->success()){
1174       msg_dialog::display(_("LDAP error"), msgPool::ldaperror($this->get_error(), $dn, "", get_class()));
1175     }
1177     return($ret);
1178   }
1180   
1181   function importcsv($str)
1182   {
1183     $lines = split("\n",$str);
1184     foreach($lines as $line)
1185     {
1186       /* continue if theres a comment */
1187       if(substr(trim($line),0,1)=="#"){
1188         continue;
1189       }
1191       $line= str_replace ("\t\t","\t",$line);
1192       $line= str_replace ("\t"  ,"," ,$line);
1193       echo $line;
1195       $cells = split(",",$line )  ;
1196       $linet= str_replace ("\t\t",",",$line);
1197       $cells = split("\t",$line);
1198       $count = count($cells);  
1199     }
1201   }
1202   
1203   function get_objectclasses( $force_reload = FALSE)
1204   {
1205     $objectclasses = array();
1206     global $config;
1208     /* Only read schema if it is allowed */
1209     if(isset($config) && preg_match("/config/i",get_class($config))){
1210       if ($config->get_cfg_value("schemaCheck") != "true"){
1211         return($objectclasses);
1212       } 
1213     }
1215     /* Return the cached results. */
1216     if(class_available('session') && session::global_is_set("LDAP_CACHE::get_objectclasses") && !$force_reload){
1217       $objectclasses = session::global_get("LDAP_CACHE::get_objectclasses");
1218       return($objectclasses);
1219     }
1220         
1221           # Get base to look for schema 
1222           $sr = @ldap_read ($this->cid, "", "objectClass=*", array("subschemaSubentry"));
1223           $attr = @ldap_get_entries($this->cid,$sr);
1224           if (!isset($attr[0]['subschemasubentry'][0])){
1225             return array();
1226           }
1227         
1228           /* Get list of objectclasses and fill array */
1229           $nb= $attr[0]['subschemasubentry'][0];
1230           $objectclasses= array();
1231           $sr= ldap_read ($this->cid, $nb, "objectClass=*", array("objectclasses"));
1232           $attrs= ldap_get_entries($this->cid,$sr);
1233           if (!isset($attrs[0])){
1234             return array();
1235           }
1236           foreach ($attrs[0]['objectclasses'] as $val){
1237       if (preg_match('/^[0-9]+$/', $val)){
1238         continue;
1239       }
1240       $name= "OID";
1241       $pattern= split(' ', $val);
1242       $ocname= preg_replace("/^.* NAME\s+\(*\s*'([^']+)'\s*\)*.*$/", '\\1', $val);
1243       $objectclasses[$ocname]= array();
1245       foreach($pattern as $chunk){
1246         switch($chunk){
1248           case '(':
1249                     $value= "";
1250                     break;
1252           case ')': if ($name != ""){
1253                       $objectclasses[$ocname][$name]= $this->value2container($value);
1254                     }
1255                     $name= "";
1256                     $value= "";
1257                     break;
1259           case 'NAME':
1260           case 'DESC':
1261           case 'SUP':
1262           case 'STRUCTURAL':
1263           case 'ABSTRACT':
1264           case 'AUXILIARY':
1265           case 'MUST':
1266           case 'MAY':
1267                     if ($name != ""){
1268                       $objectclasses[$ocname][$name]= $this->value2container($value);
1269                     }
1270                     $name= $chunk;
1271                     $value= "";
1272                     break;
1274           default:  $value.= $chunk." ";
1275         }
1276       }
1278           }
1279     if(class_available("session")){
1280       session::global_set("LDAP_CACHE::get_objectclasses",$objectclasses);
1281     }
1283           return $objectclasses;
1284   }
1287   function value2container($value)
1288   {
1289     /* Set emtpy values to "true" only */
1290     if (preg_match('/^\s*$/', $value)){
1291       return true;
1292     }
1294     /* Remove ' and " if needed */
1295     $value= preg_replace('/^[\'"]/', '', $value);
1296     $value= preg_replace('/[\'"] *$/', '', $value);
1298     /* Convert to array if $ is inside... */
1299     if (preg_match('/\$/', $value)){
1300       $container= preg_split('/\s*\$\s*/', $value);
1301     } else {
1302       $container= chop($value);
1303     }
1305     return ($container);
1306   }
1309   function log($string)
1310   {
1311     if (session::global_is_set('config')){
1312       $cfg = session::global_get('config');
1313       if (isset($cfg->current['LDAPSTATS']) && preg_match('/true/i', $cfg->current['LDAPSTATS'])){
1314         syslog (LOG_INFO, $string);
1315       }
1316     }
1317   }
1319   /* added by Guido Serra aka Zeph <zeph@purotesto.it> */
1320   function getCn($dn){
1321     $simple= split(",", $dn);
1323     foreach($simple as $piece) {
1324       $partial= split("=", $piece);
1326       if($partial[0] == "cn"){
1327         return $partial[1];
1328       }
1329     }
1330   }
1333   function get_naming_contexts($server, $admin= "", $password= "")
1334   {
1335     /* Build LDAP connection */
1336     $ds= ldap_connect ($server);
1337     if (!$ds) {
1338       die ("Can't bind to LDAP. No check possible!");
1339     }
1340     ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
1341     $r= ldap_bind ($ds, $admin, $password);
1343     /* Get base to look for naming contexts */
1344     $sr  = @ldap_read ($ds, "", "objectClass=*", array("+"));
1345     $attr= @ldap_get_entries($ds,$sr);
1347     return ($attr[0]['namingcontexts']);
1348   }
1351   function get_root_dse($server, $admin= "", $password= "")
1352   {
1353     /* Build LDAP connection */
1354     $ds= ldap_connect ($server);
1355     if (!$ds) {
1356       die ("Can't bind to LDAP. No check possible!");
1357     }
1358     ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
1359     $r= ldap_bind ($ds, $admin, $password);
1361     /* Get base to look for naming contexts */
1362     $sr  = @ldap_read ($ds, "", "objectClass=*", array("+"));
1363     $attr= @ldap_get_entries($ds,$sr);
1364    
1365     /* Return empty array, if nothing was set */
1366     if (!isset($attr[0])){
1367       return array();
1368     }
1370     /* Rework array... */
1371     $result= array();
1372     for ($i= 0; $i<$attr[0]['count']; $i++){
1373       $result[$attr[0][$i]]= $attr[0][$attr[0][$i]];
1374       unset($result[$attr[0][$i]]['count']);
1375     }
1377     return ($result);
1378   }
1381 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
1382 ?>