Code

Display a warning if the size limit of an ldap search is exceeded
[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       if ($this->error == "Size limit exceeded") {
228         global $config;
229         if (preg_match('/true/i', $config->get_cfg_value('sizelimitWarning'))) {
230           msg_dialog::display(_("Size Limit Exceeded"), sprintf(_("More than %d objects were found in a query, the rest is being ignored!"), session::global_get('size_limit')), WARNING_DIALOG);
231         }
232       }
233       $this->resetResult($srp);
234       $this->hasres[$srp]=true;
235    
236       /* Check if query took longer as specified in max_ldap_query_time */
237       if($this->max_ldap_query_time){
238         $diff = get_MicroTimeDiff($start,microtime());
239         if($diff > $this->max_ldap_query_time){
240           msg_dialog::display(_("Performance warning"), sprintf(_("LDAP performance is poor: last query took about %.2fs!"), $diff), WARNING_DIALOG);
241         }
242       }
244       $this->log("LDAP operation: time=".get_MicroTimeDiff($start,microtime())." operation=search('".LDAP::fix($this->basedn)."', '$filter')");
245       return($this->sr[$srp]);
246     }else{
247       $this->error = "Could not connect to LDAP server";
248       return("");
249     }
250   }
252   function ls($srp, $filter = "(objectclass=*)", $basedn = "",$attrs = array("*"))
253   {
254     if($this->hascon){
255       if ($this->reconnect) $this->connect();
257       $this->clearResult($srp);
258       if ($basedn == "")
259         $basedn = $this->basedn;
260       else
261         $basedn= LDAP::convert($basedn);
262   
263       $start = microtime();
264       $this->sr[$srp] = @ldap_list($this->cid, LDAP::fix($basedn), $filter,$attrs);
265       $this->error = @ldap_error($this->cid);
266       $this->resetResult($srp);
267       $this->hasres[$srp]=true;
269        /* Check if query took longer as specified in max_ldap_query_time */
270       if($this->max_ldap_query_time){
271         $diff = get_MicroTimeDiff($start,microtime());
272         if($diff > $this->max_ldap_query_time){
273           msg_dialog::display(_("Performance warning"), sprintf(_("LDAP performance is poor: last query took about %.2fs!"), $diff), WARNING_DIALOG);
274         }
275       }
277       $this->log("LDAP operation: time=".get_MicroTimeDiff($start,microtime())." operation=ls('".LDAP::fix($basedn)."', '$filter')");
279       return($this->sr[$srp]);
280     }else{
281       $this->error = "Could not connect to LDAP server";
282       return("");
283     }
284   }
286   function cat($srp, $dn,$attrs= array("*"))
287   {
288     if($this->hascon){
289       if ($this->reconnect) $this->connect();
291       $this->clearResult($srp);
292       $filter = "(objectclass=*)";
293       $this->sr[$srp] = @ldap_read($this->cid, LDAP::fix($dn), $filter,$attrs);
294       $this->error = @ldap_error($this->cid);
295       $this->resetResult($srp);
296       $this->hasres[$srp]=true;
297       return($this->sr[$srp]);
298     }else{
299       $this->error = "Could not connect to LDAP server";
300       return("");
301     }
302   }
304   function object_match_filter($dn,$filter)
305   {
306     if($this->hascon){
307       if ($this->reconnect) $this->connect();
308       $res =  @ldap_read($this->cid, LDAP::fix($dn), $filter, array("objectClass"));
309       $rv =   @ldap_count_entries($this->cid, $res);
310       return($rv);
311     }else{
312       $this->error = "Could not connect to LDAP server";
313       return(FALSE);
314     }
315   }
317   function set_size_limit($size)
318   {
319     /* Ignore zero settings */
320     if ($size == 0){
321       @ldap_set_option($this->cid, LDAP_OPT_SIZELIMIT, 10000000);
322     }
323     if($this->hascon){
324       @ldap_set_option($this->cid, LDAP_OPT_SIZELIMIT, $size);
325     } else {
326       $this->error = "Could not connect to LDAP server";
327     }
328   }
330   function fetch($srp)
331   {
332     $att= array();
333     if($this->hascon){
334       if($this->hasres[$srp]){
335         if ($this->start[$srp] == 0)
336         {
337           if ($this->sr[$srp]){
338             $this->start[$srp] = 1;
339             $this->re[$srp]= @ldap_first_entry($this->cid, $this->sr[$srp]);
340           } else {
341             return array();
342           }
343         } else {
344           $this->re[$srp]= @ldap_next_entry($this->cid, $this->re[$srp]);
345         }
346         if ($this->re[$srp])
347         {
348           $att= @ldap_get_attributes($this->cid, $this->re[$srp]);
349           $att['dn']= trim(LDAP::convert(@ldap_get_dn($this->cid, $this->re[$srp])));
350         }
351         $this->error = @ldap_error($this->cid);
352         if (!isset($att)){
353           $att= array();
354         }
355         return($att);
356       }else{
357         $this->error = "Perform a fetch with no search";
358         return("");
359       }
360     }else{
361       $this->error = "Could not connect to LDAP server";
362       return("");
363     }
364   }
366   function resetResult($srp)
367   {
368     $this->start[$srp] = 0;
369   }
371   function clearResult($srp)
372   {
373     if($this->hasres[$srp]){
374       $this->hasres[$srp] = false;
375       @ldap_free_result($this->sr[$srp]);
376     }
377   }
379   function getDN($srp)
380   {
381     if($this->hascon){
382       if($this->hasres[$srp]){
384         if((!isset($this->re[$srp])) || (!$this->re[$srp]))
385           {
386           $this->error = "Perform a Fetch with no valid Result";
387           }
388           else
389           {
390           $rv = @ldap_get_dn($this->cid, $this->re[$srp]);
391         
392           $this->error = @ldap_error($this->cid);
393           return(trim(LDAP::convert($rv)));
394            }
395       }else{
396         $this->error = "Perform a Fetch with no Search";
397         return("");
398       }
399     }else{
400       $this->error = "Could not connect to LDAP server";
401       return("");
402     }
403   }
405   function count($srp)
406   {
407     if($this->hascon){
408       if($this->hasres[$srp]){
409         $rv = @ldap_count_entries($this->cid, $this->sr[$srp]);
410         $this->error = @ldap_error($this->cid);
411         return($rv);
412       }else{
413         $this->error = "Perform a Fetch with no Search";
414         return("");
415       }
416     }else{
417       $this->error = "Could not connect to LDAP server";
418       return("");
419     }
420   }
422   function rm($attrs = "", $dn = "")
423   {
424     if($this->hascon){
425       if ($this->reconnect) $this->connect();
426       if ($dn == "")
427         $dn = $this->basedn;
429       $r = @ldap_mod_del($this->cid, LDAP::fix($dn), $attrs);
430       $this->error = @ldap_error($this->cid);
431       return($r);
432     }else{
433       $this->error = "Could not connect to LDAP server";
434       return("");
435     }
436   }
438   function rename($attrs, $dn = "")
439   {
440     if($this->hascon){
441       if ($this->reconnect) $this->connect();
442       if ($dn == "")
443         $dn = $this->basedn;
445       $r = @ldap_mod_replace($this->cid, LDAP::fix($dn), $attrs);
446       $this->error = @ldap_error($this->cid);
447       return($r);
448     }else{
449       $this->error = "Could not connect to LDAP server";
450       return("");
451     }
452   }
454   function rmdir($deletedn)
455   {
456     if($this->hascon){
457       if ($this->reconnect) $this->connect();
458       $r = @ldap_delete($this->cid, LDAP::fix($deletedn));
459       $this->error = @ldap_error($this->cid);
460       return($r ? $r : 0);
461     }else{
462       $this->error = "Could not connect to LDAP server";
463       return("");
464     }
465   }
468   /*! \brief Move the given Ldap entry from $source to $dest
469       @param  String  $source The source dn.
470       @param  String  $dest   The destination dn.
471       @return Boolean TRUE on success else FALSE.
472    */
473   function rename_dn($source,$dest)
474   {
475     /* Check if source and destination are the same entry */
476     if(strtolower($source) == strtolower($dest)){
477       trigger_error("Source and destination can't be the same entry.");
478       $this->error = "Source and destination can't be the same entry.";
479       return(FALSE);
480     }
482     /* Check if destination entry exists */    
483     if($this->dn_exists($dest)){
484       trigger_error("Destination '$dest' already exists.");
485       $this->error = "Destination '$dest' already exists.";
486       return(FALSE);
487     }
489     /* Extract the name and the parent part out ouf source dn.
490         e.g.  cn=herbert,ou=department,dc=... 
491          parent   =>  ou=department,dc=...
492          dest_rdn =>  cn=herbert
493      */
494     $parent   = preg_replace("/^[^,]+,/","", $dest);
495     $dest_rdn = preg_replace("/,.*$/","",$dest);
497     if($this->hascon){
498       if ($this->reconnect) $this->connect();
499       $r= ldap_rename($this->cid,@LDAP::fix($source), @LDAP::fix($dest_rdn),@LDAP::fix($parent),TRUE); 
500       $this->error = ldap_error($this->cid);
502       /* Check if destination dn exists, if not the 
503           server may not support this operation */
504       $r &= is_resource($this->dn_exists($dest));
505       return($r);
506     }else{
507       $this->error = "Could not connect to LDAP server";
508       return(FALSE);
509     }
510   }
513   /**
514   *  Function rmdir_recursive
515   *
516   *  Description: Based in recursive_remove, adding two thing: full subtree remove, and delete own node.
517   *  Parameters:  The dn to delete
518   *  GiveBack:    True on sucessfull , 0 in error, and "" when we don't get a ldap conection
519   *
520   */
521   function rmdir_recursive($srp, $deletedn)
522   {
523     if($this->hascon){
524       if ($this->reconnect) $this->connect();
525       $delarray= array();
526         
527       /* Get sorted list of dn's to delete */
528       $this->ls ($srp, "(objectClass=*)",$deletedn);
529       while ($this->fetch($srp)){
530         $deldn= $this->getDN($srp);
531         $delarray[$deldn]= strlen($deldn);
532       }
533       arsort ($delarray);
534       reset ($delarray);
536       /* Really Delete ALL dn's in subtree */
537       foreach ($delarray as $key => $value){
538         $this->rmdir_recursive($srp, $key);
539       }
540       
541       /* Finally Delete own Node */
542       $r = @ldap_delete($this->cid, LDAP::fix($deletedn));
543       $this->error = @ldap_error($this->cid);
544       return($r ? $r : 0);
545     }else{
546       $this->error = "Could not connect to LDAP server";
547       return("");
548     }
549   }
552   function modify($attrs)
553   {
554     if(count($attrs) == 0){
555       return (0);
556     }
557     if($this->hascon){
558       if ($this->reconnect) $this->connect();
559       $r = @ldap_modify($this->cid, LDAP::fix($this->basedn), $attrs);
560       $this->error = @ldap_error($this->cid);
561       return($r ? $r : 0);
562     }else{
563       $this->error = "Could not connect to LDAP server";
564       return("");
565     }
566   }
568   function add($attrs)
569   {
570     if($this->hascon){
571       if ($this->reconnect) $this->connect();
572       $r = @ldap_add($this->cid, LDAP::fix($this->basedn), $attrs);
573       $this->error = @ldap_error($this->cid);
574       return($r ? $r : 0);
575     }else{
576       $this->error = "Could not connect to LDAP server";
577       return("");
578     }
579   }
581   function create_missing_trees($srp, $target)
582   {
583     global $config;
585     $real_path= substr($target, 0, strlen($target) - strlen($this->basedn) -1 );
587     if ($target == $this->basedn){
588       $l= array("dummy");
589     } else {
590       $l= array_reverse(gosa_ldap_explode_dn($real_path));
591     }
592     unset($l['count']);
593     $cdn= $this->basedn;
594     $tag= "";
596     /* Load schema if available... */
597     $classes= $this->get_objectclasses();
599     foreach ($l as $part){
600       if ($part != "dummy"){
601         $cdn= "$part,$cdn";
602       }
604       /* Ignore referrals */
605       $found= false;
606       foreach($this->referrals as $ref){
607         $base= preg_replace('!^[^:]+://[^/]+/([^?]+).*$!', '\\1', $ref['URI']);
608         if ($base == $cdn){
609           $found= true;
610           break;
611         }
612       }
613       if ($found){
614         continue;
615       }
617       $this->cat ($srp, $cdn);
618       $attrs= $this->fetch($srp);
620       /* Create missing entry? */
621       if (count ($attrs)){
622       
623         /* Catch the tag - if present */
624         if (isset($attrs['gosaUnitTag'][0])){
625           $tag= $attrs['gosaUnitTag'][0];
626         }
628       } else {
629         $type= preg_replace('/^([^=]+)=.*$/', '\\1', $cdn);
630         $param= preg_replace('/^[^=]+=([^,]+).*$/', '\\1', $cdn);
632         $na= array();
634         /* Automatic or traditional? */
635         if(count($classes)){
637           /* Get name of first matching objectClass */
638           $ocname= "";
639           foreach($classes as $class){
640             if (isset($class['MUST']) && $class['MUST'] == "$type"){
642               /* Look for first classes that is structural... */
643               if (isset($class['STRUCTURAL'])){
644                 $ocname= $class['NAME'];
645                 break;
646               }
648               /* Look for classes that are auxiliary... */
649               if (isset($class['AUXILIARY'])){
650                 $ocname= $class['NAME'];
651               }
652             }
653           }
655           /* Bail out, if we've nothing to do... */
656           if ($ocname == ""){
657             msg_dialog::display(_("Internal error"), sprintf(_("Cannot automatically create subtrees with RDN '%s': no object class found!"),$type), FATAL_ERROR_DIALOG);
658             exit();
659           }
661           /* Assemble_entry */
662           if ($tag != ""){
663             $na['objectClass']= array($ocname, "gosaAdministrativeUnitTag");
664             $na["gosaUnitTag"]= $tag;
665           } else {
666             $na['objectClass']= array($ocname);
667           }
668           if (isset($classes[$ocname]['AUXILIARY'])){
669             $na['objectClass'][]= $classes[$ocname]['SUP'];
670           }
671           if ($type == "dc"){
672             /* This is bad actually, but - tell me a better way? */
673             $na['objectClass'][]= 'locality';
674           }
675           $na[$type]= $param;
676           if (is_array($classes[$ocname]['MUST'])){
677             foreach($classes[$ocname]['MUST'] as $attr){
678               $na[$attr]= "filled";
679             }
680           }
682         } else {
684           /* Use alternative add... */
685           switch ($type){
686             case 'ou':
687               if ($tag != ""){
688                 $na["objectClass"]= array("organizationalUnit", "gosaAdministrativeUnitTag");
689                 $na["gosaUnitTag"]= $tag;
690               } else {
691                 $na["objectClass"]= "organizationalUnit";
692               }
693               $na["ou"]= $param;
694               break;
695             case 'dc':
696               if ($tag != ""){
697                 $na["objectClass"]= array("dcObject", "top", "locality", "gosaAdministrativeUnitTag");
698                 $na["gosaUnitTag"]= $tag;
699               } else {
700                 $na["objectClass"]= array("dcObject", "top", "locality");
701               }
702               $na["dc"]= $param;
703               break;
704             default:
705               msg_dialog::display(_("Internal error"), sprintf(_("Cannot automatically create subtrees with RDN '%s': not supported"),$type), FATAL_ERROR_DIALOG);
706               exit();
707           }
709         }
710         $this->cd($cdn);
711         $this->add($na);
712     
713         if (!$this->success()){
715           print_a(array($cdn,$na));
717           msg_dialog::display(_("LDAP error"), msgPool::ldaperror($this->get_error(), $cdn, LDAP_ADD, get_class()));
718           return FALSE;
719         }
720       }
721     }
723     return TRUE;
724   }
727   function recursive_remove($srp)
728   {
729     $delarray= array();
731     /* Get sorted list of dn's to delete */
732     $this->search ($srp, "(objectClass=*)");
733     while ($this->fetch($srp)){
734       $deldn= $this->getDN($srp);
735       $delarray[$deldn]= strlen($deldn);
736     }
737     arsort ($delarray);
738     reset ($delarray);
740     /* Delete all dn's in subtree */
741     foreach ($delarray as $key => $value){
742       $this->rmdir($key);
743     }
744   }
746   function get_attribute($dn, $name,$r_array=0)
747   {
748     $data= "";
749     if ($this->reconnect) $this->connect();
750     $sr= @ldap_read($this->cid, LDAP::fix($dn), "objectClass=*", array("$name"));
752     /* fill data from LDAP */
753     if ($sr) {
754       $ei= @ldap_first_entry($this->cid, $sr);
755       if ($ei) {
756         if ($info= @ldap_get_values_len($this->cid, $ei, "$name")){
757           $data= $info[0];
758         }
759       }
760     }
761     if($r_array==0)
762     return ($data);
763     else
764     return ($info);
765   
766   
767   }
768  
771   function get_additional_error()
772   {
773     $error= "";
774     @ldap_get_option ($this->cid, LDAP_OPT_ERROR_STRING, $error);
775     return ($error);
776   }
779   function success()
780   {
781     return (preg_match('/Success/i', $this->error));
782   }
785   function get_error()
786   {
787     if ($this->error == 'Success'){
788       return $this->error;
789     } else {
790       $adderror= $this->get_additional_error();
791       if ($adderror != ""){
792         $error= $this->error." (".$this->get_additional_error().", ".sprintf(_("while operating on '%s' using LDAP server '%s'"), $this->basedn, $this->hostname).")";
793       } else {
794         $error= $this->error." (".sprintf(_("while operating on LDAP server %s"), $this->hostname).")";
795       }
796       return $error;
797     }
798   }
800   function get_credentials($url, $referrals= NULL)
801   {
802     $ret= array();
803     $url= preg_replace('!\?\?.*$!', '', $url);
804     $server= preg_replace('!^([^:]+://[^/]+)/.*$!', '\\1', $url);
806     if ($referrals === NULL){
807       $referrals= $this->referrals;
808     }
810     if (isset($referrals[$server])){
811       return ($referrals[$server]);
812     } else {
813       $ret['ADMINDN']= LDAP::fix($this->binddn);
814       $ret['ADMINPASSWORD']= $this->bindpw;
815     }
817     return ($ret);
818   }
821   function gen_ldif ($srp, $dn, $filter= "(objectClass=*)", $attributes= array('*'), $recursive= TRUE)
822   {
823     $display= "";
825     if ($recursive){
826       $this->cd($dn);
827       $this->ls($srp, $filter,$dn, array('dn','objectClass'));
828       $deps = array();
830       $display .= $this->gen_one_entry($dn)."\n";
832       while ($attrs= $this->fetch($srp)){
833         $deps[] = $attrs['dn'];
834       }
835       foreach($deps as $dn){
836         $display .= $this->gen_ldif($srp, $dn, $filter,$attributes,$recursive);
837       }
838     } else {
839       $display.= $this->gen_one_entry($dn);
840     }
841     return ($display);
842   }
845   function gen_xls ($srp, $dn, $filter= "(objectClass=*)", $attributes= array('*'), $recursive= TRUE,$r_array=0)
846   {
847     $display= array();
849       $this->cd($dn);
850       $this->search($srp, "$filter");
852       $i=0;
853       while ($attrs= $this->fetch($srp)){
854         $j=0;
856         foreach ($attributes as $at){
857           $display[$i][$j]= $this->get_attribute($attrs['dn'], $at,$r_array);
858           $j++;
859         }
861         $i++;
862       }
864     return ($display);
865   }
868   function gen_one_entry($dn, $filter= "(objectClass=*)" , $name= array("*"))
869   {
870     $ret = "";
871     $data = "";
872     if($this->reconnect){
873       $this->connect();
874     }
876     /* Searching Ldap Tree */
877     $sr= @ldap_read($this->cid, LDAP::fix($dn), $filter, $name);
879     /* Get the first entry */   
880     $entry= @ldap_first_entry($this->cid, $sr);
882     /* Get all attributes related to that Objekt */
883     $atts = array();
884     
885     /* Assemble dn */
886     $atts[0]['name']  = "dn";
887     $atts[0]['value'] = array('count' => 1, 0 => $dn);
889     /* Reset index */
890     $i = 1 ; 
891   $identifier = array();
892     $attribute= @ldap_first_attribute($this->cid,$entry,$identifier);
893     while ($attribute) {
894       $i++;
895       $atts[$i]['name']  = $attribute;
896       $atts[$i]['value'] = @ldap_get_values_len($this->cid, $entry, "$attribute");
898       /* Next one */
899       $attribute= @ldap_next_attribute($this->cid,$entry,$identifier);
900     }
902     foreach($atts as $at)
903     {
904       for ($i= 0; $i<$at['value']['count']; $i++){
906         /* Check if we must encode the data */
907         if(!preg_match('/^[a-z0-9+@#.=, \/ -]+$/i', $at['value'][$i])) {
908           $ret .= $at['name'].":: ".base64_encode($at['value'][$i])."\n";
909         } else {
910           $ret .= $at['name'].": ".$at['value'][$i]."\n";
911         }
912       }
913     }
915     return($ret);
916   }
919   function dn_exists($dn)
920   {
921     return @ldap_list($this->cid, LDAP::fix($dn), "(objectClass=*)", array("objectClass"));
922   }
923   
926   /*  This funktion imports ldifs 
927         
928       If DeleteOldEntries is true, the destination entry will be deleted first. 
929       If JustModify is true the destination entry will only be touched by the attributes specified in the ldif.
930       if JustMofify id false the destination dn will be overwritten by the new ldif. 
931     */
933   function import_complete_ldif($srp, $str_attr,$error,$JustModify,$DeleteOldEntries)
934   {
935     if($this->reconnect) $this->connect();
937     /* First we have to splitt the string ito detect empty lines
938        An empty line indicates an new Entry */
939     $entries = split("\n",$str_attr);
941     $data = "";
942     $cnt = 0; 
943     $current_line = 0;
945     /* FIX ldif */
946     $last = "";
947     $tmp  = "";
948     $i = 0;
949     foreach($entries as $entry){
950       if(preg_match("/^ /",$entry)){
951         $tmp[$i] .= trim($entry);
952       }else{
953         $i ++;
954         $tmp[$i] = trim($entry);
955       }
956     }
958     /* Every single line ... */
959     foreach($tmp as $entry) {
960       $current_line ++;
962       /* Removing Spaces to .. 
963          .. test if a new entry begins */
964       $tmp  = str_replace(" ","",$data );
966       /* .. prevent empty lines in an entry */
967       $tmp2 = str_replace(" ","",$entry);
969       /* If the Block ends (Empty Line) */
970       if((empty($entry))&&(!empty($tmp))) {
971         /* Add collected lines as a complete block */
972         $all[$cnt] = $data;
973         $cnt ++;
974         $data ="";
975       } else {
977         /* Append lines ... */
978         if(!empty($tmp2)) {
979           /* check if we need base64_decode for this line */
980           if(ereg("::",$tmp2))
981           {
982             $encoded = split("::",$entry);
983             $attr  = trim($encoded[0]);
984             $value = base64_decode(trim($encoded[1]));
985             /* Add linenumber */
986             $data .= $current_line."#".base64_encode($attr.":".$value)."\n";
987           }
988           else
989           {
990             /* Add Linenumber */ 
991             $data .= $current_line."#".base64_encode($entry)."\n";
992           }
993         }
994       }
995     }
997     /* The Data we collected is not in the array all[];
998        For example the Data is stored like this..
1000        all[0] = "1#dn : .... \n 
1001        2#ObjectType: person \n ...."
1002        
1003        Now we check every insertblock and try to insert */
1004     foreach ( $all as $single) {
1005       $lineone = split("\n",$single);  
1006       $ndn = split("#", $lineone[0]);
1007       $line = base64_decode($ndn[1]);
1009       $dnn = split (":",$line,2);
1010       $current_line = $ndn[0];
1011       $dn    = $dnn[0];
1012       $value = $dnn[1];
1014       /* Every block must begin with a dn */
1015       if($dn != "dn") {
1016         $error= sprintf(_("This is not a valid DN: '%s'. A block for import should begin with 'dn: ...' in line %s"), $line, $current_line);
1017         return -2;  
1018       }
1020       /* Should we use Modify instead of Add */
1021       $usemodify= false;
1023       /* Delete before insert */
1024       $usermdir= false;
1025     
1026       /* The dn address already exists, Don't delete destination entry, overwrite it */
1027       if (($this->dn_exists($value))&&((!$JustModify)&&(!$DeleteOldEntries))) {
1029         $usermdir = $usemodify = false;
1031       /* Delete old entry first, then add new */
1032       } elseif(($this->dn_exists($value))&&($DeleteOldEntries)){
1034         /* Delete first, then add */
1035         $usermdir = true;        
1037       } elseif(($this->dn_exists($value))&&($JustModify)) {
1038         
1039         /* Modify instead of Add */
1040         $usemodify = true;
1041       }
1042      
1043       /* If we can't Import, return with a file error */
1044       if(!$this->import_single_entry($srp, $single,$usemodify,$usermdir) ) {
1045         $error= sprintf(_("Error while importing dn: '%s', please check your LDIF from line %s on!"), $line,
1046                         $current_line);
1047         return UNKNOWN_TOKEN_IN_LDIF_FILE;      }
1048     }
1050     return (INSERT_OK);
1051   }
1054   /* Imports a single entry 
1055       If $delete is true;  The old entry will be deleted if it exists.
1056       if $modify is true;  All variables that are not touched by the new ldif will be kept.
1057       if $modify is false; The new ldif overwrites the old entry, and all untouched attributes get lost.
1058   */
1059   function import_single_entry($srp, $str_attr,$modify,$delete)
1060   {
1061     global $config;
1063     if(!$config){
1064       trigger_error("Can't import ldif, can't read config object.");
1065     }
1066   
1068     if($this->reconnect) $this->connect();
1070     $ret = false;
1071     $rows= split("\n",$str_attr);
1072     $data= false;
1074     foreach($rows as $row) {
1075       
1076       /* Check if we use Linenumbers (when import_complete_ldif is called we use
1077          Linenumbers) Linenumbers are use like this 123#attribute : value */
1078       if(!empty($row)) {
1079         if(strpos($row,"#")!=FALSE) {
1081           /* We are using line numbers 
1082              Because there is a # before a : */
1083           $tmp1= split("#",$row);
1084           $current_line= $tmp1[0];
1085           $row= base64_decode($tmp1[1]);
1086         }
1088         /* Split the line into  attribute  and value */
1089         $attr   = split(":", $row,2);
1090         $attr[0]= trim($attr[0]);  /* attribute */
1091         $attr[1]= $attr[1];  /* value */
1093         /* Check :: was used to indicate base64_encoded strings */
1094         if($attr[1][0] == ":"){
1095           $attr[1]=trim(preg_replace("/^:/","",$attr[1]));
1096           $attr[1]=base64_decode($attr[1]);
1097         }
1099         $attr[1] = trim($attr[1]);
1101         /* Check for attributes that are used more than once */
1102         if(!isset($data[$attr[0]])) {
1103           $data[$attr[0]]=$attr[1];
1104         } else {
1105           $tmp = $data[$attr[0]];
1107           if(!is_array($tmp)) {
1108             $new[0]=$tmp;
1109             $new[1]=$attr[1];
1110             $datas[$attr[0]]['count']=1;             
1111             $data[$attr[0]]=$new;
1112           } else {
1113             $cnt = $datas[$attr[0]]['count'];           
1114             $cnt ++;
1115             $data[$attr[0]][$cnt]=$attr[1];
1116             $datas[$attr[0]]['count'] = $cnt;
1117           }
1118         }
1119       }
1120     }
1122     /* If dn is an index of data, we should try to insert the data */
1123     if(isset($data['dn'])) {
1125       /* Fix dn */
1126       $tmp = gosa_ldap_explode_dn($data['dn']);
1127       unset($tmp['count']);
1128       $newdn ="";
1129       foreach($tmp as $tm){
1130         $newdn.= trim($tm).",";
1131       }
1132       $newdn = preg_replace("/,$/","",$newdn);
1133       $data['dn'] = $newdn;
1134    
1135       /* Creating Entry */
1136       $this->cd($data['dn']);
1138       /* Delete existing entry */
1139       if($delete){
1140         $this->rmdir_recursive($srp, $data['dn']);
1141       }
1142      
1143       /* Create missing trees */
1144       $this->cd ($this->basedn);
1145       $this->cd($config->current['BASE']);
1146       $this->create_missing_trees($srp, preg_replace("/^[^,]+,/","",$data['dn']));
1147       $this->cd($data['dn']);
1149       $dn = $data['dn'];
1150       unset($data['dn']);
1151       
1152       if(!$modify){
1154         $this->cat($srp, $dn);
1155         if($this->count($srp)){
1156         
1157           /* The destination entry exists, overwrite it with the new entry */
1158           $attrs = $this->fetch($srp);
1159           foreach($attrs as $name => $value ){
1160             if(!is_numeric($name)){
1161               if(in_array($name,array("dn","count"))) continue;
1162               if(!isset($data[$name])){
1163                 $data[$name] = array();
1164               }
1165             }
1166           }
1167           $ret = $this->modify($data);
1168     
1169         }else{
1170     
1171           /* The destination entry doesn't exists, create it */
1172           $ret = $this->add($data);
1173         }
1175       } else {
1176         
1177         /* Keep all vars that aren't touched by this ldif */
1178         $ret = $this->modify($data);
1179       }
1180     }
1182     if (!$this->success()){
1183       msg_dialog::display(_("LDAP error"), msgPool::ldaperror($this->get_error(), $dn, "", get_class()));
1184     }
1186     return($ret);
1187   }
1189   
1190   function importcsv($str)
1191   {
1192     $lines = split("\n",$str);
1193     foreach($lines as $line)
1194     {
1195       /* continue if theres a comment */
1196       if(substr(trim($line),0,1)=="#"){
1197         continue;
1198       }
1200       $line= str_replace ("\t\t","\t",$line);
1201       $line= str_replace ("\t"  ,"," ,$line);
1202       echo $line;
1204       $cells = split(",",$line )  ;
1205       $linet= str_replace ("\t\t",",",$line);
1206       $cells = split("\t",$line);
1207       $count = count($cells);  
1208     }
1210   }
1211   
1212   function get_objectclasses( $force_reload = FALSE)
1213   {
1214     $objectclasses = array();
1215     global $config;
1217     /* Only read schema if it is allowed */
1218     if(isset($config) && preg_match("/config/i",get_class($config))){
1219       if ($config->get_cfg_value("schemaCheck") != "true"){
1220         return($objectclasses);
1221       } 
1222     }
1224     /* Return the cached results. */
1225     if(class_available('session') && session::global_is_set("LDAP_CACHE::get_objectclasses") && !$force_reload){
1226       $objectclasses = session::global_get("LDAP_CACHE::get_objectclasses");
1227       return($objectclasses);
1228     }
1229         
1230           # Get base to look for schema 
1231           $sr = @ldap_read ($this->cid, "", "objectClass=*", array("subschemaSubentry"));
1232           $attr = @ldap_get_entries($this->cid,$sr);
1233           if (!isset($attr[0]['subschemasubentry'][0])){
1234             return array();
1235           }
1236         
1237           /* Get list of objectclasses and fill array */
1238           $nb= $attr[0]['subschemasubentry'][0];
1239           $objectclasses= array();
1240           $sr= ldap_read ($this->cid, $nb, "objectClass=*", array("objectclasses"));
1241           $attrs= ldap_get_entries($this->cid,$sr);
1242           if (!isset($attrs[0])){
1243             return array();
1244           }
1245           foreach ($attrs[0]['objectclasses'] as $val){
1246       if (preg_match('/^[0-9]+$/', $val)){
1247         continue;
1248       }
1249       $name= "OID";
1250       $pattern= split(' ', $val);
1251       $ocname= preg_replace("/^.* NAME\s+\(*\s*'([^']+)'\s*\)*.*$/", '\\1', $val);
1252       $objectclasses[$ocname]= array();
1254       foreach($pattern as $chunk){
1255         switch($chunk){
1257           case '(':
1258                     $value= "";
1259                     break;
1261           case ')': if ($name != ""){
1262                       $objectclasses[$ocname][$name]= $this->value2container($value);
1263                     }
1264                     $name= "";
1265                     $value= "";
1266                     break;
1268           case 'NAME':
1269           case 'DESC':
1270           case 'SUP':
1271           case 'STRUCTURAL':
1272           case 'ABSTRACT':
1273           case 'AUXILIARY':
1274           case 'MUST':
1275           case 'MAY':
1276                     if ($name != ""){
1277                       $objectclasses[$ocname][$name]= $this->value2container($value);
1278                     }
1279                     $name= $chunk;
1280                     $value= "";
1281                     break;
1283           default:  $value.= $chunk." ";
1284         }
1285       }
1287           }
1288     if(class_available("session")){
1289       session::global_set("LDAP_CACHE::get_objectclasses",$objectclasses);
1290     }
1292           return $objectclasses;
1293   }
1296   function value2container($value)
1297   {
1298     /* Set emtpy values to "true" only */
1299     if (preg_match('/^\s*$/', $value)){
1300       return true;
1301     }
1303     /* Remove ' and " if needed */
1304     $value= preg_replace('/^[\'"]/', '', $value);
1305     $value= preg_replace('/[\'"] *$/', '', $value);
1307     /* Convert to array if $ is inside... */
1308     if (preg_match('/\$/', $value)){
1309       $container= preg_split('/\s*\$\s*/', $value);
1310     } else {
1311       $container= chop($value);
1312     }
1314     return ($container);
1315   }
1318   function log($string)
1319   {
1320     if (session::global_is_set('config')){
1321       $cfg = session::global_get('config');
1322       if (isset($cfg->current['LDAPSTATS']) && preg_match('/true/i', $cfg->current['LDAPSTATS'])){
1323         syslog (LOG_INFO, $string);
1324       }
1325     }
1326   }
1328   /* added by Guido Serra aka Zeph <zeph@purotesto.it> */
1329   function getCn($dn){
1330     $simple= split(",", $dn);
1332     foreach($simple as $piece) {
1333       $partial= split("=", $piece);
1335       if($partial[0] == "cn"){
1336         return $partial[1];
1337       }
1338     }
1339   }
1342   function get_naming_contexts($server, $admin= "", $password= "")
1343   {
1344     /* Build LDAP connection */
1345     $ds= ldap_connect ($server);
1346     if (!$ds) {
1347       die ("Can't bind to LDAP. No check possible!");
1348     }
1349     ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
1350     $r= ldap_bind ($ds, $admin, $password);
1352     /* Get base to look for naming contexts */
1353     $sr  = @ldap_read ($ds, "", "objectClass=*", array("+"));
1354     $attr= @ldap_get_entries($ds,$sr);
1356     return ($attr[0]['namingcontexts']);
1357   }
1360   function get_root_dse($server, $admin= "", $password= "")
1361   {
1362     /* Build LDAP connection */
1363     $ds= ldap_connect ($server);
1364     if (!$ds) {
1365       die ("Can't bind to LDAP. No check possible!");
1366     }
1367     ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
1368     $r= ldap_bind ($ds, $admin, $password);
1370     /* Get base to look for naming contexts */
1371     $sr  = @ldap_read ($ds, "", "objectClass=*", array("+"));
1372     $attr= @ldap_get_entries($ds,$sr);
1373    
1374     /* Return empty array, if nothing was set */
1375     if (!isset($attr[0])){
1376       return array();
1377     }
1379     /* Rework array... */
1380     $result= array();
1381     for ($i= 0; $i<$attr[0]['count']; $i++){
1382       $result[$attr[0][$i]]= $attr[0][$attr[0][$i]];
1383       unset($result[$attr[0][$i]]['count']);
1384     }
1386     return ($result);
1387   }
1390 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
1391 ?>