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 rename($attrs, $dn = "")
431 {
432 if($this->hascon){
433 if ($this->reconnect) $this->connect();
434 if ($dn == "")
435 $dn = $this->basedn;
437 $r = @ldap_mod_replace($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 rmdir($deletedn)
447 {
448 if($this->hascon){
449 if ($this->reconnect) $this->connect();
450 $r = @ldap_delete($this->cid, LDAP::fix($deletedn));
451 $this->error = @ldap_error($this->cid);
452 return($r ? $r : 0);
453 }else{
454 $this->error = "Could not connect to LDAP server";
455 return("");
456 }
457 }
460 /*! \brief Move the given Ldap entry from $source to $dest
461 @param String $source The source dn.
462 @param String $dest The destination dn.
463 @return Boolean TRUE on success else FALSE.
464 */
465 function rename_dn($source,$dest)
466 {
467 /* Check if source and destination are the same entry */
468 if(strtolower($source) == strtolower($dest)){
469 trigger_error("Source and destination can't be the same entry.");
470 $this->error = "Source and destination can't be the same entry.";
471 return(FALSE);
472 }
474 /* Check if destination entry exists */
475 if($this->dn_exists($dest)){
476 trigger_error("Destination '$dest' already exists.");
477 $this->error = "Destination '$dest' already exists.";
478 return(FALSE);
479 }
481 /* Extract the name and the parent part out ouf source dn.
482 e.g. cn=herbert,ou=department,dc=...
483 parent => ou=department,dc=...
484 dest_rdn => cn=herbert
485 */
486 $parent = preg_replace("/^[^,]+,/","", $dest);
487 $dest_rdn = preg_replace("/,.*$/","",$dest);
489 if($this->hascon){
490 if ($this->reconnect) $this->connect();
491 $r= ldap_rename($this->cid,@LDAP::fix($source), @LDAP::fix($dest_rdn),@LDAP::fix($parent),TRUE);
492 $this->error = ldap_error($this->cid);
494 /* Check if destination dn exists, if not the
495 server may not support this operation */
496 $r &= is_resource($this->dn_exists($dest));
497 return($r);
498 }else{
499 $this->error = "Could not connect to LDAP server";
500 return(FALSE);
501 }
502 }
505 /**
506 * Function rmdir_recursive
507 *
508 * Description: Based in recursive_remove, adding two thing: full subtree remove, and delete own node.
509 * Parameters: The dn to delete
510 * GiveBack: True on sucessfull , 0 in error, and "" when we don't get a ldap conection
511 *
512 */
513 function rmdir_recursive($srp, $deletedn)
514 {
515 if($this->hascon){
516 if ($this->reconnect) $this->connect();
517 $delarray= array();
519 /* Get sorted list of dn's to delete */
520 $this->ls ($srp, "(objectClass=*)",$deletedn);
521 while ($this->fetch($srp)){
522 $deldn= $this->getDN($srp);
523 $delarray[$deldn]= strlen($deldn);
524 }
525 arsort ($delarray);
526 reset ($delarray);
528 /* Really Delete ALL dn's in subtree */
529 foreach ($delarray as $key => $value){
530 $this->rmdir_recursive($srp, $key);
531 }
533 /* Finally Delete own Node */
534 $r = @ldap_delete($this->cid, LDAP::fix($deletedn));
535 $this->error = @ldap_error($this->cid);
536 return($r ? $r : 0);
537 }else{
538 $this->error = "Could not connect to LDAP server";
539 return("");
540 }
541 }
544 function modify($attrs)
545 {
546 if(count($attrs) == 0){
547 return (0);
548 }
549 if($this->hascon){
550 if ($this->reconnect) $this->connect();
551 $r = @ldap_modify($this->cid, LDAP::fix($this->basedn), $attrs);
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 add($attrs)
561 {
562 if($this->hascon){
563 if ($this->reconnect) $this->connect();
564 $r = @ldap_add($this->cid, LDAP::fix($this->basedn), $attrs);
565 $this->error = @ldap_error($this->cid);
566 return($r ? $r : 0);
567 }else{
568 $this->error = "Could not connect to LDAP server";
569 return("");
570 }
571 }
573 function create_missing_trees($srp, $target)
574 {
575 global $config;
577 $real_path= substr($target, 0, strlen($target) - strlen($this->basedn) -1 );
579 if ($target == $this->basedn){
580 $l= array("dummy");
581 } else {
582 $l= array_reverse(gosa_ldap_explode_dn($real_path));
583 }
584 unset($l['count']);
585 $cdn= $this->basedn;
586 $tag= "";
588 /* Load schema if available... */
589 $classes= $this->get_objectclasses();
591 foreach ($l as $part){
592 if ($part != "dummy"){
593 $cdn= "$part,$cdn";
594 }
596 /* Ignore referrals */
597 $found= false;
598 foreach($this->referrals as $ref){
599 $base= preg_replace('!^[^:]+://[^/]+/([^?]+).*$!', '\\1', $ref['URI']);
600 if ($base == $cdn){
601 $found= true;
602 break;
603 }
604 }
605 if ($found){
606 continue;
607 }
609 $this->cat ($srp, $cdn);
610 $attrs= $this->fetch($srp);
612 /* Create missing entry? */
613 if (count ($attrs)){
615 /* Catch the tag - if present */
616 if (isset($attrs['gosaUnitTag'][0])){
617 $tag= $attrs['gosaUnitTag'][0];
618 }
620 } else {
621 $type= preg_replace('/^([^=]+)=.*$/', '\\1', $cdn);
622 $param= preg_replace('/^[^=]+=([^,]+).*$/', '\\1', $cdn);
624 $na= array();
626 /* Automatic or traditional? */
627 if(count($classes)){
629 /* Get name of first matching objectClass */
630 $ocname= "";
631 foreach($classes as $class){
632 if (isset($class['MUST']) && $class['MUST'] == "$type"){
634 /* Look for first classes that is structural... */
635 if (isset($class['STRUCTURAL'])){
636 $ocname= $class['NAME'];
637 break;
638 }
640 /* Look for classes that are auxiliary... */
641 if (isset($class['AUXILIARY'])){
642 $ocname= $class['NAME'];
643 }
644 }
645 }
647 /* Bail out, if we've nothing to do... */
648 if ($ocname == ""){
649 msg_dialog::display(_("Internal error"), sprintf(_("Cannot automatically create subtrees with RDN '%s': no object class found!"),$type), FATAL_ERROR_DIALOG);
650 exit();
651 }
653 /* Assemble_entry */
654 if ($tag != ""){
655 $na['objectClass']= array($ocname, "gosaAdministrativeUnitTag");
656 $na["gosaUnitTag"]= $tag;
657 } else {
658 $na['objectClass']= array($ocname);
659 }
660 if (isset($classes[$ocname]['AUXILIARY'])){
661 $na['objectClass'][]= $classes[$ocname]['SUP'];
662 }
663 if ($type == "dc"){
664 /* This is bad actually, but - tell me a better way? */
665 $na['objectClass'][]= 'locality';
666 }
667 $na[$type]= $param;
668 if (is_array($classes[$ocname]['MUST'])){
669 foreach($classes[$ocname]['MUST'] as $attr){
670 $na[$attr]= "filled";
671 }
672 }
674 } else {
676 /* Use alternative add... */
677 switch ($type){
678 case 'ou':
679 if ($tag != ""){
680 $na["objectClass"]= array("organizationalUnit", "gosaAdministrativeUnitTag");
681 $na["gosaUnitTag"]= $tag;
682 } else {
683 $na["objectClass"]= "organizationalUnit";
684 }
685 $na["ou"]= $param;
686 break;
687 case 'dc':
688 if ($tag != ""){
689 $na["objectClass"]= array("dcObject", "top", "locality", "gosaAdministrativeUnitTag");
690 $na["gosaUnitTag"]= $tag;
691 } else {
692 $na["objectClass"]= array("dcObject", "top", "locality");
693 }
694 $na["dc"]= $param;
695 break;
696 default:
697 msg_dialog::display(_("Internal error"), sprintf(_("Cannot automatically create subtrees with RDN '%s': not supported"),$type), FATAL_ERROR_DIALOG);
698 exit();
699 }
701 }
702 $this->cd($cdn);
703 $this->add($na);
705 if (!$this->success()){
707 print_a(array($cdn,$na));
709 msg_dialog::display(_("LDAP error"), msgPool::ldaperror($this->get_error(), $cdn, LDAP_ADD, get_class()));
710 return FALSE;
711 }
712 }
713 }
715 return TRUE;
716 }
719 function recursive_remove($srp)
720 {
721 $delarray= array();
723 /* Get sorted list of dn's to delete */
724 $this->search ($srp, "(objectClass=*)");
725 while ($this->fetch($srp)){
726 $deldn= $this->getDN($srp);
727 $delarray[$deldn]= strlen($deldn);
728 }
729 arsort ($delarray);
730 reset ($delarray);
732 /* Delete all dn's in subtree */
733 foreach ($delarray as $key => $value){
734 $this->rmdir($key);
735 }
736 }
738 function get_attribute($dn, $name,$r_array=0)
739 {
740 $data= "";
741 if ($this->reconnect) $this->connect();
742 $sr= @ldap_read($this->cid, LDAP::fix($dn), "objectClass=*", array("$name"));
744 /* fill data from LDAP */
745 if ($sr) {
746 $ei= @ldap_first_entry($this->cid, $sr);
747 if ($ei) {
748 if ($info= @ldap_get_values_len($this->cid, $ei, "$name")){
749 $data= $info[0];
750 }
751 }
752 }
753 if($r_array==0)
754 return ($data);
755 else
756 return ($info);
759 }
763 function get_additional_error()
764 {
765 $error= "";
766 @ldap_get_option ($this->cid, LDAP_OPT_ERROR_STRING, $error);
767 return ($error);
768 }
771 function success()
772 {
773 return (preg_match('/Success/i', $this->error));
774 }
777 function get_error()
778 {
779 if ($this->error == 'Success'){
780 return $this->error;
781 } else {
782 $adderror= $this->get_additional_error();
783 if ($adderror != ""){
784 $error= $this->error." (".$this->get_additional_error().", ".sprintf(_("while operating on '%s' using LDAP server '%s'"), $this->basedn, $this->hostname).")";
785 } else {
786 $error= $this->error." (".sprintf(_("while operating on LDAP server %s"), $this->hostname).")";
787 }
788 return $error;
789 }
790 }
792 function get_credentials($url, $referrals= NULL)
793 {
794 $ret= array();
795 $url= preg_replace('!\?\?.*$!', '', $url);
796 $server= preg_replace('!^([^:]+://[^/]+)/.*$!', '\\1', $url);
798 if ($referrals === NULL){
799 $referrals= $this->referrals;
800 }
802 if (isset($referrals[$server])){
803 return ($referrals[$server]);
804 } else {
805 $ret['ADMINDN']= LDAP::fix($this->binddn);
806 $ret['ADMINPASSWORD']= $this->bindpw;
807 }
809 return ($ret);
810 }
813 function gen_ldif ($srp, $dn, $filter= "(objectClass=*)", $attributes= array('*'), $recursive= TRUE)
814 {
815 $display= "";
817 if ($recursive){
818 $this->cd($dn);
819 $this->ls($srp, $filter,$dn, array('dn','objectClass'));
820 $deps = array();
822 $display .= $this->gen_one_entry($dn)."\n";
824 while ($attrs= $this->fetch($srp)){
825 $deps[] = $attrs['dn'];
826 }
827 foreach($deps as $dn){
828 $display .= $this->gen_ldif($srp, $dn, $filter,$attributes,$recursive);
829 }
830 } else {
831 $display.= $this->gen_one_entry($dn);
832 }
833 return ($display);
834 }
837 function gen_xls ($srp, $dn, $filter= "(objectClass=*)", $attributes= array('*'), $recursive= TRUE,$r_array=0)
838 {
839 $display= array();
841 $this->cd($dn);
842 $this->search($srp, "$filter");
844 $i=0;
845 while ($attrs= $this->fetch($srp)){
846 $j=0;
848 foreach ($attributes as $at){
849 $display[$i][$j]= $this->get_attribute($attrs['dn'], $at,$r_array);
850 $j++;
851 }
853 $i++;
854 }
856 return ($display);
857 }
860 function gen_one_entry($dn, $filter= "(objectClass=*)" , $name= array("*"))
861 {
862 $ret = "";
863 $data = "";
864 if($this->reconnect){
865 $this->connect();
866 }
868 /* Searching Ldap Tree */
869 $sr= @ldap_read($this->cid, LDAP::fix($dn), $filter, $name);
871 /* Get the first entry */
872 $entry= @ldap_first_entry($this->cid, $sr);
874 /* Get all attributes related to that Objekt */
875 $atts = array();
877 /* Assemble dn */
878 $atts[0]['name'] = "dn";
879 $atts[0]['value'] = array('count' => 1, 0 => $dn);
881 /* Reset index */
882 $i = 1 ;
883 $identifier = array();
884 $attribute= @ldap_first_attribute($this->cid,$entry,$identifier);
885 while ($attribute) {
886 $i++;
887 $atts[$i]['name'] = $attribute;
888 $atts[$i]['value'] = @ldap_get_values_len($this->cid, $entry, "$attribute");
890 /* Next one */
891 $attribute= @ldap_next_attribute($this->cid,$entry,$identifier);
892 }
894 foreach($atts as $at)
895 {
896 for ($i= 0; $i<$at['value']['count']; $i++){
898 /* Check if we must encode the data */
899 if(!preg_match('/^[a-z0-9+@#.=, \/ -]+$/i', $at['value'][$i])) {
900 $ret .= $at['name'].":: ".base64_encode($at['value'][$i])."\n";
901 } else {
902 $ret .= $at['name'].": ".$at['value'][$i]."\n";
903 }
904 }
905 }
907 return($ret);
908 }
911 function dn_exists($dn)
912 {
913 return @ldap_list($this->cid, LDAP::fix($dn), "(objectClass=*)", array("objectClass"));
914 }
918 /* This funktion imports ldifs
920 If DeleteOldEntries is true, the destination entry will be deleted first.
921 If JustModify is true the destination entry will only be touched by the attributes specified in the ldif.
922 if JustMofify id false the destination dn will be overwritten by the new ldif.
923 */
925 function import_complete_ldif($srp, $str_attr,$error,$JustModify,$DeleteOldEntries)
926 {
927 if($this->reconnect) $this->connect();
929 /* First we have to splitt the string ito detect empty lines
930 An empty line indicates an new Entry */
931 $entries = split("\n",$str_attr);
933 $data = "";
934 $cnt = 0;
935 $current_line = 0;
937 /* FIX ldif */
938 $last = "";
939 $tmp = "";
940 $i = 0;
941 foreach($entries as $entry){
942 if(preg_match("/^ /",$entry)){
943 $tmp[$i] .= trim($entry);
944 }else{
945 $i ++;
946 $tmp[$i] = trim($entry);
947 }
948 }
950 /* Every single line ... */
951 foreach($tmp as $entry) {
952 $current_line ++;
954 /* Removing Spaces to ..
955 .. test if a new entry begins */
956 $tmp = str_replace(" ","",$data );
958 /* .. prevent empty lines in an entry */
959 $tmp2 = str_replace(" ","",$entry);
961 /* If the Block ends (Empty Line) */
962 if((empty($entry))&&(!empty($tmp))) {
963 /* Add collected lines as a complete block */
964 $all[$cnt] = $data;
965 $cnt ++;
966 $data ="";
967 } else {
969 /* Append lines ... */
970 if(!empty($tmp2)) {
971 /* check if we need base64_decode for this line */
972 if(ereg("::",$tmp2))
973 {
974 $encoded = split("::",$entry);
975 $attr = trim($encoded[0]);
976 $value = base64_decode(trim($encoded[1]));
977 /* Add linenumber */
978 $data .= $current_line."#".base64_encode($attr.":".$value)."\n";
979 }
980 else
981 {
982 /* Add Linenumber */
983 $data .= $current_line."#".base64_encode($entry)."\n";
984 }
985 }
986 }
987 }
989 /* The Data we collected is not in the array all[];
990 For example the Data is stored like this..
992 all[0] = "1#dn : .... \n
993 2#ObjectType: person \n ...."
995 Now we check every insertblock and try to insert */
996 foreach ( $all as $single) {
997 $lineone = split("\n",$single);
998 $ndn = split("#", $lineone[0]);
999 $line = base64_decode($ndn[1]);
1001 $dnn = split (":",$line,2);
1002 $current_line = $ndn[0];
1003 $dn = $dnn[0];
1004 $value = $dnn[1];
1006 /* Every block must begin with a dn */
1007 if($dn != "dn") {
1008 $error= sprintf(_("This is not a valid DN: '%s'. A block for import should begin with 'dn: ...' in line %s"), $line, $current_line);
1009 return -2;
1010 }
1012 /* Should we use Modify instead of Add */
1013 $usemodify= false;
1015 /* Delete before insert */
1016 $usermdir= false;
1018 /* The dn address already exists, Don't delete destination entry, overwrite it */
1019 if (($this->dn_exists($value))&&((!$JustModify)&&(!$DeleteOldEntries))) {
1021 $usermdir = $usemodify = false;
1023 /* Delete old entry first, then add new */
1024 } elseif(($this->dn_exists($value))&&($DeleteOldEntries)){
1026 /* Delete first, then add */
1027 $usermdir = true;
1029 } elseif(($this->dn_exists($value))&&($JustModify)) {
1031 /* Modify instead of Add */
1032 $usemodify = true;
1033 }
1035 /* If we can't Import, return with a file error */
1036 if(!$this->import_single_entry($srp, $single,$usemodify,$usermdir) ) {
1037 $error= sprintf(_("Error while importing dn: '%s', please check your LDIF from line %s on!"), $line,
1038 $current_line);
1039 return UNKNOWN_TOKEN_IN_LDIF_FILE; }
1040 }
1042 return (INSERT_OK);
1043 }
1046 /* Imports a single entry
1047 If $delete is true; The old entry will be deleted if it exists.
1048 if $modify is true; All variables that are not touched by the new ldif will be kept.
1049 if $modify is false; The new ldif overwrites the old entry, and all untouched attributes get lost.
1050 */
1051 function import_single_entry($srp, $str_attr,$modify,$delete)
1052 {
1053 global $config;
1055 if(!$config){
1056 trigger_error("Can't import ldif, can't read config object.");
1057 }
1060 if($this->reconnect) $this->connect();
1062 $ret = false;
1063 $rows= split("\n",$str_attr);
1064 $data= false;
1066 foreach($rows as $row) {
1068 /* Check if we use Linenumbers (when import_complete_ldif is called we use
1069 Linenumbers) Linenumbers are use like this 123#attribute : value */
1070 if(!empty($row)) {
1071 if(strpos($row,"#")!=FALSE) {
1073 /* We are using line numbers
1074 Because there is a # before a : */
1075 $tmp1= split("#",$row);
1076 $current_line= $tmp1[0];
1077 $row= base64_decode($tmp1[1]);
1078 }
1080 /* Split the line into attribute and value */
1081 $attr = split(":", $row,2);
1082 $attr[0]= trim($attr[0]); /* attribute */
1083 $attr[1]= $attr[1]; /* value */
1085 /* Check :: was used to indicate base64_encoded strings */
1086 if($attr[1][0] == ":"){
1087 $attr[1]=trim(preg_replace("/^:/","",$attr[1]));
1088 $attr[1]=base64_decode($attr[1]);
1089 }
1091 $attr[1] = trim($attr[1]);
1093 /* Check for attributes that are used more than once */
1094 if(!isset($data[$attr[0]])) {
1095 $data[$attr[0]]=$attr[1];
1096 } else {
1097 $tmp = $data[$attr[0]];
1099 if(!is_array($tmp)) {
1100 $new[0]=$tmp;
1101 $new[1]=$attr[1];
1102 $datas[$attr[0]]['count']=1;
1103 $data[$attr[0]]=$new;
1104 } else {
1105 $cnt = $datas[$attr[0]]['count'];
1106 $cnt ++;
1107 $data[$attr[0]][$cnt]=$attr[1];
1108 $datas[$attr[0]]['count'] = $cnt;
1109 }
1110 }
1111 }
1112 }
1114 /* If dn is an index of data, we should try to insert the data */
1115 if(isset($data['dn'])) {
1117 /* Fix dn */
1118 $tmp = gosa_ldap_explode_dn($data['dn']);
1119 unset($tmp['count']);
1120 $newdn ="";
1121 foreach($tmp as $tm){
1122 $newdn.= trim($tm).",";
1123 }
1124 $newdn = preg_replace("/,$/","",$newdn);
1125 $data['dn'] = $newdn;
1127 /* Creating Entry */
1128 $this->cd($data['dn']);
1130 /* Delete existing entry */
1131 if($delete){
1132 $this->rmdir_recursive($srp, $data['dn']);
1133 }
1135 /* Create missing trees */
1136 $this->cd ($this->basedn);
1137 $this->cd($config->current['BASE']);
1138 $this->create_missing_trees($srp, preg_replace("/^[^,]+,/","",$data['dn']));
1139 $this->cd($data['dn']);
1141 $dn = $data['dn'];
1142 unset($data['dn']);
1144 if(!$modify){
1146 $this->cat($srp, $dn);
1147 if($this->count($srp)){
1149 /* The destination entry exists, overwrite it with the new entry */
1150 $attrs = $this->fetch($srp);
1151 foreach($attrs as $name => $value ){
1152 if(!is_numeric($name)){
1153 if(in_array($name,array("dn","count"))) continue;
1154 if(!isset($data[$name])){
1155 $data[$name] = array();
1156 }
1157 }
1158 }
1159 $ret = $this->modify($data);
1161 }else{
1163 /* The destination entry doesn't exists, create it */
1164 $ret = $this->add($data);
1165 }
1167 } else {
1169 /* Keep all vars that aren't touched by this ldif */
1170 $ret = $this->modify($data);
1171 }
1172 }
1174 if (!$this->success()){
1175 msg_dialog::display(_("LDAP error"), msgPool::ldaperror($this->get_error(), $dn, "", get_class()));
1176 }
1178 return($ret);
1179 }
1182 function importcsv($str)
1183 {
1184 $lines = split("\n",$str);
1185 foreach($lines as $line)
1186 {
1187 /* continue if theres a comment */
1188 if(substr(trim($line),0,1)=="#"){
1189 continue;
1190 }
1192 $line= str_replace ("\t\t","\t",$line);
1193 $line= str_replace ("\t" ,"," ,$line);
1194 echo $line;
1196 $cells = split(",",$line ) ;
1197 $linet= str_replace ("\t\t",",",$line);
1198 $cells = split("\t",$line);
1199 $count = count($cells);
1200 }
1202 }
1204 function get_objectclasses( $force_reload = FALSE)
1205 {
1206 $objectclasses = array();
1207 global $config;
1209 /* Only read schema if it is allowed */
1210 if(isset($config) && preg_match("/config/i",get_class($config))){
1211 if ($config->get_cfg_value("schemaCheck") != "true"){
1212 return($objectclasses);
1213 }
1214 }
1216 /* Return the cached results. */
1217 if(class_available('session') && session::global_is_set("LDAP_CACHE::get_objectclasses") && !$force_reload){
1218 $objectclasses = session::global_get("LDAP_CACHE::get_objectclasses");
1219 return($objectclasses);
1220 }
1222 # Get base to look for schema
1223 $sr = @ldap_read ($this->cid, "", "objectClass=*", array("subschemaSubentry"));
1224 $attr = @ldap_get_entries($this->cid,$sr);
1225 if (!isset($attr[0]['subschemasubentry'][0])){
1226 return array();
1227 }
1229 /* Get list of objectclasses and fill array */
1230 $nb= $attr[0]['subschemasubentry'][0];
1231 $objectclasses= array();
1232 $sr= ldap_read ($this->cid, $nb, "objectClass=*", array("objectclasses"));
1233 $attrs= ldap_get_entries($this->cid,$sr);
1234 if (!isset($attrs[0])){
1235 return array();
1236 }
1237 foreach ($attrs[0]['objectclasses'] as $val){
1238 if (preg_match('/^[0-9]+$/', $val)){
1239 continue;
1240 }
1241 $name= "OID";
1242 $pattern= split(' ', $val);
1243 $ocname= preg_replace("/^.* NAME\s+\(*\s*'([^']+)'\s*\)*.*$/", '\\1', $val);
1244 $objectclasses[$ocname]= array();
1246 foreach($pattern as $chunk){
1247 switch($chunk){
1249 case '(':
1250 $value= "";
1251 break;
1253 case ')': if ($name != ""){
1254 $objectclasses[$ocname][$name]= $this->value2container($value);
1255 }
1256 $name= "";
1257 $value= "";
1258 break;
1260 case 'NAME':
1261 case 'DESC':
1262 case 'SUP':
1263 case 'STRUCTURAL':
1264 case 'ABSTRACT':
1265 case 'AUXILIARY':
1266 case 'MUST':
1267 case 'MAY':
1268 if ($name != ""){
1269 $objectclasses[$ocname][$name]= $this->value2container($value);
1270 }
1271 $name= $chunk;
1272 $value= "";
1273 break;
1275 default: $value.= $chunk." ";
1276 }
1277 }
1279 }
1280 if(class_available("session")){
1281 session::global_set("LDAP_CACHE::get_objectclasses",$objectclasses);
1282 }
1284 return $objectclasses;
1285 }
1288 function value2container($value)
1289 {
1290 /* Set emtpy values to "true" only */
1291 if (preg_match('/^\s*$/', $value)){
1292 return true;
1293 }
1295 /* Remove ' and " if needed */
1296 $value= preg_replace('/^[\'"]/', '', $value);
1297 $value= preg_replace('/[\'"] *$/', '', $value);
1299 /* Convert to array if $ is inside... */
1300 if (preg_match('/\$/', $value)){
1301 $container= preg_split('/\s*\$\s*/', $value);
1302 } else {
1303 $container= chop($value);
1304 }
1306 return ($container);
1307 }
1310 function log($string)
1311 {
1312 if (session::global_is_set('config')){
1313 $cfg = session::global_get('config');
1314 if (isset($cfg->current['LDAPSTATS']) && preg_match('/true/i', $cfg->current['LDAPSTATS'])){
1315 syslog (LOG_INFO, $string);
1316 }
1317 }
1318 }
1320 /* added by Guido Serra aka Zeph <zeph@purotesto.it> */
1321 function getCn($dn){
1322 $simple= split(",", $dn);
1324 foreach($simple as $piece) {
1325 $partial= split("=", $piece);
1327 if($partial[0] == "cn"){
1328 return $partial[1];
1329 }
1330 }
1331 }
1334 function get_naming_contexts($server, $admin= "", $password= "")
1335 {
1336 /* Build LDAP connection */
1337 $ds= ldap_connect ($server);
1338 if (!$ds) {
1339 die ("Can't bind to LDAP. No check possible!");
1340 }
1341 ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
1342 $r= ldap_bind ($ds, $admin, $password);
1344 /* Get base to look for naming contexts */
1345 $sr = @ldap_read ($ds, "", "objectClass=*", array("+"));
1346 $attr= @ldap_get_entries($ds,$sr);
1348 return ($attr[0]['namingcontexts']);
1349 }
1352 function get_root_dse($server, $admin= "", $password= "")
1353 {
1354 /* Build LDAP connection */
1355 $ds= ldap_connect ($server);
1356 if (!$ds) {
1357 die ("Can't bind to LDAP. No check possible!");
1358 }
1359 ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
1360 $r= ldap_bind ($ds, $admin, $password);
1362 /* Get base to look for naming contexts */
1363 $sr = @ldap_read ($ds, "", "objectClass=*", array("+"));
1364 $attr= @ldap_get_entries($ds,$sr);
1366 /* Return empty array, if nothing was set */
1367 if (!isset($attr[0])){
1368 return array();
1369 }
1371 /* Rework array... */
1372 $result= array();
1373 for ($i= 0; $i<$attr[0]['count']; $i++){
1374 $result[$attr[0][$i]]= $attr[0][$attr[0][$i]];
1375 unset($result[$attr[0][$i]]['count']);
1376 }
1378 return ($result);
1379 }
1381 }
1382 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
1383 ?>