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(is_object($config) && $config->get_cfg_value("ldapMaxQueryTime") != ""){
64 $str = $config->get_cfg_value("ldapMaxQueryTime");
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.
85 Currently used codes:
86 , => CO
87 \2C => CO
88 ( => OB
89 ) => CB
90 / => SL
91 \22 => DQ */
92 static function convert($dn)
93 {
94 if (SPECIALS_OVERRIDE == TRUE){
95 $tmp= preg_replace(array("/\\\\,/", "/\\\\2C/", "/\(/", "/\)/", "/\//", "/\\\\22/", '/\\\\"/'),
96 array("\001CO", "\001CO", "\001OB", "\001CB", "\001SL", "\001DQ", "\001DQ"),
97 $dn);
98 return (preg_replace('/,\s+/', ',', $tmp));
99 } else {
100 return ($dn);
101 }
102 }
105 /* Function to fix all problematic characters inside a DN by replacing \001XX
106 codes to their original values. See "convert" for mor information.
107 ',' characters are always expanded to \, (not \2C), since all tested LDAP
108 servers seem to take it the correct way. */
109 static function fix($dn)
110 {
111 if (SPECIALS_OVERRIDE == TRUE){
112 return (preg_replace(array("/\001CO/", "/\001OB/", "/\001CB/", "/\001SL/", "/\001DQ/"),
113 array("\,", "(", ")", "/", '\"'),
114 $dn));
115 } else {
116 return ($dn);
117 }
118 }
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 $fixed= normalizeLdap(str_replace('\\\\', '\\\\\\', LDAP::fix($dn)));
125 return str_replace('\\,', '\\\\,', $fixed);
126 }
129 function connect()
130 {
131 $this->hascon=false;
132 $this->reconnect=false;
133 if ($this->cid= @ldap_connect($this->hostname)) {
134 @ldap_set_option($this->cid, LDAP_OPT_PROTOCOL_VERSION, 3);
135 if (function_exists("ldap_set_rebind_proc") && $this->follow_referral) {
136 @ldap_set_option($this->cid, LDAP_OPT_REFERRALS, 1);
137 @ldap_set_rebind_proc($this->cid, array(&$this, "rebind"));
138 }
139 if (function_exists("ldap_start_tls") && $this->tls){
140 @ldap_start_tls($this->cid);
141 }
143 $this->error = "No Error";
144 if ($bid = @ldap_bind($this->cid, LDAP::fix($this->binddn), $this->bindpw)) {
145 $this->error = "Success";
146 $this->hascon=true;
147 } else {
148 if ($this->reconnect){
149 if ($this->error != "Success"){
150 $this->error = "Could not rebind to " . $this->binddn;
151 }
152 } else {
153 $this->error = "Could not bind to " . $this->binddn;
154 }
155 }
156 } else {
157 $this->error = "Could not connect to LDAP server";
158 }
159 }
161 function rebind($ldap, $referral)
162 {
163 $credentials= $this->get_credentials($referral);
164 if (@ldap_bind($ldap, LDAP::fix($credentials['ADMINDN']), $credentials['ADMINPASSWORD'])) {
165 $this->error = "Success";
166 $this->hascon=true;
167 $this->reconnect= true;
168 return (0);
169 } else {
170 $this->error = "Could not bind to " . $credentials['ADMINDN'];
171 return NULL;
172 }
173 }
175 function reconnect()
176 {
177 if ($this->reconnect){
178 @ldap_unbind($this->cid);
179 $this->cid = NULL;
180 }
181 }
183 function unbind()
184 {
185 @ldap_unbind($this->cid);
186 $this->cid = NULL;
187 }
189 function disconnect()
190 {
191 if($this->hascon){
192 @ldap_close($this->cid);
193 $this->hascon=false;
194 }
195 }
197 function cd($dir)
198 {
199 if ($dir == ".."){
200 $this->basedn = $this->getParentDir();
201 } else {
202 $this->basedn = LDAP::convert($dir);
203 }
204 }
206 function getParentDir($basedn = "")
207 {
208 if ($basedn==""){
209 $basedn = $this->basedn;
210 } else {
211 $basedn = LDAP::convert($basedn);
212 }
213 return(preg_replace("/[^,]*[,]*[ ]*(.*)/", "$1", $basedn));
214 }
217 function search($srp, $filter, $attrs= array())
218 {
219 if($this->hascon){
220 if ($this->reconnect) $this->connect();
222 $start = microtime(true);
223 $this->clearResult($srp);
224 $this->sr[$srp] = @ldap_search($this->cid, LDAP::fix($this->basedn), $filter, $attrs);
225 $this->error = @ldap_error($this->cid);
226 $this->resetResult($srp);
227 $this->hasres[$srp]=true;
229 /* Check if query took longer as specified in max_ldap_query_time */
230 if($this->max_ldap_query_time){
231 $diff = microtime(true) - $start;
232 if($diff > $this->max_ldap_query_time){
233 msg_dialog::display(_("Performance warning"), sprintf(_("LDAP performance is poor: last query took %.2fs!"), $diff), WARNING_DIALOG);
234 }
235 }
237 $this->log("LDAP operation: time=".(microtime(true)-$start)." operation=search('".LDAP::fix($this->basedn)."', '$filter')");
238 return($this->sr[$srp]);
239 }else{
240 $this->error = "Could not connect to LDAP server";
241 return("");
242 }
243 }
245 function ls($srp, $filter = "(objectclass=*)", $basedn = "",$attrs = array("*"))
246 {
247 if($this->hascon){
248 if ($this->reconnect) $this->connect();
250 $this->clearResult($srp);
251 if ($basedn == "")
252 $basedn = $this->basedn;
253 else
254 $basedn= LDAP::convert($basedn);
256 $start = microtime(true);
257 $this->sr[$srp] = @ldap_list($this->cid, LDAP::fix($basedn), $filter,$attrs);
258 $this->error = @ldap_error($this->cid);
259 $this->resetResult($srp);
260 $this->hasres[$srp]=true;
262 /* Check if query took longer as specified in max_ldap_query_time */
263 if($this->max_ldap_query_time){
264 $diff = microtime(true) - $start;
265 if($diff > $this->max_ldap_query_time){
266 msg_dialog::display(_("Performance warning"), sprintf(_("LDAP performance is poor: last query took %.2fs!"), $diff), WARNING_DIALOG);
267 }
268 }
270 $this->log("LDAP operation: time=".(microtime(true) - $start)." operation=ls('".LDAP::fix($basedn)."', '$filter')");
272 return($this->sr[$srp]);
273 }else{
274 $this->error = "Could not connect to LDAP server";
275 return("");
276 }
277 }
279 function cat($srp, $dn,$attrs= array("*"), $filter = "(objectclass=*)")
280 {
281 if($this->hascon){
282 if ($this->reconnect) $this->connect();
284 $this->clearResult($srp);
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 object_match_filter($dn,$filter)
297 {
298 if($this->hascon){
299 if ($this->reconnect) $this->connect();
300 $res = @ldap_read($this->cid, LDAP::fix($dn), $filter, array("objectClass"));
301 $rv = @ldap_count_entries($this->cid, $res);
302 return($rv);
303 }else{
304 $this->error = "Could not connect to LDAP server";
305 return(FALSE);
306 }
307 }
309 function set_size_limit($size)
310 {
311 /* Ignore zero settings */
312 if ($size == 0){
313 @ldap_set_option($this->cid, LDAP_OPT_SIZELIMIT, 10000000);
314 }
315 if($this->hascon){
316 @ldap_set_option($this->cid, LDAP_OPT_SIZELIMIT, $size);
317 } else {
318 $this->error = "Could not connect to LDAP server";
319 }
320 }
322 function fetch($srp)
323 {
324 $att= array();
325 if($this->hascon){
326 if($this->hasres[$srp]){
327 if ($this->start[$srp] == 0)
328 {
329 if ($this->sr[$srp]){
330 $this->start[$srp] = 1;
331 $this->re[$srp]= @ldap_first_entry($this->cid, $this->sr[$srp]);
332 } else {
333 return array();
334 }
335 } else {
336 $this->re[$srp]= @ldap_next_entry($this->cid, $this->re[$srp]);
337 }
338 if ($this->re[$srp])
339 {
340 $att= @ldap_get_attributes($this->cid, $this->re[$srp]);
341 $att['dn']= trim(LDAP::convert(@ldap_get_dn($this->cid, $this->re[$srp])));
342 }
343 $this->error = @ldap_error($this->cid);
344 if (!isset($att)){
345 $att= array();
346 }
347 return($att);
348 }else{
349 $this->error = "Perform a fetch with no search";
350 return("");
351 }
352 }else{
353 $this->error = "Could not connect to LDAP server";
354 return("");
355 }
356 }
358 function resetResult($srp)
359 {
360 $this->start[$srp] = 0;
361 }
363 function clearResult($srp)
364 {
365 if($this->hasres[$srp]){
366 $this->hasres[$srp] = false;
367 @ldap_free_result($this->sr[$srp]);
368 }
369 }
371 function getDN($srp)
372 {
373 if($this->hascon){
374 if($this->hasres[$srp]){
376 if(!$this->re[$srp])
377 {
378 $this->error = "Perform a Fetch with no valid Result";
379 }
380 else
381 {
382 $rv = @ldap_get_dn($this->cid, $this->re[$srp]);
384 $this->error = @ldap_error($this->cid);
385 return(trim(LDAP::convert($rv)));
386 }
387 }else{
388 $this->error = "Perform a Fetch with no Search";
389 return("");
390 }
391 }else{
392 $this->error = "Could not connect to LDAP server";
393 return("");
394 }
395 }
397 function count($srp)
398 {
399 if($this->hascon){
400 if($this->hasres[$srp]){
401 $rv = @ldap_count_entries($this->cid, $this->sr[$srp]);
402 $this->error = @ldap_error($this->cid);
403 return($rv);
404 }else{
405 $this->error = "Perform a Fetch with no Search";
406 return("");
407 }
408 }else{
409 $this->error = "Could not connect to LDAP server";
410 return("");
411 }
412 }
414 function rm($attrs = "", $dn = "")
415 {
416 if($this->hascon){
417 if ($this->reconnect) $this->connect();
418 if ($dn == "")
419 $dn = $this->basedn;
421 $r = ldap_mod_del($this->cid, LDAP::fix($dn), $attrs);
422 $this->error = @ldap_error($this->cid);
423 return($r);
424 }else{
425 $this->error = "Could not connect to LDAP server";
426 return("");
427 }
428 }
430 function mod_add($attrs = "", $dn = "")
431 {
432 if($this->hascon){
433 if ($this->reconnect) $this->connect();
434 if ($dn == "")
435 $dn = $this->basedn;
437 $r = @ldap_mod_add($this->cid, LDAP::fix($dn), $attrs);
438 $this->error = @ldap_error($this->cid);
439 return($r);
440 }else{
441 $this->error = "Could not connect to LDAP server";
442 return("");
443 }
444 }
446 function rename($attrs, $dn = "")
447 {
448 if($this->hascon){
449 if ($this->reconnect) $this->connect();
450 if ($dn == "")
451 $dn = $this->basedn;
453 $r = @ldap_mod_replace($this->cid, LDAP::fix($dn), $attrs);
454 $this->error = @ldap_error($this->cid);
455 return($r);
456 }else{
457 $this->error = "Could not connect to LDAP server";
458 return("");
459 }
460 }
462 function rmdir($deletedn)
463 {
464 if($this->hascon){
465 if ($this->reconnect) $this->connect();
466 $r = @ldap_delete($this->cid, LDAP::fix($deletedn));
467 $this->error = @ldap_error($this->cid);
468 return($r ? $r : 0);
469 }else{
470 $this->error = "Could not connect to LDAP server";
471 return("");
472 }
473 }
476 /*! \brief Move the given Ldap entry from $source to $dest
477 @param String $source The source dn.
478 @param String $dest The destination dn.
479 @return Boolean TRUE on success else FALSE.
480 */
481 function rename_dn($source,$dest)
482 {
483 /* Check if source and destination are the same entry */
484 if(strtolower($source) == strtolower($dest)){
485 trigger_error("Source and destination can't be the same entry.");
486 $this->error = "Source and destination can't be the same entry.";
487 return(FALSE);
488 }
490 /* Check if destination entry exists */
491 if($this->dn_exists($dest)){
492 trigger_error("Destination '$dest' already exists.");
493 $this->error = "Destination '$dest' already exists.";
494 return(FALSE);
495 }
497 /* Extract the name and the parent part out ouf source dn.
498 e.g. cn=herbert,ou=department,dc=...
499 parent => ou=department,dc=...
500 dest_rdn => cn=herbert
501 */
502 $parent = preg_replace("/^[^,]+,/","", $dest);
503 $dest_rdn = preg_replace("/,.*$/","",$dest);
505 if($this->hascon){
506 if ($this->reconnect) $this->connect();
507 $r= ldap_rename($this->cid,@LDAP::fix($source), @LDAP::fix($dest_rdn),@LDAP::fix($parent),TRUE);
508 $this->error = ldap_error($this->cid);
510 /* Check if destination dn exists, if not the
511 server may not support this operation */
512 $r &= is_resource($this->dn_exists($dest));
513 return($r);
514 }else{
515 $this->error = "Could not connect to LDAP server";
516 return(FALSE);
517 }
518 }
521 /**
522 * Function rmdir_recursive
523 *
524 * Description: Based in recursive_remove, adding two thing: full subtree remove, and delete own node.
525 * Parameters: The dn to delete
526 * GiveBack: True on sucessfull , 0 in error, and "" when we don't get a ldap conection
527 *
528 */
529 function rmdir_recursive($srp, $deletedn)
530 {
531 if($this->hascon){
532 if ($this->reconnect) $this->connect();
533 $delarray= array();
535 /* Get sorted list of dn's to delete */
536 $this->ls ($srp, "(objectClass=*)",$deletedn);
537 while ($this->fetch($srp)){
538 $deldn= $this->getDN($srp);
539 $delarray[$deldn]= strlen($deldn);
540 }
541 arsort ($delarray);
542 reset ($delarray);
544 /* Really Delete ALL dn's in subtree */
545 foreach ($delarray as $key => $value){
546 $this->rmdir_recursive($srp, $key);
547 }
549 /* Finally Delete own Node */
550 $r = @ldap_delete($this->cid, LDAP::fix($deletedn));
551 $this->error = @ldap_error($this->cid);
552 return($r ? $r : 0);
553 }else{
554 $this->error = "Could not connect to LDAP server";
555 return("");
556 }
557 }
559 function makeReadableErrors($error,$attrs)
560 {
561 global $config;
563 if($this->success()) return("");
565 $str = "";
566 if(preg_match("/^objectClass: value #([0-9]*) invalid per syntax$/", $this->get_additional_error())){
567 $oc = preg_replace("/^objectClass: value #([0-9]*) invalid per syntax$/","\\1", $this->get_additional_error());
568 if(isset($attrs['objectClass'][$oc])){
569 $str.= " - <b>objectClass: ".$attrs['objectClass'][$oc]."</b>";
570 }
571 }
572 if($error == "Undefined attribute type"){
573 $str = " - <b>attribute: ".preg_replace("/:.*$/","",$this->get_additional_error())."</b>";
574 }
576 @DEBUG(DEBUG_LDAP,__LINE__,__FUNCTION__,__FILE__,$attrs,"Erroneous data");
578 return($str);
579 }
581 function modify($attrs)
582 {
583 if(count($attrs) == 0){
584 return (0);
585 }
586 if($this->hascon){
587 if ($this->reconnect) $this->connect();
588 $r = @ldap_modify($this->cid, LDAP::fix($this->basedn), $attrs);
589 $this->error = @ldap_error($this->cid);
590 if(!$this->success()){
591 $this->error.= $this->makeReadableErrors($this->error,$attrs);
592 }
593 return($r ? $r : 0);
594 }else{
595 $this->error = "Could not connect to LDAP server";
596 return("");
597 }
598 }
600 function add($attrs)
601 {
602 if($this->hascon){
603 if ($this->reconnect) $this->connect();
604 $r = @ldap_add($this->cid, LDAP::fix($this->basedn), $attrs);
605 $this->error = @ldap_error($this->cid);
606 if(!$this->success()){
607 $this->error.= $this->makeReadableErrors($this->error,$attrs);
608 }
609 return($r ? $r : 0);
610 }else{
611 $this->error = "Could not connect to LDAP server";
612 return("");
613 }
614 }
616 function create_missing_trees($srp, $target)
617 {
618 global $config;
620 $real_path= substr($target, 0, strlen($target) - strlen($this->basedn) -1 );
622 if ($target == $this->basedn){
623 $l= array("dummy");
624 } else {
625 $l= array_reverse(gosa_ldap_explode_dn($real_path));
626 }
627 unset($l['count']);
628 $cdn= $this->basedn;
629 $tag= "";
631 /* Load schema if available... */
632 $classes= $this->get_objectclasses();
634 foreach ($l as $part){
635 if ($part != "dummy"){
636 $cdn= "$part,$cdn";
637 }
639 /* Ignore referrals */
640 $found= false;
641 foreach($this->referrals as $ref){
642 $base= preg_replace('!^[^:]+://[^/]+/([^?]+).*$!', '\\1', $ref['URI']);
643 if ($base == $cdn){
644 $found= true;
645 break;
646 }
647 }
648 if ($found){
649 continue;
650 }
652 $this->cat ($srp, $cdn);
653 $attrs= $this->fetch($srp);
655 /* Create missing entry? */
656 if (count ($attrs)){
658 /* Catch the tag - if present */
659 if (isset($attrs['gosaUnitTag'][0])){
660 $tag= $attrs['gosaUnitTag'][0];
661 }
663 } else {
664 $type= preg_replace('/^([^=]+)=.*$/', '\\1', $cdn);
665 $param= LDAP::fix(preg_replace('/^[^=]+=([^,]+).*$/', '\\1', $cdn));
666 $param=preg_replace(array('/\\\\,/','/\\\\"/'),array(',','"'),$param);
668 $na= array();
670 /* Automatic or traditional? */
671 if(count($classes)){
673 /* Get name of first matching objectClass */
674 $ocname= "";
675 foreach($classes as $class){
676 if (isset($class['MUST']) && in_array($type, $class['MUST'])){
678 /* Look for first classes that is structural... */
679 if (isset($class['STRUCTURAL'])){
680 $ocname= $class['NAME'];
681 break;
682 }
684 /* Look for classes that are auxiliary... */
685 if (isset($class['AUXILIARY'])){
686 $ocname= $class['NAME'];
687 }
688 }
689 }
691 /* Bail out, if we've nothing to do... */
692 if ($ocname == ""){
693 msg_dialog::display(_("Internal error"), sprintf(_("Cannot automatically create subtrees with RDN %s: no object class found"), bold($type)), FATAL_ERROR_DIALOG);
694 exit();
695 }
697 /* Assemble_entry */
698 if ($tag != ""){
699 $na['objectClass']= array($ocname, "gosaAdministrativeUnitTag");
700 $na["gosaUnitTag"]= $tag;
701 } else {
702 $na['objectClass']= array($ocname);
703 }
704 if (isset($classes[$ocname]['AUXILIARY'])){
705 $na['objectClass'][]= $classes[$ocname]['SUP'];
706 }
707 if ($type == "dc"){
708 /* This is bad actually, but - tell me a better way? */
709 $na['objectClass'][]= 'locality';
710 }
711 $na[$type]= $param;
713 // Fill in MUST values - but do not overwrite existing ones.
714 if (is_array($classes[$ocname]['MUST'])){
715 foreach($classes[$ocname]['MUST'] as $attr){
716 if(isset($na[$attr]) && !empty($na[$attr])) continue;
717 $na[$attr]= "filled";
718 }
719 }
721 } else {
723 /* Use alternative add... */
724 switch ($type){
725 case 'ou':
726 if ($tag != ""){
727 $na["objectClass"]= array("organizationalUnit", "gosaAdministrativeUnitTag");
728 $na["gosaUnitTag"]= $tag;
729 } else {
730 $na["objectClass"]= "organizationalUnit";
731 }
732 $na["ou"]= $param;
733 break;
734 case 'dc':
735 if ($tag != ""){
736 $na["objectClass"]= array("dcObject", "top", "locality", "gosaAdministrativeUnitTag");
737 $na["gosaUnitTag"]= $tag;
738 } else {
739 $na["objectClass"]= array("dcObject", "top", "locality");
740 }
741 $na["dc"]= $param;
742 break;
743 default:
744 msg_dialog::display(_("Internal error"), sprintf(_("Cannot automatically create subtrees with RDN %s: not supported"), bold($type)), FATAL_ERROR_DIALOG);
745 exit();
746 }
748 }
749 $this->cd($cdn);
750 $this->add($na);
752 if (!$this->success()){
754 print_a(array($cdn,$na));
756 msg_dialog::display(_("LDAP error"), msgPool::ldaperror($this->get_error(), $cdn, LDAP_ADD, get_class()));
757 return FALSE;
758 }
759 }
760 }
762 return TRUE;
763 }
766 function recursive_remove($srp)
767 {
768 $delarray= array();
770 /* Get sorted list of dn's to delete */
771 $this->search ($srp, "(objectClass=*)");
772 while ($this->fetch($srp)){
773 $deldn= $this->getDN($srp);
774 $delarray[$deldn]= strlen($deldn);
775 }
776 arsort ($delarray);
777 reset ($delarray);
779 /* Delete all dn's in subtree */
780 foreach ($delarray as $key => $value){
781 $this->rmdir($key);
782 }
783 }
786 function get_attribute($dn, $name,$r_array=0)
787 {
788 $data= "";
789 if ($this->reconnect) $this->connect();
790 $sr= @ldap_read($this->cid, LDAP::fix($dn), "objectClass=*", array("$name"));
792 /* fill data from LDAP */
793 if ($sr) {
794 $ei= @ldap_first_entry($this->cid, $sr);
795 if ($ei) {
796 if ($info= @ldap_get_values_len($this->cid, $ei, "$name")){
797 $data= $info[0];
798 }
799 }
800 }
801 if($r_array==0) {
802 return ($data);
803 } else {
804 return ($info);
805 }
806 }
810 function get_additional_error()
811 {
812 $error= "";
813 @ldap_get_option ($this->cid, LDAP_OPT_ERROR_STRING, $error);
814 return ($error);
815 }
818 function success()
819 {
820 return (preg_match('/Success/i', $this->error));
821 }
824 function get_error()
825 {
826 if ($this->error == 'Success'){
827 return $this->error;
828 } else {
829 $adderror= $this->get_additional_error();
830 if ($adderror != ""){
831 $error= $this->error." (".$this->get_additional_error().", ".sprintf(_("while operating on %s using LDAP server %s"), bold($this->basedn), bold($this->hostname)).")";
832 } else {
833 $error= $this->error." (".sprintf(_("while operating on LDAP server %s"), bold($this->hostname)).")";
834 }
835 return $error;
836 }
837 }
839 function get_credentials($url, $referrals= NULL)
840 {
841 $ret= array();
842 $url= preg_replace('!\?\?.*$!', '', $url);
843 $server= preg_replace('!^([^:]+://[^/]+)/.*$!', '\\1', $url);
845 if ($referrals === NULL){
846 $referrals= $this->referrals;
847 }
849 if (isset($referrals[$server])){
850 return ($referrals[$server]);
851 } else {
852 $ret['ADMINDN']= LDAP::fix($this->binddn);
853 $ret['ADMINPASSWORD']= $this->bindpw;
854 }
856 return ($ret);
857 }
860 function generateLdif ($dn, $filter= "(objectClass=*)", $attributes= array(), $scope = 'sub', $limit=0)
861 {
862 $host = $this->hostname;
863 $attrs = (count($attributes))?implode($attributes,' '):'';
864 $scope = (!empty($scope))?' -s '.$scope: '';
865 $limit = (!$limit)?'':' -z '.$limit;
866 $dn = escapeshellarg($dn);
867 $cmd = "ldapsearch -x -LLLL '{$filter}' {$limit} {$scope} -H '{$host}' -b {$dn} $attrs";
868 exec($cmd, $ret,$code);
869 $res = implode($ret,"\n");
870 return($res);
871 }
874 function importLdif($str)
875 {
876 }
879 function gen_xls ($srp, $dn, $filter= "(objectClass=*)", $attributes= array('*'), $recursive= TRUE,$r_array=0)
880 {
881 $display= array();
883 $this->cd($dn);
884 $this->search($srp, "$filter");
886 $i=0;
887 while ($attrs= $this->fetch($srp)){
888 $j=0;
890 foreach ($attributes as $at){
891 $display[$i][$j]= $this->get_attribute($attrs['dn'], $at,$r_array);
892 $j++;
893 }
895 $i++;
896 }
898 return ($display);
899 }
902 function dn_exists($dn)
903 {
904 return @ldap_list($this->cid, LDAP::fix($dn), "(objectClass=*)", array("objectClass"));
905 }
908 function get_objectclasses( $force_reload = FALSE)
909 {
910 $objectclasses = array();
911 global $config;
913 /* Only read schema if it is allowed */
914 if(isset($config) && preg_match("/config/i",get_class($config))){
915 if ($config->get_cfg_value("schemaCheck") != "true"){
916 return($objectclasses);
917 }
918 }
920 /* Return the cached results. */
921 if(class_available('session') && session::global_is_set("LDAP_CACHE::get_objectclasses") && !$force_reload){
922 $objectclasses = session::global_get("LDAP_CACHE::get_objectclasses");
923 return($objectclasses);
924 }
926 # Get base to look for schema
927 $sr = @ldap_read ($this->cid, "", "objectClass=*", array("subschemaSubentry"));
928 $attr = @ldap_get_entries($this->cid,$sr);
929 if (!isset($attr[0]['subschemasubentry'][0])){
930 return array();
931 }
933 /* Get list of objectclasses and fill array */
934 $nb= $attr[0]['subschemasubentry'][0];
935 $objectclasses= array();
936 $sr= ldap_read ($this->cid, $nb, "objectClass=*", array("objectclasses"));
937 $attrs= ldap_get_entries($this->cid,$sr);
938 if (!isset($attrs[0])){
939 return array();
940 }
941 foreach ($attrs[0]['objectclasses'] as $val){
942 if (preg_match('/^[0-9]+$/', $val)){
943 continue;
944 }
945 $name= "OID";
946 $pattern= explode(' ', $val);
947 $ocname= preg_replace("/^.* NAME\s+\(*\s*'([^']+)'\s*\)*.*$/", '\\1', $val);
948 $objectclasses[$ocname]= array();
950 foreach($pattern as $chunk){
951 switch($chunk){
953 case '(':
954 $value= "";
955 break;
957 case ')': if ($name != ""){
958 $v = $this->value2container($value);
959 if(in_array($name, array('MUST', 'MAY')) && !is_array($v)){
960 $v = array($v);
961 }
962 $objectclasses[$ocname][$name]= $v;
963 }
964 $name= "";
965 $value= "";
966 break;
968 case 'NAME':
969 case 'DESC':
970 case 'SUP':
971 case 'STRUCTURAL':
972 case 'ABSTRACT':
973 case 'AUXILIARY':
974 case 'MUST':
975 case 'MAY':
976 if ($name != ""){
977 $v = $this->value2container($value);
978 if(in_array($name, array('MUST', 'MAY')) && !is_array($v)){
979 $v = array($v);
980 }
981 $objectclasses[$ocname][$name]= $v;
982 }
983 $name= $chunk;
984 $value= "";
985 break;
987 default: $value.= $chunk." ";
988 }
989 }
991 }
992 if(class_available("session")){
993 session::global_set("LDAP_CACHE::get_objectclasses",$objectclasses);
994 }
996 return $objectclasses;
997 }
1000 function value2container($value)
1001 {
1002 /* Set emtpy values to "true" only */
1003 if (preg_match('/^\s*$/', $value)){
1004 return true;
1005 }
1007 /* Remove ' and " if needed */
1008 $value= preg_replace('/^[\'"]/', '', $value);
1009 $value= preg_replace('/[\'"] *$/', '', $value);
1011 /* Convert to array if $ is inside... */
1012 if (preg_match('/\$/', $value)){
1013 $container= preg_split('/\s*\$\s*/', $value);
1014 } else {
1015 $container= chop($value);
1016 }
1018 return ($container);
1019 }
1022 function log($string)
1023 {
1024 if (session::global_is_set('config')){
1025 $cfg = session::global_get('config');
1026 if (isset($cfg->current['LDAPSTATS']) && preg_match('/true/i', $cfg->current['LDAPSTATS'])){
1027 syslog (LOG_INFO, $string);
1028 }
1029 }
1030 }
1032 /* added by Guido Serra aka Zeph <zeph@purotesto.it> */
1033 function getCn($dn){
1034 $simple= explode(",", $dn);
1036 foreach($simple as $piece) {
1037 $partial= explode("=", $piece);
1039 if($partial[0] == "cn"){
1040 return $partial[1];
1041 }
1042 }
1043 }
1046 function get_naming_contexts($server, $admin= "", $password= "")
1047 {
1048 /* Build LDAP connection */
1049 $ds= ldap_connect ($server);
1050 if (!$ds) {
1051 die ("Can't bind to LDAP. No check possible!");
1052 }
1053 ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
1054 $r= ldap_bind ($ds, $admin, $password);
1056 /* Get base to look for naming contexts */
1057 $sr = @ldap_read ($ds, "", "objectClass=*", array("+"));
1058 $attr= @ldap_get_entries($ds,$sr);
1060 return ($attr[0]['namingcontexts']);
1061 }
1064 function get_root_dse($server, $admin= "", $password= "")
1065 {
1066 /* Build LDAP connection */
1067 $ds= ldap_connect ($server);
1068 if (!$ds) {
1069 die ("Can't bind to LDAP. No check possible!");
1070 }
1071 ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
1072 $r= ldap_bind ($ds, $admin, $password);
1074 /* Get base to look for naming contexts */
1075 $sr = @ldap_read ($ds, "", "objectClass=*", array("+"));
1076 $attr= @ldap_get_entries($ds,$sr);
1078 /* Return empty array, if nothing was set */
1079 if (!isset($attr[0])){
1080 return array();
1081 }
1083 /* Rework array... */
1084 $result= array();
1085 for ($i= 0; $i<$attr[0]['count']; $i++){
1086 $result[$attr[0][$i]]= $attr[0][$attr[0][$i]];
1087 unset($result[$attr[0][$i]]['count']);
1088 }
1090 return ($result);
1091 }
1093 }
1094 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
1095 ?>