Code

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