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 $hasres =false;
35 var $reconnect=false;
36 var $tls = false;
37 var $basedn ="";
38 var $cid;
39 var $error = ""; // Any error messages to be returned can be put here
40 var $start = 0; // 0 if we are fetching the first entry, otherwise 1
41 var $objectClasses = array(); // Information read from slapd.oc.conf
42 var $binddn = "";
43 var $bindpw = "";
44 var $hostname = "";
45 var $follow_referral = FALSE;
46 var $referrals= array();
47 var $max_ldap_query_time = 0; // 0, empty or negative values will disable this check
49 var $re = NULL;
51 function LDAP($binddn,$bindpw, $hostname, $follow_referral= FALSE, $tls= FALSE)
52 {
53 global $config;
54 $this->follow_referral= $follow_referral;
55 $this->tls=$tls;
56 $this->binddn=LDAP::convert($binddn);
58 $this->bindpw=$bindpw;
59 $this->hostname=$hostname;
61 /* Check if MAX_LDAP_QUERY_TIME is defined */
62 if(isset($config->data['MAIN']['MAX_LDAP_QUERY_TIME'])){
63 $str = $config->data['MAIN']['MAX_LDAP_QUERY_TIME'];
64 $this->max_ldap_query_time = (float)($str);
65 }
67 $this->connect();
68 }
71 /* Function to replace all problematic characters inside a DN by \001XX, where
72 \001 is decoded to chr(1) [ctrl+a]. It is not impossible, but very unlikely
73 that this character is inside a DN.
75 Currently used codes:
76 , => CO
77 \2C => CO
78 ( => OB
79 ) => CB
80 / => SL */
81 static function convert($dn)
82 {
83 if (SPECIALS_OVERRIDE == TRUE){
84 $tmp= preg_replace(array("/\\\\,/", "/\\\\2C/", "/\(/", "/\)/", "/\//"),
85 array("\001CO", "\001CO", "\001OB", "\001CB", "\001SL"),
86 $dn);
87 return (preg_replace('/,\s+/', ',', $tmp));
88 } else {
89 return ($dn);
90 }
91 }
94 /* Function to fix all problematic characters inside a DN by replacing \001XX
95 codes to their original values. See "convert" for mor information.
96 ',' characters are always expanded to \, (not \2C), since all tested LDAP
97 servers seem to take it the correct way. */
98 static function fix($dn)
99 {
100 if (SPECIALS_OVERRIDE == TRUE){
101 return (preg_replace(array("/\001CO/", "/\001OB/", "/\001CB/", "/\001SL/"),
102 array("\,", "(", ")", "/"),
103 $dn));
104 } else {
105 return ($dn);
106 }
107 }
110 /* Function to fix problematic characters in DN's that are used for search
111 requests. I.e. member=.... */
112 static function prepare4filter($dn)
113 {
114 return normalizeLdap(preg_replace('/\\\\/', '\\\\\\', LDAP::fix($dn)));
115 }
118 function connect()
119 {
120 $this->hascon=false;
121 $this->reconnect=false;
122 if ($this->cid= @ldap_connect($this->hostname)) {
123 @ldap_set_option($this->cid, LDAP_OPT_PROTOCOL_VERSION, 3);
124 if (function_exists("ldap_set_rebind_proc") && $this->follow_referral) {
125 @ldap_set_option($this->cid, LDAP_OPT_REFERRALS, 1);
126 @ldap_set_rebind_proc($this->cid, array(&$this, "rebind"));
127 }
128 if (function_exists("ldap_start_tls") && $this->tls){
129 @ldap_start_tls($this->cid);
130 }
132 $this->error = "No Error";
133 if ($bid = @ldap_bind($this->cid, LDAP::fix($this->binddn), $this->bindpw)) {
134 $this->error = "Success";
135 $this->hascon=true;
136 } else {
137 if ($this->reconnect){
138 if ($this->error != "Success"){
139 $this->error = "Could not rebind to " . $this->binddn;
140 }
141 } else {
142 $this->error = "Could not bind to " . $this->binddn;
143 }
144 }
145 } else {
146 $this->error = "Could not connect to LDAP server";
147 }
148 }
150 function rebind($ldap, $referral)
151 {
152 $credentials= $this->get_credentials($referral);
153 if (@ldap_bind($ldap, LDAP::fix($credentials['ADMIN']), $credentials['PASSWORD'])) {
154 $this->error = "Success";
155 $this->hascon=true;
156 $this->reconnect= true;
157 return (0);
158 } else {
159 $this->error = "Could not bind to " . $credentials['ADMIN'];
160 return NULL;
161 }
162 }
164 function reconnect()
165 {
166 if ($this->reconnect){
167 @ldap_unbind($this->cid);
168 $this->cid = NULL;
169 }
170 }
172 function unbind()
173 {
174 @ldap_unbind($this->cid);
175 $this->cid = NULL;
176 }
178 function disconnect()
179 {
180 if($this->hascon){
181 @ldap_close($this->cid);
182 $this->hascon=false;
183 }
184 }
186 function cd($dir)
187 {
188 if ($dir == "..")
189 $this->basedn = $this->getParentDir();
190 else
191 $this->basedn = LDAP::convert($dir);
192 }
194 function getParentDir($basedn = "")
195 {
196 if ($basedn=="")
197 $basedn = $this->basedn;
198 else
199 $basedn = LDAP::convert($this->basedn);
200 return(ereg_replace("[^,]*[,]*[ ]*(.*)", "\\1", $basedn));
201 }
204 # /* Checks if there is still unfetched data
205 # */
206 # function checkResult()
207 # {
208 # /* Check if we have started a search before */
209 # if($this->start != 0 && $this->re){
210 #
211 # /* Check if there are still unfetched elements */
212 # if(is_resource(@ldap_next_entry($this->cid, $this->re))){
213 # new log("debug","LDAP:: CAT/SEARCH/FETCH","A new search was initiated while an older search wasn't fetched completely.");
214 # msg_dialog::display(_("Debug"),"A new search was initiated while an older search wasn't fetched completely.",ERROR_DIALOG);
215 # trigger_error("A new search was initiated while an older search wasn't fetched completely.");
216 # }
217 # }
218 # }
219 #
220 function search($filter, $attrs= array())
221 {
222 if($this->hascon){
223 if ($this->reconnect) $this->connect();
225 # /* Check if there are still unfetched objects from last search
226 # */
227 # $this->checkResult();
229 $start = microtime();
230 $this->clearResult();
231 $this->sr = @ldap_search($this->cid, LDAP::fix($this->basedn), $filter, $attrs);
232 $this->error = @ldap_error($this->cid);
233 $this->resetResult();
234 $this->hasres=true;
236 /* Check if query took longer as specified in max_ldap_query_time */
237 if($this->max_ldap_query_time){
238 $diff = get_MicroTimeDiff($start,microtime());
239 if($diff > $this->max_ldap_query_time){
240 msg_dialog::display(_("Performance warning"), sprintf(_("LDAP performance is poor: last query took about %.2fs!"), $diff), WARNING_DIALOG);
241 }
242 }
244 $this->log("LDAP operation: time=".get_MicroTimeDiff($start,microtime())." operation=search('".LDAP::fix($this->basedn)."', '$filter')");
245 return($this->sr);
246 }else{
247 $this->error = "Could not connect to LDAP server";
248 return("");
249 }
250 }
252 function ls($filter = "(objectclass=*)", $basedn = "",$attrs = array("*"))
253 {
254 if($this->hascon){
255 if ($this->reconnect) $this->connect();
257 # /* Check if there are still unfetched objects from last search
258 # */
259 # $this->checkResult();
261 $this->clearResult();
262 if ($basedn == "")
263 $basedn = $this->basedn;
264 else
265 $basedn= LDAP::convert($basedn);
267 $start = microtime();
268 $this->sr = @ldap_list($this->cid, LDAP::fix($basedn), $filter,$attrs);
269 $this->error = @ldap_error($this->cid);
270 $this->resetResult();
271 $this->hasres=true;
273 /* Check if query took longer as specified in max_ldap_query_time */
274 if($this->max_ldap_query_time){
275 $diff = get_MicroTimeDiff($start,microtime());
276 if($diff > $this->max_ldap_query_time){
277 msg_dialog::display(_("Performance warning"), sprintf(_("LDAP performance is poor: last query took about %.2fs!"), $diff), WARNING_DIALOG);
278 }
279 }
281 $this->log("LDAP operation: time=".get_MicroTimeDiff($start,microtime())." operation=ls('".LDAP::fix($basedn)."', '$filter')");
283 return($this->sr);
284 }else{
285 $this->error = "Could not connect to LDAP server";
286 return("");
287 }
288 }
290 function cat($dn,$attrs= array("*"))
291 {
292 if($this->hascon){
293 if ($this->reconnect) $this->connect();
295 # /* Check if there are still unfetched objects from last search
296 # */
297 # $this->checkResult();
299 $this->clearResult();
300 $filter = "(objectclass=*)";
301 $this->sr = @ldap_read($this->cid, LDAP::fix($dn), $filter,$attrs);
302 $this->error = @ldap_error($this->cid);
303 $this->resetResult();
304 $this->hasres=true;
305 return($this->sr);
306 }else{
307 $this->error = "Could not connect to LDAP server";
308 return("");
309 }
310 }
312 function set_size_limit($size)
313 {
314 /* Ignore zero settings */
315 if ($size == 0){
316 @ldap_set_option($this->cid, LDAP_OPT_SIZELIMIT, 10000000);
317 }
318 if($this->hascon){
319 @ldap_set_option($this->cid, LDAP_OPT_SIZELIMIT, $size);
320 } else {
321 $this->error = "Could not connect to LDAP server";
322 }
323 }
325 function fetch()
326 {
327 $att= array();
328 if($this->hascon){
329 if($this->hasres){
330 if ($this->start == 0)
331 {
332 if ($this->sr){
333 $this->start = 1;
334 $this->re= @ldap_first_entry($this->cid, $this->sr);
335 } else {
336 return array();
337 }
338 } else {
339 $this->re= @ldap_next_entry($this->cid, $this->re);
340 }
341 if ($this->re)
342 {
343 $att= @ldap_get_attributes($this->cid, $this->re);
344 $att['dn']= trim(LDAP::convert(@ldap_get_dn($this->cid, $this->re)));
345 }
346 $this->error = @ldap_error($this->cid);
347 if (!isset($att)){
348 $att= array();
349 }
350 return($att);
351 }else{
352 $this->error = "Perform a Fetch with no Search";
353 return("");
354 }
355 }else{
356 $this->error = "Could not connect to LDAP server";
357 return("");
358 }
359 }
361 function resetResult()
362 {
363 $this->start = 0;
364 }
366 function clearResult()
367 {
368 if($this->hasres){
369 $this->hasres = false;
370 @ldap_free_result($this->sr);
371 }
372 }
374 function getDN()
375 {
376 if($this->hascon){
377 if($this->hasres){
379 if(!$this->re)
380 {
381 $this->error = "Perform a Fetch with no valid Result";
382 }
383 else
384 {
385 $rv = @ldap_get_dn($this->cid, $this->re);
387 $this->error = @ldap_error($this->cid);
388 return(trim(LDAP::convert($rv)));
389 }
390 }else{
391 $this->error = "Perform a Fetch with no Search";
392 return("");
393 }
394 }else{
395 $this->error = "Could not connect to LDAP server";
396 return("");
397 }
398 }
400 function count()
401 {
402 if($this->hascon){
403 if($this->hasres){
404 $rv = @ldap_count_entries($this->cid, $this->sr);
405 $this->error = @ldap_error($this->cid);
406 return($rv);
407 }else{
408 $this->error = "Perform a Fetch with no Search";
409 return("");
410 }
411 }else{
412 $this->error = "Could not connect to LDAP server";
413 return("");
414 }
415 }
417 function rm($attrs = "", $dn = "")
418 {
419 if($this->hascon){
420 if ($this->reconnect) $this->connect();
421 if ($dn == "")
422 $dn = $this->basedn;
424 $r = @ldap_mod_del($this->cid, LDAP::fix($dn), $attrs);
425 $this->error = @ldap_error($this->cid);
426 return($r);
427 }else{
428 $this->error = "Could not connect to LDAP server";
429 return("");
430 }
431 }
433 function rename($attrs, $dn = "")
434 {
435 if($this->hascon){
436 if ($this->reconnect) $this->connect();
437 if ($dn == "")
438 $dn = $this->basedn;
440 $r = @ldap_mod_replace($this->cid, LDAP::fix($dn), $attrs);
441 $this->error = @ldap_error($this->cid);
442 return($r);
443 }else{
444 $this->error = "Could not connect to LDAP server";
445 return("");
446 }
447 }
449 function rmdir($deletedn)
450 {
451 if($this->hascon){
452 if ($this->reconnect) $this->connect();
453 $r = @ldap_delete($this->cid, LDAP::fix($deletedn));
454 $this->error = @ldap_error($this->cid);
455 return($r ? $r : 0);
456 }else{
457 $this->error = "Could not connect to LDAP server";
458 return("");
459 }
460 }
462 /**
463 * Function rmdir_recursive
464 *
465 * Description: Based in recursive_remove, adding two thing: full subtree remove, and delete own node.
466 * Parameters: The dn to delete
467 * GiveBack: True on sucessfull , 0 in error, and "" when we don't get a ldap conection
468 *
469 */
471 function rmdir_recursive($deletedn)
472 {
473 if($this->hascon){
474 if ($this->reconnect) $this->connect();
475 $delarray= array();
477 /* Get sorted list of dn's to delete */
478 $this->ls ("(objectClass=*)",$deletedn);
479 while ($this->fetch()){
480 $deldn= $this->getDN();
481 $delarray[$deldn]= strlen($deldn);
482 }
483 arsort ($delarray);
484 reset ($delarray);
486 /* Really Delete ALL dn's in subtree */
487 foreach ($delarray as $key => $value){
488 $this->rmdir_recursive($key);
489 }
491 /* Finally Delete own Node */
492 $r = @ldap_delete($this->cid, LDAP::fix($deletedn));
493 $this->error = @ldap_error($this->cid);
494 return($r ? $r : 0);
495 }else{
496 $this->error = "Could not connect to LDAP server";
497 return("");
498 }
499 }
502 function modify($attrs)
503 {
504 if(count($attrs) == 0){
505 return (0);
506 }
507 if($this->hascon){
508 if ($this->reconnect) $this->connect();
509 $r = @ldap_modify($this->cid, LDAP::fix($this->basedn), $attrs);
510 $this->error = @ldap_error($this->cid);
511 return($r ? $r : 0);
512 }else{
513 $this->error = "Could not connect to LDAP server";
514 return("");
515 }
516 }
518 function add($attrs)
519 {
520 if($this->hascon){
521 if ($this->reconnect) $this->connect();
522 $r = @ldap_add($this->cid, LDAP::fix($this->basedn), $attrs);
523 $this->error = @ldap_error($this->cid);
524 return($r ? $r : 0);
525 }else{
526 $this->error = "Could not connect to LDAP server";
527 return("");
528 }
529 }
531 function create_missing_trees($target)
532 {
533 global $config;
535 $real_path= substr($target, 0, strlen($target) - strlen($this->basedn) -1 );
537 if ($target == $this->basedn){
538 $l= array("dummy");
539 } else {
540 $l= array_reverse(gosa_ldap_explode_dn($real_path));
541 }
542 unset($l['count']);
543 $cdn= $this->basedn;
544 $tag= "";
546 /* Load schema if available... */
547 $classes= $this->get_objectclasses();
549 foreach ($l as $part){
550 if ($part != "dummy"){
551 $cdn= "$part,$cdn";
552 }
554 /* Ignore referrals */
555 $found= false;
556 foreach($this->referrals as $ref){
557 $base= preg_replace('!^[^:]+://[^/]+/([^?]+).*$!', '\\1', $ref['URL']);
558 if ($base == $cdn){
559 $found= true;
560 break;
561 }
562 }
563 if ($found){
564 continue;
565 }
567 $this->cat ($cdn);
568 $attrs= $this->fetch();
570 /* Create missing entry? */
571 if (count ($attrs)){
573 /* Catch the tag - if present */
574 if (isset($attrs['gosaUnitTag'][0])){
575 $tag= $attrs['gosaUnitTag'][0];
576 }
578 } else {
579 $type= preg_replace('/^([^=]+)=.*$/', '\\1', $cdn);
580 $param= preg_replace('/^[^=]+=([^,]+),.*$/', '\\1', $cdn);
582 $na= array();
584 /* Automatic or traditional? */
585 if(count($classes)){
587 /* Get name of first matching objectClass */
588 $ocname= "";
589 foreach($classes as $class){
590 if (isset($class['MUST']) && $class['MUST'] == "$type"){
592 /* Look for first classes that is structural... */
593 if (isset($class['STRUCTURAL'])){
594 $ocname= $class['NAME'];
595 break;
596 }
598 /* Look for classes that are auxiliary... */
599 if (isset($class['AUXILIARY'])){
600 $ocname= $class['NAME'];
601 }
602 }
603 }
605 /* Bail out, if we've nothing to do... */
606 if ($ocname == ""){
607 msg_dialog::display(_("Internal error"), sprintf(_("Cannot automatically create subtrees with RDN '%s': no object class found"),$type), FATAL_ERROR_DIALOG);
608 exit();
609 }
611 /* Assemble_entry */
612 if ($tag != ""){
613 $na['objectClass']= array($ocname, "gosaAdministrativeUnitTag");
614 $na["gosaUnitTag"]= $tag;
615 } else {
616 $na['objectClass']= array($ocname);
617 }
618 if (isset($classes[$ocname]['AUXILIARY'])){
619 $na['objectClass'][]= $classes[$ocname]['SUP'];
620 }
621 if ($type == "dc"){
622 /* This is bad actually, but - tell me a better way? */
623 $na['objectClass'][]= 'locality';
624 }
625 $na[$type]= $param;
626 if (is_array($classes[$ocname]['MUST'])){
627 foreach($classes[$ocname]['MUST'] as $attr){
628 $na[$attr]= "filled";
629 }
630 }
632 } else {
634 /* Use alternative add... */
635 switch ($type){
636 case 'ou':
637 if ($tag != ""){
638 $na["objectClass"]= array("organizationalUnit", "gosaAdministrativeUnitTag");
639 $na["gosaUnitTag"]= $tag;
640 } else {
641 $na["objectClass"]= "organizationalUnit";
642 }
643 $na["ou"]= $param;
644 break;
645 case 'dc':
646 if ($tag != ""){
647 $na["objectClass"]= array("dcObject", "top", "locality", "gosaAdministrativeUnitTag");
648 $na["gosaUnitTag"]= $tag;
649 } else {
650 $na["objectClass"]= array("dcObject", "top", "locality");
651 }
652 $na["dc"]= $param;
653 break;
654 default:
655 msg_dialog::display(_("Internal error"), sprintf(_("Cannot automatically create subtrees with RDN '%s': not supported"),$type), FATAL_ERROR_DIALOG);
656 exit();
657 }
659 }
660 $this->cd($cdn);
661 $this->add($na);
663 show_ldap_error($this->get_error(), sprintf(_("Creating subtree '%s' failed."),$cdn));
664 if (!preg_match('/success/i', $this->error)){
665 return FALSE;
666 }
667 }
668 }
670 return TRUE;
671 }
674 function recursive_remove()
675 {
676 $delarray= array();
678 /* Get sorted list of dn's to delete */
679 $this->search ("(objectClass=*)");
680 while ($this->fetch()){
681 $deldn= $this->getDN();
682 $delarray[$deldn]= strlen($deldn);
683 }
684 arsort ($delarray);
685 reset ($delarray);
687 /* Delete all dn's in subtree */
688 foreach ($delarray as $key => $value){
689 $this->rmdir($key);
690 }
691 }
693 function get_attribute($dn, $name,$r_array=0)
694 {
695 $data= "";
696 if ($this->reconnect) $this->connect();
697 $sr= @ldap_read($this->cid, LDAP::fix($dn), "objectClass=*", array("$name"));
699 /* fill data from LDAP */
700 if ($sr) {
701 $ei= @ldap_first_entry($this->cid, $sr);
702 if ($ei) {
703 if ($info= @ldap_get_values_len($this->cid, $ei, "$name")){
704 $data= $info[0];
705 }
706 }
707 }
708 if($r_array==0)
709 return ($data);
710 else
711 return ($info);
714 }
718 function get_additional_error()
719 {
720 $error= "";
721 @ldap_get_option ($this->cid, LDAP_OPT_ERROR_STRING, $error);
722 return ($error);
723 }
725 function get_error()
726 {
727 if ($this->error == 'Success'){
728 return $this->error;
729 } else {
730 $adderror= $this->get_additional_error();
731 if ($adderror != ""){
732 $error= $this->error." (".$this->get_additional_error().", ".sprintf(_("while operating on '%s' using LDAP server '%s'"), $this->basedn, $this->hostname).")";
733 } else {
734 $error= $this->error." (".sprintf(_("while operating on LDAP server %s"), $this->hostname).")";
735 }
736 return $error;
737 }
738 }
740 function get_credentials($url, $referrals= NULL)
741 {
742 $ret= array();
743 $url= preg_replace('!\?\?.*$!', '', $url);
744 $server= preg_replace('!^([^:]+://[^/]+)/.*$!', '\\1', $url);
746 if ($referrals === NULL){
747 $referrals= $this->referrals;
748 }
750 if (isset($referrals[$server])){
751 return ($referrals[$server]);
752 } else {
753 $ret['ADMIN']= LDAP::fix($this->binddn);
754 $ret['PASSWORD']= $this->bindpw;
755 }
757 return ($ret);
758 }
761 function gen_ldif ($dn, $filter= "(objectClass=*)", $attributes= array('*'), $recursive= TRUE)
762 {
763 $display= "";
765 if ($recursive){
766 $this->cd($dn);
767 $this->ls($filter,$dn, array('dn','objectClass'));
768 $deps = array();
770 $display .= $this->gen_one_entry($dn)."\n";
772 while ($attrs= $this->fetch()){
773 $deps[] = $attrs['dn'];
774 }
775 foreach($deps as $dn){
776 $display .= $this->gen_ldif($dn, $filter,$attributes,$recursive);
777 }
778 } else {
779 $display.= $this->gen_one_entry($dn);
780 }
781 return ($display);
782 }
785 function gen_xls ($dn, $filter= "(objectClass=*)", $attributes= array('*'), $recursive= TRUE,$r_array=0)
786 {
787 $display= array();
789 $this->cd($dn);
790 $this->search("$filter");
792 $i=0;
793 while ($attrs= $this->fetch()){
794 $j=0;
796 foreach ($attributes as $at){
797 $display[$i][$j]= $this->get_attribute($attrs['dn'], $at,$r_array);
798 $j++;
799 }
801 $i++;
802 }
804 return ($display);
805 }
808 function gen_one_entry($dn, $filter= "(objectClass=*)" , $name= array("*"))
809 {
810 $ret = "";
811 $data = "";
812 if($this->reconnect){
813 $this->connect();
814 }
816 /* Searching Ldap Tree */
817 $sr= @ldap_read($this->cid, LDAP::fix($dn), $filter, $name);
819 /* Get the first entry */
820 $entry= @ldap_first_entry($this->cid, $sr);
822 /* Get all attributes related to that Objekt */
823 $atts = array();
825 /* Assemble dn */
826 $atts[0]['name'] = "dn";
827 $atts[0]['value'] = array('count' => 1, 0 => $dn);
829 /* Reset index */
830 $i = 1 ;
831 $identifier = array();
832 $attribute= @ldap_first_attribute($this->cid,$entry,$identifier);
833 while ($attribute) {
834 $i++;
835 $atts[$i]['name'] = $attribute;
836 $atts[$i]['value'] = @ldap_get_values_len($this->cid, $entry, "$attribute");
838 /* Next one */
839 $attribute= @ldap_next_attribute($this->cid,$entry,$identifier);
840 }
842 foreach($atts as $at)
843 {
844 for ($i= 0; $i<$at['value']['count']; $i++){
846 /* Check if we must encode the data */
847 if(!preg_match('/^[a-z0-9+@#.=, \/ -]+$/i', $at['value'][$i])) {
848 $ret .= $at['name'].":: ".base64_encode($at['value'][$i])."\n";
849 } else {
850 $ret .= $at['name'].": ".$at['value'][$i]."\n";
851 }
852 }
853 }
855 return($ret);
856 }
859 function dn_exists($dn)
860 {
861 return @ldap_list($this->cid, LDAP::fix($dn), "(objectClass=*)", array("objectClass"));
862 }
866 /* This funktion imports ldifs
868 If DeleteOldEntries is true, the destination entry will be deleted first.
869 If JustModify is true the destination entry will only be touched by the attributes specified in the ldif.
870 if JustMofify id false the destination dn will be overwritten by the new ldif.
871 */
873 function import_complete_ldif($str_attr,&$error,$JustModify,$DeleteOldEntries)
874 {
875 if($this->reconnect) $this->connect();
877 /* First we have to splitt the string ito detect empty lines
878 An empty line indicates an new Entry */
879 $entries = split("\n",$str_attr);
881 $data = "";
882 $cnt = 0;
883 $current_line = 0;
885 /* FIX ldif */
886 $last = "";
887 $tmp = "";
888 $i = 0;
889 foreach($entries as $entry){
890 if(preg_match("/^ /",$entry)){
891 $tmp[$i] .= trim($entry);
892 }else{
893 $i ++;
894 $tmp[$i] = trim($entry);
895 }
896 }
898 /* Every single line ... */
899 foreach($tmp as $entry) {
900 $current_line ++;
902 /* Removing Spaces to ..
903 .. test if a new entry begins */
904 $tmp = str_replace(" ","",$data );
906 /* .. prevent empty lines in an entry */
907 $tmp2 = str_replace(" ","",$entry);
909 /* If the Block ends (Empty Line) */
910 if((empty($entry))&&(!empty($tmp))) {
911 /* Add collected lines as a complete block */
912 $all[$cnt] = $data;
913 $cnt ++;
914 $data ="";
915 } else {
917 /* Append lines ... */
918 if(!empty($tmp2)) {
919 /* check if we need base64_decode for this line */
920 if(ereg("::",$tmp2))
921 {
922 $encoded = split("::",$entry);
923 $attr = trim($encoded[0]);
924 $value = base64_decode(trim($encoded[1]));
925 /* Add linenumber */
926 $data .= $current_line."#".base64_encode($attr.":".$value)."\n";
927 }
928 else
929 {
930 /* Add Linenumber */
931 $data .= $current_line."#".base64_encode($entry)."\n";
932 }
933 }
934 }
935 }
937 /* The Data we collected is not in the array all[];
938 For example the Data is stored like this..
940 all[0] = "1#dn : .... \n
941 2#ObjectType: person \n ...."
943 Now we check every insertblock and try to insert */
944 foreach ( $all as $single) {
945 $lineone = split("\n",$single);
946 $ndn = split("#", $lineone[0]);
947 $line = base64_decode($ndn[1]);
949 $dnn = split (":",$line,2);
950 $current_line = $ndn[0];
951 $dn = $dnn[0];
952 $value = $dnn[1];
954 /* Every block must begin with a dn */
955 if($dn != "dn") {
956 $error= sprintf(_("This is not a valid DN: '%s'. A block for import should begin with 'dn: ...' in line %s"), $line, $current_line);
957 return -2;
958 }
960 /* Should we use Modify instead of Add */
961 $usemodify= false;
963 /* Delete before insert */
964 $usermdir= false;
966 /* The dn address already exists, Don't delete destination entry, overwrite it */
967 if (($this->dn_exists($value))&&((!$JustModify)&&(!$DeleteOldEntries))) {
969 $usermdir = $usemodify = false;
971 /* Delete old entry first, then add new */
972 } elseif(($this->dn_exists($value))&&($DeleteOldEntries)){
974 /* Delete first, then add */
975 $usermdir = true;
977 } elseif(($this->dn_exists($value))&&($JustModify)) {
979 /* Modify instead of Add */
980 $usemodify = true;
981 }
983 /* If we can't Import, return with a file error */
984 if(!$this->import_single_entry($single,$usemodify,$usermdir) ) {
985 $error= sprintf(_("Error while importing dn: '%s', please check your LDIF from line %s on!"), $line,
986 $current_line);
987 return UNKNOWN_TOKEN_IN_LDIF_FILE; }
988 }
990 return (INSERT_OK);
991 }
994 /* Imports a single entry
995 If $delete is true; The old entry will be deleted if it exists.
996 if $modify is true; All variables that are not touched by the new ldif will be kept.
997 if $modify is false; The new ldif overwrites the old entry, and all untouched attributes get lost.
998 */
999 function import_single_entry($str_attr,$modify,$delete)
1000 {
1001 global $config;
1003 if(!$config){
1004 trigger_error("Can't import ldif, can't read config object.");
1005 }
1008 if($this->reconnect) $this->connect();
1010 $ret = false;
1011 $rows= split("\n",$str_attr);
1012 $data= false;
1014 foreach($rows as $row) {
1016 /* Check if we use Linenumbers (when import_complete_ldif is called we use
1017 Linenumbers) Linenumbers are use like this 123#attribute : value */
1018 if(!empty($row)) {
1019 if(strpos($row,"#")!=FALSE) {
1021 /* We are using line numbers
1022 Because there is a # before a : */
1023 $tmp1= split("#",$row);
1024 $current_line= $tmp1[0];
1025 $row= base64_decode($tmp1[1]);
1026 }
1028 /* Split the line into attribute and value */
1029 $attr = split(":", $row,2);
1030 $attr[0]= trim($attr[0]); /* attribute */
1031 $attr[1]= $attr[1]; /* value */
1033 /* Check :: was used to indicate base64_encoded strings */
1034 if($attr[1][0] == ":"){
1035 $attr[1]=trim(preg_replace("/^:/","",$attr[1]));
1036 $attr[1]=base64_decode($attr[1]);
1037 }
1039 $attr[1] = trim($attr[1]);
1041 /* Check for attributes that are used more than once */
1042 if(!isset($data[$attr[0]])) {
1043 $data[$attr[0]]=$attr[1];
1044 } else {
1045 $tmp = $data[$attr[0]];
1047 if(!is_array($tmp)) {
1048 $new[0]=$tmp;
1049 $new[1]=$attr[1];
1050 $datas[$attr[0]]['count']=1;
1051 $data[$attr[0]]=$new;
1052 } else {
1053 $cnt = $datas[$attr[0]]['count'];
1054 $cnt ++;
1055 $data[$attr[0]][$cnt]=$attr[1];
1056 $datas[$attr[0]]['count'] = $cnt;
1057 }
1058 }
1059 }
1060 }
1062 /* If dn is an index of data, we should try to insert the data */
1063 if(isset($data['dn'])) {
1065 /* Fix dn */
1066 $tmp = gosa_ldap_explode_dn($data['dn']);
1067 unset($tmp['count']);
1068 $newdn ="";
1069 foreach($tmp as $tm){
1070 $newdn.= trim($tm).",";
1071 }
1072 $newdn = preg_replace("/,$/","",$newdn);
1073 $data['dn'] = $newdn;
1075 /* Creating Entry */
1076 $this->cd($data['dn']);
1078 /* Delete existing entry */
1079 if($delete){
1080 $this->rmdir_recursive($data['dn']);
1081 }
1083 /* Create missing trees */
1084 $this->cd ($this->basedn);
1085 $this->cd($config->current['BASE']);
1086 $this->create_missing_trees(preg_replace("/^[^,]+,/","",$data['dn']));
1087 $this->cd($data['dn']);
1089 $dn = $data['dn'];
1090 unset($data['dn']);
1092 if(!$modify){
1094 $this->cat($dn);
1095 if($this->count()){
1097 /* The destination entry exists, overwrite it with the new entry */
1098 $attrs = $this->fetch();
1099 foreach($attrs as $name => $value ){
1100 if(!is_numeric($name)){
1101 if(in_array($name,array("dn","count"))) continue;
1102 if(!isset($data[$name])){
1103 $data[$name] = array();
1104 }
1105 }
1106 }
1107 $ret = $this->modify($data);
1109 }else{
1111 /* The destination entry doesn't exists, create it */
1112 $ret = $this->add($data);
1113 }
1115 } else {
1117 /* Keep all vars that aren't touched by this ldif */
1118 $ret = $this->modify($data);
1119 }
1120 }
1121 show_ldap_error($this->get_error(), sprintf(_("Ldap import with dn '%s' failed."),$dn));
1122 return($ret);
1123 }
1126 function importcsv($str)
1127 {
1128 $lines = split("\n",$str);
1129 foreach($lines as $line)
1130 {
1131 /* continue if theres a comment */
1132 if(substr(trim($line),0,1)=="#"){
1133 continue;
1134 }
1136 $line= str_replace ("\t\t","\t",$line);
1137 $line= str_replace ("\t" ,"," ,$line);
1138 echo $line;
1140 $cells = split(",",$line ) ;
1141 $linet= str_replace ("\t\t",",",$line);
1142 $cells = split("\t",$line);
1143 $count = count($cells);
1144 }
1146 }
1148 function get_objectclasses()
1149 {
1150 $objectclasses = array();
1151 global $config;
1153 /* Only read schema if it is allowed */
1154 if(isset($config) && preg_match("/config/i",get_class($config))){
1155 if(!isset($config->data['MAIN']['SCHEMA_CHECK']) || !preg_match("/true/i",$config->data['MAIN']['SCHEMA_CHECK'])){
1156 return($objectclasses);
1157 }
1158 }
1160 /* Return the cached results. */
1161 if(class_available('session') && session::is_set("LDAP_CACHE::get_objectclasses")){
1162 $objectclasses = session::get("LDAP_CACHE::get_objectclasses");
1163 return($objectclasses);
1164 }
1166 # Get base to look for schema
1167 $sr = @ldap_read ($this->cid, NULL, "objectClass=*", array("subschemaSubentry"));
1168 if(!$sr){
1169 $sr = @ldap_read ($this->cid, "", "objectClass=*", array("subschemaSubentry"));
1170 }
1172 $attr = @ldap_get_entries($this->cid,$sr);
1173 if (!isset($attr[0]['subschemasubentry'][0])){
1174 return array();
1175 }
1177 /* Get list of objectclasses and fill array */
1178 $nb= $attr[0]['subschemasubentry'][0];
1179 $objectclasses= array();
1180 $sr= ldap_read ($this->cid, $nb, "objectClass=*", array("objectclasses"));
1181 $attrs= ldap_get_entries($this->cid,$sr);
1182 if (!isset($attrs[0])){
1183 return array();
1184 }
1185 foreach ($attrs[0]['objectclasses'] as $val){
1186 if (preg_match('/^[0-9]+$/', $val)){
1187 continue;
1188 }
1189 $name= "OID";
1190 $pattern= split(' ', $val);
1191 $ocname= preg_replace("/^.* NAME\s+\(*\s*'([^']+)'\s*\)*.*$/", '\\1', $val);
1192 $objectclasses[$ocname]= array();
1194 foreach($pattern as $chunk){
1195 switch($chunk){
1197 case '(':
1198 $value= "";
1199 break;
1201 case ')': if ($name != ""){
1202 $objectclasses[$ocname][$name]= $this->value2container($value);
1203 }
1204 $name= "";
1205 $value= "";
1206 break;
1208 case 'NAME':
1209 case 'DESC':
1210 case 'SUP':
1211 case 'STRUCTURAL':
1212 case 'ABSTRACT':
1213 case 'AUXILIARY':
1214 case 'MUST':
1215 case 'MAY':
1216 if ($name != ""){
1217 $objectclasses[$ocname][$name]= $this->value2container($value);
1218 }
1219 $name= $chunk;
1220 $value= "";
1221 break;
1223 default: $value.= $chunk." ";
1224 }
1225 }
1227 }
1228 if(class_available("session")){
1229 session::set("LDAP_CACHE::get_objectclasses",$objectclasses);
1230 }
1231 return $objectclasses;
1232 }
1235 function value2container($value)
1236 {
1237 /* Set emtpy values to "true" only */
1238 if (preg_match('/^\s*$/', $value)){
1239 return true;
1240 }
1242 /* Remove ' and " if needed */
1243 $value= preg_replace('/^[\'"]/', '', $value);
1244 $value= preg_replace('/[\'"] *$/', '', $value);
1246 /* Convert to array if $ is inside... */
1247 if (preg_match('/\$/', $value)){
1248 $container= preg_split('/\s*\$\s*/', $value);
1249 } else {
1250 $container= chop($value);
1251 }
1253 return ($container);
1254 }
1257 function log($string)
1258 {
1259 if (session::is_set('config')){
1260 $cfg = session::get('config');
1261 if (isset($cfg->current['LDAPSTATS']) && preg_match('/true/i', $cfg->current['LDAPSTATS'])){
1262 syslog (LOG_INFO, $string);
1263 }
1264 }
1265 }
1267 /* added by Guido Serra aka Zeph <zeph@purotesto.it> */
1268 function getCn($dn){
1269 $simple= split(",", $dn);
1271 foreach($simple as $piece) {
1272 $partial= split("=", $piece);
1274 if($partial[0] == "cn"){
1275 return $partial[1];
1276 }
1277 }
1278 }
1281 function get_naming_contexts($server, $admin= "", $password= "")
1282 {
1283 /* Build LDAP connection */
1284 $ds= ldap_connect ($server);
1285 if (!$ds) {
1286 die ("Can't bind to LDAP. No check possible!");
1287 }
1288 ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
1289 $r= ldap_bind ($ds, $admin, $password);
1291 /* Get base to look for naming contexts */
1292 $sr = @ldap_read ($ds, "", "objectClass=*", array("+"));
1293 $attr= @ldap_get_entries($ds,$sr);
1295 return ($attr[0]['namingcontexts']);
1296 }
1299 function get_root_dse($server, $admin= "", $password= "")
1300 {
1301 /* Build LDAP connection */
1302 $ds= ldap_connect ($server);
1303 if (!$ds) {
1304 die ("Can't bind to LDAP. No check possible!");
1305 }
1306 ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
1307 $r= ldap_bind ($ds, $admin, $password);
1309 /* Get base to look for naming contexts */
1310 $sr = @ldap_read ($ds, "", "objectClass=*", array("+"));
1311 $attr= @ldap_get_entries($ds,$sr);
1313 /* Return empty array, if nothing was set */
1314 if (!isset($attr[0])){
1315 return array();
1316 }
1318 /* Rework array... */
1319 $result= array();
1320 for ($i= 0; $i<$attr[0]['count']; $i++){
1321 $result[$attr[0][$i]]= $attr[0][$attr[0][$i]];
1322 unset($result[$attr[0][$i]]['count']);
1323 }
1325 return ($result);
1326 }
1327 }
1328 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
1329 ?>