Code

742315ad3e6142a55b81185b95e16d48da369d2d
[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         if (!$this->success()){
636           msg_dialog::display(_("LDAP error"), msgPool::ldaperror($this->get_error(), $cdn, LDAP_ADD, get_class()));
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   }
698   function success()
699   {
700     return (preg_match('/Success/i', $this->error));
701   }
704   function get_error()
705   {
706     if ($this->error == 'Success'){
707       return $this->error;
708     } else {
709       $adderror= $this->get_additional_error();
710       if ($adderror != ""){
711         $error= $this->error." (".$this->get_additional_error().", ".sprintf(_("while operating on '%s' using LDAP server '%s'"), $this->basedn, $this->hostname).")";
712       } else {
713         $error= $this->error." (".sprintf(_("while operating on LDAP server %s"), $this->hostname).")";
714       }
715       return $error;
716     }
717   }
719   function get_credentials($url, $referrals= NULL)
720   {
721     $ret= array();
722     $url= preg_replace('!\?\?.*$!', '', $url);
723     $server= preg_replace('!^([^:]+://[^/]+)/.*$!', '\\1', $url);
725     if ($referrals === NULL){
726       $referrals= $this->referrals;
727     }
729     if (isset($referrals[$server])){
730       return ($referrals[$server]);
731     } else {
732       $ret['ADMIN']= LDAP::fix($this->binddn);
733       $ret['PASSWORD']= $this->bindpw;
734     }
736     return ($ret);
737   }
740   function gen_ldif ($dn, $filter= "(objectClass=*)", $attributes= array('*'), $recursive= TRUE)
741   {
742     $display= "";
744     if ($recursive){
745       $this->cd($dn);
746       $this->ls($filter,$dn, array('dn','objectClass'));
747       $deps = array();
749       $display .= $this->gen_one_entry($dn)."\n";
751       while ($attrs= $this->fetch()){
752         $deps[] = $attrs['dn'];
753       }
754       foreach($deps as $dn){
755         $display .= $this->gen_ldif($dn, $filter,$attributes,$recursive);
756       }
757     } else {
758       $display.= $this->gen_one_entry($dn);
759     }
760     return ($display);
761   }
764   function gen_xls ($dn, $filter= "(objectClass=*)", $attributes= array('*'), $recursive= TRUE,$r_array=0)
765   {
766     $display= array();
768       $this->cd($dn);
769       $this->search("$filter");
771       $i=0;
772       while ($attrs= $this->fetch()){
773         $j=0;
775         foreach ($attributes as $at){
776           $display[$i][$j]= $this->get_attribute($attrs['dn'], $at,$r_array);
777           $j++;
778         }
780         $i++;
781       }
783     return ($display);
784   }
787   function gen_one_entry($dn, $filter= "(objectClass=*)" , $name= array("*"))
788   {
789     $ret = "";
790     $data = "";
791     if($this->reconnect){
792       $this->connect();
793     }
795     /* Searching Ldap Tree */
796     $sr= @ldap_read($this->cid, LDAP::fix($dn), $filter, $name);
798     /* Get the first entry */   
799     $entry= @ldap_first_entry($this->cid, $sr);
801     /* Get all attributes related to that Objekt */
802     $atts = array();
803     
804     /* Assemble dn */
805     $atts[0]['name']  = "dn";
806     $atts[0]['value'] = array('count' => 1, 0 => $dn);
808     /* Reset index */
809     $i = 1 ; 
810   $identifier = array();
811     $attribute= @ldap_first_attribute($this->cid,$entry,$identifier);
812     while ($attribute) {
813       $i++;
814       $atts[$i]['name']  = $attribute;
815       $atts[$i]['value'] = @ldap_get_values_len($this->cid, $entry, "$attribute");
817       /* Next one */
818       $attribute= @ldap_next_attribute($this->cid,$entry,$identifier);
819     }
821     foreach($atts as $at)
822     {
823       for ($i= 0; $i<$at['value']['count']; $i++){
825         /* Check if we must encode the data */
826         if(!preg_match('/^[a-z0-9+@#.=, \/ -]+$/i', $at['value'][$i])) {
827           $ret .= $at['name'].":: ".base64_encode($at['value'][$i])."\n";
828         } else {
829           $ret .= $at['name'].": ".$at['value'][$i]."\n";
830         }
831       }
832     }
834     return($ret);
835   }
838   function dn_exists($dn)
839   {
840     return @ldap_list($this->cid, LDAP::fix($dn), "(objectClass=*)", array("objectClass"));
841   }
842   
845   /*  This funktion imports ldifs 
846         
847       If DeleteOldEntries is true, the destination entry will be deleted first. 
848       If JustModify is true the destination entry will only be touched by the attributes specified in the ldif.
849       if JustMofify id false the destination dn will be overwritten by the new ldif. 
850     */
852   function import_complete_ldif($str_attr,&$error,$JustModify,$DeleteOldEntries)
853   {
854     if($this->reconnect) $this->connect();
856     /* First we have to splitt the string ito detect empty lines
857        An empty line indicates an new Entry */
858     $entries = split("\n",$str_attr);
860     $data = "";
861     $cnt = 0; 
862     $current_line = 0;
864     /* FIX ldif */
865     $last = "";
866     $tmp  = "";
867     $i = 0;
868     foreach($entries as $entry){
869       if(preg_match("/^ /",$entry)){
870         $tmp[$i] .= trim($entry);
871       }else{
872         $i ++;
873         $tmp[$i] = trim($entry);
874       }
875     }
877     /* Every single line ... */
878     foreach($tmp as $entry) {
879       $current_line ++;
881       /* Removing Spaces to .. 
882          .. test if a new entry begins */
883       $tmp  = str_replace(" ","",$data );
885       /* .. prevent empty lines in an entry */
886       $tmp2 = str_replace(" ","",$entry);
888       /* If the Block ends (Empty Line) */
889       if((empty($entry))&&(!empty($tmp))) {
890         /* Add collected lines as a complete block */
891         $all[$cnt] = $data;
892         $cnt ++;
893         $data ="";
894       } else {
896         /* Append lines ... */
897         if(!empty($tmp2)) {
898           /* check if we need base64_decode for this line */
899           if(ereg("::",$tmp2))
900           {
901             $encoded = split("::",$entry);
902             $attr  = trim($encoded[0]);
903             $value = base64_decode(trim($encoded[1]));
904             /* Add linenumber */
905             $data .= $current_line."#".base64_encode($attr.":".$value)."\n";
906           }
907           else
908           {
909             /* Add Linenumber */ 
910             $data .= $current_line."#".base64_encode($entry)."\n";
911           }
912         }
913       }
914     }
916     /* The Data we collected is not in the array all[];
917        For example the Data is stored like this..
919        all[0] = "1#dn : .... \n 
920        2#ObjectType: person \n ...."
921        
922        Now we check every insertblock and try to insert */
923     foreach ( $all as $single) {
924       $lineone = split("\n",$single);  
925       $ndn = split("#", $lineone[0]);
926       $line = base64_decode($ndn[1]);
928       $dnn = split (":",$line,2);
929       $current_line = $ndn[0];
930       $dn    = $dnn[0];
931       $value = $dnn[1];
933       /* Every block must begin with a dn */
934       if($dn != "dn") {
935         $error= sprintf(_("This is not a valid DN: '%s'. A block for import should begin with 'dn: ...' in line %s"), $line, $current_line);
936         return -2;  
937       }
939       /* Should we use Modify instead of Add */
940       $usemodify= false;
942       /* Delete before insert */
943       $usermdir= false;
944     
945       /* The dn address already exists, Don't delete destination entry, overwrite it */
946       if (($this->dn_exists($value))&&((!$JustModify)&&(!$DeleteOldEntries))) {
948         $usermdir = $usemodify = false;
950       /* Delete old entry first, then add new */
951       } elseif(($this->dn_exists($value))&&($DeleteOldEntries)){
953         /* Delete first, then add */
954         $usermdir = true;        
956       } elseif(($this->dn_exists($value))&&($JustModify)) {
957         
958         /* Modify instead of Add */
959         $usemodify = true;
960       }
961      
962       /* If we can't Import, return with a file error */
963       if(!$this->import_single_entry($single,$usemodify,$usermdir) ) {
964         $error= sprintf(_("Error while importing dn: '%s', please check your LDIF from line %s on!"), $line,
965                         $current_line);
966         return UNKNOWN_TOKEN_IN_LDIF_FILE;      }
967     }
969     return (INSERT_OK);
970   }
973   /* Imports a single entry 
974       If $delete is true;  The old entry will be deleted if it exists.
975       if $modify is true;  All variables that are not touched by the new ldif will be kept.
976       if $modify is false; The new ldif overwrites the old entry, and all untouched attributes get lost.
977   */
978   function import_single_entry($str_attr,$modify,$delete)
979   {
980     global $config;
982     if(!$config){
983       trigger_error("Can't import ldif, can't read config object.");
984     }
985   
987     if($this->reconnect) $this->connect();
989     $ret = false;
990     $rows= split("\n",$str_attr);
991     $data= false;
993     foreach($rows as $row) {
994       
995       /* Check if we use Linenumbers (when import_complete_ldif is called we use
996          Linenumbers) Linenumbers are use like this 123#attribute : value */
997       if(!empty($row)) {
998         if(strpos($row,"#")!=FALSE) {
1000           /* We are using line numbers 
1001              Because there is a # before a : */
1002           $tmp1= split("#",$row);
1003           $current_line= $tmp1[0];
1004           $row= base64_decode($tmp1[1]);
1005         }
1007         /* Split the line into  attribute  and value */
1008         $attr   = split(":", $row,2);
1009         $attr[0]= trim($attr[0]);  /* attribute */
1010         $attr[1]= $attr[1];  /* value */
1012         /* Check :: was used to indicate base64_encoded strings */
1013         if($attr[1][0] == ":"){
1014           $attr[1]=trim(preg_replace("/^:/","",$attr[1]));
1015           $attr[1]=base64_decode($attr[1]);
1016         }
1018         $attr[1] = trim($attr[1]);
1020         /* Check for attributes that are used more than once */
1021         if(!isset($data[$attr[0]])) {
1022           $data[$attr[0]]=$attr[1];
1023         } else {
1024           $tmp = $data[$attr[0]];
1026           if(!is_array($tmp)) {
1027             $new[0]=$tmp;
1028             $new[1]=$attr[1];
1029             $datas[$attr[0]]['count']=1;             
1030             $data[$attr[0]]=$new;
1031           } else {
1032             $cnt = $datas[$attr[0]]['count'];           
1033             $cnt ++;
1034             $data[$attr[0]][$cnt]=$attr[1];
1035             $datas[$attr[0]]['count'] = $cnt;
1036           }
1037         }
1038       }
1039     }
1041     /* If dn is an index of data, we should try to insert the data */
1042     if(isset($data['dn'])) {
1044       /* Fix dn */
1045       $tmp = gosa_ldap_explode_dn($data['dn']);
1046       unset($tmp['count']);
1047       $newdn ="";
1048       foreach($tmp as $tm){
1049         $newdn.= trim($tm).",";
1050       }
1051       $newdn = preg_replace("/,$/","",$newdn);
1052       $data['dn'] = $newdn;
1053    
1054       /* Creating Entry */
1055       $this->cd($data['dn']);
1057       /* Delete existing entry */
1058       if($delete){
1059         $this->rmdir_recursive($data['dn']);
1060       }
1061      
1062       /* Create missing trees */
1063       $this->cd ($this->basedn);
1064       $this->cd($config->current['BASE']);
1065       $this->create_missing_trees(preg_replace("/^[^,]+,/","",$data['dn']));
1066       $this->cd($data['dn']);
1068       $dn = $data['dn'];
1069       unset($data['dn']);
1070       
1071       if(!$modify){
1073         $this->cat($dn);
1074         if($this->count()){
1075         
1076           /* The destination entry exists, overwrite it with the new entry */
1077           $attrs = $this->fetch();
1078           foreach($attrs as $name => $value ){
1079             if(!is_numeric($name)){
1080               if(in_array($name,array("dn","count"))) continue;
1081               if(!isset($data[$name])){
1082                 $data[$name] = array();
1083               }
1084             }
1085           }
1086           $ret = $this->modify($data);
1087     
1088         }else{
1089     
1090           /* The destination entry doesn't exists, create it */
1091           $ret = $this->add($data);
1092         }
1094       } else {
1095         
1096         /* Keep all vars that aren't touched by this ldif */
1097         $ret = $this->modify($data);
1098       }
1099     }
1101     if (!$this->success()){
1102       msg_dialog::display(_("LDAP error"), msgPool::ldaperror($this->get_error(), $dn, "", get_class()));
1103     }
1105     return($ret);
1106   }
1108   
1109   function importcsv($str)
1110   {
1111     $lines = split("\n",$str);
1112     foreach($lines as $line)
1113     {
1114       /* continue if theres a comment */
1115       if(substr(trim($line),0,1)=="#"){
1116         continue;
1117       }
1119       $line= str_replace ("\t\t","\t",$line);
1120       $line= str_replace ("\t"  ,"," ,$line);
1121       echo $line;
1123       $cells = split(",",$line )  ;
1124       $linet= str_replace ("\t\t",",",$line);
1125       $cells = split("\t",$line);
1126       $count = count($cells);  
1127     }
1129   }
1130   
1131   function get_objectclasses()
1132   {
1133     $objectclasses = array();
1134     global $config;
1136     /* Only read schema if it is allowed */
1137     if(isset($config) && preg_match("/config/i",get_class($config))){
1138       if(!isset($config->data['MAIN']['SCHEMA_CHECK']) || !preg_match("/true/i",$config->data['MAIN']['SCHEMA_CHECK'])){
1139         return($objectclasses);
1140       } 
1141     }
1143     /* Return the cached results. */
1144     if(class_available('session') && session::is_set("LDAP_CACHE::get_objectclasses")){
1145       $objectclasses = session::get("LDAP_CACHE::get_objectclasses");
1146       return($objectclasses);
1147     }
1148         
1149           # Get base to look for schema 
1150           $sr = @ldap_read ($this->cid, NULL, "objectClass=*", array("subschemaSubentry"));
1151     if(!$sr){
1152             $sr = @ldap_read ($this->cid, "", "objectClass=*", array("subschemaSubentry"));
1153     }
1155           $attr = @ldap_get_entries($this->cid,$sr);
1156           if (!isset($attr[0]['subschemasubentry'][0])){
1157             return array();
1158           }
1159         
1160           /* Get list of objectclasses and fill array */
1161           $nb= $attr[0]['subschemasubentry'][0];
1162           $objectclasses= array();
1163           $sr= ldap_read ($this->cid, $nb, "objectClass=*", array("objectclasses"));
1164           $attrs= ldap_get_entries($this->cid,$sr);
1165           if (!isset($attrs[0])){
1166             return array();
1167           }
1168           foreach ($attrs[0]['objectclasses'] as $val){
1169       if (preg_match('/^[0-9]+$/', $val)){
1170         continue;
1171       }
1172       $name= "OID";
1173       $pattern= split(' ', $val);
1174       $ocname= preg_replace("/^.* NAME\s+\(*\s*'([^']+)'\s*\)*.*$/", '\\1', $val);
1175       $objectclasses[$ocname]= array();
1177       foreach($pattern as $chunk){
1178         switch($chunk){
1180           case '(':
1181                     $value= "";
1182                     break;
1184           case ')': if ($name != ""){
1185                       $objectclasses[$ocname][$name]= $this->value2container($value);
1186                     }
1187                     $name= "";
1188                     $value= "";
1189                     break;
1191           case 'NAME':
1192           case 'DESC':
1193           case 'SUP':
1194           case 'STRUCTURAL':
1195           case 'ABSTRACT':
1196           case 'AUXILIARY':
1197           case 'MUST':
1198           case 'MAY':
1199                     if ($name != ""){
1200                       $objectclasses[$ocname][$name]= $this->value2container($value);
1201                     }
1202                     $name= $chunk;
1203                     $value= "";
1204                     break;
1206           default:  $value.= $chunk." ";
1207         }
1208       }
1210           }
1211     if(class_available("session")){
1212       session::set("LDAP_CACHE::get_objectclasses",$objectclasses);
1213     }
1214           return $objectclasses;
1215   }
1218   function value2container($value)
1219   {
1220     /* Set emtpy values to "true" only */
1221     if (preg_match('/^\s*$/', $value)){
1222       return true;
1223     }
1225     /* Remove ' and " if needed */
1226     $value= preg_replace('/^[\'"]/', '', $value);
1227     $value= preg_replace('/[\'"] *$/', '', $value);
1229     /* Convert to array if $ is inside... */
1230     if (preg_match('/\$/', $value)){
1231       $container= preg_split('/\s*\$\s*/', $value);
1232     } else {
1233       $container= chop($value);
1234     }
1236     return ($container);
1237   }
1240   function log($string)
1241   {
1242     if (session::is_set('config')){
1243       $cfg = session::get('config');
1244       if (isset($cfg->current['LDAPSTATS']) && preg_match('/true/i', $cfg->current['LDAPSTATS'])){
1245         syslog (LOG_INFO, $string);
1246       }
1247     }
1248   }
1250   /* added by Guido Serra aka Zeph <zeph@purotesto.it> */
1251   function getCn($dn){
1252     $simple= split(",", $dn);
1254     foreach($simple as $piece) {
1255       $partial= split("=", $piece);
1257       if($partial[0] == "cn"){
1258         return $partial[1];
1259       }
1260     }
1261   }
1264   function get_naming_contexts($server, $admin= "", $password= "")
1265   {
1266     /* Build LDAP connection */
1267     $ds= ldap_connect ($server);
1268     if (!$ds) {
1269       die ("Can't bind to LDAP. No check possible!");
1270     }
1271     ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
1272     $r= ldap_bind ($ds, $admin, $password);
1274     /* Get base to look for naming contexts */
1275     $sr  = @ldap_read ($ds, "", "objectClass=*", array("+"));
1276     $attr= @ldap_get_entries($ds,$sr);
1278     return ($attr[0]['namingcontexts']);
1279   }
1282   function get_root_dse($server, $admin= "", $password= "")
1283   {
1284     /* Build LDAP connection */
1285     $ds= ldap_connect ($server);
1286     if (!$ds) {
1287       die ("Can't bind to LDAP. No check possible!");
1288     }
1289     ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
1290     $r= ldap_bind ($ds, $admin, $password);
1292     /* Get base to look for naming contexts */
1293     $sr  = @ldap_read ($ds, "", "objectClass=*", array("+"));
1294     $attr= @ldap_get_entries($ds,$sr);
1295    
1296     /* Return empty array, if nothing was set */
1297     if (!isset($attr[0])){
1298       return array();
1299     }
1301     /* Rework array... */
1302     $result= array();
1303     for ($i= 0; $i<$attr[0]['count']; $i++){
1304       $result[$attr[0][$i]]= $attr[0][$attr[0][$i]];
1305       unset($result[$attr[0][$i]]['count']);
1306     }
1308     return ($result);
1309   }
1312 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
1313 ?>