Code

1263256612ad436c864a2dcd8188a7c1431007ab
[gosa.git] / trunk / 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     $str = normalizeLdap(str_replace('\\\\', '\\\\\\', LDAP::fix($dn)));
124     /* Special-case '\,' for filters */
125     $str = str_replace('\\,', '\\5C2C', $str);
126     return $str;
127   }
130   function connect()
131   {
132     $this->hascon=false;
133     $this->reconnect=false;
134     if ($this->cid= @ldap_connect($this->hostname)) {
135       @ldap_set_option($this->cid, LDAP_OPT_PROTOCOL_VERSION, 3);
136       if (function_exists("ldap_set_rebind_proc") && $this->follow_referral) {
137         @ldap_set_option($this->cid, LDAP_OPT_REFERRALS, 1);
138         @ldap_set_rebind_proc($this->cid, array(&$this, "rebind"));
139       }
140       if (function_exists("ldap_start_tls") && $this->tls){
141         @ldap_start_tls($this->cid);
142       }
144       $this->error = "No Error";
145       if ($bid = @ldap_bind($this->cid, LDAP::fix($this->binddn), $this->bindpw)) {
146         $this->error = "Success";
147         $this->hascon=true;
148       } else {
149         if ($this->reconnect){
150           if ($this->error != "Success"){
151             $this->error = "Could not rebind to " . $this->binddn;
152           }
153         } else {
154           $this->error = "Could not bind to " . $this->binddn;
155         }
156       }
157     } else {
158       $this->error = "Could not connect to LDAP server";
159     }
160   }
162   function rebind($ldap, $referral)
163   {
164     $credentials= $this->get_credentials($referral);
165     if (@ldap_bind($ldap, LDAP::fix($credentials['ADMINDN']), $credentials['ADMINPASSWORD'])) {
166       $this->error = "Success";
167       $this->hascon=true;
168       $this->reconnect= true;
169       return (0);
170     } else {
171       $this->error = "Could not bind to " . $credentials['ADMINDN'];
172       return NULL;
173     }
174   }
176   function reconnect()
177   {
178     if ($this->reconnect){
179       @ldap_unbind($this->cid);
180       $this->cid = NULL;
181     }
182   }
184   function unbind()
185   {
186     @ldap_unbind($this->cid);
187     $this->cid = NULL;
188   }
190   function disconnect()
191   {
192     if($this->hascon){
193       @ldap_close($this->cid);
194       $this->hascon=false;
195     }
196   }
198   function cd($dir)
199   {
200     if ($dir == ".."){
201       $this->basedn = $this->getParentDir();
202     } else {
203       $this->basedn = LDAP::convert($dir);
204     }
205   }
207   function getParentDir($basedn = "")
208   {
209     if ($basedn==""){
210       $basedn = $this->basedn;
211     } else {
212       $basedn = LDAP::convert($this->basedn);
213     }
214     return(ereg_replace("[^,]*[,]*[ ]*(.*)", "\\1", $basedn));
215   }
217   
218   function search($srp, $filter, $attrs= array())
219   {
220     if($this->hascon){
221       if ($this->reconnect) $this->connect();
223       $start = microtime();
224       $this->clearResult($srp);
225       $this->sr[$srp] = @ldap_search($this->cid, LDAP::fix($this->basedn), $filter, $attrs);
226       $this->error = @ldap_error($this->cid);
227       $this->resetResult($srp);
228       $this->hasres[$srp]=true;
229    
230       /* Check if query took longer as specified in max_ldap_query_time */
231       if($this->max_ldap_query_time){
232         $diff = get_MicroTimeDiff($start,microtime());
233         if($diff > $this->max_ldap_query_time){
234           msg_dialog::display(_("Performance warning"), sprintf(_("LDAP performance is poor: last query took about %.2fs!"), $diff), WARNING_DIALOG);
235         }
236       }
238       $this->log("LDAP operation: time=".get_MicroTimeDiff($start,microtime())." operation=search('".LDAP::fix($this->basedn)."', '$filter')");
239       return($this->sr[$srp]);
240     }else{
241       $this->error = "Could not connect to LDAP server";
242       return("");
243     }
244   }
246   function ls($srp, $filter = "(objectclass=*)", $basedn = "",$attrs = array("*"))
247   {
248     if($this->hascon){
249       if ($this->reconnect) $this->connect();
251       $this->clearResult($srp);
252       if ($basedn == "")
253         $basedn = $this->basedn;
254       else
255         $basedn= LDAP::convert($basedn);
256   
257       $start = microtime();
258       $this->sr[$srp] = @ldap_list($this->cid, LDAP::fix($basedn), $filter,$attrs);
259       $this->error = @ldap_error($this->cid);
260       $this->resetResult($srp);
261       $this->hasres[$srp]=true;
263        /* Check if query took longer as specified in max_ldap_query_time */
264       if($this->max_ldap_query_time){
265         $diff = get_MicroTimeDiff($start,microtime());
266         if($diff > $this->max_ldap_query_time){
267           msg_dialog::display(_("Performance warning"), sprintf(_("LDAP performance is poor: last query took about %.2fs!"), $diff), WARNING_DIALOG);
268         }
269       }
271       $this->log("LDAP operation: time=".get_MicroTimeDiff($start,microtime())." operation=ls('".LDAP::fix($basedn)."', '$filter')");
273       return($this->sr[$srp]);
274     }else{
275       $this->error = "Could not connect to LDAP server";
276       return("");
277     }
278   }
280   function cat($srp, $dn,$attrs= array("*"))
281   {
282     if($this->hascon){
283       if ($this->reconnect) $this->connect();
285       $this->clearResult($srp);
286       $filter = "(objectclass=*)";
287       $this->sr[$srp] = @ldap_read($this->cid, LDAP::fix($dn), $filter,$attrs);
288       $this->error = @ldap_error($this->cid);
289       $this->resetResult($srp);
290       $this->hasres[$srp]=true;
291       return($this->sr[$srp]);
292     }else{
293       $this->error = "Could not connect to LDAP server";
294       return("");
295     }
296   }
298   function object_match_filter($dn,$filter)
299   {
300     if($this->hascon){
301       if ($this->reconnect) $this->connect();
302       $res =  @ldap_read($this->cid, LDAP::fix($dn), $filter, array("objectClass"));
303       $rv =   @ldap_count_entries($this->cid, $res);
304       return($rv);
305     }else{
306       $this->error = "Could not connect to LDAP server";
307       return(FALSE);
308     }
309   }
311   function set_size_limit($size)
312   {
313     /* Ignore zero settings */
314     if ($size == 0){
315       @ldap_set_option($this->cid, LDAP_OPT_SIZELIMIT, 10000000);
316     }
317     if($this->hascon){
318       @ldap_set_option($this->cid, LDAP_OPT_SIZELIMIT, $size);
319     } else {
320       $this->error = "Could not connect to LDAP server";
321     }
322   }
324   function fetch($srp)
325   {
326     $att= array();
327     if($this->hascon){
328       if($this->hasres[$srp]){
329         if ($this->start[$srp] == 0)
330         {
331           if ($this->sr[$srp]){
332             $this->start[$srp] = 1;
333             $this->re[$srp]= @ldap_first_entry($this->cid, $this->sr[$srp]);
334           } else {
335             return array();
336           }
337         } else {
338           $this->re[$srp]= @ldap_next_entry($this->cid, $this->re[$srp]);
339         }
340         if ($this->re[$srp])
341         {
342           $att= @ldap_get_attributes($this->cid, $this->re[$srp]);
343           $att['dn']= trim(LDAP::convert(@ldap_get_dn($this->cid, $this->re[$srp])));
344         }
345         $this->error = @ldap_error($this->cid);
346         if (!isset($att)){
347           $att= array();
348         }
349         return($att);
350       }else{
351         $this->error = "Perform a fetch with no search";
352         return("");
353       }
354     }else{
355       $this->error = "Could not connect to LDAP server";
356       return("");
357     }
358   }
360   function resetResult($srp)
361   {
362     $this->start[$srp] = 0;
363   }
365   function clearResult($srp)
366   {
367     if($this->hasres[$srp]){
368       $this->hasres[$srp] = false;
369       @ldap_free_result($this->sr[$srp]);
370     }
371   }
373   function getDN($srp)
374   {
375     if($this->hascon){
376       if($this->hasres[$srp]){
378         if((!isset($this->re[$srp])) || (!$this->re[$srp]))
379           {
380           $this->error = "Perform a Fetch with no valid Result";
381           }
382           else
383           {
384           $rv = @ldap_get_dn($this->cid, $this->re[$srp]);
385         
386           $this->error = @ldap_error($this->cid);
387           return(trim(LDAP::convert($rv)));
388            }
389       }else{
390         $this->error = "Perform a Fetch with no Search";
391         return("");
392       }
393     }else{
394       $this->error = "Could not connect to LDAP server";
395       return("");
396     }
397   }
399   function count($srp)
400   {
401     if($this->hascon){
402       if($this->hasres[$srp]){
403         $rv = @ldap_count_entries($this->cid, $this->sr[$srp]);
404         $this->error = @ldap_error($this->cid);
405         return($rv);
406       }else{
407         $this->error = "Perform a Fetch with no Search";
408         return("");
409       }
410     }else{
411       $this->error = "Could not connect to LDAP server";
412       return("");
413     }
414   }
416   function rm($attrs = "", $dn = "")
417   {
418     if($this->hascon){
419       if ($this->reconnect) $this->connect();
420       if ($dn == "")
421         $dn = $this->basedn;
423       $r = @ldap_mod_del($this->cid, LDAP::fix($dn), $attrs);
424       $this->error = @ldap_error($this->cid);
425       return($r);
426     }else{
427       $this->error = "Could not connect to LDAP server";
428       return("");
429     }
430   }
432   function rename($attrs, $dn = "")
433   {
434     if($this->hascon){
435       if ($this->reconnect) $this->connect();
436       if ($dn == "")
437         $dn = $this->basedn;
439       $r = @ldap_mod_replace($this->cid, LDAP::fix($dn), $attrs);
440       $this->error = @ldap_error($this->cid);
441       return($r);
442     }else{
443       $this->error = "Could not connect to LDAP server";
444       return("");
445     }
446   }
448   function rmdir($deletedn)
449   {
450     if($this->hascon){
451       if ($this->reconnect) $this->connect();
452       $r = @ldap_delete($this->cid, LDAP::fix($deletedn));
453       $this->error = @ldap_error($this->cid);
454       return($r ? $r : 0);
455     }else{
456       $this->error = "Could not connect to LDAP server";
457       return("");
458     }
459   }
462   /*! \brief Move the given Ldap entry from $source to $dest
463       @param  String  $source The source dn.
464       @param  String  $dest   The destination dn.
465       @return Boolean TRUE on success else FALSE.
466    */
467   function rename_dn($source,$dest)
468   {
469     /* Check if source and destination are the same entry */
470     if(strtolower($source) == strtolower($dest)){
471       trigger_error("Source and destination can't be the same entry.");
472       $this->error = "Source and destination can't be the same entry.";
473       return(FALSE);
474     }
476     /* Check if destination entry exists */    
477     if($this->dn_exists($dest)){
478       trigger_error("Destination '$dest' already exists.");
479       $this->error = "Destination '$dest' already exists.";
480       return(FALSE);
481     }
483     /* Extract the name and the parent part out ouf source dn.
484         e.g.  cn=herbert,ou=department,dc=... 
485          parent   =>  ou=department,dc=...
486          dest_rdn =>  cn=herbert
487      */
488     $parent   = preg_replace("/^[^,]+,/","", $dest);
489     $dest_rdn = preg_replace("/,.*$/","",$dest);
491     if($this->hascon){
492       if ($this->reconnect) $this->connect();
493       $r= ldap_rename($this->cid,@LDAP::fix($source), @LDAP::fix($dest_rdn),@LDAP::fix($parent),TRUE); 
494       $this->error = ldap_error($this->cid);
496       /* Check if destination dn exists, if not the 
497           server may not support this operation */
498       $r &= is_resource($this->dn_exists($dest));
499       return($r);
500     }else{
501       $this->error = "Could not connect to LDAP server";
502       return(FALSE);
503     }
504   }
507   /**
508   *  Function rmdir_recursive
509   *
510   *  Description: Based in recursive_remove, adding two thing: full subtree remove, and delete own node.
511   *  Parameters:  The dn to delete
512   *  GiveBack:    True on sucessfull , 0 in error, and "" when we don't get a ldap conection
513   *
514   */
515   function rmdir_recursive($srp, $deletedn)
516   {
517     if($this->hascon){
518       if ($this->reconnect) $this->connect();
519       $delarray= array();
520         
521       /* Get sorted list of dn's to delete */
522       $this->ls ($srp, "(objectClass=*)",$deletedn);
523       while ($this->fetch($srp)){
524         $deldn= $this->getDN($srp);
525         $delarray[$deldn]= strlen($deldn);
526       }
527       arsort ($delarray);
528       reset ($delarray);
530       /* Really Delete ALL dn's in subtree */
531       foreach ($delarray as $key => $value){
532         $this->rmdir_recursive($srp, $key);
533       }
534       
535       /* Finally Delete own Node */
536       $r = @ldap_delete($this->cid, LDAP::fix($deletedn));
537       $this->error = @ldap_error($this->cid);
538       return($r ? $r : 0);
539     }else{
540       $this->error = "Could not connect to LDAP server";
541       return("");
542     }
543   }
546   function modify($attrs)
547   {
548     if(count($attrs) == 0){
549       return (0);
550     }
551     if($this->hascon){
552       if ($this->reconnect) $this->connect();
553       $r = @ldap_modify($this->cid, LDAP::fix($this->basedn), $attrs);
554       $this->error = @ldap_error($this->cid);
555       return($r ? $r : 0);
556     }else{
557       $this->error = "Could not connect to LDAP server";
558       return("");
559     }
560   }
562   function add($attrs)
563   {
564     if($this->hascon){
565       if ($this->reconnect) $this->connect();
566       $r = @ldap_add($this->cid, LDAP::fix($this->basedn), $attrs);
567       $this->error = @ldap_error($this->cid);
568       return($r ? $r : 0);
569     }else{
570       $this->error = "Could not connect to LDAP server";
571       return("");
572     }
573   }
575   function create_missing_trees($srp, $target)
576   {
577     global $config;
579     $real_path= substr($target, 0, strlen($target) - strlen($this->basedn) -1 );
581     if ($target == $this->basedn){
582       $l= array("dummy");
583     } else {
584       $l= array_reverse(gosa_ldap_explode_dn($real_path));
585     }
586     unset($l['count']);
587     $cdn= $this->basedn;
588     $tag= "";
590     /* Load schema if available... */
591     $classes= $this->get_objectclasses();
593     foreach ($l as $part){
594       if ($part != "dummy"){
595         $cdn= "$part,$cdn";
596       }
598       /* Ignore referrals */
599       $found= false;
600       foreach($this->referrals as $ref){
601         $base= preg_replace('!^[^:]+://[^/]+/([^?]+).*$!', '\\1', $ref['URI']);
602         if ($base == $cdn){
603           $found= true;
604           break;
605         }
606       }
607       if ($found){
608         continue;
609       }
611       $this->cat ($srp, $cdn);
612       $attrs= $this->fetch($srp);
614       /* Create missing entry? */
615       if (count ($attrs)){
616       
617         /* Catch the tag - if present */
618         if (isset($attrs['gosaUnitTag'][0])){
619           $tag= $attrs['gosaUnitTag'][0];
620         }
622       } else {
623         $type= preg_replace('/^([^=]+)=.*$/', '\\1', $cdn);
624         $param= preg_replace('/^[^=]+=([^,]+).*$/', '\\1', $cdn);
626         $na= array();
628         /* Automatic or traditional? */
629         if(count($classes)){
631           /* Get name of first matching objectClass */
632           $ocname= "";
633           foreach($classes as $class){
634             if (isset($class['MUST']) && $class['MUST'] == "$type"){
636               /* Look for first classes that is structural... */
637               if (isset($class['STRUCTURAL'])){
638                 $ocname= $class['NAME'];
639                 break;
640               }
642               /* Look for classes that are auxiliary... */
643               if (isset($class['AUXILIARY'])){
644                 $ocname= $class['NAME'];
645               }
646             }
647           }
649           /* Bail out, if we've nothing to do... */
650           if ($ocname == ""){
651             msg_dialog::display(_("Internal error"), sprintf(_("Cannot automatically create subtrees with RDN '%s': no object class found!"),$type), FATAL_ERROR_DIALOG);
652             exit();
653           }
655           /* Assemble_entry */
656           if ($tag != ""){
657             $na['objectClass']= array($ocname, "gosaAdministrativeUnitTag");
658             $na["gosaUnitTag"]= $tag;
659           } else {
660             $na['objectClass']= array($ocname);
661           }
662           if (isset($classes[$ocname]['AUXILIARY'])){
663             $na['objectClass'][]= $classes[$ocname]['SUP'];
664           }
665           if ($type == "dc"){
666             /* This is bad actually, but - tell me a better way? */
667             $na['objectClass'][]= 'locality';
668           }
669           $na[$type]= $param;
670           if (is_array($classes[$ocname]['MUST'])){
671             foreach($classes[$ocname]['MUST'] as $attr){
672               $na[$attr]= "filled";
673             }
674           }
676         } else {
678           /* Use alternative add... */
679           switch ($type){
680             case 'ou':
681               if ($tag != ""){
682                 $na["objectClass"]= array("organizationalUnit", "gosaAdministrativeUnitTag");
683                 $na["gosaUnitTag"]= $tag;
684               } else {
685                 $na["objectClass"]= "organizationalUnit";
686               }
687               $na["ou"]= $param;
688               break;
689             case 'dc':
690               if ($tag != ""){
691                 $na["objectClass"]= array("dcObject", "top", "locality", "gosaAdministrativeUnitTag");
692                 $na["gosaUnitTag"]= $tag;
693               } else {
694                 $na["objectClass"]= array("dcObject", "top", "locality");
695               }
696               $na["dc"]= $param;
697               break;
698             default:
699               msg_dialog::display(_("Internal error"), sprintf(_("Cannot automatically create subtrees with RDN '%s': not supported"),$type), FATAL_ERROR_DIALOG);
700               exit();
701           }
703         }
704         $this->cd($cdn);
705         $this->add($na);
706     
707         if (!$this->success()){
709           print_a(array($cdn,$na));
711           msg_dialog::display(_("LDAP error"), msgPool::ldaperror($this->get_error(), $cdn, LDAP_ADD, get_class()));
712           return FALSE;
713         }
714       }
715     }
717     return TRUE;
718   }
721   function recursive_remove($srp)
722   {
723     $delarray= array();
725     /* Get sorted list of dn's to delete */
726     $this->search ($srp, "(objectClass=*)");
727     while ($this->fetch($srp)){
728       $deldn= $this->getDN($srp);
729       $delarray[$deldn]= strlen($deldn);
730     }
731     arsort ($delarray);
732     reset ($delarray);
734     /* Delete all dn's in subtree */
735     foreach ($delarray as $key => $value){
736       $this->rmdir($key);
737     }
738   }
740   function get_attribute($dn, $name,$r_array=0)
741   {
742     $data= "";
743     if ($this->reconnect) $this->connect();
744     $sr= @ldap_read($this->cid, LDAP::fix($dn), "objectClass=*", array("$name"));
746     /* fill data from LDAP */
747     if ($sr) {
748       $ei= @ldap_first_entry($this->cid, $sr);
749       if ($ei) {
750         if ($info= @ldap_get_values_len($this->cid, $ei, "$name")){
751           $data= $info[0];
752         }
753       }
754     }
755     if($r_array==0)
756     return ($data);
757     else
758     return ($info);
759   
760   
761   }
762  
765   function get_additional_error()
766   {
767     $error= "";
768     @ldap_get_option ($this->cid, LDAP_OPT_ERROR_STRING, $error);
769     return ($error);
770   }
773   function success()
774   {
775     return (preg_match('/Success/i', $this->error));
776   }
779   function get_error()
780   {
781     if ($this->error == 'Success'){
782       return $this->error;
783     } else {
784       $adderror= $this->get_additional_error();
785       if ($adderror != ""){
786         $error= $this->error." (".$this->get_additional_error().", ".sprintf(_("while operating on '%s' using LDAP server '%s'"), $this->basedn, $this->hostname).")";
787       } else {
788         $error= $this->error." (".sprintf(_("while operating on LDAP server %s"), $this->hostname).")";
789       }
790       return $error;
791     }
792   }
794   function get_credentials($url, $referrals= NULL)
795   {
796     $ret= array();
797     $url= preg_replace('!\?\?.*$!', '', $url);
798     $server= preg_replace('!^([^:]+://[^/]+)/.*$!', '\\1', $url);
800     if ($referrals === NULL){
801       $referrals= $this->referrals;
802     }
804     if (isset($referrals[$server])){
805       return ($referrals[$server]);
806     } else {
807       $ret['ADMINDN']= LDAP::fix($this->binddn);
808       $ret['ADMINPASSWORD']= $this->bindpw;
809     }
811     return ($ret);
812   }
815   function gen_ldif ($srp, $dn, $filter= "(objectClass=*)", $attributes= array('*'), $recursive= TRUE)
816   {
817     $display= "";
819     if ($recursive){
820       $this->cd($dn);
821       $this->ls($srp, $filter,$dn, array('dn','objectClass'));
822       $deps = array();
824       $display .= $this->gen_one_entry($dn)."\n";
826       while ($attrs= $this->fetch($srp)){
827         $deps[] = $attrs['dn'];
828       }
829       foreach($deps as $dn){
830         $display .= $this->gen_ldif($srp, $dn, $filter,$attributes,$recursive);
831       }
832     } else {
833       $display.= $this->gen_one_entry($dn);
834     }
835     return ($display);
836   }
839   function gen_xls ($srp, $dn, $filter= "(objectClass=*)", $attributes= array('*'), $recursive= TRUE,$r_array=0)
840   {
841     $display= array();
843       $this->cd($dn);
844       $this->search($srp, "$filter");
846       $i=0;
847       while ($attrs= $this->fetch($srp)){
848         $j=0;
850         foreach ($attributes as $at){
851           $display[$i][$j]= $this->get_attribute($attrs['dn'], $at,$r_array);
852           $j++;
853         }
855         $i++;
856       }
858     return ($display);
859   }
862   function gen_one_entry($dn, $filter= "(objectClass=*)" , $name= array("*"))
863   {
864     $ret = "";
865     $data = "";
866     if($this->reconnect){
867       $this->connect();
868     }
870     /* Searching Ldap Tree */
871     $sr= @ldap_read($this->cid, LDAP::fix($dn), $filter, $name);
873     /* Get the first entry */   
874     $entry= @ldap_first_entry($this->cid, $sr);
876     /* Get all attributes related to that Objekt */
877     $atts = array();
878     
879     /* Assemble dn */
880     $atts[0]['name']  = "dn";
881     $atts[0]['value'] = array('count' => 1, 0 => $dn);
883     /* Reset index */
884     $i = 1 ; 
885   $identifier = array();
886     $attribute= @ldap_first_attribute($this->cid,$entry,$identifier);
887     while ($attribute) {
888       $i++;
889       $atts[$i]['name']  = $attribute;
890       $atts[$i]['value'] = @ldap_get_values_len($this->cid, $entry, "$attribute");
892       /* Next one */
893       $attribute= @ldap_next_attribute($this->cid,$entry,$identifier);
894     }
896     foreach($atts as $at)
897     {
898       for ($i= 0; $i<$at['value']['count']; $i++){
900         /* Check if we must encode the data */
901         if(!preg_match('/^[a-z0-9+@#.=, \/ -]+$/i', $at['value'][$i])) {
902           $ret .= $at['name'].":: ".base64_encode($at['value'][$i])."\n";
903         } else {
904           $ret .= $at['name'].": ".$at['value'][$i]."\n";
905         }
906       }
907     }
909     return($ret);
910   }
913   function dn_exists($dn)
914   {
915     return @ldap_list($this->cid, LDAP::fix($dn), "(objectClass=*)", array("objectClass"));
916   }
917   
920   /*  This funktion imports ldifs 
921         
922       If DeleteOldEntries is true, the destination entry will be deleted first. 
923       If JustModify is true the destination entry will only be touched by the attributes specified in the ldif.
924       if JustMofify id false the destination dn will be overwritten by the new ldif. 
925     */
927   function import_complete_ldif($srp, $str_attr,$error,$JustModify,$DeleteOldEntries)
928   {
929     if($this->reconnect) $this->connect();
931     /* First we have to splitt the string ito detect empty lines
932        An empty line indicates an new Entry */
933     $entries = split("\n",$str_attr);
935     $data = "";
936     $cnt = 0; 
937     $current_line = 0;
939     /* FIX ldif */
940     $last = "";
941     $tmp  = "";
942     $i = 0;
943     foreach($entries as $entry){
944       if(preg_match("/^ /",$entry)){
945         $tmp[$i] .= trim($entry);
946       }else{
947         $i ++;
948         $tmp[$i] = trim($entry);
949       }
950     }
952     /* Every single line ... */
953     foreach($tmp as $entry) {
954       $current_line ++;
956       /* Removing Spaces to .. 
957          .. test if a new entry begins */
958       $tmp  = str_replace(" ","",$data );
960       /* .. prevent empty lines in an entry */
961       $tmp2 = str_replace(" ","",$entry);
963       /* If the Block ends (Empty Line) */
964       if((empty($entry))&&(!empty($tmp))) {
965         /* Add collected lines as a complete block */
966         $all[$cnt] = $data;
967         $cnt ++;
968         $data ="";
969       } else {
971         /* Append lines ... */
972         if(!empty($tmp2)) {
973           /* check if we need base64_decode for this line */
974           if(ereg("::",$tmp2))
975           {
976             $encoded = split("::",$entry);
977             $attr  = trim($encoded[0]);
978             $value = base64_decode(trim($encoded[1]));
979             /* Add linenumber */
980             $data .= $current_line."#".base64_encode($attr.":".$value)."\n";
981           }
982           else
983           {
984             /* Add Linenumber */ 
985             $data .= $current_line."#".base64_encode($entry)."\n";
986           }
987         }
988       }
989     }
991     /* The Data we collected is not in the array all[];
992        For example the Data is stored like this..
994        all[0] = "1#dn : .... \n 
995        2#ObjectType: person \n ...."
996        
997        Now we check every insertblock and try to insert */
998     foreach ( $all as $single) {
999       $lineone = split("\n",$single);  
1000       $ndn = split("#", $lineone[0]);
1001       $line = base64_decode($ndn[1]);
1003       $dnn = split (":",$line,2);
1004       $current_line = $ndn[0];
1005       $dn    = $dnn[0];
1006       $value = $dnn[1];
1008       /* Every block must begin with a dn */
1009       if($dn != "dn") {
1010         $error= sprintf(_("This is not a valid DN: '%s'. A block for import should begin with 'dn: ...' in line %s"), $line, $current_line);
1011         return -2;  
1012       }
1014       /* Should we use Modify instead of Add */
1015       $usemodify= false;
1017       /* Delete before insert */
1018       $usermdir= false;
1019     
1020       /* The dn address already exists, Don't delete destination entry, overwrite it */
1021       if (($this->dn_exists($value))&&((!$JustModify)&&(!$DeleteOldEntries))) {
1023         $usermdir = $usemodify = false;
1025       /* Delete old entry first, then add new */
1026       } elseif(($this->dn_exists($value))&&($DeleteOldEntries)){
1028         /* Delete first, then add */
1029         $usermdir = true;        
1031       } elseif(($this->dn_exists($value))&&($JustModify)) {
1032         
1033         /* Modify instead of Add */
1034         $usemodify = true;
1035       }
1036      
1037       /* If we can't Import, return with a file error */
1038       if(!$this->import_single_entry($srp, $single,$usemodify,$usermdir) ) {
1039         $error= sprintf(_("Error while importing dn: '%s', please check your LDIF from line %s on!"), $line,
1040                         $current_line);
1041         return UNKNOWN_TOKEN_IN_LDIF_FILE;      }
1042     }
1044     return (INSERT_OK);
1045   }
1048   /* Imports a single entry 
1049       If $delete is true;  The old entry will be deleted if it exists.
1050       if $modify is true;  All variables that are not touched by the new ldif will be kept.
1051       if $modify is false; The new ldif overwrites the old entry, and all untouched attributes get lost.
1052   */
1053   function import_single_entry($srp, $str_attr,$modify,$delete)
1054   {
1055     global $config;
1057     if(!$config){
1058       trigger_error("Can't import ldif, can't read config object.");
1059     }
1060   
1062     if($this->reconnect) $this->connect();
1064     $ret = false;
1065     $rows= split("\n",$str_attr);
1066     $data= false;
1068     foreach($rows as $row) {
1069       
1070       /* Check if we use Linenumbers (when import_complete_ldif is called we use
1071          Linenumbers) Linenumbers are use like this 123#attribute : value */
1072       if(!empty($row)) {
1073         if(strpos($row,"#")!=FALSE) {
1075           /* We are using line numbers 
1076              Because there is a # before a : */
1077           $tmp1= split("#",$row);
1078           $current_line= $tmp1[0];
1079           $row= base64_decode($tmp1[1]);
1080         }
1082         /* Split the line into  attribute  and value */
1083         $attr   = split(":", $row,2);
1084         $attr[0]= trim($attr[0]);  /* attribute */
1085         $attr[1]= $attr[1];  /* value */
1087         /* Check :: was used to indicate base64_encoded strings */
1088         if($attr[1][0] == ":"){
1089           $attr[1]=trim(preg_replace("/^:/","",$attr[1]));
1090           $attr[1]=base64_decode($attr[1]);
1091         }
1093         $attr[1] = trim($attr[1]);
1095         /* Check for attributes that are used more than once */
1096         if(!isset($data[$attr[0]])) {
1097           $data[$attr[0]]=$attr[1];
1098         } else {
1099           $tmp = $data[$attr[0]];
1101           if(!is_array($tmp)) {
1102             $new[0]=$tmp;
1103             $new[1]=$attr[1];
1104             $datas[$attr[0]]['count']=1;             
1105             $data[$attr[0]]=$new;
1106           } else {
1107             $cnt = $datas[$attr[0]]['count'];           
1108             $cnt ++;
1109             $data[$attr[0]][$cnt]=$attr[1];
1110             $datas[$attr[0]]['count'] = $cnt;
1111           }
1112         }
1113       }
1114     }
1116     /* If dn is an index of data, we should try to insert the data */
1117     if(isset($data['dn'])) {
1119       /* Fix dn */
1120       $tmp = gosa_ldap_explode_dn($data['dn']);
1121       unset($tmp['count']);
1122       $newdn ="";
1123       foreach($tmp as $tm){
1124         $newdn.= trim($tm).",";
1125       }
1126       $newdn = preg_replace("/,$/","",$newdn);
1127       $data['dn'] = $newdn;
1128    
1129       /* Creating Entry */
1130       $this->cd($data['dn']);
1132       /* Delete existing entry */
1133       if($delete){
1134         $this->rmdir_recursive($srp, $data['dn']);
1135       }
1136      
1137       /* Create missing trees */
1138       $this->cd ($this->basedn);
1139       $this->cd($config->current['BASE']);
1140       $this->create_missing_trees($srp, preg_replace("/^[^,]+,/","",$data['dn']));
1141       $this->cd($data['dn']);
1143       $dn = $data['dn'];
1144       unset($data['dn']);
1145       
1146       if(!$modify){
1148         $this->cat($srp, $dn);
1149         if($this->count($srp)){
1150         
1151           /* The destination entry exists, overwrite it with the new entry */
1152           $attrs = $this->fetch($srp);
1153           foreach($attrs as $name => $value ){
1154             if(!is_numeric($name)){
1155               if(in_array($name,array("dn","count"))) continue;
1156               if(!isset($data[$name])){
1157                 $data[$name] = array();
1158               }
1159             }
1160           }
1161           $ret = $this->modify($data);
1162     
1163         }else{
1164     
1165           /* The destination entry doesn't exists, create it */
1166           $ret = $this->add($data);
1167         }
1169       } else {
1170         
1171         /* Keep all vars that aren't touched by this ldif */
1172         $ret = $this->modify($data);
1173       }
1174     }
1176     if (!$this->success()){
1177       msg_dialog::display(_("LDAP error"), msgPool::ldaperror($this->get_error(), $dn, "", get_class()));
1178     }
1180     return($ret);
1181   }
1183   
1184   function importcsv($str)
1185   {
1186     $lines = split("\n",$str);
1187     foreach($lines as $line)
1188     {
1189       /* continue if theres a comment */
1190       if(substr(trim($line),0,1)=="#"){
1191         continue;
1192       }
1194       $line= str_replace ("\t\t","\t",$line);
1195       $line= str_replace ("\t"  ,"," ,$line);
1196       echo $line;
1198       $cells = split(",",$line )  ;
1199       $linet= str_replace ("\t\t",",",$line);
1200       $cells = split("\t",$line);
1201       $count = count($cells);  
1202     }
1204   }
1205   
1206   function get_objectclasses( $force_reload = FALSE)
1207   {
1208     $objectclasses = array();
1209     global $config;
1211     /* Only read schema if it is allowed */
1212     if(isset($config) && preg_match("/config/i",get_class($config))){
1213       if ($config->get_cfg_value("schemaCheck") != "true"){
1214         return($objectclasses);
1215       } 
1216     }
1218     /* Return the cached results. */
1219     if(class_available('session') && session::global_is_set("LDAP_CACHE::get_objectclasses") && !$force_reload){
1220       $objectclasses = session::global_get("LDAP_CACHE::get_objectclasses");
1221       return($objectclasses);
1222     }
1223         
1224           # Get base to look for schema 
1225           $sr = @ldap_read ($this->cid, "", "objectClass=*", array("subschemaSubentry"));
1226           $attr = @ldap_get_entries($this->cid,$sr);
1227           if (!isset($attr[0]['subschemasubentry'][0])){
1228             return array();
1229           }
1230         
1231           /* Get list of objectclasses and fill array */
1232           $nb= $attr[0]['subschemasubentry'][0];
1233           $objectclasses= array();
1234           $sr= ldap_read ($this->cid, $nb, "objectClass=*", array("objectclasses"));
1235           $attrs= ldap_get_entries($this->cid,$sr);
1236           if (!isset($attrs[0])){
1237             return array();
1238           }
1239           foreach ($attrs[0]['objectclasses'] as $val){
1240       if (preg_match('/^[0-9]+$/', $val)){
1241         continue;
1242       }
1243       $name= "OID";
1244       $pattern= split(' ', $val);
1245       $ocname= preg_replace("/^.* NAME\s+\(*\s*'([^']+)'\s*\)*.*$/", '\\1', $val);
1246       $objectclasses[$ocname]= array();
1248       foreach($pattern as $chunk){
1249         switch($chunk){
1251           case '(':
1252                     $value= "";
1253                     break;
1255           case ')': if ($name != ""){
1256                       $objectclasses[$ocname][$name]= $this->value2container($value);
1257                     }
1258                     $name= "";
1259                     $value= "";
1260                     break;
1262           case 'NAME':
1263           case 'DESC':
1264           case 'SUP':
1265           case 'STRUCTURAL':
1266           case 'ABSTRACT':
1267           case 'AUXILIARY':
1268           case 'MUST':
1269           case 'MAY':
1270                     if ($name != ""){
1271                       $objectclasses[$ocname][$name]= $this->value2container($value);
1272                     }
1273                     $name= $chunk;
1274                     $value= "";
1275                     break;
1277           default:  $value.= $chunk." ";
1278         }
1279       }
1281           }
1282     if(class_available("session")){
1283       session::global_set("LDAP_CACHE::get_objectclasses",$objectclasses);
1284     }
1286           return $objectclasses;
1287   }
1290   function value2container($value)
1291   {
1292     /* Set emtpy values to "true" only */
1293     if (preg_match('/^\s*$/', $value)){
1294       return true;
1295     }
1297     /* Remove ' and " if needed */
1298     $value= preg_replace('/^[\'"]/', '', $value);
1299     $value= preg_replace('/[\'"] *$/', '', $value);
1301     /* Convert to array if $ is inside... */
1302     if (preg_match('/\$/', $value)){
1303       $container= preg_split('/\s*\$\s*/', $value);
1304     } else {
1305       $container= chop($value);
1306     }
1308     return ($container);
1309   }
1312   function log($string)
1313   {
1314     if (session::global_is_set('config')){
1315       $cfg = session::global_get('config');
1316       if (isset($cfg->current['LDAPSTATS']) && preg_match('/true/i', $cfg->current['LDAPSTATS'])){
1317         syslog (LOG_INFO, $string);
1318       }
1319     }
1320   }
1322   /* added by Guido Serra aka Zeph <zeph@purotesto.it> */
1323   function getCn($dn){
1324     $simple= split(",", $dn);
1326     foreach($simple as $piece) {
1327       $partial= split("=", $piece);
1329       if($partial[0] == "cn"){
1330         return $partial[1];
1331       }
1332     }
1333   }
1336   function get_naming_contexts($server, $admin= "", $password= "")
1337   {
1338     /* Build LDAP connection */
1339     $ds= ldap_connect ($server);
1340     if (!$ds) {
1341       die ("Can't bind to LDAP. No check possible!");
1342     }
1343     ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
1344     $r= ldap_bind ($ds, $admin, $password);
1346     /* Get base to look for naming contexts */
1347     $sr  = @ldap_read ($ds, "", "objectClass=*", array("+"));
1348     $attr= @ldap_get_entries($ds,$sr);
1350     return ($attr[0]['namingcontexts']);
1351   }
1354   function get_root_dse($server, $admin= "", $password= "")
1355   {
1356     /* Build LDAP connection */
1357     $ds= ldap_connect ($server);
1358     if (!$ds) {
1359       die ("Can't bind to LDAP. No check possible!");
1360     }
1361     ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
1362     $r= ldap_bind ($ds, $admin, $password);
1364     /* Get base to look for naming contexts */
1365     $sr  = @ldap_read ($ds, "", "objectClass=*", array("+"));
1366     $attr= @ldap_get_entries($ds,$sr);
1367    
1368     /* Return empty array, if nothing was set */
1369     if (!isset($attr[0])){
1370       return array();
1371     }
1373     /* Rework array... */
1374     $result= array();
1375     for ($i= 0; $i<$attr[0]['count']; $i++){
1376       $result[$attr[0][$i]]= $attr[0][$attr[0][$i]];
1377       unset($result[$attr[0][$i]]['count']);
1378     }
1380     return ($result);
1381   }
1384 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
1385 ?>