Code

cleanup of code
[gosa.git] / include / class_ldap.inc
1 <?php
2 /*****************************************************************************
3   newldap.inc - version 1.0
4   Copyright (C) 2003 Alejandro Escanero Blanco <alex@ofmin.com>
5   Copyright (C) 2004 Cajus Pollmeier <pollmeier@gonicus.de>
7   Based in code of ldap.inc of
8   Copyright (C) 1998  Eric Kilfoil <eric@ipass.net>
9  *****************************************************************************/
11 define("ALREADY_EXISTING_ENTRY",-10001);
12 define("UNKNOWN_TOKEN_IN_LDIF_FILE",-10002);
13 define("NO_FILE_UPLOADED",10003);
16 define("INSERT_OK",10000);
20 class LDAP{
22   var $hascon   =false;
23   var $hasres   =false;
24   var $reconnect=false;
25   var $tls      = false;
26   var $basedn   ="";
27   var $cid;
28   var $error    = ""; // Any error messages to be returned can be put here
29   var $start    = 0; // 0 if we are fetching the first entry, otherwise 1
30   var $objectClasses = array(); // Information read from slapd.oc.conf
31   var $binddn   = "";
32   var $bindpw   = "";
33   var $hostname = "";
34   var $follow_referral = FALSE;
35   var $referrals= array();
37   function LDAP($binddn,$bindpw, $hostname, $follow_referral= FALSE, $tls= FALSE)
38   {
39     $this->follow_referral= $follow_referral;
40     $this->tls=$tls;
41     $this->binddn=$binddn;
42     $this->bindpw=$bindpw;
43     $this->hostname=$hostname;
44     $this->connect();
45   }
47   function connect()
48   {
49     $this->hascon=false;
50     $this->reconnect=false;
51     if ($this->cid= @ldap_connect($this->hostname)) {
52       @ldap_set_option($this->cid, LDAP_OPT_PROTOCOL_VERSION, 3);
53       if (function_exists("ldap_set_rebind_proc") && $this->follow_referral) {
54         @ldap_set_option($this->cid, LDAP_OPT_REFERRALS, 1);
55         @ldap_set_rebind_proc($this->cid, array(&$this, "rebind"));
56       }
57       if (function_exists("ldap_start_tls") && $this->tls){
58         @ldap_start_tls($this->cid);
59       }
61       $this->error = "No Error";
62       if ($bid = @ldap_bind($this->cid, $this->binddn, $this->bindpw)) {
63         $this->error = "Success";
64         $this->hascon=true;
65       } else {
66         if ($this->reconnect){
67           if ($this->error != "Success"){
68             $this->error = "Could not rebind to " . $this->binddn;
69           }
70         } else {
71           $this->error = "Could not bind to " . $this->binddn;
72         }
73       }
74     } else {
75       $this->error = "Could not connect to LDAP server";
76     }
77   }
79   function rebind($ldap, $referral)
80   {
81     $credentials= $this->get_credentials($referral);
82     if (@ldap_bind($ldap, $credentials['ADMIN'], $credentials['PASSWORD'])) {
83       $this->error = "Success";
84       $this->hascon=true;
85       $this->reconnect= true;
86       return (0);
87     } else {
88       $this->error = "Could not bind to " . $credentials['ADMIN'];
89       return NULL;
90     }
91   }
93   function reconnect()
94   {
95     if ($this->reconnect){
96       @ldap_unbind($this->cid);
97       $this->cid = NULL;
98     }
99   }
101   function unbind()
102   {
103     @ldap_unbind($this->cid);
104     $this->cid = NULL;
105   }
107   function disconnect()
108   {
109     if($this->hascon){
110       @ldap_close($this->cid);
111       $this->hascon=false;
112     }
113   }
115   function cd($dir)
116   {
117     if ($dir == "..")
118       $this->basedn = $this->getParentDir();
119     else
120       $this->basedn = $dir;
121   }
123   function getParentDir($basedn = "")
124   {
125     if ($basedn=="")
126       $basedn = $this->basedn;
127     return(ereg_replace("[^,]*[,]*[ ]*(.*)", "\\1", $basedn));
128   }
130   function search($filter, $attrs= array())
131   {
132     
133     if($this->hascon){
134       if ($this->reconnect) $this->connect();
135       $this->clearResult();
136       $this->sr = @ldap_search($this->cid, $this->basedn, $filter, $attrs);
137       $this->error = @ldap_error($this->cid);
138       $this->resetResult();
139       $this->hasres=true;
140       return($this->sr);
141     }else{
142       $this->error = "Could not connect to LDAP server";
143       return("");
144     }
145   }
147   function ls($filter = "(objectclass=*)", $basedn = "")
148   {
149     if($this->hascon){
150       if ($this->reconnect) $this->connect();
151       $this->clearResult();
152       if ($basedn == "")
153         $basedn = $this->basedn;
154       $this->sr = @ldap_list($this->cid, $basedn, $filter);
155       $this->error = @ldap_error($this->cid);
156       $this->resetResult();
157       $this->hasres=true;
158       return($this->sr);
159     }else{
160       $this->error = "Could not connect to LDAP server";
161       return("");
162     }
163   }
165   function cat($dn)
166   {
167     if($this->hascon){
168       if ($this->reconnect) $this->connect();
169       $this->clearResult();
170       $filter = "(objectclass=*)";
171       $this->sr = @ldap_read($this->cid, $dn, $filter);
172       $this->error = @ldap_error($this->cid);
173       $this->resetResult();
174       $this->hasres=true;
175       return($this->sr);
176     }else{
177       $this->error = "Could not connect to LDAP server";
178       return("");
179     }
180   }
182   function set_size_limit($size)
183   {
184     /* Ignore zero settings */
185     if ($size == 0){
186       @ldap_set_option($this->cid, LDAP_OPT_SIZELIMIT, 10000000);
187     }
188     if($this->hascon){
189       @ldap_set_option($this->cid, LDAP_OPT_SIZELIMIT, $size);
190     } else {
191       $this->error = "Could not connect to LDAP server";
192     }
193   }
195   function fetch()
196   {
197     if($this->hascon){
198       if($this->hasres){
199         if ($this->start == 0)
200         {
201           $this->start = 1;
202           $this->re= @ldap_first_entry($this->cid, $this->sr);
203         } else {
204           $this->re= @ldap_next_entry($this->cid, $this->re);
205         }
206         if ($this->re)
207         {
208           $att= @ldap_get_attributes($this->cid, $this->re);
209           $att['dn']= @ldap_get_dn($this->cid, $this->re);
210         }
211         $this->error = @ldap_error($this->cid);
212         if (!isset($att)){
213           $att= array();
214         }
215         return($att);
216       }else{
217         $this->error = "Perform a Fetch with no Search";
218         return("");
219       }
220     }else{
221       $this->error = "Could not connect to LDAP server";
222       return("");
223     }
224   }
226   function resetResult()
227   {
228     $this->start = 0;
229   }
231   function clearResult()
232   {
233     if($this->hasres){
234       $this->hasres = false;
235       @ldap_free_result($this->sr);
236     }
237   }
239   function getDN()
240   {
241     if($this->hascon){
242       if($this->hasres){
244         if(!$this->re)
245           {
246           $this->error = "Perform a Fetch with no valid Result";
247           }
248           else
249           {
250           $rv = @ldap_get_dn($this->cid, $this->re);
251         
252           $this->error = @ldap_error($this->cid);
253           $rv= preg_replace("/[ ]*,[ ]*/", ",", $rv);
254           return($rv);
255            }
256       }else{
257         $this->error = "Perform a Fetch with no Search";
258         return("");
259       }
260     }else{
261       $this->error = "Could not connect to LDAP server";
262       return("");
263     }
264   }
266   function count()
267   {
268     if($this->hascon){
269       if($this->hasres){
270         $rv = @ldap_count_entries($this->cid, $this->sr);
271         $this->error = @ldap_error($this->cid);
272         return($rv);
273       }else{
274         $this->error = "Perform a Fetch with no Search";
275         return("");
276       }
277     }else{
278       $this->error = "Could not connect to LDAP server";
279       return("");
280     }
281   }
283   function rm($attrs = "", $dn = "")
284   {
285     if($this->hascon){
286       if ($this->reconnect) $this->connect();
287       if ($dn == "")
288         $dn = $this->basedn;
290       $r = @ldap_mod_del($this->cid, $dn, $attrs);
291       $this->error = @ldap_error($this->cid);
292       return($r);
293     }else{
294       $this->error = "Could not connect to LDAP server";
295       return("");
296     }
297   }
299   function rename($attrs, $dn = "")
300   {
301     if($this->hascon){
302       if ($this->reconnect) $this->connect();
303       if ($dn == "")
304         $dn = $this->basedn;
306       $r = @ldap_mod_replace($this->cid, $dn, $attrs);
307       $this->error = @ldap_error($this->cid);
308       return($r);
309     }else{
310       $this->error = "Could not connect to LDAP server";
311       return("");
312     }
313   }
315   function rmdir($deletedn)
316   {
317     if($this->hascon){
318       if ($this->reconnect) $this->connect();
319       $r = @ldap_delete($this->cid, $deletedn);
320       $this->error = @ldap_error($this->cid);
321       return($r ? $r : 0);
322     }else{
323       $this->error = "Could not connect to LDAP server";
324       return("");
325     }
326   }
328   /**
329   *  Function rmdir_recursive
330   *
331   *  Description: Based in recursive_remove, adding two thing: full subtree remove, and delete own node.
332   *  Parameters:  The dn to delete
333   *  GiveBack:    True on sucessfull , 0 in error, and "" when we don't get a ldap conection
334   *
335   */
337   function rmdir_recursive($deletedn)
338   {
339     if($this->hascon){
340       if ($this->reconnect) $this->connect();
341       $delarray= array();
342         
343       /* Get sorted list of dn's to delete */
344       $this->ls ("(objectClass=*)",$deletedn);
345       while ($this->fetch()){
346         $deldn= $this->getDN();
347         $delarray[$deldn]= strlen($deldn);
348       }
349       arsort ($delarray);
350       reset ($delarray);
352       /* Really Delete ALL dn's in subtree */
353       foreach ($delarray as $key => $value){
354         $this->rmdir_recursive($key);
355       }
356       
357       /* Finally Delete own Node */
358       $r = @ldap_delete($this->cid, $deletedn);
359       $this->error = @ldap_error($this->cid);
360       return($r ? $r : 0);
361     }else{
362       $this->error = "Could not connect to LDAP server";
363       return("");
364     }
365   }
368   function modify($attrs)
369   {
370     if($this->hascon){
371       if ($this->reconnect) $this->connect();
372       $r = @ldap_modify($this->cid, $this->basedn, $attrs);
373       $this->error = @ldap_error($this->cid);
374       return($r ? $r : 0);
375     }else{
376       $this->error = "Could not connect to LDAP server";
377       return("");
378     }
379   }
381   function add($attrs)
382   {
383     if($this->hascon){
384       if ($this->reconnect) $this->connect();
385       $r = @ldap_add($this->cid, $this->basedn, $attrs);
386       $this->error = @ldap_error($this->cid);
387       return($r ? $r : 0);
388     }else{
389       $this->error = "Could not connect to LDAP server";
390       return("");
391     }
392   }
394   function create_missing_trees($target)
395   {
396     /* Ignore create_missing trees if the base equals target */
397     if ($target == $this->basedn){
398      return;
399     }
400     $l= array_reverse(explode(",", preg_replace("/,".$this->basedn."/", "", $target)));
401     $cdn= $this->basedn;
402     foreach ($l as $part){
403       $cdn= "$part,$cdn";
405       /* Ignore referrals */
406       $found= false;
407       foreach($this->referrals as $ref){
408         $base= preg_replace('!^[^:]+://[^/]+/([^?]+).*$!', '\\1', $ref['URL']);
409         if ($base == $cdn){
410           $found= true;
411           break;
412         }
413       }
414       if ($found){
415         continue;
416       }
418       $this->cat ($cdn);
419       $attrs= $this->fetch();
421       /* Create missing entry? */
422       if (!count ($attrs)){
423         $type= preg_replace('/^([^=]+)=.*$/', '\\1', $cdn);
424         $param= preg_replace('/^[^=]+=([^,]+),.*$/', '\\1', $cdn);
426         $na= array();
427         switch ($type){
428           case 'ou':
429             $na["objectClass"]= "organizationalUnit";
430             $na["ou"]= $param;
431             break;
432           case 'dc':
433             $na["objectClass"]= array("dcObject", "top", "locality");
434             $na["dc"]= $param;
435             break;
436           default:
437             print_red(sprintf(_("Autocreation of type '%s' is currently not supported. Please report to the GOsa team."), $type));
438             echo $_SESSION['errors'];
439             exit;
440         }
441         $this->cd($cdn);
442         $this->add($na);
443       }
444     }
445   }
447   function recursive_remove()
448   {
449     $delarray= array();
451     /* Get sorted list of dn's to delete */
452     $this->search ("(objectClass=*)");
453     while ($this->fetch()){
454       $deldn= $this->getDN();
455       $delarray[$deldn]= strlen($deldn);
456     }
457     arsort ($delarray);
458     reset ($delarray);
460     /* Delete all dn's in subtree */
461     foreach ($delarray as $key => $value){
462       $this->rmdir($key);
463     }
464   }
466   function get_attribute($dn, $name,$r_array=0)
467   {
468     $data= "";
469     if ($this->reconnect) $this->connect();
470     $sr= @ldap_read($this->cid, $dn, "objectClass=*", array("$name"));
472     /* fill data from LDAP */
473     if ($sr) {
474       $ei= @ldap_first_entry($this->cid, $sr);
475       if ($ei) {
476         if ($info= @ldap_get_values_len($this->cid, $ei, "$name")){
477           $data= $info[0];
478         }
480       }
481     }
482     if($r_array==0)
483     return ($data);
484     else
485     return ($info);
486         
487         
488   }
489  
492   function get_additional_error()
493   {
494     $error= "";
495     @ldap_get_option ($this->cid, LDAP_OPT_ERROR_STRING, $error);
496     return ($error);
497   }
499   function get_error()
500   {
501     if ($this->error == 'Success'){
502       return $this->error;
503     } else {
504       $error= $this->error." (".$this->get_additional_error().")";
505       return $error;
506     }
507   }
509   function get_credentials($url, $referrals= NULL)
510   {
511     $ret= array();
512     $url= preg_replace('!\?\?.*$!', '', $url);
513     $server= preg_replace('!^([^:]+://[^/]+)/.*$!', '\\1', $url);
515     if ($referrals == NULL){
516       $referrals= $this->referrals;
517     }
519     if (isset($referrals[$server])){
520       return ($referrals[$server]);
521     } else {
522       $ret['ADMIN']= $this->binddn;
523       $ret['PASSWORD']= $this->bindpw;
524     }
526     return ($ret);
527   }
530   function gen_ldif ($dn, $filter= "(objectClass=*)", $attributes= array('*'), $recursive= TRUE)
531   {
532     $display= "";
534     if ($recursive){
535       $this->cd($dn);
536       $this->search("$filter", array('dn'));
537       while ($attrs= $this->fetch()){
538         $display.= $this->gen_one_entry($attrs['dn'], $filter, $attributes);
539         $display.= "\n";
540       }
541     } else {
542       $display.= $this->gen_one_entry($dn);
543     }
545     return ($display);
546   }
548 function gen_xls ($dn, $filter= "(objectClass=*)", $attributes= array('*'), $recursive= TRUE,$r_array=0)
549   {
550     $display= "";
552       $this->cd($dn);
553       $this->search("$filter");
554         $i=0;
555       while ($attrs= $this->fetch()){
556         $j=0;
557         foreach ($attributes as $at)
558         {
559         
560         $display[$i][$j]= $this->get_attribute($attrs['dn'], $at,$r_array);
561         $j++;}
562         $i++;
563       }
565     return ($display);
566   }
569   function gen_one_entry($dn, $filter= "(objectClass=*)" , $name= array("*"))
570   {
571     $ret = "";
572     $data = "";
573     if($this->reconnect){
574       $this->connect();
575     }
577     /* Searching Ldap Tree */
578     $sr= @ldap_read($this->cid, $dn, $filter, $name);
580     /* Get the first entry */           
581     $entry= @ldap_first_entry($this->cid, $sr);
583     /* Get all attributes related to that Objekt */
584     $atts = array();
585     
586     /* Assemble dn */
587     $atts[0]['name']  = "dn";
588     $atts[0]['value'] = array('count' => 1, 0 => $dn);
590     /* Reset index */
591     $i = 1 ; 
592         $identifier = array();
593     $attribute= @ldap_first_attribute($this->cid,$entry,$identifier);
594     while ($attribute) {
595       $i++;
596       $atts[$i]['name']  = $attribute;
597       $atts[$i]['value'] = @ldap_get_values_len($this->cid, $entry, "$attribute");
599       /* Next one */
600       $attribute= @ldap_next_attribute($this->cid,$entry,$identifier);
601     }
603     foreach($atts as $at)
604     {
605       for ($i= 0; $i<$at['value']['count']; $i++){
607         /* Check if we must encode the data */
608         if(!preg_match('/^[a-z0-9+@#.=, \/ -]+$/i', $at['value'][$i])) {
609           $ret .= $at['name'].":: ".base64_encode($at['value'][$i])."\n";
610         } else {
611           $ret .= $at['name'].": ".$at['value'][$i]."\n";
612         }
613       }
614     }
616     return($ret);
617   }
620   function dn_exists($dn)
621   {
622     return @ldap_list($this->cid, $dn, "(objectClass=*)", array("objectClass"));
623   }
624   
627   function import_complete_ldif($str_attr,&$error,$overwrite,$cleanup)
628   {
629     if($this->reconnect) $this->connect();
631     /* First we have to splitt the string ito detect empty lines
632        An empty line indicates an new Entry */
633     $entries = split("\n",$str_attr);
635     $data = "";
636     $cnt = 0; 
637     $current_line = 0;
639     /* Every single line ... */
640     foreach($entries as $entry) {
641       $current_line ++;
643       /* Removing Spaces to .. 
644          .. test if a new entry begins */
645       $tmp  = str_replace(" ","",$data );
647       /* .. prevent empty lines in an entry */
648       $tmp2 = str_replace(" ","",$entry);
650       /* If the Block ends (Empty Line) */
651       if((empty($entry))&&(!empty($tmp))) {
652         /* Add collected lines as a complete block */
653         $all[$cnt] = $data;
654         $cnt ++;
655         $data ="";
656       } else {
658         /* Append lines ... */
659         if(!empty($tmp2)) {
660           /* check if we need base64_decode for this line */
661           if(ereg("::",$tmp2))
662           {
663             $encoded = split("::",$entry);
664             $attr  = $encoded[0];
665             $value = base64_decode($encoded[1]);
666             /* Add linenumber */
667             $data .= $current_line."#".$attr.":".$value."\n";
668           }
669           else
670           {
671             /* Add Linenumber */ 
672             $data .= $current_line."#".$entry."\n";
673           }
674         }
675       }
676     }
678     /* The Data we collected is not in the array all[];
679        For example the Data is stored like this..
681        all[0] = "1#dn : .... \n 
682        2#ObjectType: person \n ...."
683        
684        Now we check every insertblock and try to insert */
685     foreach ( $all as $single) {
686       $lineone = split("\n",$single);  
687       $ndn = split("#", $lineone[0]);
688       $line = $ndn[1];
690       $dnn = split (":",$line);
691       $current_line = $ndn[0];
692       $dn    = $dnn[0];
693       $value = $dnn[1];
695       /* Every block must begin with a dn */
696       if($dn != "dn") {
697         $error= sprintf(_("This is not a valid DN: '%s'. A block for import should begin with 'dn: ...' in line %s"), $line, $current_line);
698         return -2;  
699       }
701       /* Should we use Modify instead of Add */
702       $usemodify= false;
704       /* Delete before insert */
705       $usermdir= false;
706     
707       /* The dn address already exists! */
708       if (($this->dn_exists($value))&&((!$overwrite)&&(!$cleanup))) {
710         $error= sprintf(_("The dn: '%s' (from line %s) already exists in the LDAP database."), $line, $current_line);
711         return ALREADY_EXISTING_ENTRY;   
713       } elseif(($this->dn_exists($value))&&($cleanup)){
715         /* Delete first, then add */
716         $usermdir = true;        
718       } elseif(($this->dn_exists($value))&&($overwrite)) {
719         
720         /* Modify instead of Add */
721         $usemodify = true;
722       }
723      
724       /* If we can't Import, return with a file error */
725       if(!$this->import_single_entry($single,$usemodify,$usermdir) ) {
726         $error= sprintf(_("Error while importing dn: '%s', please check your LDIF from line %s on!"), $line,
727                         $current_line);
728         return UNKNOWN_TOKEN_IN_LDIF_FILE;      }
729     }
731     return (INSERT_OK);
732   }
735   /* Imports a single entry */
736   function import_single_entry($str_attr,$modify,$delete)
737   {
738     if($this->reconnect) $this->connect();
740     $ret = false;
741     $rows= split("\n",$str_attr);
742     $data= false;
744     foreach($rows as $row) {
745       
746       /* Check if we use Linenumbers (when import_complete_ldif is called we use
747          Linenumbers) Linenumbers are use like this 123#attribute : value */
748       if(!empty($row)) {
749         if((strpos($row,"#")!=FALSE)&&(strpos($row,"#")<strpos($row,":"))) {
751           /* We are using line numbers 
752              Because there is a # before a : */
753           $tmp1= split("#",$row);
754           $current_line= $tmp1[0];
755           $row= $tmp1[1];
756         }
758         /* Split the line into  attribute  and value */
759         $attr   = split(":", $row);
760         $attr[0]= trim($attr[0]);  /* attribute */
761         $attr[1]= trim($attr[1]);  /* value */
763         /* Check for attributes that are used more than once */
764         if(!isset($data[$attr[0]])) {
765           $data[$attr[0]]=$attr[1];
766         } else {
767           $tmp = $data[$attr[0]];
769           if(!is_array($tmp)) {
770             $new[0]=$tmp;
771             $new[1]=$attr[1];
772             $datas[$attr[0]]['count']=1;             
773             $data[$attr[0]]=$new;
774           } else {
775             $cnt = $datas[$attr[0]]['count'];           
776             $cnt ++;
777             $data[$attr[0]][$cnt]=$attr[1];
778             $datas[$attr[0]]['count'] = $cnt;
779           }
780         }
781       }
782     } 
783     
784     /* If dn is an index of data, we should try to insert the data */
785     if(isset($data['dn'])) {
786       /* Creating Entry */
787       $this->cd($data['dn']);
789       /* Delete existing entry */
790       if($delete){
791         $this->rmdir($data['dn']);
792       }
793       
794       /* Create missing trees */
795       $this->create_missing_trees($data['dn']);
796       unset($data['dn']);
797       
798       /* If entry exists use modify */
799       if(!$modify){
800         $ret = $this->add($data);
801       } else {
802         $ret = $this->modify($data);
803       }
804     }
806     return($ret);
807   }
809   
810   function importcsv($str)
811   {
812     $lines = split("\n",$str);
813     foreach($lines as $line)
814     {
815       /* continue if theres a comment */
816       if(substr(trim($line),0,1)=="#"){
817         continue;
818       }
820       $line= str_replace ("\t\t","\t",$line);
821       $line= str_replace ("\t"  ,"," ,$line);
822       echo $line;
824       $cells = split(",",$line )  ;
825       $linet= str_replace ("\t\t",",",$line);
826       $cells = split("\t",$line);
827       $count = count($cells);  
828     }
830   }
834 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
835 ?>