Code

Added new function which allows renaming of entries without creating copies and remov...
[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     /* Extract the name and the parent part out ouf source dn.
455         e.g.  cn=herbert,ou=department,dc=... 
456          parent =>  ou=department,dc=...
457          dest   =>  cn=herbert
458      */
459     $parent = preg_replace("/^[^,]+,/","",$dest);
460     $dest   = preg_replace("/,.*$/","",$dest);
461   
462     if($this->hascon){
463       if ($this->reconnect) $this->connect();
464       $r= @ldap_rename($this->cid,$source,$dest,$parent,TRUE); 
465       $this->error = @ldap_error($this->cid);
466       return(!$r ? $r : TRUE);
467     }else{
468       $this->error = "Could not connect to LDAP server";
469       return(FALSE);
470     }
471   }
474   /**
475   *  Function rmdir_recursive
476   *
477   *  Description: Based in recursive_remove, adding two thing: full subtree remove, and delete own node.
478   *  Parameters:  The dn to delete
479   *  GiveBack:    True on sucessfull , 0 in error, and "" when we don't get a ldap conection
480   *
481   */
482   function rmdir_recursive($srp, $deletedn)
483   {
484     if($this->hascon){
485       if ($this->reconnect) $this->connect();
486       $delarray= array();
487         
488       /* Get sorted list of dn's to delete */
489       $this->ls ($srp, "(objectClass=*)",$deletedn);
490       while ($this->fetch($srp)){
491         $deldn= $this->getDN($srp);
492         $delarray[$deldn]= strlen($deldn);
493       }
494       arsort ($delarray);
495       reset ($delarray);
497       /* Really Delete ALL dn's in subtree */
498       foreach ($delarray as $key => $value){
499         $this->rmdir_recursive($srp, $key);
500       }
501       
502       /* Finally Delete own Node */
503       $r = @ldap_delete($this->cid, LDAP::fix($deletedn));
504       $this->error = @ldap_error($this->cid);
505       return($r ? $r : 0);
506     }else{
507       $this->error = "Could not connect to LDAP server";
508       return("");
509     }
510   }
513   function modify($attrs)
514   {
515     if(count($attrs) == 0){
516       return (0);
517     }
518     if($this->hascon){
519       if ($this->reconnect) $this->connect();
520       $r = @ldap_modify($this->cid, LDAP::fix($this->basedn), $attrs);
521       $this->error = @ldap_error($this->cid);
522       return($r ? $r : 0);
523     }else{
524       $this->error = "Could not connect to LDAP server";
525       return("");
526     }
527   }
529   function add($attrs)
530   {
531     if($this->hascon){
532       if ($this->reconnect) $this->connect();
533       $r = @ldap_add($this->cid, LDAP::fix($this->basedn), $attrs);
534       $this->error = @ldap_error($this->cid);
535       return($r ? $r : 0);
536     }else{
537       $this->error = "Could not connect to LDAP server";
538       return("");
539     }
540   }
542   function create_missing_trees($srp, $target)
543   {
544     global $config;
546     $real_path= substr($target, 0, strlen($target) - strlen($this->basedn) -1 );
548     if ($target == $this->basedn){
549       $l= array("dummy");
550     } else {
551       $l= array_reverse(gosa_ldap_explode_dn($real_path));
552     }
553     unset($l['count']);
554     $cdn= $this->basedn;
555     $tag= "";
557     /* Load schema if available... */
558     $classes= $this->get_objectclasses();
560     foreach ($l as $part){
561       if ($part != "dummy"){
562         $cdn= "$part,$cdn";
563       }
565       /* Ignore referrals */
566       $found= false;
567       foreach($this->referrals as $ref){
568         $base= preg_replace('!^[^:]+://[^/]+/([^?]+).*$!', '\\1', $ref['URL']);
569         if ($base == $cdn){
570           $found= true;
571           break;
572         }
573       }
574       if ($found){
575         continue;
576       }
578       $this->cat ($srp, $cdn);
579       $attrs= $this->fetch($srp);
581       /* Create missing entry? */
582       if (count ($attrs)){
583       
584         /* Catch the tag - if present */
585         if (isset($attrs['gosaUnitTag'][0])){
586           $tag= $attrs['gosaUnitTag'][0];
587         }
589       } else {
590         $type= preg_replace('/^([^=]+)=.*$/', '\\1', $cdn);
591         $param= preg_replace('/^[^=]+=([^,]+),.*$/', '\\1', $cdn);
593         $na= array();
595         /* Automatic or traditional? */
596         if(count($classes)){
598           /* Get name of first matching objectClass */
599           $ocname= "";
600           foreach($classes as $class){
601             if (isset($class['MUST']) && $class['MUST'] == "$type"){
603               /* Look for first classes that is structural... */
604               if (isset($class['STRUCTURAL'])){
605                 $ocname= $class['NAME'];
606                 break;
607               }
609               /* Look for classes that are auxiliary... */
610               if (isset($class['AUXILIARY'])){
611                 $ocname= $class['NAME'];
612               }
613             }
614           }
616           /* Bail out, if we've nothing to do... */
617           if ($ocname == ""){
618             msg_dialog::display(_("Internal error"), sprintf(_("Cannot automatically create subtrees with RDN '%s': no object class found!"),$type), FATAL_ERROR_DIALOG);
619             exit();
620           }
622           /* Assemble_entry */
623           if ($tag != ""){
624             $na['objectClass']= array($ocname, "gosaAdministrativeUnitTag");
625             $na["gosaUnitTag"]= $tag;
626           } else {
627             $na['objectClass']= array($ocname);
628           }
629           if (isset($classes[$ocname]['AUXILIARY'])){
630             $na['objectClass'][]= $classes[$ocname]['SUP'];
631           }
632           if ($type == "dc"){
633             /* This is bad actually, but - tell me a better way? */
634             $na['objectClass'][]= 'locality';
635           }
636           $na[$type]= $param;
637           if (is_array($classes[$ocname]['MUST'])){
638             foreach($classes[$ocname]['MUST'] as $attr){
639               $na[$attr]= "filled";
640             }
641           }
643         } else {
645           /* Use alternative add... */
646           switch ($type){
647             case 'ou':
648               if ($tag != ""){
649                 $na["objectClass"]= array("organizationalUnit", "gosaAdministrativeUnitTag");
650                 $na["gosaUnitTag"]= $tag;
651               } else {
652                 $na["objectClass"]= "organizationalUnit";
653               }
654               $na["ou"]= $param;
655               break;
656             case 'dc':
657               if ($tag != ""){
658                 $na["objectClass"]= array("dcObject", "top", "locality", "gosaAdministrativeUnitTag");
659                 $na["gosaUnitTag"]= $tag;
660               } else {
661                 $na["objectClass"]= array("dcObject", "top", "locality");
662               }
663               $na["dc"]= $param;
664               break;
665             default:
666               msg_dialog::display(_("Internal error"), sprintf(_("Cannot automatically create subtrees with RDN '%s': not supported"),$type), FATAL_ERROR_DIALOG);
667               exit();
668           }
670         }
671         $this->cd($cdn);
672         $this->add($na);
673     
674         if (!$this->success()){
675           msg_dialog::display(_("LDAP error"), msgPool::ldaperror($this->get_error(), $cdn, LDAP_ADD, get_class()));
676           return FALSE;
677         }
678       }
679     }
681     return TRUE;
682   }
685   function recursive_remove($srp)
686   {
687     $delarray= array();
689     /* Get sorted list of dn's to delete */
690     $this->search ($srp, "(objectClass=*)");
691     while ($this->fetch($srp)){
692       $deldn= $this->getDN($srp);
693       $delarray[$deldn]= strlen($deldn);
694     }
695     arsort ($delarray);
696     reset ($delarray);
698     /* Delete all dn's in subtree */
699     foreach ($delarray as $key => $value){
700       $this->rmdir($key);
701     }
702   }
704   function get_attribute($dn, $name,$r_array=0)
705   {
706     $data= "";
707     if ($this->reconnect) $this->connect();
708     $sr= @ldap_read($this->cid, LDAP::fix($dn), "objectClass=*", array("$name"));
710     /* fill data from LDAP */
711     if ($sr) {
712       $ei= @ldap_first_entry($this->cid, $sr);
713       if ($ei) {
714         if ($info= @ldap_get_values_len($this->cid, $ei, "$name")){
715           $data= $info[0];
716         }
717       }
718     }
719     if($r_array==0)
720     return ($data);
721     else
722     return ($info);
723   
724   
725   }
726  
729   function get_additional_error()
730   {
731     $error= "";
732     @ldap_get_option ($this->cid, LDAP_OPT_ERROR_STRING, $error);
733     return ($error);
734   }
737   function success()
738   {
739     return (preg_match('/Success/i', $this->error));
740   }
743   function get_error()
744   {
745     if ($this->error == 'Success'){
746       return $this->error;
747     } else {
748       $adderror= $this->get_additional_error();
749       if ($adderror != ""){
750         $error= $this->error." (".$this->get_additional_error().", ".sprintf(_("while operating on '%s' using LDAP server '%s'"), $this->basedn, $this->hostname).")";
751       } else {
752         $error= $this->error." (".sprintf(_("while operating on LDAP server %s"), $this->hostname).")";
753       }
754       return $error;
755     }
756   }
758   function get_credentials($url, $referrals= NULL)
759   {
760     $ret= array();
761     $url= preg_replace('!\?\?.*$!', '', $url);
762     $server= preg_replace('!^([^:]+://[^/]+)/.*$!', '\\1', $url);
764     if ($referrals === NULL){
765       $referrals= $this->referrals;
766     }
768     if (isset($referrals[$server])){
769       return ($referrals[$server]);
770     } else {
771       $ret['ADMIN']= LDAP::fix($this->binddn);
772       $ret['PASSWORD']= $this->bindpw;
773     }
775     return ($ret);
776   }
779   function gen_ldif ($srp, $dn, $filter= "(objectClass=*)", $attributes= array('*'), $recursive= TRUE)
780   {
781     $display= "";
783     if ($recursive){
784       $this->cd($dn);
785       $this->ls($srp, $filter,$dn, array('dn','objectClass'));
786       $deps = array();
788       $display .= $this->gen_one_entry($dn)."\n";
790       while ($attrs= $this->fetch($srp)){
791         $deps[] = $attrs['dn'];
792       }
793       foreach($deps as $dn){
794         $display .= $this->gen_ldif($srp, $dn, $filter,$attributes,$recursive);
795       }
796     } else {
797       $display.= $this->gen_one_entry($dn);
798     }
799     return ($display);
800   }
803   function gen_xls ($srp, $dn, $filter= "(objectClass=*)", $attributes= array('*'), $recursive= TRUE,$r_array=0)
804   {
805     $display= array();
807       $this->cd($dn);
808       $this->search($srp, "$filter");
810       $i=0;
811       while ($attrs= $this->fetch($srp)){
812         $j=0;
814         foreach ($attributes as $at){
815           $display[$i][$j]= $this->get_attribute($attrs['dn'], $at,$r_array);
816           $j++;
817         }
819         $i++;
820       }
822     return ($display);
823   }
826   function gen_one_entry($dn, $filter= "(objectClass=*)" , $name= array("*"))
827   {
828     $ret = "";
829     $data = "";
830     if($this->reconnect){
831       $this->connect();
832     }
834     /* Searching Ldap Tree */
835     $sr= @ldap_read($this->cid, LDAP::fix($dn), $filter, $name);
837     /* Get the first entry */   
838     $entry= @ldap_first_entry($this->cid, $sr);
840     /* Get all attributes related to that Objekt */
841     $atts = array();
842     
843     /* Assemble dn */
844     $atts[0]['name']  = "dn";
845     $atts[0]['value'] = array('count' => 1, 0 => $dn);
847     /* Reset index */
848     $i = 1 ; 
849   $identifier = array();
850     $attribute= @ldap_first_attribute($this->cid,$entry,$identifier);
851     while ($attribute) {
852       $i++;
853       $atts[$i]['name']  = $attribute;
854       $atts[$i]['value'] = @ldap_get_values_len($this->cid, $entry, "$attribute");
856       /* Next one */
857       $attribute= @ldap_next_attribute($this->cid,$entry,$identifier);
858     }
860     foreach($atts as $at)
861     {
862       for ($i= 0; $i<$at['value']['count']; $i++){
864         /* Check if we must encode the data */
865         if(!preg_match('/^[a-z0-9+@#.=, \/ -]+$/i', $at['value'][$i])) {
866           $ret .= $at['name'].":: ".base64_encode($at['value'][$i])."\n";
867         } else {
868           $ret .= $at['name'].": ".$at['value'][$i]."\n";
869         }
870       }
871     }
873     return($ret);
874   }
877   function dn_exists($dn)
878   {
879     return @ldap_list($this->cid, LDAP::fix($dn), "(objectClass=*)", array("objectClass"));
880   }
881   
884   /*  This funktion imports ldifs 
885         
886       If DeleteOldEntries is true, the destination entry will be deleted first. 
887       If JustModify is true the destination entry will only be touched by the attributes specified in the ldif.
888       if JustMofify id false the destination dn will be overwritten by the new ldif. 
889     */
891   function import_complete_ldif($srp, $str_attr,$error,$JustModify,$DeleteOldEntries)
892   {
893     if($this->reconnect) $this->connect();
895     /* First we have to splitt the string ito detect empty lines
896        An empty line indicates an new Entry */
897     $entries = split("\n",$str_attr);
899     $data = "";
900     $cnt = 0; 
901     $current_line = 0;
903     /* FIX ldif */
904     $last = "";
905     $tmp  = "";
906     $i = 0;
907     foreach($entries as $entry){
908       if(preg_match("/^ /",$entry)){
909         $tmp[$i] .= trim($entry);
910       }else{
911         $i ++;
912         $tmp[$i] = trim($entry);
913       }
914     }
916     /* Every single line ... */
917     foreach($tmp as $entry) {
918       $current_line ++;
920       /* Removing Spaces to .. 
921          .. test if a new entry begins */
922       $tmp  = str_replace(" ","",$data );
924       /* .. prevent empty lines in an entry */
925       $tmp2 = str_replace(" ","",$entry);
927       /* If the Block ends (Empty Line) */
928       if((empty($entry))&&(!empty($tmp))) {
929         /* Add collected lines as a complete block */
930         $all[$cnt] = $data;
931         $cnt ++;
932         $data ="";
933       } else {
935         /* Append lines ... */
936         if(!empty($tmp2)) {
937           /* check if we need base64_decode for this line */
938           if(ereg("::",$tmp2))
939           {
940             $encoded = split("::",$entry);
941             $attr  = trim($encoded[0]);
942             $value = base64_decode(trim($encoded[1]));
943             /* Add linenumber */
944             $data .= $current_line."#".base64_encode($attr.":".$value)."\n";
945           }
946           else
947           {
948             /* Add Linenumber */ 
949             $data .= $current_line."#".base64_encode($entry)."\n";
950           }
951         }
952       }
953     }
955     /* The Data we collected is not in the array all[];
956        For example the Data is stored like this..
958        all[0] = "1#dn : .... \n 
959        2#ObjectType: person \n ...."
960        
961        Now we check every insertblock and try to insert */
962     foreach ( $all as $single) {
963       $lineone = split("\n",$single);  
964       $ndn = split("#", $lineone[0]);
965       $line = base64_decode($ndn[1]);
967       $dnn = split (":",$line,2);
968       $current_line = $ndn[0];
969       $dn    = $dnn[0];
970       $value = $dnn[1];
972       /* Every block must begin with a dn */
973       if($dn != "dn") {
974         $error= sprintf(_("This is not a valid DN: '%s'. A block for import should begin with 'dn: ...' in line %s"), $line, $current_line);
975         return -2;  
976       }
978       /* Should we use Modify instead of Add */
979       $usemodify= false;
981       /* Delete before insert */
982       $usermdir= false;
983     
984       /* The dn address already exists, Don't delete destination entry, overwrite it */
985       if (($this->dn_exists($value))&&((!$JustModify)&&(!$DeleteOldEntries))) {
987         $usermdir = $usemodify = false;
989       /* Delete old entry first, then add new */
990       } elseif(($this->dn_exists($value))&&($DeleteOldEntries)){
992         /* Delete first, then add */
993         $usermdir = true;        
995       } elseif(($this->dn_exists($value))&&($JustModify)) {
996         
997         /* Modify instead of Add */
998         $usemodify = true;
999       }
1000      
1001       /* If we can't Import, return with a file error */
1002       if(!$this->import_single_entry($srp, $single,$usemodify,$usermdir) ) {
1003         $error= sprintf(_("Error while importing dn: '%s', please check your LDIF from line %s on!"), $line,
1004                         $current_line);
1005         return UNKNOWN_TOKEN_IN_LDIF_FILE;      }
1006     }
1008     return (INSERT_OK);
1009   }
1012   /* Imports a single entry 
1013       If $delete is true;  The old entry will be deleted if it exists.
1014       if $modify is true;  All variables that are not touched by the new ldif will be kept.
1015       if $modify is false; The new ldif overwrites the old entry, and all untouched attributes get lost.
1016   */
1017   function import_single_entry($srp, $str_attr,$modify,$delete)
1018   {
1019     global $config;
1021     if(!$config){
1022       trigger_error("Can't import ldif, can't read config object.");
1023     }
1024   
1026     if($this->reconnect) $this->connect();
1028     $ret = false;
1029     $rows= split("\n",$str_attr);
1030     $data= false;
1032     foreach($rows as $row) {
1033       
1034       /* Check if we use Linenumbers (when import_complete_ldif is called we use
1035          Linenumbers) Linenumbers are use like this 123#attribute : value */
1036       if(!empty($row)) {
1037         if(strpos($row,"#")!=FALSE) {
1039           /* We are using line numbers 
1040              Because there is a # before a : */
1041           $tmp1= split("#",$row);
1042           $current_line= $tmp1[0];
1043           $row= base64_decode($tmp1[1]);
1044         }
1046         /* Split the line into  attribute  and value */
1047         $attr   = split(":", $row,2);
1048         $attr[0]= trim($attr[0]);  /* attribute */
1049         $attr[1]= $attr[1];  /* value */
1051         /* Check :: was used to indicate base64_encoded strings */
1052         if($attr[1][0] == ":"){
1053           $attr[1]=trim(preg_replace("/^:/","",$attr[1]));
1054           $attr[1]=base64_decode($attr[1]);
1055         }
1057         $attr[1] = trim($attr[1]);
1059         /* Check for attributes that are used more than once */
1060         if(!isset($data[$attr[0]])) {
1061           $data[$attr[0]]=$attr[1];
1062         } else {
1063           $tmp = $data[$attr[0]];
1065           if(!is_array($tmp)) {
1066             $new[0]=$tmp;
1067             $new[1]=$attr[1];
1068             $datas[$attr[0]]['count']=1;             
1069             $data[$attr[0]]=$new;
1070           } else {
1071             $cnt = $datas[$attr[0]]['count'];           
1072             $cnt ++;
1073             $data[$attr[0]][$cnt]=$attr[1];
1074             $datas[$attr[0]]['count'] = $cnt;
1075           }
1076         }
1077       }
1078     }
1080     /* If dn is an index of data, we should try to insert the data */
1081     if(isset($data['dn'])) {
1083       /* Fix dn */
1084       $tmp = gosa_ldap_explode_dn($data['dn']);
1085       unset($tmp['count']);
1086       $newdn ="";
1087       foreach($tmp as $tm){
1088         $newdn.= trim($tm).",";
1089       }
1090       $newdn = preg_replace("/,$/","",$newdn);
1091       $data['dn'] = $newdn;
1092    
1093       /* Creating Entry */
1094       $this->cd($data['dn']);
1096       /* Delete existing entry */
1097       if($delete){
1098         $this->rmdir_recursive($srp, $data['dn']);
1099       }
1100      
1101       /* Create missing trees */
1102       $this->cd ($this->basedn);
1103       $this->cd($config->current['BASE']);
1104       $this->create_missing_trees($srp, preg_replace("/^[^,]+,/","",$data['dn']));
1105       $this->cd($data['dn']);
1107       $dn = $data['dn'];
1108       unset($data['dn']);
1109       
1110       if(!$modify){
1112         $this->cat($srp, $dn);
1113         if($this->count($srp)){
1114         
1115           /* The destination entry exists, overwrite it with the new entry */
1116           $attrs = $this->fetch($srp);
1117           foreach($attrs as $name => $value ){
1118             if(!is_numeric($name)){
1119               if(in_array($name,array("dn","count"))) continue;
1120               if(!isset($data[$name])){
1121                 $data[$name] = array();
1122               }
1123             }
1124           }
1125           $ret = $this->modify($data);
1126     
1127         }else{
1128     
1129           /* The destination entry doesn't exists, create it */
1130           $ret = $this->add($data);
1131         }
1133       } else {
1134         
1135         /* Keep all vars that aren't touched by this ldif */
1136         $ret = $this->modify($data);
1137       }
1138     }
1140     if (!$this->success()){
1141       msg_dialog::display(_("LDAP error"), msgPool::ldaperror($this->get_error(), $dn, "", get_class()));
1142     }
1144     return($ret);
1145   }
1147   
1148   function importcsv($str)
1149   {
1150     $lines = split("\n",$str);
1151     foreach($lines as $line)
1152     {
1153       /* continue if theres a comment */
1154       if(substr(trim($line),0,1)=="#"){
1155         continue;
1156       }
1158       $line= str_replace ("\t\t","\t",$line);
1159       $line= str_replace ("\t"  ,"," ,$line);
1160       echo $line;
1162       $cells = split(",",$line )  ;
1163       $linet= str_replace ("\t\t",",",$line);
1164       $cells = split("\t",$line);
1165       $count = count($cells);  
1166     }
1168   }
1169   
1170   function get_objectclasses()
1171   {
1172     $objectclasses = array();
1173     global $config;
1175     /* Only read schema if it is allowed */
1176     if(isset($config) && preg_match("/config/i",get_class($config))){
1177       if(!isset($config->data['MAIN']['SCHEMA_CHECK']) || !preg_match("/true/i",$config->data['MAIN']['SCHEMA_CHECK'])){
1178         return($objectclasses);
1179       } 
1180     }
1182     /* Return the cached results. */
1183     if(class_available('session') && session::is_set("LDAP_CACHE::get_objectclasses")){
1184       $objectclasses = session::get("LDAP_CACHE::get_objectclasses");
1185       return($objectclasses);
1186     }
1187         
1188           # Get base to look for schema 
1189           $sr = @ldap_read ($this->cid, NULL, "objectClass=*", array("subschemaSubentry"));
1190     if(!$sr){
1191             $sr = @ldap_read ($this->cid, "", "objectClass=*", array("subschemaSubentry"));
1192     }
1194           $attr = @ldap_get_entries($this->cid,$sr);
1195           if (!isset($attr[0]['subschemasubentry'][0])){
1196             return array();
1197           }
1198         
1199           /* Get list of objectclasses and fill array */
1200           $nb= $attr[0]['subschemasubentry'][0];
1201           $objectclasses= array();
1202           $sr= ldap_read ($this->cid, $nb, "objectClass=*", array("objectclasses"));
1203           $attrs= ldap_get_entries($this->cid,$sr);
1204           if (!isset($attrs[0])){
1205             return array();
1206           }
1207           foreach ($attrs[0]['objectclasses'] as $val){
1208       if (preg_match('/^[0-9]+$/', $val)){
1209         continue;
1210       }
1211       $name= "OID";
1212       $pattern= split(' ', $val);
1213       $ocname= preg_replace("/^.* NAME\s+\(*\s*'([^']+)'\s*\)*.*$/", '\\1', $val);
1214       $objectclasses[$ocname]= array();
1216       foreach($pattern as $chunk){
1217         switch($chunk){
1219           case '(':
1220                     $value= "";
1221                     break;
1223           case ')': if ($name != ""){
1224                       $objectclasses[$ocname][$name]= $this->value2container($value);
1225                     }
1226                     $name= "";
1227                     $value= "";
1228                     break;
1230           case 'NAME':
1231           case 'DESC':
1232           case 'SUP':
1233           case 'STRUCTURAL':
1234           case 'ABSTRACT':
1235           case 'AUXILIARY':
1236           case 'MUST':
1237           case 'MAY':
1238                     if ($name != ""){
1239                       $objectclasses[$ocname][$name]= $this->value2container($value);
1240                     }
1241                     $name= $chunk;
1242                     $value= "";
1243                     break;
1245           default:  $value.= $chunk." ";
1246         }
1247       }
1249           }
1250     if(class_available("session")){
1251       session::set("LDAP_CACHE::get_objectclasses",$objectclasses);
1252     }
1253           return $objectclasses;
1254   }
1257   function value2container($value)
1258   {
1259     /* Set emtpy values to "true" only */
1260     if (preg_match('/^\s*$/', $value)){
1261       return true;
1262     }
1264     /* Remove ' and " if needed */
1265     $value= preg_replace('/^[\'"]/', '', $value);
1266     $value= preg_replace('/[\'"] *$/', '', $value);
1268     /* Convert to array if $ is inside... */
1269     if (preg_match('/\$/', $value)){
1270       $container= preg_split('/\s*\$\s*/', $value);
1271     } else {
1272       $container= chop($value);
1273     }
1275     return ($container);
1276   }
1279   function log($string)
1280   {
1281     if (session::is_set('config')){
1282       $cfg = session::get('config');
1283       if (isset($cfg->current['LDAPSTATS']) && preg_match('/true/i', $cfg->current['LDAPSTATS'])){
1284         syslog (LOG_INFO, $string);
1285       }
1286     }
1287   }
1289   /* added by Guido Serra aka Zeph <zeph@purotesto.it> */
1290   function getCn($dn){
1291     $simple= split(",", $dn);
1293     foreach($simple as $piece) {
1294       $partial= split("=", $piece);
1296       if($partial[0] == "cn"){
1297         return $partial[1];
1298       }
1299     }
1300   }
1303   function get_naming_contexts($server, $admin= "", $password= "")
1304   {
1305     /* Build LDAP connection */
1306     $ds= ldap_connect ($server);
1307     if (!$ds) {
1308       die ("Can't bind to LDAP. No check possible!");
1309     }
1310     ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
1311     $r= ldap_bind ($ds, $admin, $password);
1313     /* Get base to look for naming contexts */
1314     $sr  = @ldap_read ($ds, "", "objectClass=*", array("+"));
1315     $attr= @ldap_get_entries($ds,$sr);
1317     return ($attr[0]['namingcontexts']);
1318   }
1321   function get_root_dse($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);
1334    
1335     /* Return empty array, if nothing was set */
1336     if (!isset($attr[0])){
1337       return array();
1338     }
1340     /* Rework array... */
1341     $result= array();
1342     for ($i= 0; $i<$attr[0]['count']; $i++){
1343       $result[$attr[0][$i]]= $attr[0][$attr[0][$i]];
1344       unset($result[$attr[0][$i]]['count']);
1345     }
1347     return ($result);
1348   }
1351 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
1352 ?>