Code

Updated msgPool
[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 $hasres   =false;
35   var $reconnect=false;
36   var $tls      = false;
37   var $basedn   ="";
38   var $cid;
39   var $error    = ""; // Any error messages to be returned can be put here
40   var $start    = 0; // 0 if we are fetching the first entry, otherwise 1
41   var $objectClasses = array(); // Information read from slapd.oc.conf
42   var $binddn   = "";
43   var $bindpw   = "";
44   var $hostname = "";
45   var $follow_referral = FALSE;
46   var $referrals= array();
47   var $max_ldap_query_time = 0;   // 0, empty or negative values will disable this check 
49   var $re = NULL;  
51   function LDAP($binddn,$bindpw, $hostname, $follow_referral= FALSE, $tls= FALSE)
52   {
53     global $config;
54     $this->follow_referral= $follow_referral;
55     $this->tls=$tls;
56     $this->binddn=LDAP::convert($binddn);
58     $this->bindpw=$bindpw;
59     $this->hostname=$hostname;
61     /* Check if MAX_LDAP_QUERY_TIME is defined */ 
62     if(isset($config->data['MAIN']['MAX_LDAP_QUERY_TIME'])){
63       $str = $config->data['MAIN']['MAX_LDAP_QUERY_TIME'];
64       $this->max_ldap_query_time = (float)($str);
65     }
67     $this->connect();
68   }
71   /* Function to replace all problematic characters inside a DN by \001XX, where
72      \001 is decoded to chr(1) [ctrl+a]. It is not impossible, but very unlikely
73      that this character is inside a DN.
74      
75      Currently used codes:
76       ,   => CO
77       \2C => CO
78       (   => OB
79       )   => CB
80       /   => SL                                                                  */
81   static function convert($dn)
82   {
83     if (SPECIALS_OVERRIDE == TRUE){
84       $tmp= preg_replace(array("/\\\\,/", "/\\\\2C/", "/\(/", "/\)/", "/\//"),
85                            array("\001CO", "\001CO", "\001OB", "\001CB", "\001SL"),
86                            $dn);
87       return (preg_replace('/,\s+/', ',', $tmp));
88     } else {
89       return ($dn);
90     }
91   }
94   /* Function to fix all problematic characters inside a DN by replacing \001XX
95      codes to their original values. See "convert" for mor information. 
96      ',' characters are always expanded to \, (not \2C), since all tested LDAP
97      servers seem to take it the correct way.                                  */
98   static function fix($dn)
99   {
100     if (SPECIALS_OVERRIDE == TRUE){
101       return (preg_replace(array("/\001CO/", "/\001OB/", "/\001CB/", "/\001SL/"),
102                            array("\,", "(", ")", "/"),
103                            $dn));
104     } else {
105       return ($dn);
106     }
107   }
110   /* Function to fix problematic characters in DN's that are used for search
111      requests. I.e. member=....                                               */
112   static function prepare4filter($dn)
113   {
114         return normalizeLdap(preg_replace('/\\\\/', '\\\\\\', LDAP::fix($dn)));
115   }
118   function connect()
119   {
120     $this->hascon=false;
121     $this->reconnect=false;
122     if ($this->cid= @ldap_connect($this->hostname)) {
123       @ldap_set_option($this->cid, LDAP_OPT_PROTOCOL_VERSION, 3);
124       if (function_exists("ldap_set_rebind_proc") && $this->follow_referral) {
125         @ldap_set_option($this->cid, LDAP_OPT_REFERRALS, 1);
126         @ldap_set_rebind_proc($this->cid, array(&$this, "rebind"));
127       }
128       if (function_exists("ldap_start_tls") && $this->tls){
129         @ldap_start_tls($this->cid);
130       }
132       $this->error = "No Error";
133       if ($bid = @ldap_bind($this->cid, LDAP::fix($this->binddn), $this->bindpw)) {
134         $this->error = "Success";
135         $this->hascon=true;
136       } else {
137         if ($this->reconnect){
138           if ($this->error != "Success"){
139             $this->error = "Could not rebind to " . $this->binddn;
140           }
141         } else {
142           $this->error = "Could not bind to " . $this->binddn;
143         }
144       }
145     } else {
146       $this->error = "Could not connect to LDAP server";
147     }
148   }
150   function rebind($ldap, $referral)
151   {
152     $credentials= $this->get_credentials($referral);
153     if (@ldap_bind($ldap, LDAP::fix($credentials['ADMIN']), $credentials['PASSWORD'])) {
154       $this->error = "Success";
155       $this->hascon=true;
156       $this->reconnect= true;
157       return (0);
158     } else {
159       $this->error = "Could not bind to " . $credentials['ADMIN'];
160       return NULL;
161     }
162   }
164   function reconnect()
165   {
166     if ($this->reconnect){
167       @ldap_unbind($this->cid);
168       $this->cid = NULL;
169     }
170   }
172   function unbind()
173   {
174     @ldap_unbind($this->cid);
175     $this->cid = NULL;
176   }
178   function disconnect()
179   {
180     if($this->hascon){
181       @ldap_close($this->cid);
182       $this->hascon=false;
183     }
184   }
186   function cd($dir)
187   {
188     if ($dir == "..")
189       $this->basedn = $this->getParentDir();
190     else
191       $this->basedn = LDAP::convert($dir);
192   }
194   function getParentDir($basedn = "")
195   {
196     if ($basedn=="")
197       $basedn = $this->basedn;
198     else
199       $basedn = LDAP::convert($this->basedn);
200     return(ereg_replace("[^,]*[,]*[ ]*(.*)", "\\1", $basedn));
201   }
203   
204   function search($filter, $attrs= array())
205   {
206     if($this->hascon){
207       if ($this->reconnect) $this->connect();
209       $start = microtime();
210       $this->clearResult();
211       $this->sr = @ldap_search($this->cid, LDAP::fix($this->basedn), $filter, $attrs);
212       $this->error = @ldap_error($this->cid);
213       $this->resetResult();
214       $this->hasres=true;
215    
216       /* Check if query took longer as specified in max_ldap_query_time */
217       if($this->max_ldap_query_time){
218         $diff = get_MicroTimeDiff($start,microtime());
219         if($diff > $this->max_ldap_query_time){
220           msg_dialog::display(_("Performance warning"), sprintf(_("LDAP performance is poor: last query took about %.2fs!"), $diff), WARNING_DIALOG);
221         }
222       }
224       $this->log("LDAP operation: time=".get_MicroTimeDiff($start,microtime())." operation=search('".LDAP::fix($this->basedn)."', '$filter')");
225       return($this->sr);
226     }else{
227       $this->error = "Could not connect to LDAP server";
228       return("");
229     }
230   }
232   function ls($filter = "(objectclass=*)", $basedn = "",$attrs = array("*"))
233   {
234     if($this->hascon){
235       if ($this->reconnect) $this->connect();
237       $this->clearResult();
238       if ($basedn == "")
239         $basedn = $this->basedn;
240       else
241         $basedn= LDAP::convert($basedn);
242   
243       $start = microtime();
244       $this->sr = @ldap_list($this->cid, LDAP::fix($basedn), $filter,$attrs);
245       $this->error = @ldap_error($this->cid);
246       $this->resetResult();
247       $this->hasres=true;
249        /* Check if query took longer as specified in max_ldap_query_time */
250       if($this->max_ldap_query_time){
251         $diff = get_MicroTimeDiff($start,microtime());
252         if($diff > $this->max_ldap_query_time){
253           msg_dialog::display(_("Performance warning"), sprintf(_("LDAP performance is poor: last query took about %.2fs!"), $diff), WARNING_DIALOG);
254         }
255       }
257       $this->log("LDAP operation: time=".get_MicroTimeDiff($start,microtime())." operation=ls('".LDAP::fix($basedn)."', '$filter')");
259       return($this->sr);
260     }else{
261       $this->error = "Could not connect to LDAP server";
262       return("");
263     }
264   }
266   function cat($dn,$attrs= array("*"))
267   {
268     if($this->hascon){
269       if ($this->reconnect) $this->connect();
271       $this->clearResult();
272       $filter = "(objectclass=*)";
273       $this->sr = @ldap_read($this->cid, LDAP::fix($dn), $filter,$attrs);
274       $this->error = @ldap_error($this->cid);
275       $this->resetResult();
276       $this->hasres=true;
277       return($this->sr);
278     }else{
279       $this->error = "Could not connect to LDAP server";
280       return("");
281     }
282   }
284   function set_size_limit($size)
285   {
286     /* Ignore zero settings */
287     if ($size == 0){
288       @ldap_set_option($this->cid, LDAP_OPT_SIZELIMIT, 10000000);
289     }
290     if($this->hascon){
291       @ldap_set_option($this->cid, LDAP_OPT_SIZELIMIT, $size);
292     } else {
293       $this->error = "Could not connect to LDAP server";
294     }
295   }
297   function fetch()
298   {
299     $att= array();
300     if($this->hascon){
301       if($this->hasres){
302         if ($this->start == 0)
303         {
304           if ($this->sr){
305             $this->start = 1;
306             $this->re= @ldap_first_entry($this->cid, $this->sr);
307           } else {
308             return array();
309           }
310         } else {
311           $this->re= @ldap_next_entry($this->cid, $this->re);
312         }
313         if ($this->re)
314         {
315           $att= @ldap_get_attributes($this->cid, $this->re);
316           $att['dn']= trim(LDAP::convert(@ldap_get_dn($this->cid, $this->re)));
317         }
318         $this->error = @ldap_error($this->cid);
319         if (!isset($att)){
320           $att= array();
321         }
322         return($att);
323       }else{
324         $this->error = "Perform a Fetch with no Search";
325         return("");
326       }
327     }else{
328       $this->error = "Could not connect to LDAP server";
329       return("");
330     }
331   }
333   function resetResult()
334   {
335     $this->start = 0;
336   }
338   function clearResult()
339   {
340     if($this->hasres){
341       $this->hasres = false;
342       @ldap_free_result($this->sr);
343     }
344   }
346   function getDN()
347   {
348     if($this->hascon){
349       if($this->hasres){
351         if(!$this->re)
352           {
353           $this->error = "Perform a Fetch with no valid Result";
354           }
355           else
356           {
357           $rv = @ldap_get_dn($this->cid, $this->re);
358         
359           $this->error = @ldap_error($this->cid);
360           return(trim(LDAP::convert($rv)));
361            }
362       }else{
363         $this->error = "Perform a Fetch with no Search";
364         return("");
365       }
366     }else{
367       $this->error = "Could not connect to LDAP server";
368       return("");
369     }
370   }
372   function count()
373   {
374     if($this->hascon){
375       if($this->hasres){
376         $rv = @ldap_count_entries($this->cid, $this->sr);
377         $this->error = @ldap_error($this->cid);
378         return($rv);
379       }else{
380         $this->error = "Perform a Fetch with no Search";
381         return("");
382       }
383     }else{
384       $this->error = "Could not connect to LDAP server";
385       return("");
386     }
387   }
389   function rm($attrs = "", $dn = "")
390   {
391     if($this->hascon){
392       if ($this->reconnect) $this->connect();
393       if ($dn == "")
394         $dn = $this->basedn;
396       $r = @ldap_mod_del($this->cid, LDAP::fix($dn), $attrs);
397       $this->error = @ldap_error($this->cid);
398       return($r);
399     }else{
400       $this->error = "Could not connect to LDAP server";
401       return("");
402     }
403   }
405   function rename($attrs, $dn = "")
406   {
407     if($this->hascon){
408       if ($this->reconnect) $this->connect();
409       if ($dn == "")
410         $dn = $this->basedn;
412       $r = @ldap_mod_replace($this->cid, LDAP::fix($dn), $attrs);
413       $this->error = @ldap_error($this->cid);
414       return($r);
415     }else{
416       $this->error = "Could not connect to LDAP server";
417       return("");
418     }
419   }
421   function rmdir($deletedn)
422   {
423     if($this->hascon){
424       if ($this->reconnect) $this->connect();
425       $r = @ldap_delete($this->cid, LDAP::fix($deletedn));
426       $this->error = @ldap_error($this->cid);
427       return($r ? $r : 0);
428     }else{
429       $this->error = "Could not connect to LDAP server";
430       return("");
431     }
432   }
434   /**
435   *  Function rmdir_recursive
436   *
437   *  Description: Based in recursive_remove, adding two thing: full subtree remove, and delete own node.
438   *  Parameters:  The dn to delete
439   *  GiveBack:    True on sucessfull , 0 in error, and "" when we don't get a ldap conection
440   *
441   */
443   function rmdir_recursive($deletedn)
444   {
445     if($this->hascon){
446       if ($this->reconnect) $this->connect();
447       $delarray= array();
448         
449       /* Get sorted list of dn's to delete */
450       $this->ls ("(objectClass=*)",$deletedn);
451       while ($this->fetch()){
452         $deldn= $this->getDN();
453         $delarray[$deldn]= strlen($deldn);
454       }
455       arsort ($delarray);
456       reset ($delarray);
458       /* Really Delete ALL dn's in subtree */
459       foreach ($delarray as $key => $value){
460         $this->rmdir_recursive($key);
461       }
462       
463       /* Finally Delete own Node */
464       $r = @ldap_delete($this->cid, LDAP::fix($deletedn));
465       $this->error = @ldap_error($this->cid);
466       return($r ? $r : 0);
467     }else{
468       $this->error = "Could not connect to LDAP server";
469       return("");
470     }
471   }
474   function modify($attrs)
475   {
476     if(count($attrs) == 0){
477       return (0);
478     }
479     if($this->hascon){
480       if ($this->reconnect) $this->connect();
481       $r = @ldap_modify($this->cid, LDAP::fix($this->basedn), $attrs);
482       $this->error = @ldap_error($this->cid);
483       return($r ? $r : 0);
484     }else{
485       $this->error = "Could not connect to LDAP server";
486       return("");
487     }
488   }
490   function add($attrs)
491   {
492     if($this->hascon){
493       if ($this->reconnect) $this->connect();
494       $r = @ldap_add($this->cid, LDAP::fix($this->basedn), $attrs);
495       $this->error = @ldap_error($this->cid);
496       return($r ? $r : 0);
497     }else{
498       $this->error = "Could not connect to LDAP server";
499       return("");
500     }
501   }
503   function create_missing_trees($target)
504   {
505     global $config;
507     $real_path= substr($target, 0, strlen($target) - strlen($this->basedn) -1 );
509     if ($target == $this->basedn){
510       $l= array("dummy");
511     } else {
512       $l= array_reverse(gosa_ldap_explode_dn($real_path));
513     }
514     unset($l['count']);
515     $cdn= $this->basedn;
516     $tag= "";
518     /* Load schema if available... */
519     $classes= $this->get_objectclasses();
521     foreach ($l as $part){
522       if ($part != "dummy"){
523         $cdn= "$part,$cdn";
524       }
526       /* Ignore referrals */
527       $found= false;
528       foreach($this->referrals as $ref){
529         $base= preg_replace('!^[^:]+://[^/]+/([^?]+).*$!', '\\1', $ref['URL']);
530         if ($base == $cdn){
531           $found= true;
532           break;
533         }
534       }
535       if ($found){
536         continue;
537       }
539       $this->cat ($cdn);
540       $attrs= $this->fetch();
542       /* Create missing entry? */
543       if (count ($attrs)){
544       
545         /* Catch the tag - if present */
546         if (isset($attrs['gosaUnitTag'][0])){
547           $tag= $attrs['gosaUnitTag'][0];
548         }
550       } else {
551         $type= preg_replace('/^([^=]+)=.*$/', '\\1', $cdn);
552         $param= preg_replace('/^[^=]+=([^,]+),.*$/', '\\1', $cdn);
554         $na= array();
556         /* Automatic or traditional? */
557         if(count($classes)){
559           /* Get name of first matching objectClass */
560           $ocname= "";
561           foreach($classes as $class){
562             if (isset($class['MUST']) && $class['MUST'] == "$type"){
564               /* Look for first classes that is structural... */
565               if (isset($class['STRUCTURAL'])){
566                 $ocname= $class['NAME'];
567                 break;
568               }
570               /* Look for classes that are auxiliary... */
571               if (isset($class['AUXILIARY'])){
572                 $ocname= $class['NAME'];
573               }
574             }
575           }
577           /* Bail out, if we've nothing to do... */
578           if ($ocname == ""){
579             msg_dialog::display(_("Internal error"), sprintf(_("Cannot automatically create subtrees with RDN '%s': no object class found"),$type), FATAL_ERROR_DIALOG);
580             exit();
581           }
583           /* Assemble_entry */
584           if ($tag != ""){
585             $na['objectClass']= array($ocname, "gosaAdministrativeUnitTag");
586             $na["gosaUnitTag"]= $tag;
587           } else {
588             $na['objectClass']= array($ocname);
589           }
590           if (isset($classes[$ocname]['AUXILIARY'])){
591             $na['objectClass'][]= $classes[$ocname]['SUP'];
592           }
593           if ($type == "dc"){
594             /* This is bad actually, but - tell me a better way? */
595             $na['objectClass'][]= 'locality';
596           }
597           $na[$type]= $param;
598           if (is_array($classes[$ocname]['MUST'])){
599             foreach($classes[$ocname]['MUST'] as $attr){
600               $na[$attr]= "filled";
601             }
602           }
604         } else {
606           /* Use alternative add... */
607           switch ($type){
608             case 'ou':
609               if ($tag != ""){
610                 $na["objectClass"]= array("organizationalUnit", "gosaAdministrativeUnitTag");
611                 $na["gosaUnitTag"]= $tag;
612               } else {
613                 $na["objectClass"]= "organizationalUnit";
614               }
615               $na["ou"]= $param;
616               break;
617             case 'dc':
618               if ($tag != ""){
619                 $na["objectClass"]= array("dcObject", "top", "locality", "gosaAdministrativeUnitTag");
620                 $na["gosaUnitTag"]= $tag;
621               } else {
622                 $na["objectClass"]= array("dcObject", "top", "locality");
623               }
624               $na["dc"]= $param;
625               break;
626             default:
627               msg_dialog::display(_("Internal error"), sprintf(_("Cannot automatically create subtrees with RDN '%s': not supported"),$type), FATAL_ERROR_DIALOG);
628               exit();
629           }
631         }
632         $this->cd($cdn);
633         $this->add($na);
634     
635         show_ldap_error($this->get_error(), sprintf(_("Creating subtree '%s' failed."),$cdn));
636         if (!preg_match('/success/i', $this->error)){
637           return FALSE;
638         }
639       }
640     }
642     return TRUE;
643   }
646   function recursive_remove()
647   {
648     $delarray= array();
650     /* Get sorted list of dn's to delete */
651     $this->search ("(objectClass=*)");
652     while ($this->fetch()){
653       $deldn= $this->getDN();
654       $delarray[$deldn]= strlen($deldn);
655     }
656     arsort ($delarray);
657     reset ($delarray);
659     /* Delete all dn's in subtree */
660     foreach ($delarray as $key => $value){
661       $this->rmdir($key);
662     }
663   }
665   function get_attribute($dn, $name,$r_array=0)
666   {
667     $data= "";
668     if ($this->reconnect) $this->connect();
669     $sr= @ldap_read($this->cid, LDAP::fix($dn), "objectClass=*", array("$name"));
671     /* fill data from LDAP */
672     if ($sr) {
673       $ei= @ldap_first_entry($this->cid, $sr);
674       if ($ei) {
675         if ($info= @ldap_get_values_len($this->cid, $ei, "$name")){
676           $data= $info[0];
677         }
678       }
679     }
680     if($r_array==0)
681     return ($data);
682     else
683     return ($info);
684   
685   
686   }
687  
690   function get_additional_error()
691   {
692     $error= "";
693     @ldap_get_option ($this->cid, LDAP_OPT_ERROR_STRING, $error);
694     return ($error);
695   }
697   function get_error()
698   {
699     if ($this->error == 'Success'){
700       return $this->error;
701     } else {
702       $adderror= $this->get_additional_error();
703       if ($adderror != ""){
704         $error= $this->error." (".$this->get_additional_error().", ".sprintf(_("while operating on '%s' using LDAP server '%s'"), $this->basedn, $this->hostname).")";
705       } else {
706         $error= $this->error." (".sprintf(_("while operating on LDAP server %s"), $this->hostname).")";
707       }
708       return $error;
709     }
710   }
712   function get_credentials($url, $referrals= NULL)
713   {
714     $ret= array();
715     $url= preg_replace('!\?\?.*$!', '', $url);
716     $server= preg_replace('!^([^:]+://[^/]+)/.*$!', '\\1', $url);
718     if ($referrals === NULL){
719       $referrals= $this->referrals;
720     }
722     if (isset($referrals[$server])){
723       return ($referrals[$server]);
724     } else {
725       $ret['ADMIN']= LDAP::fix($this->binddn);
726       $ret['PASSWORD']= $this->bindpw;
727     }
729     return ($ret);
730   }
733   function gen_ldif ($dn, $filter= "(objectClass=*)", $attributes= array('*'), $recursive= TRUE)
734   {
735     $display= "";
737     if ($recursive){
738       $this->cd($dn);
739       $this->ls($filter,$dn, array('dn','objectClass'));
740       $deps = array();
742       $display .= $this->gen_one_entry($dn)."\n";
744       while ($attrs= $this->fetch()){
745         $deps[] = $attrs['dn'];
746       }
747       foreach($deps as $dn){
748         $display .= $this->gen_ldif($dn, $filter,$attributes,$recursive);
749       }
750     } else {
751       $display.= $this->gen_one_entry($dn);
752     }
753     return ($display);
754   }
757   function gen_xls ($dn, $filter= "(objectClass=*)", $attributes= array('*'), $recursive= TRUE,$r_array=0)
758   {
759     $display= array();
761       $this->cd($dn);
762       $this->search("$filter");
764       $i=0;
765       while ($attrs= $this->fetch()){
766         $j=0;
768         foreach ($attributes as $at){
769           $display[$i][$j]= $this->get_attribute($attrs['dn'], $at,$r_array);
770           $j++;
771         }
773         $i++;
774       }
776     return ($display);
777   }
780   function gen_one_entry($dn, $filter= "(objectClass=*)" , $name= array("*"))
781   {
782     $ret = "";
783     $data = "";
784     if($this->reconnect){
785       $this->connect();
786     }
788     /* Searching Ldap Tree */
789     $sr= @ldap_read($this->cid, LDAP::fix($dn), $filter, $name);
791     /* Get the first entry */   
792     $entry= @ldap_first_entry($this->cid, $sr);
794     /* Get all attributes related to that Objekt */
795     $atts = array();
796     
797     /* Assemble dn */
798     $atts[0]['name']  = "dn";
799     $atts[0]['value'] = array('count' => 1, 0 => $dn);
801     /* Reset index */
802     $i = 1 ; 
803   $identifier = array();
804     $attribute= @ldap_first_attribute($this->cid,$entry,$identifier);
805     while ($attribute) {
806       $i++;
807       $atts[$i]['name']  = $attribute;
808       $atts[$i]['value'] = @ldap_get_values_len($this->cid, $entry, "$attribute");
810       /* Next one */
811       $attribute= @ldap_next_attribute($this->cid,$entry,$identifier);
812     }
814     foreach($atts as $at)
815     {
816       for ($i= 0; $i<$at['value']['count']; $i++){
818         /* Check if we must encode the data */
819         if(!preg_match('/^[a-z0-9+@#.=, \/ -]+$/i', $at['value'][$i])) {
820           $ret .= $at['name'].":: ".base64_encode($at['value'][$i])."\n";
821         } else {
822           $ret .= $at['name'].": ".$at['value'][$i]."\n";
823         }
824       }
825     }
827     return($ret);
828   }
831   function dn_exists($dn)
832   {
833     return @ldap_list($this->cid, LDAP::fix($dn), "(objectClass=*)", array("objectClass"));
834   }
835   
838   /*  This funktion imports ldifs 
839         
840       If DeleteOldEntries is true, the destination entry will be deleted first. 
841       If JustModify is true the destination entry will only be touched by the attributes specified in the ldif.
842       if JustMofify id false the destination dn will be overwritten by the new ldif. 
843     */
845   function import_complete_ldif($str_attr,&$error,$JustModify,$DeleteOldEntries)
846   {
847     if($this->reconnect) $this->connect();
849     /* First we have to splitt the string ito detect empty lines
850        An empty line indicates an new Entry */
851     $entries = split("\n",$str_attr);
853     $data = "";
854     $cnt = 0; 
855     $current_line = 0;
857     /* FIX ldif */
858     $last = "";
859     $tmp  = "";
860     $i = 0;
861     foreach($entries as $entry){
862       if(preg_match("/^ /",$entry)){
863         $tmp[$i] .= trim($entry);
864       }else{
865         $i ++;
866         $tmp[$i] = trim($entry);
867       }
868     }
870     /* Every single line ... */
871     foreach($tmp as $entry) {
872       $current_line ++;
874       /* Removing Spaces to .. 
875          .. test if a new entry begins */
876       $tmp  = str_replace(" ","",$data );
878       /* .. prevent empty lines in an entry */
879       $tmp2 = str_replace(" ","",$entry);
881       /* If the Block ends (Empty Line) */
882       if((empty($entry))&&(!empty($tmp))) {
883         /* Add collected lines as a complete block */
884         $all[$cnt] = $data;
885         $cnt ++;
886         $data ="";
887       } else {
889         /* Append lines ... */
890         if(!empty($tmp2)) {
891           /* check if we need base64_decode for this line */
892           if(ereg("::",$tmp2))
893           {
894             $encoded = split("::",$entry);
895             $attr  = trim($encoded[0]);
896             $value = base64_decode(trim($encoded[1]));
897             /* Add linenumber */
898             $data .= $current_line."#".base64_encode($attr.":".$value)."\n";
899           }
900           else
901           {
902             /* Add Linenumber */ 
903             $data .= $current_line."#".base64_encode($entry)."\n";
904           }
905         }
906       }
907     }
909     /* The Data we collected is not in the array all[];
910        For example the Data is stored like this..
912        all[0] = "1#dn : .... \n 
913        2#ObjectType: person \n ...."
914        
915        Now we check every insertblock and try to insert */
916     foreach ( $all as $single) {
917       $lineone = split("\n",$single);  
918       $ndn = split("#", $lineone[0]);
919       $line = base64_decode($ndn[1]);
921       $dnn = split (":",$line,2);
922       $current_line = $ndn[0];
923       $dn    = $dnn[0];
924       $value = $dnn[1];
926       /* Every block must begin with a dn */
927       if($dn != "dn") {
928         $error= sprintf(_("This is not a valid DN: '%s'. A block for import should begin with 'dn: ...' in line %s"), $line, $current_line);
929         return -2;  
930       }
932       /* Should we use Modify instead of Add */
933       $usemodify= false;
935       /* Delete before insert */
936       $usermdir= false;
937     
938       /* The dn address already exists, Don't delete destination entry, overwrite it */
939       if (($this->dn_exists($value))&&((!$JustModify)&&(!$DeleteOldEntries))) {
941         $usermdir = $usemodify = false;
943       /* Delete old entry first, then add new */
944       } elseif(($this->dn_exists($value))&&($DeleteOldEntries)){
946         /* Delete first, then add */
947         $usermdir = true;        
949       } elseif(($this->dn_exists($value))&&($JustModify)) {
950         
951         /* Modify instead of Add */
952         $usemodify = true;
953       }
954      
955       /* If we can't Import, return with a file error */
956       if(!$this->import_single_entry($single,$usemodify,$usermdir) ) {
957         $error= sprintf(_("Error while importing dn: '%s', please check your LDIF from line %s on!"), $line,
958                         $current_line);
959         return UNKNOWN_TOKEN_IN_LDIF_FILE;      }
960     }
962     return (INSERT_OK);
963   }
966   /* Imports a single entry 
967       If $delete is true;  The old entry will be deleted if it exists.
968       if $modify is true;  All variables that are not touched by the new ldif will be kept.
969       if $modify is false; The new ldif overwrites the old entry, and all untouched attributes get lost.
970   */
971   function import_single_entry($str_attr,$modify,$delete)
972   {
973     global $config;
975     if(!$config){
976       trigger_error("Can't import ldif, can't read config object.");
977     }
978   
980     if($this->reconnect) $this->connect();
982     $ret = false;
983     $rows= split("\n",$str_attr);
984     $data= false;
986     foreach($rows as $row) {
987       
988       /* Check if we use Linenumbers (when import_complete_ldif is called we use
989          Linenumbers) Linenumbers are use like this 123#attribute : value */
990       if(!empty($row)) {
991         if(strpos($row,"#")!=FALSE) {
993           /* We are using line numbers 
994              Because there is a # before a : */
995           $tmp1= split("#",$row);
996           $current_line= $tmp1[0];
997           $row= base64_decode($tmp1[1]);
998         }
1000         /* Split the line into  attribute  and value */
1001         $attr   = split(":", $row,2);
1002         $attr[0]= trim($attr[0]);  /* attribute */
1003         $attr[1]= $attr[1];  /* value */
1005         /* Check :: was used to indicate base64_encoded strings */
1006         if($attr[1][0] == ":"){
1007           $attr[1]=trim(preg_replace("/^:/","",$attr[1]));
1008           $attr[1]=base64_decode($attr[1]);
1009         }
1011         $attr[1] = trim($attr[1]);
1013         /* Check for attributes that are used more than once */
1014         if(!isset($data[$attr[0]])) {
1015           $data[$attr[0]]=$attr[1];
1016         } else {
1017           $tmp = $data[$attr[0]];
1019           if(!is_array($tmp)) {
1020             $new[0]=$tmp;
1021             $new[1]=$attr[1];
1022             $datas[$attr[0]]['count']=1;             
1023             $data[$attr[0]]=$new;
1024           } else {
1025             $cnt = $datas[$attr[0]]['count'];           
1026             $cnt ++;
1027             $data[$attr[0]][$cnt]=$attr[1];
1028             $datas[$attr[0]]['count'] = $cnt;
1029           }
1030         }
1031       }
1032     }
1034     /* If dn is an index of data, we should try to insert the data */
1035     if(isset($data['dn'])) {
1037       /* Fix dn */
1038       $tmp = gosa_ldap_explode_dn($data['dn']);
1039       unset($tmp['count']);
1040       $newdn ="";
1041       foreach($tmp as $tm){
1042         $newdn.= trim($tm).",";
1043       }
1044       $newdn = preg_replace("/,$/","",$newdn);
1045       $data['dn'] = $newdn;
1046    
1047       /* Creating Entry */
1048       $this->cd($data['dn']);
1050       /* Delete existing entry */
1051       if($delete){
1052         $this->rmdir_recursive($data['dn']);
1053       }
1054      
1055       /* Create missing trees */
1056       $this->cd ($this->basedn);
1057       $this->cd($config->current['BASE']);
1058       $this->create_missing_trees(preg_replace("/^[^,]+,/","",$data['dn']));
1059       $this->cd($data['dn']);
1061       $dn = $data['dn'];
1062       unset($data['dn']);
1063       
1064       if(!$modify){
1066         $this->cat($dn);
1067         if($this->count()){
1068         
1069           /* The destination entry exists, overwrite it with the new entry */
1070           $attrs = $this->fetch();
1071           foreach($attrs as $name => $value ){
1072             if(!is_numeric($name)){
1073               if(in_array($name,array("dn","count"))) continue;
1074               if(!isset($data[$name])){
1075                 $data[$name] = array();
1076               }
1077             }
1078           }
1079           $ret = $this->modify($data);
1080     
1081         }else{
1082     
1083           /* The destination entry doesn't exists, create it */
1084           $ret = $this->add($data);
1085         }
1087       } else {
1088         
1089         /* Keep all vars that aren't touched by this ldif */
1090         $ret = $this->modify($data);
1091       }
1092     }
1093     show_ldap_error($this->get_error(), sprintf(_("Ldap import with dn '%s' failed."),$dn));
1094     return($ret);
1095   }
1097   
1098   function importcsv($str)
1099   {
1100     $lines = split("\n",$str);
1101     foreach($lines as $line)
1102     {
1103       /* continue if theres a comment */
1104       if(substr(trim($line),0,1)=="#"){
1105         continue;
1106       }
1108       $line= str_replace ("\t\t","\t",$line);
1109       $line= str_replace ("\t"  ,"," ,$line);
1110       echo $line;
1112       $cells = split(",",$line )  ;
1113       $linet= str_replace ("\t\t",",",$line);
1114       $cells = split("\t",$line);
1115       $count = count($cells);  
1116     }
1118   }
1119   
1120   function get_objectclasses()
1121   {
1122     $objectclasses = array();
1123     global $config;
1125     /* Only read schema if it is allowed */
1126     if(isset($config) && preg_match("/config/i",get_class($config))){
1127       if(!isset($config->data['MAIN']['SCHEMA_CHECK']) || !preg_match("/true/i",$config->data['MAIN']['SCHEMA_CHECK'])){
1128         return($objectclasses);
1129       } 
1130     }
1132     /* Return the cached results. */
1133     if(class_available('session') && session::is_set("LDAP_CACHE::get_objectclasses")){
1134       $objectclasses = session::get("LDAP_CACHE::get_objectclasses");
1135       return($objectclasses);
1136     }
1137         
1138           # Get base to look for schema 
1139           $sr = @ldap_read ($this->cid, NULL, "objectClass=*", array("subschemaSubentry"));
1140     if(!$sr){
1141             $sr = @ldap_read ($this->cid, "", "objectClass=*", array("subschemaSubentry"));
1142     }
1144           $attr = @ldap_get_entries($this->cid,$sr);
1145           if (!isset($attr[0]['subschemasubentry'][0])){
1146             return array();
1147           }
1148         
1149           /* Get list of objectclasses and fill array */
1150           $nb= $attr[0]['subschemasubentry'][0];
1151           $objectclasses= array();
1152           $sr= ldap_read ($this->cid, $nb, "objectClass=*", array("objectclasses"));
1153           $attrs= ldap_get_entries($this->cid,$sr);
1154           if (!isset($attrs[0])){
1155             return array();
1156           }
1157           foreach ($attrs[0]['objectclasses'] as $val){
1158       if (preg_match('/^[0-9]+$/', $val)){
1159         continue;
1160       }
1161       $name= "OID";
1162       $pattern= split(' ', $val);
1163       $ocname= preg_replace("/^.* NAME\s+\(*\s*'([^']+)'\s*\)*.*$/", '\\1', $val);
1164       $objectclasses[$ocname]= array();
1166       foreach($pattern as $chunk){
1167         switch($chunk){
1169           case '(':
1170                     $value= "";
1171                     break;
1173           case ')': if ($name != ""){
1174                       $objectclasses[$ocname][$name]= $this->value2container($value);
1175                     }
1176                     $name= "";
1177                     $value= "";
1178                     break;
1180           case 'NAME':
1181           case 'DESC':
1182           case 'SUP':
1183           case 'STRUCTURAL':
1184           case 'ABSTRACT':
1185           case 'AUXILIARY':
1186           case 'MUST':
1187           case 'MAY':
1188                     if ($name != ""){
1189                       $objectclasses[$ocname][$name]= $this->value2container($value);
1190                     }
1191                     $name= $chunk;
1192                     $value= "";
1193                     break;
1195           default:  $value.= $chunk." ";
1196         }
1197       }
1199           }
1200     if(class_available("session")){
1201       session::set("LDAP_CACHE::get_objectclasses",$objectclasses);
1202     }
1203           return $objectclasses;
1204   }
1207   function value2container($value)
1208   {
1209     /* Set emtpy values to "true" only */
1210     if (preg_match('/^\s*$/', $value)){
1211       return true;
1212     }
1214     /* Remove ' and " if needed */
1215     $value= preg_replace('/^[\'"]/', '', $value);
1216     $value= preg_replace('/[\'"] *$/', '', $value);
1218     /* Convert to array if $ is inside... */
1219     if (preg_match('/\$/', $value)){
1220       $container= preg_split('/\s*\$\s*/', $value);
1221     } else {
1222       $container= chop($value);
1223     }
1225     return ($container);
1226   }
1229   function log($string)
1230   {
1231     if (session::is_set('config')){
1232       $cfg = session::get('config');
1233       if (isset($cfg->current['LDAPSTATS']) && preg_match('/true/i', $cfg->current['LDAPSTATS'])){
1234         syslog (LOG_INFO, $string);
1235       }
1236     }
1237   }
1239   /* added by Guido Serra aka Zeph <zeph@purotesto.it> */
1240   function getCn($dn){
1241     $simple= split(",", $dn);
1243     foreach($simple as $piece) {
1244       $partial= split("=", $piece);
1246       if($partial[0] == "cn"){
1247         return $partial[1];
1248       }
1249     }
1250   }
1253   function get_naming_contexts($server, $admin= "", $password= "")
1254   {
1255     /* Build LDAP connection */
1256     $ds= ldap_connect ($server);
1257     if (!$ds) {
1258       die ("Can't bind to LDAP. No check possible!");
1259     }
1260     ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
1261     $r= ldap_bind ($ds, $admin, $password);
1263     /* Get base to look for naming contexts */
1264     $sr  = @ldap_read ($ds, "", "objectClass=*", array("+"));
1265     $attr= @ldap_get_entries($ds,$sr);
1267     return ($attr[0]['namingcontexts']);
1268   }
1271   function get_root_dse($server, $admin= "", $password= "")
1272   {
1273     /* Build LDAP connection */
1274     $ds= ldap_connect ($server);
1275     if (!$ds) {
1276       die ("Can't bind to LDAP. No check possible!");
1277     }
1278     ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
1279     $r= ldap_bind ($ds, $admin, $password);
1281     /* Get base to look for naming contexts */
1282     $sr  = @ldap_read ($ds, "", "objectClass=*", array("+"));
1283     $attr= @ldap_get_entries($ds,$sr);
1284    
1285     /* Return empty array, if nothing was set */
1286     if (!isset($attr[0])){
1287       return array();
1288     }
1290     /* Rework array... */
1291     $result= array();
1292     for ($i= 0; $i<$attr[0]['count']; $i++){
1293       $result[$attr[0][$i]]= $attr[0][$attr[0][$i]];
1294       unset($result[$attr[0][$i]]['count']);
1295     }
1297     return ($result);
1298   }
1301 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
1302 ?>