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 " . $binddn;
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 {
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);
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 function modify($attrs)
329 {
330 if($this->hascon){
331 if ($this->reconnect) $this->connect();
332 $r = @ldap_modify($this->cid, $this->basedn, $attrs);
333 $this->error = @ldap_error($this->cid);
334 return($r ? $r : 0);
335 }else{
336 $this->error = "Could not connect to LDAP server";
337 return("");
338 }
339 }
341 function add($attrs)
342 {
343 if($this->hascon){
344 if ($this->reconnect) $this->connect();
345 $r = @ldap_add($this->cid, $this->basedn, $attrs);
346 $this->error = @ldap_error($this->cid);
347 return($r ? $r : 0);
348 }else{
349 $this->error = "Could not connect to LDAP server";
350 return("");
351 }
352 }
354 function create_missing_trees($target)
355 {
357 /* Ignore create_missing trees if the base equals target */
358 if ($target == $this->basedn){
359 return;
360 }
361 $l= array_reverse(explode(",", preg_replace("/,".$this->basedn."/", "", $target)));
362 $cdn= $this->basedn;
363 foreach ($l as $part){
364 $cdn= "$part,$cdn";
366 /* Ignore referrals */
367 $found= false;
368 foreach($this->referrals as $ref){
369 $base= preg_replace('!^[^:]+://[^/]+/([^?]+).*$!', '\\1', $ref['URL']);
370 if ($base == $cdn){
371 $found= true;
372 break;
373 }
374 }
375 if ($found){
376 continue;
377 }
379 $this->cat ($cdn);
380 $attrs= $this->fetch();
382 /* Create missing entry? */
383 if (!count ($attrs)){
384 $type= preg_replace('/^([^=]+)=.*$/', '\\1', $cdn);
385 $param= preg_replace('/^[^=]+=([^,]+),.*$/', '\\1', $cdn);
387 $na= array();
388 switch ($type){
389 case 'ou':
390 $na["objectClass"]= "organizationalUnit";
391 $na["ou"]= $param;
392 break;
393 case 'dc':
394 $na["objectClass"]= array("dcObject", "top", "locality");
395 $na["dc"]= $param;
396 break;
397 default:
398 print_red(sprintf(_("Autocreation of type '%s' is currently not supported. Please report to the GOsa team."), $type));
399 exit;
400 }
401 $this->cd($cdn);
402 $this->add($na);
403 }
404 }
405 }
407 function recursive_remove()
408 {
409 $delarray= array();
411 /* Get sorted list of dn's to delete */
412 $this->search ("(objectClass=*)");
413 while ($this->fetch()){
414 $deldn= $this->getDN();
415 $delarray[$deldn]= strlen($deldn);
416 }
417 arsort ($delarray);
418 reset ($delarray);
420 /* Delete all dn's in subtree */
421 foreach ($delarray as $key => $value){
422 $this->rmdir($key);
423 }
424 }
426 function get_attribute($dn, $name)
427 {
428 $data= "";
429 if ($this->reconnect) $this->connect();
430 $sr= @ldap_read($this->cid, $dn, "objectClass=*", array("$name"));
432 /* fill data from LDAP */
433 if ($sr) {
434 $ei= @ldap_first_entry($this->cid, $sr);
435 if ($ei) {
436 if ($info= @ldap_get_values_len($this->cid, $ei, "$name")){
437 $data= $info[0];
438 }
439 }
440 }
442 return ($data);
443 }
445 function get_additional_error()
446 {
447 $error= "";
448 @ldap_get_option ($this->cid, LDAP_OPT_ERROR_STRING, $error);
449 return ($error);
450 }
452 function get_error()
453 {
454 if ($this->error == 'Success'){
455 return $this->error;
456 } else {
457 $error= $this->error." (".$this->get_additional_error().")";
458 return $error;
459 }
460 }
462 function get_credentials($url, $referrals= NULL)
463 {
464 $ret= array();
465 $url= preg_replace('!\?\?.*$!', '', $url);
466 $server= preg_replace('!^([^:]+://[^/]+)/.*$!', '\\1', $url);
468 if ($referrals == NULL){
469 $referrals= $this->referrals;
470 }
472 if (isset($referrals[$server])){
473 return ($referrals[$server]);
474 } else {
475 $ret['ADMIN']= $this->binddn;
476 $ret['PASSWORD']= $this->bindpw;
477 }
479 return ($ret);
480 }
483 function gen_ldif ($dn, $filter= "(objectClass=*)", $attributes= array('*'), $recursive= TRUE)
484 {
485 $display= "";
487 if ($recursive){
488 $this->cd($dn);
489 $this->search("$filter", array('dn'));
490 while ($attrs= $this->fetch()){
491 $display.= $this->gen_one_entry($attrs['dn'], $filter, $attributes);
492 $display.= "\n";
493 }
494 } else {
495 $display.= $this->gen_one_entry($dn);
496 }
498 return ($display);
499 }
502 function gen_one_entry($dn, $filter= "(objectClass=*)" , $name= array("*"))
503 {
504 $ret = "";
505 $data = "";
506 if($this->reconnect){
507 $this->connect();
508 }
510 /* Searching Ldap Tree */
511 $sr= @ldap_read($this->cid, $dn, $filter, $name);
513 /* Get the first entry */
514 $entry= @ldap_first_entry($this->cid, $sr);
516 /* Get all attributes related to that Objekt */
517 $atts = array();
519 /* Assemble dn */
520 $atts[0]['name'] = "dn";
521 $atts[0]['value'] = array('count' => 1, 0 => $dn);
523 /* Reset index */
524 $i = 1 ;
526 $attribute= @ldap_first_attribute($this->cid,$entry,$identifier);
527 while ($attribute) {
528 $i++;
529 $atts[$i]['name'] = $attribute;
530 $atts[$i]['value'] = @ldap_get_values_len($this->cid, $entry, "$attribute");
532 /* Next one */
533 $attribute= @ldap_next_attribute($this->cid,$entry,$identifier);
534 }
536 foreach($atts as $at)
537 {
538 for ($i= 0; $i<$at['value']['count']; $i++){
540 /* Check if we must encode the data */
541 if(!preg_match('/^[a-z0-9+@#.=, \/ -]+$/i', $at['value'][$i])) {
542 $ret .= $at['name'].":: ".base64_encode($at['value'][$i])."\n";
543 } else {
544 $ret .= $at['name'].": ".$at['value'][$i]."\n";
545 }
546 }
547 }
549 return($ret);
550 }
553 function dn_exists($dn)
554 {
555 return @ldap_list($this->cid, $dn, "(objectClass=*)", array("objectClass"));
556 }
560 function import_complete_ldif($str_attr,&$error,$overwrite,$cleanup)
561 {
562 if($this->reconnect) $this->connect();
564 /* First we have to splitt the string ito detect empty lines
565 An empty line indicates an new Entry */
566 $entries = split("\n",$str_attr);
568 $data = "";
569 $cnt = 0;
570 $current_line = 0;
572 /* Every single line ... */
573 foreach($entries as $entry) {
574 $current_line ++;
576 /* Removing Spaces to ..
577 .. test if a new entry begins */
578 $tmp = str_replace(" ","",$data );
580 /* .. prevent empty lines in an entry */
581 $tmp2 = str_replace(" ","",$entry);
583 /* If the Block ends (Empty Line) */
584 if((empty($entry))&&(!empty($tmp))) {
585 /* Add collected lines as a complete block */
586 $all[$cnt] = $data;
587 $cnt ++;
588 $data ="";
589 } else {
591 /* Append lines ... */
592 if(!empty($tmp2)) {
593 /* check if we need base64_decode for this line */
594 if(ereg("::",$tmp2))
595 {
596 $encoded = split("::",$entry);
597 $attr = $encoded[0];
598 $value = base64_decode($encoded[1]);
599 /* Add linenumber */
600 $data .= $current_line."#".$attr.":".$value."\n";
601 }
602 else
603 {
604 /* Add Linenumber */
605 $data .= $current_line."#".$entry."\n";
606 }
607 }
608 }
609 }
611 /* The Data we collected is not in the array all[];
612 For example the Data is stored like this..
614 all[0] = "1#dn : .... \n
615 2#ObjectType: person \n ...."
617 Now we check every insertblock and try to insert */
618 foreach ( $all as $single) {
619 $lineone = split("\n",$single);
620 $ndn = split("#", $lineone[0]);
621 $line = $ndn[1];
623 $dnn = split (":",$line);
624 $current_line = $ndn[0];
625 $dn = $dnn[0];
626 $value = $dnn[1];
628 /* Every block must begin with a dn */
629 if($dn != "dn") {
630 $error= sprintf(_("This is not a valid DN: '%s'. A block for import should begin with 'dn: ...' in line %s"),
631 $line, $current_line);
632 return -2;
633 }
636 // Should we use Modify instead of Add
637 $usemodify = false;
639 // Delete before insert
640 $usermdir = false;
644 /* The dn address already exists! */
645 if (($this->dn_exists($value))&&((!$overwrite)&&(!$cleanup))) {
646 $error= sprintf(_("The dn: '%s' (from line %s) already exists in the LDAP database."), $line, $current_line);
647 return ALREADY_EXISTING_ENTRY;
648 }
649 elseif(($this->dn_exists($value))&&($cleanup)){
650 ;//Delete first, then add
651 $usermdir = true;
652 }
653 elseif(($this->dn_exists($value))&&($overwrite)) {
654 ;//Modify instead of Add
655 $usemodify = true;
656 }
659 /* If we can't Import, return with a file error */
660 if(!$this->import_single_entry($single,$usemodify,$usermdir) ) {
661 $error= sprintf(_("Error while importing dn: '%s', please check your LDIF from line %s on!"), $line,
662 $current_line);
663 return UNKNOWN_TOKEN_IN_LDIF_FILE; }
665 }
666 return (INSERT_OK);
667 }
669 /* Imports a single entry */
670 function import_single_entry($str_attr,$modify,$delete)
671 {
675 if($this->reconnect) $this->connect();
677 $ret = false;
679 $rows = split("\n",$str_attr);
680 $data = false;
681 foreach($rows as $row) {
683 /* Check if we use Linenumbers (when import_complete_ldif is called we use
684 Linenumbers) Linenumbers are use like this 123#attribute : value */
685 if(!empty($row)) {
686 if((strpos($row,"#")!=FALSE)&&(strpos($row,"#")<strpos($row,":"))) {
687 /* We are using line numbers
688 Because there is a # before a : */
689 $tmp1 = split("#",$row);
690 $current_line = $tmp1[0];
691 $row = $tmp1[1];
692 }
694 /* Split the line into attribute and value */
695 $attr = split(":", $row);
696 $attr[0] = trim($attr[0]); /* attribute */
697 $attr[1] = trim($attr[1]); /* value */
699 /* Check for attributes that are used more than once */
700 if(!isset($data[$attr[0]])) {
701 $data[$attr[0]]=$attr[1];
702 } else {
703 $tmp = $data[$attr[0]];
705 if(!is_array($tmp)) {
706 $new[0]=$tmp;
707 $new[1]=$attr[1];
708 $datas[$attr[0]]['count']=1;
709 $data[$attr[0]]=$new;
710 } else {
711 $cnt = $datas[$attr[0]]['count'];
712 $cnt ++;
713 $data[$attr[0]][$cnt]=$attr[1];
714 $datas[$attr[0]]['count'] = $cnt;
715 }
716 }
717 }
718 }
720 /* If dn is an index of data, we should try to insert the data */
721 if(isset($data['dn'])) {
722 /* Creating Entry */
723 $this->cd($data['dn']);
725 /* Delete existing entry */
726 if($delete)
727 $this->rmdir($data['dn']);
730 /* Create missing trees */
731 $this->create_missing_trees($data['dn']);
732 unset($data['dn']);
734 /* If entry exists use modify */
735 if(!$modify)
736 $ret = $this->add($data);
737 else
738 $ret = $this->modify($data);
742 }
744 return($ret);
745 }
748 function importcsv($str)
749 {
750 $lines = split("\n",$str);
751 foreach($lines as $line)
752 {
753 /* continue if theres a comment */
754 if(substr(trim($line),0,1)=="#")
755 continue;
757 $line= str_replace ("\t\t","\t",$line);
758 $line= str_replace ("\t" ,"," ,$line);
759 print $line;
763 $cells = split(",",$line ) ;
764 #print_a($cells);
765 $linet= str_replace ("\t\t",",",$line);
766 $cells = split("\t",$line);
767 $count = count($cells);
768 }
770 }
772 }
774 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
775 ?>