Code

Updated generateLdif method
[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("core","ldapMaxQueryTime") != ""){
64       $str = $config->get_cfg_value("core","ldapMaxQueryTime");
65       $this->max_ldap_query_time = (float)($str);
66     }
68     $this->connect();
69   }
72   function getSearchResource()
73   {
74     $this->sr[$this->srp]= NULL;
75     $this->start[$this->srp]= 0;
76     $this->hasres[$this->srp]= false;
77     return $this->srp++;
78   }
81   /* Function to replace all problematic characters inside a DN by \001XX, where
82      \001 is decoded to chr(1) [ctrl+a]. It is not impossible, but very unlikely
83      that this character is inside a DN.
85      Currently used codes:
86      ,   => CO
87      \2C => CO
88      (   => OB
89      )   => CB
90      /   => SL                                                                  
91      \22 => DQ                                                                  */
92   static function convert($dn)
93   {
94     if (SPECIALS_OVERRIDE == TRUE){
95       $tmp= preg_replace(array("/\\\\,/", "/\\\\2C/", "/\(/", "/\)/", "/\//", "/\\\\22/", '/\\\\"/'),
96           array("\001CO", "\001CO", "\001OB", "\001CB", "\001SL", "\001DQ", "\001DQ"),
97           $dn);
98       return (preg_replace('/,\s+/', ',', $tmp));
99     } else {
100       return ($dn);
101     }
102   }
105   /* Function to fix all problematic characters inside a DN by replacing \001XX
106      codes to their original values. See "convert" for mor information. 
107      ',' characters are always expanded to \, (not \2C), since all tested LDAP
108      servers seem to take it the correct way.                                  */
109   static function fix($dn)
110   {
111     if (SPECIALS_OVERRIDE == TRUE){
112       return (preg_replace(array("/\001CO/", "/\001OB/", "/\001CB/", "/\001SL/", "/\001DQ/"),
113             array("\,", "(", ")", "/", '\"'),
114             $dn));
115     } else {
116       return ($dn);
117     }
118   }
120   /* Function to fix problematic characters in DN's that are used for search
121      requests. I.e. member=....                                               */
122   static function prepare4filter($dn)
123   {
124     $fixed= normalizeLdap(str_replace('\\\\', '\\\\\\', LDAP::fix($dn)));
125     return str_replace('\\,', '\\\\,', $fixed);
126   }
129   function connect()
130   {
131     $this->hascon=false;
132     $this->reconnect=false;
133     if ($this->cid= @ldap_connect($this->hostname)) {
134       @ldap_set_option($this->cid, LDAP_OPT_PROTOCOL_VERSION, 3);
135       if (function_exists("ldap_set_rebind_proc") && $this->follow_referral) {
136         @ldap_set_option($this->cid, LDAP_OPT_REFERRALS, 1);
137         @ldap_set_rebind_proc($this->cid, array(&$this, "rebind"));
138       }
139       if (function_exists("ldap_start_tls") && $this->tls){
140         @ldap_start_tls($this->cid);
141       }
143       $this->error = "No Error";
144       if ($bid = @ldap_bind($this->cid, LDAP::fix($this->binddn), $this->bindpw)) {
145         $this->error = "Success";
146         $this->hascon=true;
147       } else {
148         if ($this->reconnect){
149           if ($this->error != "Success"){
150             $this->error = "Could not rebind to " . $this->binddn;
151           }
152         } else {
153           $this->error = "Could not bind to " . $this->binddn;
154         }
155       }
156     } else {
157       $this->error = "Could not connect to LDAP server";
158     }
159   }
161   function rebind($ldap, $referral)
162   {
163     $credentials= $this->get_credentials($referral);
164     if (@ldap_bind($ldap, LDAP::fix($credentials['ADMINDN']), $credentials['ADMINPASSWORD'])) {
165       $this->error = "Success";
166       $this->hascon=true;
167       $this->reconnect= true;
168       return (0);
169     } else {
170       $this->error = "Could not bind to " . $credentials['ADMINDN'];
171       return NULL;
172     }
173   }
175   function reconnect()
176   {
177     if ($this->reconnect){
178       @ldap_unbind($this->cid);
179       $this->cid = NULL;
180     }
181   }
183   function unbind()
184   {
185     @ldap_unbind($this->cid);
186     $this->cid = NULL;
187   }
189   function disconnect()
190   {
191     if($this->hascon){
192       @ldap_close($this->cid);
193       $this->hascon=false;
194     }
195   }
197   function cd($dir)
198   {
199     if ($dir == ".."){
200       $this->basedn = $this->getParentDir();
201     } else {
202       $this->basedn = LDAP::convert($dir);
203     }
204   }
206   function getParentDir($basedn = "")
207   {
208     if ($basedn==""){
209       $basedn = $this->basedn;
210     } else {
211       $basedn = LDAP::convert($basedn);
212     }
213     return(preg_replace("/[^,]*[,]*[ ]*(.*)/", "$1", $basedn));
214   }
216   
217   function search($srp, $filter, $attrs= array())
218   {
219     if($this->hascon){
220       if ($this->reconnect) $this->connect();
222       $start = microtime(true);
223       $this->clearResult($srp);
224       $this->sr[$srp] = @ldap_search($this->cid, LDAP::fix($this->basedn), $filter, $attrs);
225       $this->error = @ldap_error($this->cid);
226       $this->resetResult($srp);
227       $this->hasres[$srp]=true;
228    
229       /* Check if query took longer as specified in max_ldap_query_time */
230       if($this->max_ldap_query_time){
231         $diff = microtime(true) - $start;
232         if($diff > $this->max_ldap_query_time){
233           msg_dialog::display(_("Performance warning"), sprintf(_("LDAP performance is poor: last query took %.2fs!"), $diff), WARNING_DIALOG);
234         }
235       }
237       $this->log("LDAP operation: time=".(microtime(true)-$start)." operation=search('".LDAP::fix($this->basedn)."', '$filter')");
239       // Create statistic table entry 
240       stats::log('ldap', $class = get_class($this), $category = array(),  $action = __FUNCTION__, 
241               $amount = 1, $duration = (microtime(TRUE) - $start));
242       return($this->sr[$srp]);
243     }else{
244       $this->error = "Could not connect to LDAP server";
245       return("");
246     }
247   }
249   function ls($srp, $filter = "(objectclass=*)", $basedn = "",$attrs = array("*"))
250   {
251     if($this->hascon){
252       if ($this->reconnect) $this->connect();
254       $this->clearResult($srp);
255       if ($basedn == "")
256         $basedn = $this->basedn;
257       else
258         $basedn= LDAP::convert($basedn);
259   
260       $start = microtime(true);
261       $this->sr[$srp] = @ldap_list($this->cid, LDAP::fix($basedn), $filter,$attrs);
262       $this->error = @ldap_error($this->cid);
263       $this->resetResult($srp);
264       $this->hasres[$srp]=true;
266        /* Check if query took longer as specified in max_ldap_query_time */
267       if($this->max_ldap_query_time){
268         $diff = microtime(true) - $start;
269         if($diff > $this->max_ldap_query_time){
270           msg_dialog::display(_("Performance warning"), sprintf(_("LDAP performance is poor: last query took %.2fs!"), $diff), WARNING_DIALOG);
271         }
272       }
274       $this->log("LDAP operation: time=".(microtime(true) - $start)." operation=ls('".LDAP::fix($basedn)."', '$filter')");
276       // Create statistic table entry 
277       stats::log('ldap', $class = get_class($this), $category = array(),  $action = __FUNCTION__, 
278               $amount = 1, $duration = (microtime(TRUE) - $start));
280       return($this->sr[$srp]);
281     }else{
282       $this->error = "Could not connect to LDAP server";
283       return("");
284     }
285   }
287   function cat($srp, $dn,$attrs= array("*"), $filter = "(objectclass=*)")
288   {
289     if($this->hascon){
290       if ($this->reconnect) $this->connect();
292       $this->clearResult($srp);
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(!$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 mod_add($attrs = "", $dn = "")
439   {
440     if($this->hascon){
441       if ($this->reconnect) $this->connect();
442       if ($dn == "")
443         $dn = $this->basedn;
445       $r = @ldap_mod_add($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 rename($attrs, $dn = "")
455   {
456     if($this->hascon){
457       if ($this->reconnect) $this->connect();
458       if ($dn == "")
459         $dn = $this->basedn;
461       $r = @ldap_mod_replace($this->cid, LDAP::fix($dn), $attrs);
462       $this->error = @ldap_error($this->cid);
463       return($r);
464     }else{
465       $this->error = "Could not connect to LDAP server";
466       return("");
467     }
468   }
470   function rmdir($deletedn)
471   {
472     if($this->hascon){
473       if ($this->reconnect) $this->connect();
474       $r = @ldap_delete($this->cid, LDAP::fix($deletedn));
475       $this->error = @ldap_error($this->cid);
476       return($r ? $r : 0);
477     }else{
478       $this->error = "Could not connect to LDAP server";
479       return("");
480     }
481   }
484   /*! \brief Move the given Ldap entry from $source to $dest
485       @param  String  $source The source dn.
486       @param  String  $dest   The destination dn.
487       @return Boolean TRUE on success else FALSE.
488    */
489   function rename_dn($source,$dest)
490   {
491     /* Check if source and destination are the same entry */
492     if(strtolower($source) == strtolower($dest)){
493       trigger_error("Source and destination can't be the same entry.");
494       $this->error = "Source and destination can't be the same entry.";
495       return(FALSE);
496     }
498     /* Check if destination entry exists */    
499     if($this->dn_exists($dest)){
500       trigger_error("Destination '$dest' already exists.");
501       $this->error = "Destination '$dest' already exists.";
502       return(FALSE);
503     }
505     /* Extract the name and the parent part out ouf source dn.
506         e.g.  cn=herbert,ou=department,dc=... 
507          parent   =>  ou=department,dc=...
508          dest_rdn =>  cn=herbert
509      */
510     $parent   = preg_replace("/^[^,]+,/","", $dest);
511     $dest_rdn = preg_replace("/,.*$/","",$dest);
513     if($this->hascon){
514       if ($this->reconnect) $this->connect();
515       $r= ldap_rename($this->cid,@LDAP::fix($source), @LDAP::fix($dest_rdn),@LDAP::fix($parent),TRUE); 
516       $this->error = ldap_error($this->cid);
518       /* Check if destination dn exists, if not the 
519           server may not support this operation */
520       $r &= is_resource($this->dn_exists($dest));
521       return($r);
522     }else{
523       $this->error = "Could not connect to LDAP server";
524       return(FALSE);
525     }
526   }
529   /**
530   *  Function rmdir_recursive
531   *
532   *  Description: Based in recursive_remove, adding two thing: full subtree remove, and delete own node.
533   *  Parameters:  The dn to delete
534   *  GiveBack:    True on sucessfull , 0 in error, and "" when we don't get a ldap conection
535   *
536   */
537   function rmdir_recursive($srp, $deletedn)
538   {
539     if($this->hascon){
540       if ($this->reconnect) $this->connect();
541       $delarray= array();
542         
543       /* Get sorted list of dn's to delete */
544       $this->ls ($srp, "(objectClass=*)",$deletedn);
545       while ($this->fetch($srp)){
546         $deldn= $this->getDN($srp);
547         $delarray[$deldn]= strlen($deldn);
548       }
549       arsort ($delarray);
550       reset ($delarray);
552       /* Really Delete ALL dn's in subtree */
553       foreach ($delarray as $key => $value){
554         $this->rmdir_recursive($srp, $key);
555       }
556       
557       /* Finally Delete own Node */
558       $r = @ldap_delete($this->cid, LDAP::fix($deletedn));
559       $this->error = @ldap_error($this->cid);
560       return($r ? $r : 0);
561     }else{
562       $this->error = "Could not connect to LDAP server";
563       return("");
564     }
565   }
567   function makeReadableErrors($error,$attrs)
568   { 
569     global $config;
571     if($this->success()) return("");
573     $str = "";
574     if(preg_match("/^objectClass: value #([0-9]*) invalid per syntax$/", $this->get_additional_error())){
575       $oc = preg_replace("/^objectClass: value #([0-9]*) invalid per syntax$/","\\1", $this->get_additional_error());
576       if(isset($attrs['objectClass'][$oc])){
577         $str.= " - <b>objectClass: ".$attrs['objectClass'][$oc]."</b>";
578       }
579     }
580     if($error == "Undefined attribute type"){
581       $str = " - <b>attribute: ".preg_replace("/:.*$/","",$this->get_additional_error())."</b>";
582     } 
584     @DEBUG(DEBUG_LDAP,__LINE__,__FUNCTION__,__FILE__,$attrs,"Erroneous data");
586     return($str);
587   }
589   function modify($attrs)
590   {
591     if(count($attrs) == 0){
592       return (0);
593     }
594     if($this->hascon){
595       $start = microtime(TRUE);
596       if ($this->reconnect) $this->connect();
597       $r = @ldap_modify($this->cid, LDAP::fix($this->basedn), $attrs);
598       $this->error = @ldap_error($this->cid);
599       if(!$this->success()){
600         $this->error.= $this->makeReadableErrors($this->error,$attrs);
601       }
603       // Create statistic table entry 
604       stats::log('ldap', $class = get_class($this), $category = array(),  $action = __FUNCTION__, 
605               $amount = 1, $duration = (microtime(TRUE) - $start));
606       return($r ? $r : 0);
607     }else{
608       $this->error = "Could not connect to LDAP server";
609       return("");
610     }
611   }
613   function add($attrs)
614   {
615     if($this->hascon){
616       $start = microtime(TRUE);
617       if ($this->reconnect) $this->connect();
618       $r = @ldap_add($this->cid, LDAP::fix($this->basedn), $attrs);
619       $this->error = @ldap_error($this->cid);
620       if(!$this->success()){
621         $this->error.= $this->makeReadableErrors($this->error,$attrs);
622       }
624       // Create statistic table entry 
625       stats::log('ldap', $class = get_class($this), $category = array(),  $action = __FUNCTION__, 
626               $amount = 1, $duration = (microtime(TRUE) - $start));
628       return($r ? $r : 0);
629     }else{
630       $this->error = "Could not connect to LDAP server";
631       return("");
632     }
633   }
635   function create_missing_trees($srp, $target)
636   {
637     global $config;
639     $real_path= substr($target, 0, strlen($target) - strlen($this->basedn) -1 );
641     if ($target == $this->basedn){
642       $l= array("dummy");
643     } else {
644       $l= array_reverse(gosa_ldap_explode_dn($real_path));
645     }
646     unset($l['count']);
647     $cdn= $this->basedn;
648     $tag= "";
650     /* Load schema if available... */
651     $classes= $this->get_objectclasses();
653     foreach ($l as $part){
654       if ($part != "dummy"){
655         $cdn= "$part,$cdn";
656       }
658       /* Ignore referrals */
659       $found= false;
660       foreach($this->referrals as $ref){
661         $base= preg_replace('!^[^:]+://[^/]+/([^?]+).*$!', '\\1', $ref['URI']);
662         if ($base == $cdn){
663           $found= true;
664           break;
665         }
666       }
667       if ($found){
668         continue;
669       }
671       $this->cat ($srp, $cdn);
672       $attrs= $this->fetch($srp);
674       /* Create missing entry? */
675       if (count ($attrs)){
676       
677         /* Catch the tag - if present */
678         if (isset($attrs['gosaUnitTag'][0])){
679           $tag= $attrs['gosaUnitTag'][0];
680         }
682       } else {
683         $type= preg_replace('/^([^=]+)=.*$/', '\\1', $cdn);
684         $param= LDAP::fix(preg_replace('/^[^=]+=([^,]+).*$/', '\\1', $cdn));
685         $param=preg_replace(array('/\\\\,/','/\\\\"/'),array(',','"'),$param);
687         $na= array();
689         /* Automatic or traditional? */
690         if(count($classes)){
692           /* Get name of first matching objectClass */
693           $ocname= "";
694           foreach($classes as $class){
695             if (isset($class['MUST']) && in_array($type, $class['MUST'])){
697               /* Look for first classes that is structural... */
698               if (isset($class['STRUCTURAL'])){
699                 $ocname= $class['NAME'];
700                 break;
701               }
703               /* Look for classes that are auxiliary... */
704               if (isset($class['AUXILIARY'])){
705                 $ocname= $class['NAME'];
706               }
707             }
708           }
710           /* Bail out, if we've nothing to do... */
711           if ($ocname == ""){
712             msg_dialog::display(_("Internal error"), sprintf(_("Cannot automatically create subtrees with RDN %s: no object class found"), bold($type)), FATAL_ERROR_DIALOG);
713             exit();
714           }
716           /* Assemble_entry */
717           if ($tag != ""){
718             $na['objectClass']= array($ocname, "gosaAdministrativeUnitTag");
719             $na["gosaUnitTag"]= $tag;
720           } else {
721             $na['objectClass']= array($ocname);
722           }
723           if (isset($classes[$ocname]['AUXILIARY'])){
724             $na['objectClass'][]= $classes[$ocname]['SUP'];
725           }
726           if ($type == "dc"){
727             /* This is bad actually, but - tell me a better way? */
728             $na['objectClass'][]= 'locality';
729           }
730           $na[$type]= $param;
732           // Fill in MUST values - but do not overwrite existing ones.
733           if (is_array($classes[$ocname]['MUST'])){
734             foreach($classes[$ocname]['MUST'] as $attr){
735               if(isset($na[$attr]) && !empty($na[$attr])) continue;
736               $na[$attr]= "filled";
737             }
738           }
740         } else {
742           /* Use alternative add... */
743           switch ($type){
744             case 'ou':
745               if ($tag != ""){
746                 $na["objectClass"]= array("organizationalUnit", "gosaAdministrativeUnitTag");
747                 $na["gosaUnitTag"]= $tag;
748               } else {
749                 $na["objectClass"]= "organizationalUnit";
750               }
751               $na["ou"]= $param;
752               break;
753             case 'dc':
754               if ($tag != ""){
755                 $na["objectClass"]= array("dcObject", "top", "locality", "gosaAdministrativeUnitTag");
756                 $na["gosaUnitTag"]= $tag;
757               } else {
758                 $na["objectClass"]= array("dcObject", "top", "locality");
759               }
760               $na["dc"]= $param;
761               break;
762             default:
763               msg_dialog::display(_("Internal error"), sprintf(_("Cannot automatically create subtrees with RDN %s: not supported"), bold($type)), FATAL_ERROR_DIALOG);
764               exit();
765           }
767         }
768         $this->cd($cdn);
769         $this->add($na);
770     
771         if (!$this->success()){
773           print_a(array($cdn,$na));
775           msg_dialog::display(_("LDAP error"), msgPool::ldaperror($this->get_error(), $cdn, LDAP_ADD, get_class()));
776           return FALSE;
777         }
778       }
779     }
781     return TRUE;
782   }
785   function recursive_remove($srp)
786   {
787     $delarray= array();
789     /* Get sorted list of dn's to delete */
790     $this->search ($srp, "(objectClass=*)");
791     while ($this->fetch($srp)){
792       $deldn= $this->getDN($srp);
793       $delarray[$deldn]= strlen($deldn);
794     }
795     arsort ($delarray);
796     reset ($delarray);
798     /* Delete all dn's in subtree */
799     foreach ($delarray as $key => $value){
800       $this->rmdir($key);
801     }
802   }
805   function get_attribute($dn, $name,$r_array=0)
806   {
807     $data= "";
808     if ($this->reconnect) $this->connect();
809     $sr= @ldap_read($this->cid, LDAP::fix($dn), "objectClass=*", array("$name"));
811     /* fill data from LDAP */
812     if ($sr) {
813       $ei= @ldap_first_entry($this->cid, $sr);
814       if ($ei) {
815         if ($info= @ldap_get_values_len($this->cid, $ei, "$name")){
816           $data= $info[0];
817         }
818       }
819     }
820     if($r_array==0) {
821       return ($data);
822     } else {
823       return ($info);
824     }
825   }
826  
829   function get_additional_error()
830   {
831     $error= "";
832     @ldap_get_option ($this->cid, LDAP_OPT_ERROR_STRING, $error);
833     return ($error);
834   }
837   function success()
838   {
839     return (preg_match('/Success/i', $this->error));
840   }
843   function get_error()
844   {
845     if ($this->error == 'Success'){
846       return $this->error;
847     } else {
848       $adderror= $this->get_additional_error();
849       if ($adderror != ""){
850         $error= $this->error." (".$this->get_additional_error().", ".sprintf(_("while operating on %s using LDAP server %s"), bold($this->basedn), bold($this->hostname)).")";
851       } else {
852         $error= $this->error." (".sprintf(_("while operating on LDAP server %s"), bold($this->hostname)).")";
853       }
854       return $error;
855     }
856   }
858   function get_credentials($url, $referrals= NULL)
859   {
860     $ret= array();
861     $url= preg_replace('!\?\?.*$!', '', $url);
862     $server= preg_replace('!^([^:]+://[^/]+)/.*$!', '\\1', $url);
864     if ($referrals === NULL){
865       $referrals= $this->referrals;
866     }
868     if (isset($referrals[$server])){
869       return ($referrals[$server]);
870     } else {
871       $ret['ADMINDN']= LDAP::fix($this->binddn);
872       $ret['ADMINPASSWORD']= $this->bindpw;
873     }
875     return ($ret);
876   }
879   /*! \brief  Generates an ldif for all entries matching the filter settings, scope and limit.
880    *  @param  $dn           The entry to export.
881    *  @param  $filter       Limit the exported object to those maching this filter.
882    *  @param  $attributes   Specify the attributes to export here, empty means all.
883    *  @param  $scope        'base', 'sub' .. see manpage for 'ldapmodify' for details.
884    *  @param  $limit        Limits the result.
885    */
886   function generateLdif ($dn, $filter= "(objectClass=*)", $scope = 'sub', $limit=0)
887   {
888       $attrs  = (count($attributes))?implode($attributes,' '):'';
890       // Ensure that limit is numeric if not skip here.
891       if(!empty($limit) && !is_numeric($limit)){
892           trigger_error(sprintf("Invalid parameter for limit '%s', a numeric value is required."), $limit);
893           return(NULL);
894       }
895       $limit = (!$limit)?'':' -z '.$limit;
897       // Check scope values
898       $scope = trim($scope);
899       if(!empty($scope) && !in_array($scope, array('base', 'one', 'sub', 'children'))){
900           trigger_error(sprintf("Invalid parameter for scope '%s', please use 'base', 'one', 'sub' or 'children'."), $scope);
901           return(NULL);
902       }
903       $scope = (!empty($scope))?' -s '.$scope: '';
905       // Prepare paramters
906       $dn = escapeshellarg($dn);
907       $pwd = $this->bindpw;
908       $host = escapeshellarg($this->hostname);
909       $admin = escapeshellarg($this->binddn);
910       $filter = escapeshellarg($filter);
911       $cmd = "ldapsearch -x -LLLL -D {$admin} {$filter} {$limit} {$scope} -H {$host} -b {$dn} -W ";
913       // Create list of process pipes  
914       $descriptorspec = array(
915               0 => array("pipe", "r"),  // stdin
916               1 => array("pipe", "w"),  // stdout
917               2 => array("pipe", "w")); // stderr
918     
919       // Try to open the process 
920       $process = proc_open($cmd, $descriptorspec, $pipes);
921       if (is_resource($process)) {
923           // Write the password to stdin
924           fwrite($pipes[0], $pwd);
925           fclose($pipes[0]);
927           // Get results from stdout and stderr
928           $res = stream_get_contents($pipes[1]);
929           $err = stream_get_contents($pipes[2]);
930           fclose($pipes[1]);
932           // Close the process and check its return value
933           if(proc_close($process) != 0){
934               trigger_error($err);
935           }
936       }
937       return($res);
938   }
941   function gen_xls ($srp, $dn, $filter= "(objectClass=*)", $attributes= array('*'), $recursive= TRUE,$r_array=0)
942   {
943     $display= array();
945       $this->cd($dn);
946       $this->search($srp, "$filter");
948       $i=0;
949       while ($attrs= $this->fetch($srp)){
950         $j=0;
952         foreach ($attributes as $at){
953           $display[$i][$j]= $this->get_attribute($attrs['dn'], $at,$r_array);
954           $j++;
955         }
957         $i++;
958       }
960     return ($display);
961   }
964   function dn_exists($dn)
965   {
966     return @ldap_list($this->cid, LDAP::fix($dn), "(objectClass=*)", array("objectClass"));
967   }
968   
971   /*  This funktion imports ldifs 
972         
973       If DeleteOldEntries is true, the destination entry will be deleted first. 
974       If JustModify is true the destination entry will only be touched by the attributes specified in the ldif.
975       if JustMofify id false the destination dn will be overwritten by the new ldif. 
976     */
978   function import_complete_ldif($srp, $str_attr,$error,$JustModify,$DeleteOldEntries)
979   {
980     if($this->reconnect) $this->connect();
982     /* First we have to split the string into empty lines.
983        An empty line indicates an new Entry */
984     $entries = preg_split("/\n/",$str_attr);
986     $data = "";
987     $cnt = 0; 
988     $current_line = 0;
990     /* FIX ldif */
991     $last = "";
992     $tmp  = "";
993     $i = 0;
994     foreach($entries as $entry){
995       if(preg_match("/^ /",$entry)){
996         $tmp[$i] .= trim($entry);
997       }else{
998         $i ++;
999         $tmp[$i] = trim($entry);
1000       }
1001     }
1003     /* Every single line ... */
1004     foreach($tmp as $entry) {
1005       $current_line ++;
1007       /* Removing Spaces to .. 
1008          .. test if a new entry begins */
1009       $tmp  = str_replace(" ","",$data );
1011       /* .. prevent empty lines in an entry */
1012       $tmp2 = str_replace(" ","",$entry);
1014       /* If the Block ends (Empty Line) */
1015       if((empty($entry))&&(!empty($tmp))) {
1016         /* Add collected lines as a complete block */
1017         $all[$cnt] = $data;
1018         $cnt ++;
1019         $data ="";
1020       } else {
1022         /* Append lines ... */
1023         if(!empty($tmp2)) {
1024           /* check if we need base64_decode for this line */
1025           if(strstr($tmp2, "::") !== false)
1026           {
1027             $encoded = explode("::",$entry);
1028             $attr  = trim($encoded[0]);
1029             $value = base64_decode(trim($encoded[1]));
1030             /* Add linenumber */
1031             $data .= $current_line."#".base64_encode($attr.":".$value)."\n";
1032           }
1033           else
1034           {
1035             /* Add Linenumber */ 
1036             $data .= $current_line."#".base64_encode($entry)."\n";
1037           }
1038         }
1039       }
1040     }
1042     /* The Data we collected is not in the array all[];
1043        For example the Data is stored like this..
1045        all[0] = "1#dn : .... \n 
1046        2#ObjectType: person \n ...."
1047        
1048        Now we check every insertblock and try to insert */
1049     foreach ( $all as $single) {
1050       $lineone = preg_split("/\n/",$single);  
1051       $ndn = explode("#", $lineone[0]);
1052       $line = base64_decode($ndn[1]);
1054       $dnn = explode (":",$line,2);
1055       $current_line = $ndn[0];
1056       $dn    = $dnn[0];
1057       $value = $dnn[1];
1059       /* Every block must begin with a dn */
1060       if($dn != "dn") {
1061         $error= sprintf(_("Invalid DN %s: block to be imported should start with 'dn: ...' in line %s"), bold($line), bold($current_line));
1062         return -2;  
1063       }
1065       /* Should we use Modify instead of Add */
1066       $usemodify= false;
1068       /* Delete before insert */
1069       $usermdir= false;
1070     
1071       /* The dn address already exists, Don't delete destination entry, overwrite it */
1072       if (($this->dn_exists($value))&&((!$JustModify)&&(!$DeleteOldEntries))) {
1074         $usermdir = $usemodify = false;
1076       /* Delete old entry first, then add new */
1077       } elseif(($this->dn_exists($value))&&($DeleteOldEntries)){
1079         /* Delete first, then add */
1080         $usermdir = true;        
1082       } elseif(($this->dn_exists($value))&&($JustModify)) {
1083         
1084         /* Modify instead of Add */
1085         $usemodify = true;
1086       }
1087      
1088       /* If we can't Import, return with a file error */
1089       if(!$this->import_single_entry($srp, $single,$usemodify,$usermdir) ) {
1090         $error= sprintf(_("Error while importing DN %s: please check LDIF from line %s on!"), bold($line),
1091                         $current_line);
1092         return UNKNOWN_TOKEN_IN_LDIF_FILE;      }
1093     }
1095     return (INSERT_OK);
1096   }
1099   /* Imports a single entry 
1100       If $delete is true;  The old entry will be deleted if it exists.
1101       if $modify is true;  All variables that are not touched by the new ldif will be kept.
1102       if $modify is false; The new ldif overwrites the old entry, and all untouched attributes get lost.
1103   */
1104   function import_single_entry($srp, $str_attr,$modify,$delete)
1105   {
1106     global $config;
1108     if(!$config){
1109       trigger_error("Can't import ldif, can't read config object.");
1110     }
1111   
1113     if($this->reconnect) $this->connect();
1115     $ret = false;
1116     $rows= preg_split("/\n/",$str_attr);
1117     $data= false;
1119     foreach($rows as $row) {
1120       
1121       /* Check if we use Linenumbers (when import_complete_ldif is called we use
1122          Linenumbers) Linenumbers are use like this 123#attribute : value */
1123       if(!empty($row)) {
1124         if(strpos($row,"#")!=FALSE) {
1126           /* We are using line numbers 
1127              Because there is a # before a : */
1128           $tmp1= explode("#",$row);
1129           $current_line= $tmp1[0];
1130           $row= base64_decode($tmp1[1]);
1131         }
1133         /* Split the line into  attribute  and value */
1134         $attr   = explode(":", $row,2);
1135         $attr[0]= trim($attr[0]);  /* attribute */
1136         $attr[1]= $attr[1];  /* value */
1138         /* Check :: was used to indicate base64_encoded strings */
1139         if($attr[1][0] == ":"){
1140           $attr[1]=trim(preg_replace("/^:/","",$attr[1]));
1141           $attr[1]=base64_decode($attr[1]);
1142         }
1144         $attr[1] = trim($attr[1]);
1146         /* Check for attributes that are used more than once */
1147         if(!isset($data[$attr[0]])) {
1148           $data[$attr[0]]=$attr[1];
1149         } else {
1150           $tmp = $data[$attr[0]];
1152           if(!is_array($tmp)) {
1153             $new[0]=$tmp;
1154             $new[1]=$attr[1];
1155             $datas[$attr[0]]['count']=1;             
1156             $data[$attr[0]]=$new;
1157           } else {
1158             $cnt = $datas[$attr[0]]['count'];           
1159             $cnt ++;
1160             $data[$attr[0]][$cnt]=$attr[1];
1161             $datas[$attr[0]]['count'] = $cnt;
1162           }
1163         }
1164       }
1165     }
1167     /* If dn is an index of data, we should try to insert the data */
1168     if(isset($data['dn'])) {
1170       /* Fix dn */
1171       $tmp = gosa_ldap_explode_dn($data['dn']);
1172       unset($tmp['count']);
1173       $newdn ="";
1174       foreach($tmp as $tm){
1175         $newdn.= trim($tm).",";
1176       }
1177       $newdn = preg_replace("/,$/","",$newdn);
1178       $data['dn'] = $newdn;
1179    
1180       /* Creating Entry */
1181       $this->cd($data['dn']);
1183       /* Delete existing entry */
1184       if($delete){
1185         $this->rmdir_recursive($srp, $data['dn']);
1186       }
1187      
1188       /* Create missing trees */
1189       $this->cd ($this->basedn);
1190       $this->cd($config->current['BASE']);
1191       $this->create_missing_trees($srp, preg_replace("/^[^,]+,/","",$data['dn']));
1192       $this->cd($data['dn']);
1194       $dn = $data['dn'];
1195       unset($data['dn']);
1196       
1197       if(!$modify){
1199         $this->cat($srp, $dn);
1200         if($this->count($srp)){
1201         
1202           /* The destination entry exists, overwrite it with the new entry */
1203           $attrs = $this->fetch($srp);
1204           foreach($attrs as $name => $value ){
1205             if(!is_numeric($name)){
1206               if(in_array($name,array("dn","count"))) continue;
1207               if(!isset($data[$name])){
1208                 $data[$name] = array();
1209               }
1210             }
1211           }
1212           $ret = $this->modify($data);
1213     
1214         }else{
1215     
1216           /* The destination entry doesn't exists, create it */
1217           $ret = $this->add($data);
1218         }
1220       } else {
1221         
1222         /* Keep all vars that aren't touched by this ldif */
1223         $ret = $this->modify($data);
1224       }
1225     }
1227     if (!$this->success()){
1228       msg_dialog::display(_("LDAP error"), msgPool::ldaperror($this->get_error(), $dn, "", get_class()));
1229     }
1231     return($ret);
1232   }
1234   
1235   function importcsv($str)
1236   {
1237     $lines = preg_split("/\n/",$str);
1238     foreach($lines as $line)
1239     {
1240       /* continue if theres a comment */
1241       if(substr(trim($line),0,1)=="#"){
1242         continue;
1243       }
1245       $line= str_replace ("\t\t","\t",$line);
1246       $line= str_replace ("\t"  ,"," ,$line);
1247       echo $line;
1249       $cells = explode(",",$line )  ;
1250       $linet= str_replace ("\t\t",",",$line);
1251       $cells = preg_split("/\t/",$line);
1252       $count = count($cells);  
1253     }
1255   }
1256   
1257   function get_objectclasses( $force_reload = FALSE)
1258   {
1259     $objectclasses = array();
1260     global $config;
1262     /* Return the cached results. */
1263     if(class_available('session') && session::global_is_set("LDAP_CACHE::get_objectclasses") && !$force_reload){
1264       $objectclasses = session::global_get("LDAP_CACHE::get_objectclasses");
1265       return($objectclasses);
1266     }
1267         
1268           # Get base to look for schema 
1269           $sr = @ldap_read ($this->cid, "", "objectClass=*", array("subschemaSubentry"));
1270           $attr = @ldap_get_entries($this->cid,$sr);
1271           if (!isset($attr[0]['subschemasubentry'][0])){
1272             return array();
1273           }
1274         
1275           /* Get list of objectclasses and fill array */
1276           $nb= $attr[0]['subschemasubentry'][0];
1277           $objectclasses= array();
1278           $sr= ldap_read ($this->cid, $nb, "objectClass=*", array("objectclasses"));
1279           $attrs= ldap_get_entries($this->cid,$sr);
1280           if (!isset($attrs[0])){
1281             return array();
1282           }
1283           foreach ($attrs[0]['objectclasses'] as $val){
1284       if (preg_match('/^[0-9]+$/', $val)){
1285         continue;
1286       }
1287       $name= "OID";
1288       $pattern= explode(' ', $val);
1289       $ocname= preg_replace("/^.* NAME\s+\(*\s*'([^']+)'\s*\)*.*$/", '\\1', $val);
1290       $objectclasses[$ocname]= array();
1292       foreach($pattern as $chunk){
1293         switch($chunk){
1295           case '(':
1296                     $value= "";
1297                     break;
1299           case ')': if ($name != ""){
1300                       $v = $this->value2container($value);
1301                       if(in_array($name, array('MUST', 'MAY')) && !is_array($v)){
1302                         $v = array($v);
1303                       }
1304                       $objectclasses[$ocname][$name]= $v;
1305                     }
1306                     $name= "";
1307                     $value= "";
1308                     break;
1310           case 'NAME':
1311           case 'DESC':
1312           case 'SUP':
1313           case 'STRUCTURAL':
1314           case 'ABSTRACT':
1315           case 'AUXILIARY':
1316           case 'MUST':
1317           case 'MAY':
1318                     if ($name != ""){
1319                       $v = $this->value2container($value);
1320                       if(in_array($name, array('MUST', 'MAY')) && !is_array($v)){
1321                         $v = array($v);
1322                       }
1323                       $objectclasses[$ocname][$name]= $v;
1324                     }
1325                     $name= $chunk;
1326                     $value= "";
1327                     break;
1329           default:  $value.= $chunk." ";
1330         }
1331       }
1333           }
1334     if(class_available("session")){
1335       session::global_set("LDAP_CACHE::get_objectclasses",$objectclasses);
1336     }
1338           return $objectclasses;
1339   }
1342   function value2container($value)
1343   {
1344     /* Set emtpy values to "true" only */
1345     if (preg_match('/^\s*$/', $value)){
1346       return true;
1347     }
1349     /* Remove ' and " if needed */
1350     $value= preg_replace('/^[\'"]/', '', $value);
1351     $value= preg_replace('/[\'"] *$/', '', $value);
1353     /* Convert to array if $ is inside... */
1354     if (preg_match('/\$/', $value)){
1355       $container= preg_split('/\s*\$\s*/', $value);
1356     } else {
1357       $container= chop($value);
1358     }
1360     return ($container);
1361   }
1364   function log($string)
1365   {
1366     if (session::global_is_set('config')){
1367       $cfg = session::global_get('config');
1368       if (isset($cfg->current['LDAPSTATS']) && preg_match('/true/i', $cfg->current['LDAPSTATS'])){
1369         syslog (LOG_INFO, $string);
1370       }
1371     }
1372   }
1374   /* added by Guido Serra aka Zeph <zeph@purotesto.it> */
1375   function getCn($dn){
1376     $simple= explode(",", $dn);
1378     foreach($simple as $piece) {
1379       $partial= explode("=", $piece);
1381       if($partial[0] == "cn"){
1382         return $partial[1];
1383       }
1384     }
1385   }
1388   function get_naming_contexts($server, $admin= "", $password= "")
1389   {
1390     /* Build LDAP connection */
1391     $ds= ldap_connect ($server);
1392     if (!$ds) {
1393       die ("Can't bind to LDAP. No check possible!");
1394     }
1395     ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
1396     $r= ldap_bind ($ds, $admin, $password);
1398     /* Get base to look for naming contexts */
1399     $sr  = @ldap_read ($ds, "", "objectClass=*", array("+"));
1400     $attr= @ldap_get_entries($ds,$sr);
1402     return ($attr[0]['namingcontexts']);
1403   }
1406   function get_root_dse($server, $admin= "", $password= "")
1407   {
1408     /* Build LDAP connection */
1409     $ds= ldap_connect ($server);
1410     if (!$ds) {
1411       die ("Can't bind to LDAP. No check possible!");
1412     }
1413     ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
1414     $r= ldap_bind ($ds, $admin, $password);
1416     /* Get base to look for naming contexts */
1417     $sr  = @ldap_read ($ds, "", "objectClass=*", array("+"));
1418     $attr= @ldap_get_entries($ds,$sr);
1419    
1420     /* Return empty array, if nothing was set */
1421     if (!isset($attr[0])){
1422       return array();
1423     }
1425     /* Rework array... */
1426     $result= array();
1427     for ($i= 0; $i<$attr[0]['count']; $i++){
1428       $result[$attr[0][$i]]= $attr[0][$attr[0][$i]];
1429       unset($result[$attr[0][$i]]['count']);
1430     }
1432     return ($result);
1433   }
1436 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
1437 ?>