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($this->basedn);
212 }
213 return(ereg_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();
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 = get_MicroTimeDiff($start,microtime());
232 if($diff > $this->max_ldap_query_time){
233 msg_dialog::display(_("Performance warning"), sprintf(_("LDAP performance is poor: last query took about %.2fs!"), $diff), WARNING_DIALOG);
234 }
235 }
237 $this->log("LDAP operation: time=".get_MicroTimeDiff($start,microtime())." 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();
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 = get_MicroTimeDiff($start,microtime());
265 if($diff > $this->max_ldap_query_time){
266 msg_dialog::display(_("Performance warning"), sprintf(_("LDAP performance is poor: last query took about %.2fs!"), $diff), WARNING_DIALOG);
267 }
268 }
270 $this->log("LDAP operation: time=".get_MicroTimeDiff($start,microtime())." 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("*"))
280 {
281 if($this->hascon){
282 if ($this->reconnect) $this->connect();
284 $this->clearResult($srp);
285 $filter = "(objectclass=*)";
286 $this->sr[$srp] = @ldap_read($this->cid, LDAP::fix($dn), $filter,$attrs);
287 $this->error = @ldap_error($this->cid);
288 $this->resetResult($srp);
289 $this->hasres[$srp]=true;
290 return($this->sr[$srp]);
291 }else{
292 $this->error = "Could not connect to LDAP server";
293 return("");
294 }
295 }
297 function object_match_filter($dn,$filter)
298 {
299 if($this->hascon){
300 if ($this->reconnect) $this->connect();
301 $res = @ldap_read($this->cid, LDAP::fix($dn), $filter, array("objectClass"));
302 $rv = @ldap_count_entries($this->cid, $res);
303 return($rv);
304 }else{
305 $this->error = "Could not connect to LDAP server";
306 return(FALSE);
307 }
308 }
310 function set_size_limit($size)
311 {
312 /* Ignore zero settings */
313 if ($size == 0){
314 @ldap_set_option($this->cid, LDAP_OPT_SIZELIMIT, 10000000);
315 }
316 if($this->hascon){
317 @ldap_set_option($this->cid, LDAP_OPT_SIZELIMIT, $size);
318 } else {
319 $this->error = "Could not connect to LDAP server";
320 }
321 }
323 function fetch($srp)
324 {
325 $att= array();
326 if($this->hascon){
327 if($this->hasres[$srp]){
328 if ($this->start[$srp] == 0)
329 {
330 if ($this->sr[$srp]){
331 $this->start[$srp] = 1;
332 $this->re[$srp]= @ldap_first_entry($this->cid, $this->sr[$srp]);
333 } else {
334 return array();
335 }
336 } else {
337 $this->re[$srp]= @ldap_next_entry($this->cid, $this->re[$srp]);
338 }
339 if ($this->re[$srp])
340 {
341 $att= @ldap_get_attributes($this->cid, $this->re[$srp]);
342 $att['dn']= trim(LDAP::convert(@ldap_get_dn($this->cid, $this->re[$srp])));
343 }
344 $this->error = @ldap_error($this->cid);
345 if (!isset($att)){
346 $att= array();
347 }
348 return($att);
349 }else{
350 $this->error = "Perform a fetch with no search";
351 return("");
352 }
353 }else{
354 $this->error = "Could not connect to LDAP server";
355 return("");
356 }
357 }
359 function resetResult($srp)
360 {
361 $this->start[$srp] = 0;
362 }
364 function clearResult($srp)
365 {
366 if($this->hasres[$srp]){
367 $this->hasres[$srp] = false;
368 @ldap_free_result($this->sr[$srp]);
369 }
370 }
372 function getDN($srp)
373 {
374 if($this->hascon){
375 if($this->hasres[$srp]){
377 if(!$this->re[$srp])
378 {
379 $this->error = "Perform a Fetch with no valid Result";
380 }
381 else
382 {
383 $rv = @ldap_get_dn($this->cid, $this->re[$srp]);
385 $this->error = @ldap_error($this->cid);
386 return(trim(LDAP::convert($rv)));
387 }
388 }else{
389 $this->error = "Perform a Fetch with no Search";
390 return("");
391 }
392 }else{
393 $this->error = "Could not connect to LDAP server";
394 return("");
395 }
396 }
398 function count($srp)
399 {
400 if($this->hascon){
401 if($this->hasres[$srp]){
402 $rv = @ldap_count_entries($this->cid, $this->sr[$srp]);
403 $this->error = @ldap_error($this->cid);
404 return($rv);
405 }else{
406 $this->error = "Perform a Fetch with no Search";
407 return("");
408 }
409 }else{
410 $this->error = "Could not connect to LDAP server";
411 return("");
412 }
413 }
415 function rm($attrs = "", $dn = "")
416 {
417 if($this->hascon){
418 if ($this->reconnect) $this->connect();
419 if ($dn == "")
420 $dn = $this->basedn;
422 $r = ldap_mod_del($this->cid, LDAP::fix($dn), $attrs);
423 $this->error = @ldap_error($this->cid);
424 return($r);
425 }else{
426 $this->error = "Could not connect to LDAP server";
427 return("");
428 }
429 }
431 function mod_add($attrs = "", $dn = "")
432 {
433 if($this->hascon){
434 if ($this->reconnect) $this->connect();
435 if ($dn == "")
436 $dn = $this->basedn;
438 $r = @ldap_mod_add($this->cid, LDAP::fix($dn), $attrs);
439 $this->error = @ldap_error($this->cid);
440 return($r);
441 }else{
442 $this->error = "Could not connect to LDAP server";
443 return("");
444 }
445 }
447 function rename($attrs, $dn = "")
448 {
449 if($this->hascon){
450 if ($this->reconnect) $this->connect();
451 if ($dn == "")
452 $dn = $this->basedn;
454 $r = @ldap_mod_replace($this->cid, LDAP::fix($dn), $attrs);
455 $this->error = @ldap_error($this->cid);
456 return($r);
457 }else{
458 $this->error = "Could not connect to LDAP server";
459 return("");
460 }
461 }
463 function rmdir($deletedn)
464 {
465 if($this->hascon){
466 if ($this->reconnect) $this->connect();
467 $r = @ldap_delete($this->cid, LDAP::fix($deletedn));
468 $this->error = @ldap_error($this->cid);
469 return($r ? $r : 0);
470 }else{
471 $this->error = "Could not connect to LDAP server";
472 return("");
473 }
474 }
477 /*! \brief Move the given Ldap entry from $source to $dest
478 @param String $source The source dn.
479 @param String $dest The destination dn.
480 @return Boolean TRUE on success else FALSE.
481 */
482 function rename_dn($source,$dest)
483 {
484 /* Check if source and destination are the same entry */
485 if(strtolower($source) == strtolower($dest)){
486 trigger_error("Source and destination can't be the same entry.");
487 $this->error = "Source and destination can't be the same entry.";
488 return(FALSE);
489 }
491 /* Check if destination entry exists */
492 if($this->dn_exists($dest)){
493 trigger_error("Destination '$dest' already exists.");
494 $this->error = "Destination '$dest' already exists.";
495 return(FALSE);
496 }
498 /* Extract the name and the parent part out ouf source dn.
499 e.g. cn=herbert,ou=department,dc=...
500 parent => ou=department,dc=...
501 dest_rdn => cn=herbert
502 */
503 $parent = preg_replace("/^[^,]+,/","", $dest);
504 $dest_rdn = preg_replace("/,.*$/","",$dest);
506 if($this->hascon){
507 if ($this->reconnect) $this->connect();
508 $r= ldap_rename($this->cid,@LDAP::fix($source), @LDAP::fix($dest_rdn),@LDAP::fix($parent),TRUE);
509 $this->error = ldap_error($this->cid);
511 /* Check if destination dn exists, if not the
512 server may not support this operation */
513 $r &= is_resource($this->dn_exists($dest));
514 return($r);
515 }else{
516 $this->error = "Could not connect to LDAP server";
517 return(FALSE);
518 }
519 }
522 /**
523 * Function rmdir_recursive
524 *
525 * Description: Based in recursive_remove, adding two thing: full subtree remove, and delete own node.
526 * Parameters: The dn to delete
527 * GiveBack: True on sucessfull , 0 in error, and "" when we don't get a ldap conection
528 *
529 */
530 function rmdir_recursive($srp, $deletedn)
531 {
532 if($this->hascon){
533 if ($this->reconnect) $this->connect();
534 $delarray= array();
536 /* Get sorted list of dn's to delete */
537 $this->ls ($srp, "(objectClass=*)",$deletedn);
538 while ($this->fetch($srp)){
539 $deldn= $this->getDN($srp);
540 $delarray[$deldn]= strlen($deldn);
541 }
542 arsort ($delarray);
543 reset ($delarray);
545 /* Really Delete ALL dn's in subtree */
546 foreach ($delarray as $key => $value){
547 $this->rmdir_recursive($srp, $key);
548 }
550 /* Finally Delete own Node */
551 $r = @ldap_delete($this->cid, LDAP::fix($deletedn));
552 $this->error = @ldap_error($this->cid);
553 return($r ? $r : 0);
554 }else{
555 $this->error = "Could not connect to LDAP server";
556 return("");
557 }
558 }
560 function makeReadableErrors($error,$attrs)
561 {
562 global $config;
564 if($this->success()) return("");
566 $str = "";
567 if(preg_match("/^objectClass: value #([0-9]*) invalid per syntax$/", $this->get_additional_error())){
568 $oc = preg_replace("/^objectClass: value #([0-9]*) invalid per syntax$/","\\1", $this->get_additional_error());
569 if(isset($attrs['objectClass'][$oc])){
570 $str.= " - <b>objectClass: ".$attrs['objectClass'][$oc]."</b>";
571 }
572 }
573 if($error == "Undefined attribute type"){
574 $str = " - <b>attribute: ".preg_replace("/:.*$/","",$this->get_additional_error())."</b>";
575 }
577 if(is_object($config) && $config->get_cfg_value("displayerrors") == "true" && function_exists("print_a")){
578 $str .= print_a($attrs,true);
579 }
581 return($str);
582 }
584 function modify($attrs)
585 {
586 if(count($attrs) == 0){
587 return (0);
588 }
589 if($this->hascon){
591 $attrs['objectClass'][0] = "Herb ert";
592 if ($this->reconnect) $this->connect();
593 $r = @ldap_modify($this->cid, LDAP::fix($this->basedn), $attrs);
594 $this->error = @ldap_error($this->cid);
595 if(!$this->success()){
596 $this->error.= $this->makeReadableErrors($this->error,$attrs);
597 }
598 return($r ? $r : 0);
599 }else{
600 $this->error = "Could not connect to LDAP server";
601 return("");
602 }
603 }
605 function add($attrs)
606 {
607 if($this->hascon){
608 if ($this->reconnect) $this->connect();
609 $r = @ldap_add($this->cid, LDAP::fix($this->basedn), $attrs);
610 $this->error = @ldap_error($this->cid);
611 if(!$this->success()){
612 $this->error.= $this->makeReadableErrors($this->error,$attrs);
613 }
614 return($r ? $r : 0);
615 }else{
616 $this->error = "Could not connect to LDAP server";
617 return("");
618 }
619 }
621 function create_missing_trees($srp, $target)
622 {
623 global $config;
625 $real_path= substr($target, 0, strlen($target) - strlen($this->basedn) -1 );
627 if ($target == $this->basedn){
628 $l= array("dummy");
629 } else {
630 $l= array_reverse(gosa_ldap_explode_dn($real_path));
631 }
632 unset($l['count']);
633 $cdn= $this->basedn;
634 $tag= "";
636 /* Load schema if available... */
637 $classes= $this->get_objectclasses();
639 foreach ($l as $part){
640 if ($part != "dummy"){
641 $cdn= "$part,$cdn";
642 }
644 /* Ignore referrals */
645 $found= false;
646 foreach($this->referrals as $ref){
647 $base= preg_replace('!^[^:]+://[^/]+/([^?]+).*$!', '\\1', $ref['URI']);
648 if ($base == $cdn){
649 $found= true;
650 break;
651 }
652 }
653 if ($found){
654 continue;
655 }
657 $this->cat ($srp, $cdn);
658 $attrs= $this->fetch($srp);
660 /* Create missing entry? */
661 if (count ($attrs)){
663 /* Catch the tag - if present */
664 if (isset($attrs['gosaUnitTag'][0])){
665 $tag= $attrs['gosaUnitTag'][0];
666 }
668 } else {
669 $type= preg_replace('/^([^=]+)=.*$/', '\\1', $cdn);
670 $param= preg_replace('/^[^=]+=([^,]+).*$/', '\\1', $cdn);
672 $na= array();
674 /* Automatic or traditional? */
675 if(count($classes)){
677 /* Get name of first matching objectClass */
678 $ocname= "";
679 foreach($classes as $class){
680 if (isset($class['MUST']) && $class['MUST'] == "$type"){
682 /* Look for first classes that is structural... */
683 if (isset($class['STRUCTURAL'])){
684 $ocname= $class['NAME'];
685 break;
686 }
688 /* Look for classes that are auxiliary... */
689 if (isset($class['AUXILIARY'])){
690 $ocname= $class['NAME'];
691 }
692 }
693 }
695 /* Bail out, if we've nothing to do... */
696 if ($ocname == ""){
697 msg_dialog::display(_("Internal error"), sprintf(_("Cannot automatically create subtrees with RDN '%s': no object class found!"),$type), FATAL_ERROR_DIALOG);
698 exit();
699 }
701 /* Assemble_entry */
702 if ($tag != ""){
703 $na['objectClass']= array($ocname, "gosaAdministrativeUnitTag");
704 $na["gosaUnitTag"]= $tag;
705 } else {
706 $na['objectClass']= array($ocname);
707 }
708 if (isset($classes[$ocname]['AUXILIARY'])){
709 $na['objectClass'][]= $classes[$ocname]['SUP'];
710 }
711 if ($type == "dc"){
712 /* This is bad actually, but - tell me a better way? */
713 $na['objectClass'][]= 'locality';
714 }
715 $na[$type]= $param;
716 if (is_array($classes[$ocname]['MUST'])){
717 foreach($classes[$ocname]['MUST'] as $attr){
718 $na[$attr]= "filled";
719 }
720 }
722 } else {
724 /* Use alternative add... */
725 switch ($type){
726 case 'ou':
727 if ($tag != ""){
728 $na["objectClass"]= array("organizationalUnit", "gosaAdministrativeUnitTag");
729 $na["gosaUnitTag"]= $tag;
730 } else {
731 $na["objectClass"]= "organizationalUnit";
732 }
733 $na["ou"]= $param;
734 break;
735 case 'dc':
736 if ($tag != ""){
737 $na["objectClass"]= array("dcObject", "top", "locality", "gosaAdministrativeUnitTag");
738 $na["gosaUnitTag"]= $tag;
739 } else {
740 $na["objectClass"]= array("dcObject", "top", "locality");
741 }
742 $na["dc"]= $param;
743 break;
744 default:
745 msg_dialog::display(_("Internal error"), sprintf(_("Cannot automatically create subtrees with RDN '%s': not supported"),$type), FATAL_ERROR_DIALOG);
746 exit();
747 }
749 }
750 $this->cd($cdn);
751 $this->add($na);
753 if (!$this->success()){
755 print_a(array($cdn,$na));
757 msg_dialog::display(_("LDAP error"), msgPool::ldaperror($this->get_error(), $cdn, LDAP_ADD, get_class()));
758 return FALSE;
759 }
760 }
761 }
763 return TRUE;
764 }
767 function recursive_remove($srp)
768 {
769 $delarray= array();
771 /* Get sorted list of dn's to delete */
772 $this->search ($srp, "(objectClass=*)");
773 while ($this->fetch($srp)){
774 $deldn= $this->getDN($srp);
775 $delarray[$deldn]= strlen($deldn);
776 }
777 arsort ($delarray);
778 reset ($delarray);
780 /* Delete all dn's in subtree */
781 foreach ($delarray as $key => $value){
782 $this->rmdir($key);
783 }
784 }
787 function get_attribute($dn, $name,$r_array=0)
788 {
789 $data= "";
790 if ($this->reconnect) $this->connect();
791 $sr= @ldap_read($this->cid, LDAP::fix($dn), "objectClass=*", array("$name"));
793 /* fill data from LDAP */
794 if ($sr) {
795 $ei= @ldap_first_entry($this->cid, $sr);
796 if ($ei) {
797 if ($info= @ldap_get_values_len($this->cid, $ei, "$name")){
798 $data= $info[0];
799 }
800 }
801 }
802 if($r_array==0) {
803 return ($data);
804 } else {
805 return ($info);
806 }
807 }
811 function get_additional_error()
812 {
813 $error= "";
814 @ldap_get_option ($this->cid, LDAP_OPT_ERROR_STRING, $error);
815 return ($error);
816 }
819 function success()
820 {
821 return (preg_match('/Success/i', $this->error));
822 }
825 function get_error()
826 {
827 if ($this->error == 'Success'){
828 return $this->error;
829 } else {
830 $adderror= $this->get_additional_error();
831 if ($adderror != ""){
832 $error= $this->error." (".$this->get_additional_error().", ".sprintf(_("while operating on '%s' using LDAP server '%s'"), $this->basedn, $this->hostname).")";
833 } else {
834 $error= $this->error." (".sprintf(_("while operating on LDAP server %s"), $this->hostname).")";
835 }
836 return $error;
837 }
838 }
840 function get_credentials($url, $referrals= NULL)
841 {
842 $ret= array();
843 $url= preg_replace('!\?\?.*$!', '', $url);
844 $server= preg_replace('!^([^:]+://[^/]+)/.*$!', '\\1', $url);
846 if ($referrals === NULL){
847 $referrals= $this->referrals;
848 }
850 if (isset($referrals[$server])){
851 return ($referrals[$server]);
852 } else {
853 $ret['ADMINDN']= LDAP::fix($this->binddn);
854 $ret['ADMINPASSWORD']= $this->bindpw;
855 }
857 return ($ret);
858 }
861 function gen_ldif ($srp, $dn, $filter= "(objectClass=*)", $attributes= array('*'), $recursive= TRUE)
862 {
863 $display= "";
865 if ($recursive){
866 $this->cd($dn);
867 $this->ls($srp, $filter,$dn, array('dn','objectClass'));
868 $deps = array();
870 $display .= $this->gen_one_entry($dn)."\n";
872 while ($attrs= $this->fetch($srp)){
873 $deps[] = $attrs['dn'];
874 }
875 foreach($deps as $dn){
876 $display .= $this->gen_ldif($srp, $dn, $filter,$attributes,$recursive);
877 }
878 } else {
879 $display.= $this->gen_one_entry($dn);
880 }
881 return ($display);
882 }
885 function gen_xls ($srp, $dn, $filter= "(objectClass=*)", $attributes= array('*'), $recursive= TRUE,$r_array=0)
886 {
887 $display= array();
889 $this->cd($dn);
890 $this->search($srp, "$filter");
892 $i=0;
893 while ($attrs= $this->fetch($srp)){
894 $j=0;
896 foreach ($attributes as $at){
897 $display[$i][$j]= $this->get_attribute($attrs['dn'], $at,$r_array);
898 $j++;
899 }
901 $i++;
902 }
904 return ($display);
905 }
908 function gen_one_entry($dn, $filter= "(objectClass=*)" , $name= array("*"))
909 {
910 $ret = "";
911 $data = "";
912 if($this->reconnect){
913 $this->connect();
914 }
916 /* Searching Ldap Tree */
917 $sr= @ldap_read($this->cid, LDAP::fix($dn), $filter, $name);
919 /* Get the first entry */
920 $entry= @ldap_first_entry($this->cid, $sr);
922 /* Get all attributes related to that Objekt */
923 $atts = array();
925 /* Assemble dn */
926 $atts[0]['name'] = "dn";
927 $atts[0]['value'] = array('count' => 1, 0 => $dn);
929 /* Reset index */
930 $i = 1 ;
931 $identifier = array();
932 $attribute= @ldap_first_attribute($this->cid,$entry,$identifier);
933 while ($attribute) {
934 $i++;
935 $atts[$i]['name'] = $attribute;
936 $atts[$i]['value'] = @ldap_get_values_len($this->cid, $entry, "$attribute");
938 /* Next one */
939 $attribute= @ldap_next_attribute($this->cid,$entry,$identifier);
940 }
942 foreach($atts as $at)
943 {
944 for ($i= 0; $i<$at['value']['count']; $i++){
946 /* Check if we must encode the data */
947 if(!preg_match('/^[a-z0-9+@#.=, \/ -]+$/i', $at['value'][$i])) {
948 $ret .= $at['name'].":: ".base64_encode($at['value'][$i])."\n";
949 } else {
950 $ret .= $at['name'].": ".$at['value'][$i]."\n";
951 }
952 }
953 }
955 return($ret);
956 }
959 function dn_exists($dn)
960 {
961 return @ldap_list($this->cid, LDAP::fix($dn), "(objectClass=*)", array("objectClass"));
962 }
966 /* This funktion imports ldifs
968 If DeleteOldEntries is true, the destination entry will be deleted first.
969 If JustModify is true the destination entry will only be touched by the attributes specified in the ldif.
970 if JustMofify id false the destination dn will be overwritten by the new ldif.
971 */
973 function import_complete_ldif($srp, $str_attr,$error,$JustModify,$DeleteOldEntries)
974 {
975 if($this->reconnect) $this->connect();
977 /* First we have to splitt the string ito detect empty lines
978 An empty line indicates an new Entry */
979 $entries = split("\n",$str_attr);
981 $data = "";
982 $cnt = 0;
983 $current_line = 0;
985 /* FIX ldif */
986 $last = "";
987 $tmp = "";
988 $i = 0;
989 foreach($entries as $entry){
990 if(preg_match("/^ /",$entry)){
991 $tmp[$i] .= trim($entry);
992 }else{
993 $i ++;
994 $tmp[$i] = trim($entry);
995 }
996 }
998 /* Every single line ... */
999 foreach($tmp as $entry) {
1000 $current_line ++;
1002 /* Removing Spaces to ..
1003 .. test if a new entry begins */
1004 $tmp = str_replace(" ","",$data );
1006 /* .. prevent empty lines in an entry */
1007 $tmp2 = str_replace(" ","",$entry);
1009 /* If the Block ends (Empty Line) */
1010 if((empty($entry))&&(!empty($tmp))) {
1011 /* Add collected lines as a complete block */
1012 $all[$cnt] = $data;
1013 $cnt ++;
1014 $data ="";
1015 } else {
1017 /* Append lines ... */
1018 if(!empty($tmp2)) {
1019 /* check if we need base64_decode for this line */
1020 if(ereg("::",$tmp2))
1021 {
1022 $encoded = split("::",$entry);
1023 $attr = trim($encoded[0]);
1024 $value = base64_decode(trim($encoded[1]));
1025 /* Add linenumber */
1026 $data .= $current_line."#".base64_encode($attr.":".$value)."\n";
1027 }
1028 else
1029 {
1030 /* Add Linenumber */
1031 $data .= $current_line."#".base64_encode($entry)."\n";
1032 }
1033 }
1034 }
1035 }
1037 /* The Data we collected is not in the array all[];
1038 For example the Data is stored like this..
1040 all[0] = "1#dn : .... \n
1041 2#ObjectType: person \n ...."
1043 Now we check every insertblock and try to insert */
1044 foreach ( $all as $single) {
1045 $lineone = split("\n",$single);
1046 $ndn = split("#", $lineone[0]);
1047 $line = base64_decode($ndn[1]);
1049 $dnn = split (":",$line,2);
1050 $current_line = $ndn[0];
1051 $dn = $dnn[0];
1052 $value = $dnn[1];
1054 /* Every block must begin with a dn */
1055 if($dn != "dn") {
1056 $error= sprintf(_("This is not a valid DN: '%s'. A block for import should begin with 'dn: ...' in line %s"), $line, $current_line);
1057 return -2;
1058 }
1060 /* Should we use Modify instead of Add */
1061 $usemodify= false;
1063 /* Delete before insert */
1064 $usermdir= false;
1066 /* The dn address already exists, Don't delete destination entry, overwrite it */
1067 if (($this->dn_exists($value))&&((!$JustModify)&&(!$DeleteOldEntries))) {
1069 $usermdir = $usemodify = false;
1071 /* Delete old entry first, then add new */
1072 } elseif(($this->dn_exists($value))&&($DeleteOldEntries)){
1074 /* Delete first, then add */
1075 $usermdir = true;
1077 } elseif(($this->dn_exists($value))&&($JustModify)) {
1079 /* Modify instead of Add */
1080 $usemodify = true;
1081 }
1083 /* If we can't Import, return with a file error */
1084 if(!$this->import_single_entry($srp, $single,$usemodify,$usermdir) ) {
1085 $error= sprintf(_("Error while importing dn: '%s', please check your LDIF from line %s on!"), $line,
1086 $current_line);
1087 return UNKNOWN_TOKEN_IN_LDIF_FILE; }
1088 }
1090 return (INSERT_OK);
1091 }
1094 /* Imports a single entry
1095 If $delete is true; The old entry will be deleted if it exists.
1096 if $modify is true; All variables that are not touched by the new ldif will be kept.
1097 if $modify is false; The new ldif overwrites the old entry, and all untouched attributes get lost.
1098 */
1099 function import_single_entry($srp, $str_attr,$modify,$delete)
1100 {
1101 global $config;
1103 if(!$config){
1104 trigger_error("Can't import ldif, can't read config object.");
1105 }
1108 if($this->reconnect) $this->connect();
1110 $ret = false;
1111 $rows= split("\n",$str_attr);
1112 $data= false;
1114 foreach($rows as $row) {
1116 /* Check if we use Linenumbers (when import_complete_ldif is called we use
1117 Linenumbers) Linenumbers are use like this 123#attribute : value */
1118 if(!empty($row)) {
1119 if(strpos($row,"#")!=FALSE) {
1121 /* We are using line numbers
1122 Because there is a # before a : */
1123 $tmp1= split("#",$row);
1124 $current_line= $tmp1[0];
1125 $row= base64_decode($tmp1[1]);
1126 }
1128 /* Split the line into attribute and value */
1129 $attr = split(":", $row,2);
1130 $attr[0]= trim($attr[0]); /* attribute */
1131 $attr[1]= $attr[1]; /* value */
1133 /* Check :: was used to indicate base64_encoded strings */
1134 if($attr[1][0] == ":"){
1135 $attr[1]=trim(preg_replace("/^:/","",$attr[1]));
1136 $attr[1]=base64_decode($attr[1]);
1137 }
1139 $attr[1] = trim($attr[1]);
1141 /* Check for attributes that are used more than once */
1142 if(!isset($data[$attr[0]])) {
1143 $data[$attr[0]]=$attr[1];
1144 } else {
1145 $tmp = $data[$attr[0]];
1147 if(!is_array($tmp)) {
1148 $new[0]=$tmp;
1149 $new[1]=$attr[1];
1150 $datas[$attr[0]]['count']=1;
1151 $data[$attr[0]]=$new;
1152 } else {
1153 $cnt = $datas[$attr[0]]['count'];
1154 $cnt ++;
1155 $data[$attr[0]][$cnt]=$attr[1];
1156 $datas[$attr[0]]['count'] = $cnt;
1157 }
1158 }
1159 }
1160 }
1162 /* If dn is an index of data, we should try to insert the data */
1163 if(isset($data['dn'])) {
1165 /* Fix dn */
1166 $tmp = gosa_ldap_explode_dn($data['dn']);
1167 unset($tmp['count']);
1168 $newdn ="";
1169 foreach($tmp as $tm){
1170 $newdn.= trim($tm).",";
1171 }
1172 $newdn = preg_replace("/,$/","",$newdn);
1173 $data['dn'] = $newdn;
1175 /* Creating Entry */
1176 $this->cd($data['dn']);
1178 /* Delete existing entry */
1179 if($delete){
1180 $this->rmdir_recursive($srp, $data['dn']);
1181 }
1183 /* Create missing trees */
1184 $this->cd ($this->basedn);
1185 $this->cd($config->current['BASE']);
1186 $this->create_missing_trees($srp, preg_replace("/^[^,]+,/","",$data['dn']));
1187 $this->cd($data['dn']);
1189 $dn = $data['dn'];
1190 unset($data['dn']);
1192 if(!$modify){
1194 $this->cat($srp, $dn);
1195 if($this->count($srp)){
1197 /* The destination entry exists, overwrite it with the new entry */
1198 $attrs = $this->fetch($srp);
1199 foreach($attrs as $name => $value ){
1200 if(!is_numeric($name)){
1201 if(in_array($name,array("dn","count"))) continue;
1202 if(!isset($data[$name])){
1203 $data[$name] = array();
1204 }
1205 }
1206 }
1207 $ret = $this->modify($data);
1209 }else{
1211 /* The destination entry doesn't exists, create it */
1212 $ret = $this->add($data);
1213 }
1215 } else {
1217 /* Keep all vars that aren't touched by this ldif */
1218 $ret = $this->modify($data);
1219 }
1220 }
1222 if (!$this->success()){
1223 msg_dialog::display(_("LDAP error"), msgPool::ldaperror($this->get_error(), $dn, "", get_class()));
1224 }
1226 return($ret);
1227 }
1230 function importcsv($str)
1231 {
1232 $lines = split("\n",$str);
1233 foreach($lines as $line)
1234 {
1235 /* continue if theres a comment */
1236 if(substr(trim($line),0,1)=="#"){
1237 continue;
1238 }
1240 $line= str_replace ("\t\t","\t",$line);
1241 $line= str_replace ("\t" ,"," ,$line);
1242 echo $line;
1244 $cells = split(",",$line ) ;
1245 $linet= str_replace ("\t\t",",",$line);
1246 $cells = split("\t",$line);
1247 $count = count($cells);
1248 }
1250 }
1252 function get_objectclasses( $force_reload = FALSE)
1253 {
1254 $objectclasses = array();
1255 global $config;
1257 /* Only read schema if it is allowed */
1258 if(isset($config) && preg_match("/config/i",get_class($config))){
1259 if ($config->get_cfg_value("schemaCheck") != "true"){
1260 return($objectclasses);
1261 }
1262 }
1264 /* Return the cached results. */
1265 if(class_available('session') && session::global_is_set("LDAP_CACHE::get_objectclasses") && !$force_reload){
1266 $objectclasses = session::global_get("LDAP_CACHE::get_objectclasses");
1267 return($objectclasses);
1268 }
1270 # Get base to look for schema
1271 $sr = @ldap_read ($this->cid, "", "objectClass=*", array("subschemaSubentry"));
1272 $attr = @ldap_get_entries($this->cid,$sr);
1273 if (!isset($attr[0]['subschemasubentry'][0])){
1274 return array();
1275 }
1277 /* Get list of objectclasses and fill array */
1278 $nb= $attr[0]['subschemasubentry'][0];
1279 $objectclasses= array();
1280 $sr= ldap_read ($this->cid, $nb, "objectClass=*", array("objectclasses"));
1281 $attrs= ldap_get_entries($this->cid,$sr);
1282 if (!isset($attrs[0])){
1283 return array();
1284 }
1285 foreach ($attrs[0]['objectclasses'] as $val){
1286 if (preg_match('/^[0-9]+$/', $val)){
1287 continue;
1288 }
1289 $name= "OID";
1290 $pattern= split(' ', $val);
1291 $ocname= preg_replace("/^.* NAME\s+\(*\s*'([^']+)'\s*\)*.*$/", '\\1', $val);
1292 $objectclasses[$ocname]= array();
1294 foreach($pattern as $chunk){
1295 switch($chunk){
1297 case '(':
1298 $value= "";
1299 break;
1301 case ')': if ($name != ""){
1302 $objectclasses[$ocname][$name]= $this->value2container($value);
1303 }
1304 $name= "";
1305 $value= "";
1306 break;
1308 case 'NAME':
1309 case 'DESC':
1310 case 'SUP':
1311 case 'STRUCTURAL':
1312 case 'ABSTRACT':
1313 case 'AUXILIARY':
1314 case 'MUST':
1315 case 'MAY':
1316 if ($name != ""){
1317 $objectclasses[$ocname][$name]= $this->value2container($value);
1318 }
1319 $name= $chunk;
1320 $value= "";
1321 break;
1323 default: $value.= $chunk." ";
1324 }
1325 }
1327 }
1328 if(class_available("session")){
1329 session::global_set("LDAP_CACHE::get_objectclasses",$objectclasses);
1330 }
1332 return $objectclasses;
1333 }
1336 function value2container($value)
1337 {
1338 /* Set emtpy values to "true" only */
1339 if (preg_match('/^\s*$/', $value)){
1340 return true;
1341 }
1343 /* Remove ' and " if needed */
1344 $value= preg_replace('/^[\'"]/', '', $value);
1345 $value= preg_replace('/[\'"] *$/', '', $value);
1347 /* Convert to array if $ is inside... */
1348 if (preg_match('/\$/', $value)){
1349 $container= preg_split('/\s*\$\s*/', $value);
1350 } else {
1351 $container= chop($value);
1352 }
1354 return ($container);
1355 }
1358 function log($string)
1359 {
1360 if (session::global_is_set('config')){
1361 $cfg = session::global_get('config');
1362 if (isset($cfg->current['LDAPSTATS']) && preg_match('/true/i', $cfg->current['LDAPSTATS'])){
1363 syslog (LOG_INFO, $string);
1364 }
1365 }
1366 }
1368 /* added by Guido Serra aka Zeph <zeph@purotesto.it> */
1369 function getCn($dn){
1370 $simple= split(",", $dn);
1372 foreach($simple as $piece) {
1373 $partial= split("=", $piece);
1375 if($partial[0] == "cn"){
1376 return $partial[1];
1377 }
1378 }
1379 }
1382 function get_naming_contexts($server, $admin= "", $password= "")
1383 {
1384 /* Build LDAP connection */
1385 $ds= ldap_connect ($server);
1386 if (!$ds) {
1387 die ("Can't bind to LDAP. No check possible!");
1388 }
1389 ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
1390 $r= ldap_bind ($ds, $admin, $password);
1392 /* Get base to look for naming contexts */
1393 $sr = @ldap_read ($ds, "", "objectClass=*", array("+"));
1394 $attr= @ldap_get_entries($ds,$sr);
1396 return ($attr[0]['namingcontexts']);
1397 }
1400 function get_root_dse($server, $admin= "", $password= "")
1401 {
1402 /* Build LDAP connection */
1403 $ds= ldap_connect ($server);
1404 if (!$ds) {
1405 die ("Can't bind to LDAP. No check possible!");
1406 }
1407 ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
1408 $r= ldap_bind ($ds, $admin, $password);
1410 /* Get base to look for naming contexts */
1411 $sr = @ldap_read ($ds, "", "objectClass=*", array("+"));
1412 $attr= @ldap_get_entries($ds,$sr);
1414 /* Return empty array, if nothing was set */
1415 if (!isset($attr[0])){
1416 return array();
1417 }
1419 /* Rework array... */
1420 $result= array();
1421 for ($i= 0; $i<$attr[0]['count']; $i++){
1422 $result[$attr[0][$i]]= $attr[0][$attr[0][$i]];
1423 unset($result[$attr[0][$i]]['count']);
1424 }
1426 return ($result);
1427 }
1429 }
1430 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
1431 ?>