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 static function convert($dn)
92 {
93 if (SPECIALS_OVERRIDE == TRUE){
94 $tmp= preg_replace(array("/\\\\,/", "/\\\\2C/", "/\(/", "/\)/", "/\//"),
95 array("\001CO", "\001CO", "\001OB", "\001CB", "\001SL"),
96 $dn);
97 return (preg_replace('/,\s+/', ',', $tmp));
98 } else {
99 return ($dn);
100 }
101 }
104 /* Function to fix all problematic characters inside a DN by replacing \001XX
105 codes to their original values. See "convert" for mor information.
106 ',' characters are always expanded to \, (not \2C), since all tested LDAP
107 servers seem to take it the correct way. */
108 static function fix($dn)
109 {
110 if (SPECIALS_OVERRIDE == TRUE){
111 return (preg_replace(array("/\001CO/", "/\001OB/", "/\001CB/", "/\001SL/"),
112 array("\,", "(", ")", "/"),
113 $dn));
114 } else {
115 return ($dn);
116 }
117 }
119 /* Function to fix problematic characters in DN's that are used for search
120 requests. I.e. member=.... */
121 static function prepare4filter($dn)
122 {
123 $fixed= normalizeLdap(str_replace('\\\\', '\\\\\\', LDAP::fix($dn)));
124 return str_replace('\\,', '\\\\,', $fixed);
125 }
128 function connect()
129 {
130 $this->hascon=false;
131 $this->reconnect=false;
132 if ($this->cid= @ldap_connect($this->hostname)) {
133 @ldap_set_option($this->cid, LDAP_OPT_PROTOCOL_VERSION, 3);
134 if (function_exists("ldap_set_rebind_proc") && $this->follow_referral) {
135 @ldap_set_option($this->cid, LDAP_OPT_REFERRALS, 1);
136 @ldap_set_rebind_proc($this->cid, array(&$this, "rebind"));
137 }
138 if (function_exists("ldap_start_tls") && $this->tls){
139 @ldap_start_tls($this->cid);
140 }
142 $this->error = "No Error";
143 if ($bid = @ldap_bind($this->cid, LDAP::fix($this->binddn), $this->bindpw)) {
144 $this->error = "Success";
145 $this->hascon=true;
146 } else {
147 if ($this->reconnect){
148 if ($this->error != "Success"){
149 $this->error = "Could not rebind to " . $this->binddn;
150 }
151 } else {
152 $this->error = "Could not bind to " . $this->binddn;
153 }
154 }
155 } else {
156 $this->error = "Could not connect to LDAP server";
157 }
158 }
160 function rebind($ldap, $referral)
161 {
162 $credentials= $this->get_credentials($referral);
163 if (@ldap_bind($ldap, LDAP::fix($credentials['ADMINDN']), $credentials['ADMINPASSWORD'])) {
164 $this->error = "Success";
165 $this->hascon=true;
166 $this->reconnect= true;
167 return (0);
168 } else {
169 $this->error = "Could not bind to " . $credentials['ADMINDN'];
170 return NULL;
171 }
172 }
174 function reconnect()
175 {
176 if ($this->reconnect){
177 @ldap_unbind($this->cid);
178 $this->cid = NULL;
179 }
180 }
182 function unbind()
183 {
184 @ldap_unbind($this->cid);
185 $this->cid = NULL;
186 }
188 function disconnect()
189 {
190 if($this->hascon){
191 @ldap_close($this->cid);
192 $this->hascon=false;
193 }
194 }
196 function cd($dir)
197 {
198 if ($dir == ".."){
199 $this->basedn = $this->getParentDir();
200 } else {
201 $this->basedn = LDAP::convert($dir);
202 }
203 }
205 function getParentDir($basedn = "")
206 {
207 if ($basedn==""){
208 $basedn = $this->basedn;
209 } else {
210 $basedn = LDAP::convert($this->basedn);
211 }
212 return(ereg_replace("[^,]*[,]*[ ]*(.*)", "\\1", $basedn));
213 }
216 function search($srp, $filter, $attrs= array())
217 {
218 if($this->hascon){
219 if ($this->reconnect) $this->connect();
221 $start = microtime();
222 $this->clearResult($srp);
223 $this->sr[$srp] = @ldap_search($this->cid, LDAP::fix($this->basedn), $filter, $attrs);
224 $this->error = @ldap_error($this->cid);
225 $this->resetResult($srp);
226 $this->hasres[$srp]=true;
228 /* Check if query took longer as specified in max_ldap_query_time */
229 if($this->max_ldap_query_time){
230 $diff = get_MicroTimeDiff($start,microtime());
231 if($diff > $this->max_ldap_query_time){
232 msg_dialog::display(_("Performance warning"), sprintf(_("LDAP performance is poor: last query took about %.2fs!"), $diff), WARNING_DIALOG);
233 }
234 }
236 $this->log("LDAP operation: time=".get_MicroTimeDiff($start,microtime())." operation=search('".LDAP::fix($this->basedn)."', '$filter')");
237 return($this->sr[$srp]);
238 }else{
239 $this->error = "Could not connect to LDAP server";
240 return("");
241 }
242 }
244 function ls($srp, $filter = "(objectclass=*)", $basedn = "",$attrs = array("*"))
245 {
246 if($this->hascon){
247 if ($this->reconnect) $this->connect();
249 $this->clearResult($srp);
250 if ($basedn == "")
251 $basedn = $this->basedn;
252 else
253 $basedn= LDAP::convert($basedn);
255 $start = microtime();
256 $this->sr[$srp] = @ldap_list($this->cid, LDAP::fix($basedn), $filter,$attrs);
257 $this->error = @ldap_error($this->cid);
258 $this->resetResult($srp);
259 $this->hasres[$srp]=true;
261 /* Check if query took longer as specified in max_ldap_query_time */
262 if($this->max_ldap_query_time){
263 $diff = get_MicroTimeDiff($start,microtime());
264 if($diff > $this->max_ldap_query_time){
265 msg_dialog::display(_("Performance warning"), sprintf(_("LDAP performance is poor: last query took about %.2fs!"), $diff), WARNING_DIALOG);
266 }
267 }
269 $this->log("LDAP operation: time=".get_MicroTimeDiff($start,microtime())." operation=ls('".LDAP::fix($basedn)."', '$filter')");
271 return($this->sr[$srp]);
272 }else{
273 $this->error = "Could not connect to LDAP server";
274 return("");
275 }
276 }
278 function cat($srp, $dn,$attrs= array("*"))
279 {
280 if($this->hascon){
281 if ($this->reconnect) $this->connect();
283 $this->clearResult($srp);
284 $filter = "(objectclass=*)";
285 $this->sr[$srp] = @ldap_read($this->cid, LDAP::fix($dn), $filter,$attrs);
286 $this->error = @ldap_error($this->cid);
287 $this->resetResult($srp);
288 $this->hasres[$srp]=true;
289 return($this->sr[$srp]);
290 }else{
291 $this->error = "Could not connect to LDAP server";
292 return("");
293 }
294 }
296 function 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 }
560 function modify($attrs)
561 {
562 if(count($attrs) == 0){
563 return (0);
564 }
565 if($this->hascon){
566 if ($this->reconnect) $this->connect();
567 $r = @ldap_modify($this->cid, LDAP::fix($this->basedn), $attrs);
568 $this->error = @ldap_error($this->cid);
569 if(!$this->success() && preg_match("/^objectClass: value #([0-9]*) invalid per syntax$/", $this->get_additional_error())){
570 $oc = preg_replace("/^objectClass: value #([0-9]*) invalid per syntax$/","\\1", $this->get_additional_error());
571 if(isset($attrs['objectClass'][$oc])){
572 $this->error.= " <b>objectClass: ".$attrs['objectClass'][$oc]."</b>";
573 }
574 }
575 return($r ? $r : 0);
576 }else{
577 $this->error = "Could not connect to LDAP server";
578 return("");
579 }
580 }
582 function add($attrs)
583 {
584 if($this->hascon){
585 if ($this->reconnect) $this->connect();
586 $r = @ldap_add($this->cid, LDAP::fix($this->basedn), $attrs);
587 $this->error = @ldap_error($this->cid);
588 if(!$this->success() && preg_match("/^objectClass: value #([0-9]*) invalid per syntax$/", $this->get_additional_error())){
589 $oc = preg_replace("/^objectClass: value #([0-9]*) invalid per syntax$/","\\1", $this->get_additional_error());
590 if(isset($attrs['objectClass'][$oc])){
591 $this->error.= " <b>objectClass: ".$attrs['objectClass'][$oc]."</b>";
592 }
593 }
594 return($r ? $r : 0);
595 }else{
596 $this->error = "Could not connect to LDAP server";
597 return("");
598 }
599 }
601 function create_missing_trees($srp, $target)
602 {
603 global $config;
605 $real_path= substr($target, 0, strlen($target) - strlen($this->basedn) -1 );
607 if ($target == $this->basedn){
608 $l= array("dummy");
609 } else {
610 $l= array_reverse(gosa_ldap_explode_dn($real_path));
611 }
612 unset($l['count']);
613 $cdn= $this->basedn;
614 $tag= "";
616 /* Load schema if available... */
617 $classes= $this->get_objectclasses();
619 foreach ($l as $part){
620 if ($part != "dummy"){
621 $cdn= "$part,$cdn";
622 }
624 /* Ignore referrals */
625 $found= false;
626 foreach($this->referrals as $ref){
627 $base= preg_replace('!^[^:]+://[^/]+/([^?]+).*$!', '\\1', $ref['URI']);
628 if ($base == $cdn){
629 $found= true;
630 break;
631 }
632 }
633 if ($found){
634 continue;
635 }
637 $this->cat ($srp, $cdn);
638 $attrs= $this->fetch($srp);
640 /* Create missing entry? */
641 if (count ($attrs)){
643 /* Catch the tag - if present */
644 if (isset($attrs['gosaUnitTag'][0])){
645 $tag= $attrs['gosaUnitTag'][0];
646 }
648 } else {
649 $type= preg_replace('/^([^=]+)=.*$/', '\\1', $cdn);
650 $param= preg_replace('/^[^=]+=([^,]+).*$/', '\\1', $cdn);
652 $na= array();
654 /* Automatic or traditional? */
655 if(count($classes)){
657 /* Get name of first matching objectClass */
658 $ocname= "";
659 foreach($classes as $class){
660 if (isset($class['MUST']) && $class['MUST'] == "$type"){
662 /* Look for first classes that is structural... */
663 if (isset($class['STRUCTURAL'])){
664 $ocname= $class['NAME'];
665 break;
666 }
668 /* Look for classes that are auxiliary... */
669 if (isset($class['AUXILIARY'])){
670 $ocname= $class['NAME'];
671 }
672 }
673 }
675 /* Bail out, if we've nothing to do... */
676 if ($ocname == ""){
677 msg_dialog::display(_("Internal error"), sprintf(_("Cannot automatically create subtrees with RDN '%s': no object class found!"),$type), FATAL_ERROR_DIALOG);
678 exit();
679 }
681 /* Assemble_entry */
682 if ($tag != ""){
683 $na['objectClass']= array($ocname, "gosaAdministrativeUnitTag");
684 $na["gosaUnitTag"]= $tag;
685 } else {
686 $na['objectClass']= array($ocname);
687 }
688 if (isset($classes[$ocname]['AUXILIARY'])){
689 $na['objectClass'][]= $classes[$ocname]['SUP'];
690 }
691 if ($type == "dc"){
692 /* This is bad actually, but - tell me a better way? */
693 $na['objectClass'][]= 'locality';
694 }
695 $na[$type]= $param;
696 if (is_array($classes[$ocname]['MUST'])){
697 foreach($classes[$ocname]['MUST'] as $attr){
698 $na[$attr]= "filled";
699 }
700 }
702 } else {
704 /* Use alternative add... */
705 switch ($type){
706 case 'ou':
707 if ($tag != ""){
708 $na["objectClass"]= array("organizationalUnit", "gosaAdministrativeUnitTag");
709 $na["gosaUnitTag"]= $tag;
710 } else {
711 $na["objectClass"]= "organizationalUnit";
712 }
713 $na["ou"]= $param;
714 break;
715 case 'dc':
716 if ($tag != ""){
717 $na["objectClass"]= array("dcObject", "top", "locality", "gosaAdministrativeUnitTag");
718 $na["gosaUnitTag"]= $tag;
719 } else {
720 $na["objectClass"]= array("dcObject", "top", "locality");
721 }
722 $na["dc"]= $param;
723 break;
724 default:
725 msg_dialog::display(_("Internal error"), sprintf(_("Cannot automatically create subtrees with RDN '%s': not supported"),$type), FATAL_ERROR_DIALOG);
726 exit();
727 }
729 }
730 $this->cd($cdn);
731 $this->add($na);
733 if (!$this->success()){
735 print_a(array($cdn,$na));
737 msg_dialog::display(_("LDAP error"), msgPool::ldaperror($this->get_error(), $cdn, LDAP_ADD, get_class()));
738 return FALSE;
739 }
740 }
741 }
743 return TRUE;
744 }
747 function recursive_remove($srp)
748 {
749 $delarray= array();
751 /* Get sorted list of dn's to delete */
752 $this->search ($srp, "(objectClass=*)");
753 while ($this->fetch($srp)){
754 $deldn= $this->getDN($srp);
755 $delarray[$deldn]= strlen($deldn);
756 }
757 arsort ($delarray);
758 reset ($delarray);
760 /* Delete all dn's in subtree */
761 foreach ($delarray as $key => $value){
762 $this->rmdir($key);
763 }
764 }
767 function get_attribute($dn, $name,$r_array=0)
768 {
769 $data= "";
770 if ($this->reconnect) $this->connect();
771 $sr= @ldap_read($this->cid, LDAP::fix($dn), "objectClass=*", array("$name"));
773 /* fill data from LDAP */
774 if ($sr) {
775 $ei= @ldap_first_entry($this->cid, $sr);
776 if ($ei) {
777 if ($info= @ldap_get_values_len($this->cid, $ei, "$name")){
778 $data= $info[0];
779 }
780 }
781 }
782 if($r_array==0) {
783 return ($data);
784 } else {
785 return ($info);
786 }
787 }
791 function get_additional_error()
792 {
793 $error= "";
794 @ldap_get_option ($this->cid, LDAP_OPT_ERROR_STRING, $error);
795 return ($error);
796 }
799 function success()
800 {
801 return (preg_match('/Success/i', $this->error));
802 }
805 function get_error()
806 {
807 if ($this->error == 'Success'){
808 return $this->error;
809 } else {
810 $adderror= $this->get_additional_error();
811 if ($adderror != ""){
812 $error= $this->error." (".$this->get_additional_error().", ".sprintf(_("while operating on '%s' using LDAP server '%s'"), $this->basedn, $this->hostname).")";
813 } else {
814 $error= $this->error." (".sprintf(_("while operating on LDAP server %s"), $this->hostname).")";
815 }
816 return $error;
817 }
818 }
820 function get_credentials($url, $referrals= NULL)
821 {
822 $ret= array();
823 $url= preg_replace('!\?\?.*$!', '', $url);
824 $server= preg_replace('!^([^:]+://[^/]+)/.*$!', '\\1', $url);
826 if ($referrals === NULL){
827 $referrals= $this->referrals;
828 }
830 if (isset($referrals[$server])){
831 return ($referrals[$server]);
832 } else {
833 $ret['ADMINDN']= LDAP::fix($this->binddn);
834 $ret['ADMINPASSWORD']= $this->bindpw;
835 }
837 return ($ret);
838 }
841 function gen_ldif ($srp, $dn, $filter= "(objectClass=*)", $attributes= array('*'), $recursive= TRUE)
842 {
843 $display= "";
845 if ($recursive){
846 $this->cd($dn);
847 $this->ls($srp, $filter,$dn, array('dn','objectClass'));
848 $deps = array();
850 $display .= $this->gen_one_entry($dn)."\n";
852 while ($attrs= $this->fetch($srp)){
853 $deps[] = $attrs['dn'];
854 }
855 foreach($deps as $dn){
856 $display .= $this->gen_ldif($srp, $dn, $filter,$attributes,$recursive);
857 }
858 } else {
859 $display.= $this->gen_one_entry($dn);
860 }
861 return ($display);
862 }
865 function gen_xls ($srp, $dn, $filter= "(objectClass=*)", $attributes= array('*'), $recursive= TRUE,$r_array=0)
866 {
867 $display= array();
869 $this->cd($dn);
870 $this->search($srp, "$filter");
872 $i=0;
873 while ($attrs= $this->fetch($srp)){
874 $j=0;
876 foreach ($attributes as $at){
877 $display[$i][$j]= $this->get_attribute($attrs['dn'], $at,$r_array);
878 $j++;
879 }
881 $i++;
882 }
884 return ($display);
885 }
888 function gen_one_entry($dn, $filter= "(objectClass=*)" , $name= array("*"))
889 {
890 $ret = "";
891 $data = "";
892 if($this->reconnect){
893 $this->connect();
894 }
896 /* Searching Ldap Tree */
897 $sr= @ldap_read($this->cid, LDAP::fix($dn), $filter, $name);
899 /* Get the first entry */
900 $entry= @ldap_first_entry($this->cid, $sr);
902 /* Get all attributes related to that Objekt */
903 $atts = array();
905 /* Assemble dn */
906 $atts[0]['name'] = "dn";
907 $atts[0]['value'] = array('count' => 1, 0 => $dn);
909 /* Reset index */
910 $i = 1 ;
911 $identifier = array();
912 $attribute= @ldap_first_attribute($this->cid,$entry,$identifier);
913 while ($attribute) {
914 $i++;
915 $atts[$i]['name'] = $attribute;
916 $atts[$i]['value'] = @ldap_get_values_len($this->cid, $entry, "$attribute");
918 /* Next one */
919 $attribute= @ldap_next_attribute($this->cid,$entry,$identifier);
920 }
922 foreach($atts as $at)
923 {
924 for ($i= 0; $i<$at['value']['count']; $i++){
926 /* Check if we must encode the data */
927 if(!preg_match('/^[a-z0-9+@#.=, \/ -]+$/i', $at['value'][$i])) {
928 $ret .= $at['name'].":: ".base64_encode($at['value'][$i])."\n";
929 } else {
930 $ret .= $at['name'].": ".$at['value'][$i]."\n";
931 }
932 }
933 }
935 return($ret);
936 }
939 function dn_exists($dn)
940 {
941 return @ldap_list($this->cid, LDAP::fix($dn), "(objectClass=*)", array("objectClass"));
942 }
946 /* This funktion imports ldifs
948 If DeleteOldEntries is true, the destination entry will be deleted first.
949 If JustModify is true the destination entry will only be touched by the attributes specified in the ldif.
950 if JustMofify id false the destination dn will be overwritten by the new ldif.
951 */
953 function import_complete_ldif($srp, $str_attr,$error,$JustModify,$DeleteOldEntries)
954 {
955 if($this->reconnect) $this->connect();
957 /* First we have to splitt the string ito detect empty lines
958 An empty line indicates an new Entry */
959 $entries = split("\n",$str_attr);
961 $data = "";
962 $cnt = 0;
963 $current_line = 0;
965 /* FIX ldif */
966 $last = "";
967 $tmp = "";
968 $i = 0;
969 foreach($entries as $entry){
970 if(preg_match("/^ /",$entry)){
971 $tmp[$i] .= trim($entry);
972 }else{
973 $i ++;
974 $tmp[$i] = trim($entry);
975 }
976 }
978 /* Every single line ... */
979 foreach($tmp as $entry) {
980 $current_line ++;
982 /* Removing Spaces to ..
983 .. test if a new entry begins */
984 $tmp = str_replace(" ","",$data );
986 /* .. prevent empty lines in an entry */
987 $tmp2 = str_replace(" ","",$entry);
989 /* If the Block ends (Empty Line) */
990 if((empty($entry))&&(!empty($tmp))) {
991 /* Add collected lines as a complete block */
992 $all[$cnt] = $data;
993 $cnt ++;
994 $data ="";
995 } else {
997 /* Append lines ... */
998 if(!empty($tmp2)) {
999 /* check if we need base64_decode for this line */
1000 if(ereg("::",$tmp2))
1001 {
1002 $encoded = split("::",$entry);
1003 $attr = trim($encoded[0]);
1004 $value = base64_decode(trim($encoded[1]));
1005 /* Add linenumber */
1006 $data .= $current_line."#".base64_encode($attr.":".$value)."\n";
1007 }
1008 else
1009 {
1010 /* Add Linenumber */
1011 $data .= $current_line."#".base64_encode($entry)."\n";
1012 }
1013 }
1014 }
1015 }
1017 /* The Data we collected is not in the array all[];
1018 For example the Data is stored like this..
1020 all[0] = "1#dn : .... \n
1021 2#ObjectType: person \n ...."
1023 Now we check every insertblock and try to insert */
1024 foreach ( $all as $single) {
1025 $lineone = split("\n",$single);
1026 $ndn = split("#", $lineone[0]);
1027 $line = base64_decode($ndn[1]);
1029 $dnn = split (":",$line,2);
1030 $current_line = $ndn[0];
1031 $dn = $dnn[0];
1032 $value = $dnn[1];
1034 /* Every block must begin with a dn */
1035 if($dn != "dn") {
1036 $error= sprintf(_("This is not a valid DN: '%s'. A block for import should begin with 'dn: ...' in line %s"), $line, $current_line);
1037 return -2;
1038 }
1040 /* Should we use Modify instead of Add */
1041 $usemodify= false;
1043 /* Delete before insert */
1044 $usermdir= false;
1046 /* The dn address already exists, Don't delete destination entry, overwrite it */
1047 if (($this->dn_exists($value))&&((!$JustModify)&&(!$DeleteOldEntries))) {
1049 $usermdir = $usemodify = false;
1051 /* Delete old entry first, then add new */
1052 } elseif(($this->dn_exists($value))&&($DeleteOldEntries)){
1054 /* Delete first, then add */
1055 $usermdir = true;
1057 } elseif(($this->dn_exists($value))&&($JustModify)) {
1059 /* Modify instead of Add */
1060 $usemodify = true;
1061 }
1063 /* If we can't Import, return with a file error */
1064 if(!$this->import_single_entry($srp, $single,$usemodify,$usermdir) ) {
1065 $error= sprintf(_("Error while importing dn: '%s', please check your LDIF from line %s on!"), $line,
1066 $current_line);
1067 return UNKNOWN_TOKEN_IN_LDIF_FILE; }
1068 }
1070 return (INSERT_OK);
1071 }
1074 /* Imports a single entry
1075 If $delete is true; The old entry will be deleted if it exists.
1076 if $modify is true; All variables that are not touched by the new ldif will be kept.
1077 if $modify is false; The new ldif overwrites the old entry, and all untouched attributes get lost.
1078 */
1079 function import_single_entry($srp, $str_attr,$modify,$delete)
1080 {
1081 global $config;
1083 if(!$config){
1084 trigger_error("Can't import ldif, can't read config object.");
1085 }
1088 if($this->reconnect) $this->connect();
1090 $ret = false;
1091 $rows= split("\n",$str_attr);
1092 $data= false;
1094 foreach($rows as $row) {
1096 /* Check if we use Linenumbers (when import_complete_ldif is called we use
1097 Linenumbers) Linenumbers are use like this 123#attribute : value */
1098 if(!empty($row)) {
1099 if(strpos($row,"#")!=FALSE) {
1101 /* We are using line numbers
1102 Because there is a # before a : */
1103 $tmp1= split("#",$row);
1104 $current_line= $tmp1[0];
1105 $row= base64_decode($tmp1[1]);
1106 }
1108 /* Split the line into attribute and value */
1109 $attr = split(":", $row,2);
1110 $attr[0]= trim($attr[0]); /* attribute */
1111 $attr[1]= $attr[1]; /* value */
1113 /* Check :: was used to indicate base64_encoded strings */
1114 if($attr[1][0] == ":"){
1115 $attr[1]=trim(preg_replace("/^:/","",$attr[1]));
1116 $attr[1]=base64_decode($attr[1]);
1117 }
1119 $attr[1] = trim($attr[1]);
1121 /* Check for attributes that are used more than once */
1122 if(!isset($data[$attr[0]])) {
1123 $data[$attr[0]]=$attr[1];
1124 } else {
1125 $tmp = $data[$attr[0]];
1127 if(!is_array($tmp)) {
1128 $new[0]=$tmp;
1129 $new[1]=$attr[1];
1130 $datas[$attr[0]]['count']=1;
1131 $data[$attr[0]]=$new;
1132 } else {
1133 $cnt = $datas[$attr[0]]['count'];
1134 $cnt ++;
1135 $data[$attr[0]][$cnt]=$attr[1];
1136 $datas[$attr[0]]['count'] = $cnt;
1137 }
1138 }
1139 }
1140 }
1142 /* If dn is an index of data, we should try to insert the data */
1143 if(isset($data['dn'])) {
1145 /* Fix dn */
1146 $tmp = gosa_ldap_explode_dn($data['dn']);
1147 unset($tmp['count']);
1148 $newdn ="";
1149 foreach($tmp as $tm){
1150 $newdn.= trim($tm).",";
1151 }
1152 $newdn = preg_replace("/,$/","",$newdn);
1153 $data['dn'] = $newdn;
1155 /* Creating Entry */
1156 $this->cd($data['dn']);
1158 /* Delete existing entry */
1159 if($delete){
1160 $this->rmdir_recursive($srp, $data['dn']);
1161 }
1163 /* Create missing trees */
1164 $this->cd ($this->basedn);
1165 $this->cd($config->current['BASE']);
1166 $this->create_missing_trees($srp, preg_replace("/^[^,]+,/","",$data['dn']));
1167 $this->cd($data['dn']);
1169 $dn = $data['dn'];
1170 unset($data['dn']);
1172 if(!$modify){
1174 $this->cat($srp, $dn);
1175 if($this->count($srp)){
1177 /* The destination entry exists, overwrite it with the new entry */
1178 $attrs = $this->fetch($srp);
1179 foreach($attrs as $name => $value ){
1180 if(!is_numeric($name)){
1181 if(in_array($name,array("dn","count"))) continue;
1182 if(!isset($data[$name])){
1183 $data[$name] = array();
1184 }
1185 }
1186 }
1187 $ret = $this->modify($data);
1189 }else{
1191 /* The destination entry doesn't exists, create it */
1192 $ret = $this->add($data);
1193 }
1195 } else {
1197 /* Keep all vars that aren't touched by this ldif */
1198 $ret = $this->modify($data);
1199 }
1200 }
1202 if (!$this->success()){
1203 msg_dialog::display(_("LDAP error"), msgPool::ldaperror($this->get_error(), $dn, "", get_class()));
1204 }
1206 return($ret);
1207 }
1210 function importcsv($str)
1211 {
1212 $lines = split("\n",$str);
1213 foreach($lines as $line)
1214 {
1215 /* continue if theres a comment */
1216 if(substr(trim($line),0,1)=="#"){
1217 continue;
1218 }
1220 $line= str_replace ("\t\t","\t",$line);
1221 $line= str_replace ("\t" ,"," ,$line);
1222 echo $line;
1224 $cells = split(",",$line ) ;
1225 $linet= str_replace ("\t\t",",",$line);
1226 $cells = split("\t",$line);
1227 $count = count($cells);
1228 }
1230 }
1232 function get_objectclasses( $force_reload = FALSE)
1233 {
1234 $objectclasses = array();
1235 global $config;
1237 /* Only read schema if it is allowed */
1238 if(isset($config) && preg_match("/config/i",get_class($config))){
1239 if ($config->get_cfg_value("schemaCheck") != "true"){
1240 return($objectclasses);
1241 }
1242 }
1244 /* Return the cached results. */
1245 if(class_available('session') && session::global_is_set("LDAP_CACHE::get_objectclasses") && !$force_reload){
1246 $objectclasses = session::global_get("LDAP_CACHE::get_objectclasses");
1247 return($objectclasses);
1248 }
1250 # Get base to look for schema
1251 $sr = @ldap_read ($this->cid, "", "objectClass=*", array("subschemaSubentry"));
1252 $attr = @ldap_get_entries($this->cid,$sr);
1253 if (!isset($attr[0]['subschemasubentry'][0])){
1254 return array();
1255 }
1257 /* Get list of objectclasses and fill array */
1258 $nb= $attr[0]['subschemasubentry'][0];
1259 $objectclasses= array();
1260 $sr= ldap_read ($this->cid, $nb, "objectClass=*", array("objectclasses"));
1261 $attrs= ldap_get_entries($this->cid,$sr);
1262 if (!isset($attrs[0])){
1263 return array();
1264 }
1265 foreach ($attrs[0]['objectclasses'] as $val){
1266 if (preg_match('/^[0-9]+$/', $val)){
1267 continue;
1268 }
1269 $name= "OID";
1270 $pattern= split(' ', $val);
1271 $ocname= preg_replace("/^.* NAME\s+\(*\s*'([^']+)'\s*\)*.*$/", '\\1', $val);
1272 $objectclasses[$ocname]= array();
1274 foreach($pattern as $chunk){
1275 switch($chunk){
1277 case '(':
1278 $value= "";
1279 break;
1281 case ')': if ($name != ""){
1282 $objectclasses[$ocname][$name]= $this->value2container($value);
1283 }
1284 $name= "";
1285 $value= "";
1286 break;
1288 case 'NAME':
1289 case 'DESC':
1290 case 'SUP':
1291 case 'STRUCTURAL':
1292 case 'ABSTRACT':
1293 case 'AUXILIARY':
1294 case 'MUST':
1295 case 'MAY':
1296 if ($name != ""){
1297 $objectclasses[$ocname][$name]= $this->value2container($value);
1298 }
1299 $name= $chunk;
1300 $value= "";
1301 break;
1303 default: $value.= $chunk." ";
1304 }
1305 }
1307 }
1308 if(class_available("session")){
1309 session::global_set("LDAP_CACHE::get_objectclasses",$objectclasses);
1310 }
1312 return $objectclasses;
1313 }
1316 function value2container($value)
1317 {
1318 /* Set emtpy values to "true" only */
1319 if (preg_match('/^\s*$/', $value)){
1320 return true;
1321 }
1323 /* Remove ' and " if needed */
1324 $value= preg_replace('/^[\'"]/', '', $value);
1325 $value= preg_replace('/[\'"] *$/', '', $value);
1327 /* Convert to array if $ is inside... */
1328 if (preg_match('/\$/', $value)){
1329 $container= preg_split('/\s*\$\s*/', $value);
1330 } else {
1331 $container= chop($value);
1332 }
1334 return ($container);
1335 }
1338 function log($string)
1339 {
1340 if (session::global_is_set('config')){
1341 $cfg = session::global_get('config');
1342 if (isset($cfg->current['LDAPSTATS']) && preg_match('/true/i', $cfg->current['LDAPSTATS'])){
1343 syslog (LOG_INFO, $string);
1344 }
1345 }
1346 }
1348 /* added by Guido Serra aka Zeph <zeph@purotesto.it> */
1349 function getCn($dn){
1350 $simple= split(",", $dn);
1352 foreach($simple as $piece) {
1353 $partial= split("=", $piece);
1355 if($partial[0] == "cn"){
1356 return $partial[1];
1357 }
1358 }
1359 }
1362 function get_naming_contexts($server, $admin= "", $password= "")
1363 {
1364 /* Build LDAP connection */
1365 $ds= ldap_connect ($server);
1366 if (!$ds) {
1367 die ("Can't bind to LDAP. No check possible!");
1368 }
1369 ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
1370 $r= ldap_bind ($ds, $admin, $password);
1372 /* Get base to look for naming contexts */
1373 $sr = @ldap_read ($ds, "", "objectClass=*", array("+"));
1374 $attr= @ldap_get_entries($ds,$sr);
1376 return ($attr[0]['namingcontexts']);
1377 }
1380 function get_root_dse($server, $admin= "", $password= "")
1381 {
1382 /* Build LDAP connection */
1383 $ds= ldap_connect ($server);
1384 if (!$ds) {
1385 die ("Can't bind to LDAP. No check possible!");
1386 }
1387 ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
1388 $r= ldap_bind ($ds, $admin, $password);
1390 /* Get base to look for naming contexts */
1391 $sr = @ldap_read ($ds, "", "objectClass=*", array("+"));
1392 $attr= @ldap_get_entries($ds,$sr);
1394 /* Return empty array, if nothing was set */
1395 if (!isset($attr[0])){
1396 return array();
1397 }
1399 /* Rework array... */
1400 $result= array();
1401 for ($i= 0; $i<$attr[0]['count']; $i++){
1402 $result[$attr[0][$i]]= $attr[0][$attr[0][$i]];
1403 unset($result[$attr[0][$i]]['count']);
1404 }
1406 return ($result);
1407 }
1409 }
1410 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
1411 ?>