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 return normalizeLdap(str_replace('\\\\', '\\\\\\', LDAP::fix($dn)));
124 }
127 function connect()
128 {
129 $this->hascon=false;
130 $this->reconnect=false;
131 if ($this->cid= @ldap_connect($this->hostname)) {
132 @ldap_set_option($this->cid, LDAP_OPT_PROTOCOL_VERSION, 3);
133 if (function_exists("ldap_set_rebind_proc") && $this->follow_referral) {
134 @ldap_set_option($this->cid, LDAP_OPT_REFERRALS, 1);
135 @ldap_set_rebind_proc($this->cid, array(&$this, "rebind"));
136 }
137 if (function_exists("ldap_start_tls") && $this->tls){
138 @ldap_start_tls($this->cid);
139 }
141 $this->error = "No Error";
142 if ($bid = @ldap_bind($this->cid, LDAP::fix($this->binddn), $this->bindpw)) {
143 $this->error = "Success";
144 $this->hascon=true;
145 } else {
146 if ($this->reconnect){
147 if ($this->error != "Success"){
148 $this->error = "Could not rebind to " . $this->binddn;
149 }
150 } else {
151 $this->error = "Could not bind to " . $this->binddn;
152 }
153 }
154 } else {
155 $this->error = "Could not connect to LDAP server";
156 }
157 }
159 function rebind($ldap, $referral)
160 {
161 $credentials= $this->get_credentials($referral);
162 if (@ldap_bind($ldap, LDAP::fix($credentials['ADMINDN']), $credentials['ADMINPASSWORD'])) {
163 $this->error = "Success";
164 $this->hascon=true;
165 $this->reconnect= true;
166 return (0);
167 } else {
168 $this->error = "Could not bind to " . $credentials['ADMINDN'];
169 return NULL;
170 }
171 }
173 function reconnect()
174 {
175 if ($this->reconnect){
176 @ldap_unbind($this->cid);
177 $this->cid = NULL;
178 }
179 }
181 function unbind()
182 {
183 @ldap_unbind($this->cid);
184 $this->cid = NULL;
185 }
187 function disconnect()
188 {
189 if($this->hascon){
190 @ldap_close($this->cid);
191 $this->hascon=false;
192 }
193 }
195 function cd($dir)
196 {
197 if ($dir == ".."){
198 $this->basedn = $this->getParentDir();
199 } else {
200 $this->basedn = LDAP::convert($dir);
201 }
202 }
204 function getParentDir($basedn = "")
205 {
206 if ($basedn==""){
207 $basedn = $this->basedn;
208 } else {
209 $basedn = LDAP::convert($this->basedn);
210 }
211 return(ereg_replace("[^,]*[,]*[ ]*(.*)", "\\1", $basedn));
212 }
215 function search($srp, $filter, $attrs= array())
216 {
217 if($this->hascon){
218 if ($this->reconnect) $this->connect();
220 $start = microtime();
221 $this->clearResult($srp);
222 $this->sr[$srp] = @ldap_search($this->cid, LDAP::fix($this->basedn), $filter, $attrs);
223 $this->error = @ldap_error($this->cid);
224 $this->resetResult($srp);
225 $this->hasres[$srp]=true;
227 /* Check if query took longer as specified in max_ldap_query_time */
228 if($this->max_ldap_query_time){
229 $diff = get_MicroTimeDiff($start,microtime());
230 if($diff > $this->max_ldap_query_time){
231 msg_dialog::display(_("Performance warning"), sprintf(_("LDAP performance is poor: last query took about %.2fs!"), $diff), WARNING_DIALOG);
232 }
233 }
235 $this->log("LDAP operation: time=".get_MicroTimeDiff($start,microtime())." operation=search('".LDAP::fix($this->basedn)."', '$filter')");
236 return($this->sr[$srp]);
237 }else{
238 $this->error = "Could not connect to LDAP server";
239 return("");
240 }
241 }
243 function ls($srp, $filter = "(objectclass=*)", $basedn = "",$attrs = array("*"))
244 {
245 if($this->hascon){
246 if ($this->reconnect) $this->connect();
248 $this->clearResult($srp);
249 if ($basedn == "")
250 $basedn = $this->basedn;
251 else
252 $basedn= LDAP::convert($basedn);
254 $start = microtime();
255 $this->sr[$srp] = @ldap_list($this->cid, LDAP::fix($basedn), $filter,$attrs);
256 $this->error = @ldap_error($this->cid);
257 $this->resetResult($srp);
258 $this->hasres[$srp]=true;
260 /* Check if query took longer as specified in max_ldap_query_time */
261 if($this->max_ldap_query_time){
262 $diff = get_MicroTimeDiff($start,microtime());
263 if($diff > $this->max_ldap_query_time){
264 msg_dialog::display(_("Performance warning"), sprintf(_("LDAP performance is poor: last query took about %.2fs!"), $diff), WARNING_DIALOG);
265 }
266 }
268 $this->log("LDAP operation: time=".get_MicroTimeDiff($start,microtime())." operation=ls('".LDAP::fix($basedn)."', '$filter')");
270 return($this->sr[$srp]);
271 }else{
272 $this->error = "Could not connect to LDAP server";
273 return("");
274 }
275 }
277 function cat($srp, $dn,$attrs= array("*"))
278 {
279 if($this->hascon){
280 if ($this->reconnect) $this->connect();
282 $this->clearResult($srp);
283 $filter = "(objectclass=*)";
284 $this->sr[$srp] = @ldap_read($this->cid, LDAP::fix($dn), $filter,$attrs);
285 $this->error = @ldap_error($this->cid);
286 $this->resetResult($srp);
287 $this->hasres[$srp]=true;
288 return($this->sr[$srp]);
289 }else{
290 $this->error = "Could not connect to LDAP server";
291 return("");
292 }
293 }
295 function object_match_filter($dn,$filter)
296 {
297 if($this->hascon){
298 if ($this->reconnect) $this->connect();
299 $res = @ldap_read($this->cid, LDAP::fix($dn), $filter, array("objectClass"));
300 $rv = @ldap_count_entries($this->cid, $res);
301 return($rv);
302 }else{
303 $this->error = "Could not connect to LDAP server";
304 return(FALSE);
305 }
306 }
308 function set_size_limit($size)
309 {
310 /* Ignore zero settings */
311 if ($size == 0){
312 @ldap_set_option($this->cid, LDAP_OPT_SIZELIMIT, 10000000);
313 }
314 if($this->hascon){
315 @ldap_set_option($this->cid, LDAP_OPT_SIZELIMIT, $size);
316 } else {
317 $this->error = "Could not connect to LDAP server";
318 }
319 }
321 function fetch($srp)
322 {
323 $att= array();
324 if($this->hascon){
325 if($this->hasres[$srp]){
326 if ($this->start[$srp] == 0)
327 {
328 if ($this->sr[$srp]){
329 $this->start[$srp] = 1;
330 $this->re[$srp]= @ldap_first_entry($this->cid, $this->sr[$srp]);
331 } else {
332 return array();
333 }
334 } else {
335 $this->re[$srp]= @ldap_next_entry($this->cid, $this->re[$srp]);
336 }
337 if ($this->re[$srp])
338 {
339 $att= @ldap_get_attributes($this->cid, $this->re[$srp]);
340 $att['dn']= trim(LDAP::convert(@ldap_get_dn($this->cid, $this->re[$srp])));
341 }
342 $this->error = @ldap_error($this->cid);
343 if (!isset($att)){
344 $att= array();
345 }
346 return($att);
347 }else{
348 $this->error = "Perform a fetch with no search";
349 return("");
350 }
351 }else{
352 $this->error = "Could not connect to LDAP server";
353 return("");
354 }
355 }
357 function resetResult($srp)
358 {
359 $this->start[$srp] = 0;
360 }
362 function clearResult($srp)
363 {
364 if($this->hasres[$srp]){
365 $this->hasres[$srp] = false;
366 @ldap_free_result($this->sr[$srp]);
367 }
368 }
370 function getDN($srp)
371 {
372 if($this->hascon){
373 if($this->hasres[$srp]){
375 if(!$this->re[$srp])
376 {
377 $this->error = "Perform a Fetch with no valid Result";
378 }
379 else
380 {
381 $rv = @ldap_get_dn($this->cid, $this->re[$srp]);
383 $this->error = @ldap_error($this->cid);
384 return(trim(LDAP::convert($rv)));
385 }
386 }else{
387 $this->error = "Perform a Fetch with no Search";
388 return("");
389 }
390 }else{
391 $this->error = "Could not connect to LDAP server";
392 return("");
393 }
394 }
396 function count($srp)
397 {
398 if($this->hascon){
399 if($this->hasres[$srp]){
400 $rv = @ldap_count_entries($this->cid, $this->sr[$srp]);
401 $this->error = @ldap_error($this->cid);
402 return($rv);
403 }else{
404 $this->error = "Perform a Fetch with no Search";
405 return("");
406 }
407 }else{
408 $this->error = "Could not connect to LDAP server";
409 return("");
410 }
411 }
413 function rm($attrs = "", $dn = "")
414 {
415 if($this->hascon){
416 if ($this->reconnect) $this->connect();
417 if ($dn == "")
418 $dn = $this->basedn;
420 $r = @ldap_mod_del($this->cid, LDAP::fix($dn), $attrs);
421 $this->error = @ldap_error($this->cid);
422 return($r);
423 }else{
424 $this->error = "Could not connect to LDAP server";
425 return("");
426 }
427 }
429 function rename($attrs, $dn = "")
430 {
431 if($this->hascon){
432 if ($this->reconnect) $this->connect();
433 if ($dn == "")
434 $dn = $this->basedn;
436 $r = @ldap_mod_replace($this->cid, LDAP::fix($dn), $attrs);
437 $this->error = @ldap_error($this->cid);
438 return($r);
439 }else{
440 $this->error = "Could not connect to LDAP server";
441 return("");
442 }
443 }
445 function rmdir($deletedn)
446 {
447 if($this->hascon){
448 if ($this->reconnect) $this->connect();
449 $r = @ldap_delete($this->cid, LDAP::fix($deletedn));
450 $this->error = @ldap_error($this->cid);
451 return($r ? $r : 0);
452 }else{
453 $this->error = "Could not connect to LDAP server";
454 return("");
455 }
456 }
459 /*! \brief Move the given Ldap entry from $source to $dest
460 @param String $source The source dn.
461 @param String $dest The destination dn.
462 @return Boolean TRUE on success else FALSE.
463 */
464 function rename_dn($source,$dest)
465 {
466 /* Check if source and destination are the same entry */
467 if(strtolower($source) == strtolower($dest)){
468 trigger_error("Source and destination can't be the same entry.");
469 $this->error = "Source and destination can't be the same entry.";
470 return(FALSE);
471 }
473 /* Check if destination entry exists */
474 if($this->dn_exists($dest)){
475 trigger_error("Destination '$dest' already exists.");
476 $this->error = "Destination '$dest' already exists.";
477 return(FALSE);
478 }
480 /* Extract the name and the parent part out ouf source dn.
481 e.g. cn=herbert,ou=department,dc=...
482 parent => ou=department,dc=...
483 dest_rdn => cn=herbert
484 */
485 $parent = preg_replace("/^[^,]+,/","", $dest);
486 $dest_rdn = preg_replace("/,.*$/","",$dest);
488 if($this->hascon){
489 if ($this->reconnect) $this->connect();
490 $r= ldap_rename($this->cid,@LDAP::fix($source), @LDAP::fix($dest_rdn),@LDAP::fix($parent),TRUE);
491 $this->error = ldap_error($this->cid);
493 /* Check if destination dn exists, if not the
494 server may not support this operation */
495 $r &= is_resource($this->dn_exists($dest));
496 return($r);
497 }else{
498 $this->error = "Could not connect to LDAP server";
499 return(FALSE);
500 }
501 }
504 /**
505 * Function rmdir_recursive
506 *
507 * Description: Based in recursive_remove, adding two thing: full subtree remove, and delete own node.
508 * Parameters: The dn to delete
509 * GiveBack: True on sucessfull , 0 in error, and "" when we don't get a ldap conection
510 *
511 */
512 function rmdir_recursive($srp, $deletedn)
513 {
514 if($this->hascon){
515 if ($this->reconnect) $this->connect();
516 $delarray= array();
518 /* Get sorted list of dn's to delete */
519 $this->ls ($srp, "(objectClass=*)",$deletedn);
520 while ($this->fetch($srp)){
521 $deldn= $this->getDN($srp);
522 $delarray[$deldn]= strlen($deldn);
523 }
524 arsort ($delarray);
525 reset ($delarray);
527 /* Really Delete ALL dn's in subtree */
528 foreach ($delarray as $key => $value){
529 $this->rmdir_recursive($srp, $key);
530 }
532 /* Finally Delete own Node */
533 $r = @ldap_delete($this->cid, LDAP::fix($deletedn));
534 $this->error = @ldap_error($this->cid);
535 return($r ? $r : 0);
536 }else{
537 $this->error = "Could not connect to LDAP server";
538 return("");
539 }
540 }
543 function modify($attrs)
544 {
545 if(count($attrs) == 0){
546 return (0);
547 }
548 if($this->hascon){
549 if ($this->reconnect) $this->connect();
550 $r = @ldap_modify($this->cid, LDAP::fix($this->basedn), $attrs);
551 $this->error = @ldap_error($this->cid);
552 return($r ? $r : 0);
553 }else{
554 $this->error = "Could not connect to LDAP server";
555 return("");
556 }
557 }
559 function add($attrs)
560 {
561 if($this->hascon){
562 if ($this->reconnect) $this->connect();
563 $r = @ldap_add($this->cid, LDAP::fix($this->basedn), $attrs);
564 $this->error = @ldap_error($this->cid);
565 return($r ? $r : 0);
566 }else{
567 $this->error = "Could not connect to LDAP server";
568 return("");
569 }
570 }
572 function create_missing_trees($srp, $target)
573 {
574 global $config;
576 $real_path= substr($target, 0, strlen($target) - strlen($this->basedn) -1 );
578 if ($target == $this->basedn){
579 $l= array("dummy");
580 } else {
581 $l= array_reverse(gosa_ldap_explode_dn($real_path));
582 }
583 unset($l['count']);
584 $cdn= $this->basedn;
585 $tag= "";
587 /* Load schema if available... */
588 $classes= $this->get_objectclasses();
590 foreach ($l as $part){
591 if ($part != "dummy"){
592 $cdn= "$part,$cdn";
593 }
595 /* Ignore referrals */
596 $found= false;
597 foreach($this->referrals as $ref){
598 $base= preg_replace('!^[^:]+://[^/]+/([^?]+).*$!', '\\1', $ref['URI']);
599 if ($base == $cdn){
600 $found= true;
601 break;
602 }
603 }
604 if ($found){
605 continue;
606 }
608 $this->cat ($srp, $cdn);
609 $attrs= $this->fetch($srp);
611 /* Create missing entry? */
612 if (count ($attrs)){
614 /* Catch the tag - if present */
615 if (isset($attrs['gosaUnitTag'][0])){
616 $tag= $attrs['gosaUnitTag'][0];
617 }
619 } else {
620 $type= preg_replace('/^([^=]+)=.*$/', '\\1', $cdn);
621 $param= preg_replace('/^[^=]+=([^,]+),.*$/', '\\1', $cdn);
623 $na= array();
625 /* Automatic or traditional? */
626 if(count($classes)){
628 /* Get name of first matching objectClass */
629 $ocname= "";
630 foreach($classes as $class){
631 if (isset($class['MUST']) && $class['MUST'] == "$type"){
633 /* Look for first classes that is structural... */
634 if (isset($class['STRUCTURAL'])){
635 $ocname= $class['NAME'];
636 break;
637 }
639 /* Look for classes that are auxiliary... */
640 if (isset($class['AUXILIARY'])){
641 $ocname= $class['NAME'];
642 }
643 }
644 }
646 /* Bail out, if we've nothing to do... */
647 if ($ocname == ""){
648 msg_dialog::display(_("Internal error"), sprintf(_("Cannot automatically create subtrees with RDN '%s': no object class found!"),$type), FATAL_ERROR_DIALOG);
649 exit();
650 }
652 /* Assemble_entry */
653 if ($tag != ""){
654 $na['objectClass']= array($ocname, "gosaAdministrativeUnitTag");
655 $na["gosaUnitTag"]= $tag;
656 } else {
657 $na['objectClass']= array($ocname);
658 }
659 if (isset($classes[$ocname]['AUXILIARY'])){
660 $na['objectClass'][]= $classes[$ocname]['SUP'];
661 }
662 if ($type == "dc"){
663 /* This is bad actually, but - tell me a better way? */
664 $na['objectClass'][]= 'locality';
665 }
666 $na[$type]= $param;
667 if (is_array($classes[$ocname]['MUST'])){
668 foreach($classes[$ocname]['MUST'] as $attr){
669 $na[$attr]= "filled";
670 }
671 }
673 } else {
675 /* Use alternative add... */
676 switch ($type){
677 case 'ou':
678 if ($tag != ""){
679 $na["objectClass"]= array("organizationalUnit", "gosaAdministrativeUnitTag");
680 $na["gosaUnitTag"]= $tag;
681 } else {
682 $na["objectClass"]= "organizationalUnit";
683 }
684 $na["ou"]= $param;
685 break;
686 case 'dc':
687 if ($tag != ""){
688 $na["objectClass"]= array("dcObject", "top", "locality", "gosaAdministrativeUnitTag");
689 $na["gosaUnitTag"]= $tag;
690 } else {
691 $na["objectClass"]= array("dcObject", "top", "locality");
692 }
693 $na["dc"]= $param;
694 break;
695 default:
696 msg_dialog::display(_("Internal error"), sprintf(_("Cannot automatically create subtrees with RDN '%s': not supported"),$type), FATAL_ERROR_DIALOG);
697 exit();
698 }
700 }
701 $this->cd($cdn);
702 $this->add($na);
704 if (!$this->success()){
705 msg_dialog::display(_("LDAP error"), msgPool::ldaperror($this->get_error(), $cdn, LDAP_ADD, get_class()));
706 return FALSE;
707 }
708 }
709 }
711 return TRUE;
712 }
715 function recursive_remove($srp)
716 {
717 $delarray= array();
719 /* Get sorted list of dn's to delete */
720 $this->search ($srp, "(objectClass=*)");
721 while ($this->fetch($srp)){
722 $deldn= $this->getDN($srp);
723 $delarray[$deldn]= strlen($deldn);
724 }
725 arsort ($delarray);
726 reset ($delarray);
728 /* Delete all dn's in subtree */
729 foreach ($delarray as $key => $value){
730 $this->rmdir($key);
731 }
732 }
734 function get_attribute($dn, $name,$r_array=0)
735 {
736 $data= "";
737 if ($this->reconnect) $this->connect();
738 $sr= @ldap_read($this->cid, LDAP::fix($dn), "objectClass=*", array("$name"));
740 /* fill data from LDAP */
741 if ($sr) {
742 $ei= @ldap_first_entry($this->cid, $sr);
743 if ($ei) {
744 if ($info= @ldap_get_values_len($this->cid, $ei, "$name")){
745 $data= $info[0];
746 }
747 }
748 }
749 if($r_array==0)
750 return ($data);
751 else
752 return ($info);
755 }
759 function get_additional_error()
760 {
761 $error= "";
762 @ldap_get_option ($this->cid, LDAP_OPT_ERROR_STRING, $error);
763 return ($error);
764 }
767 function success()
768 {
769 return (preg_match('/Success/i', $this->error));
770 }
773 function get_error()
774 {
775 if ($this->error == 'Success'){
776 return $this->error;
777 } else {
778 $adderror= $this->get_additional_error();
779 if ($adderror != ""){
780 $error= $this->error." (".$this->get_additional_error().", ".sprintf(_("while operating on '%s' using LDAP server '%s'"), $this->basedn, $this->hostname).")";
781 } else {
782 $error= $this->error." (".sprintf(_("while operating on LDAP server %s"), $this->hostname).")";
783 }
784 return $error;
785 }
786 }
788 function get_credentials($url, $referrals= NULL)
789 {
790 $ret= array();
791 $url= preg_replace('!\?\?.*$!', '', $url);
792 $server= preg_replace('!^([^:]+://[^/]+)/.*$!', '\\1', $url);
794 if ($referrals === NULL){
795 $referrals= $this->referrals;
796 }
798 if (isset($referrals[$server])){
799 return ($referrals[$server]);
800 } else {
801 $ret['ADMINDN']= LDAP::fix($this->binddn);
802 $ret['ADMINPASSWORD']= $this->bindpw;
803 }
805 return ($ret);
806 }
809 function gen_ldif ($srp, $dn, $filter= "(objectClass=*)", $attributes= array('*'), $recursive= TRUE)
810 {
811 $display= "";
813 if ($recursive){
814 $this->cd($dn);
815 $this->ls($srp, $filter,$dn, array('dn','objectClass'));
816 $deps = array();
818 $display .= $this->gen_one_entry($dn)."\n";
820 while ($attrs= $this->fetch($srp)){
821 $deps[] = $attrs['dn'];
822 }
823 foreach($deps as $dn){
824 $display .= $this->gen_ldif($srp, $dn, $filter,$attributes,$recursive);
825 }
826 } else {
827 $display.= $this->gen_one_entry($dn);
828 }
829 return ($display);
830 }
833 function gen_xls ($srp, $dn, $filter= "(objectClass=*)", $attributes= array('*'), $recursive= TRUE,$r_array=0)
834 {
835 $display= array();
837 $this->cd($dn);
838 $this->search($srp, "$filter");
840 $i=0;
841 while ($attrs= $this->fetch($srp)){
842 $j=0;
844 foreach ($attributes as $at){
845 $display[$i][$j]= $this->get_attribute($attrs['dn'], $at,$r_array);
846 $j++;
847 }
849 $i++;
850 }
852 return ($display);
853 }
856 function gen_one_entry($dn, $filter= "(objectClass=*)" , $name= array("*"))
857 {
858 $ret = "";
859 $data = "";
860 if($this->reconnect){
861 $this->connect();
862 }
864 /* Searching Ldap Tree */
865 $sr= @ldap_read($this->cid, LDAP::fix($dn), $filter, $name);
867 /* Get the first entry */
868 $entry= @ldap_first_entry($this->cid, $sr);
870 /* Get all attributes related to that Objekt */
871 $atts = array();
873 /* Assemble dn */
874 $atts[0]['name'] = "dn";
875 $atts[0]['value'] = array('count' => 1, 0 => $dn);
877 /* Reset index */
878 $i = 1 ;
879 $identifier = array();
880 $attribute= @ldap_first_attribute($this->cid,$entry,$identifier);
881 while ($attribute) {
882 $i++;
883 $atts[$i]['name'] = $attribute;
884 $atts[$i]['value'] = @ldap_get_values_len($this->cid, $entry, "$attribute");
886 /* Next one */
887 $attribute= @ldap_next_attribute($this->cid,$entry,$identifier);
888 }
890 foreach($atts as $at)
891 {
892 for ($i= 0; $i<$at['value']['count']; $i++){
894 /* Check if we must encode the data */
895 if(!preg_match('/^[a-z0-9+@#.=, \/ -]+$/i', $at['value'][$i])) {
896 $ret .= $at['name'].":: ".base64_encode($at['value'][$i])."\n";
897 } else {
898 $ret .= $at['name'].": ".$at['value'][$i]."\n";
899 }
900 }
901 }
903 return($ret);
904 }
907 function dn_exists($dn)
908 {
909 return @ldap_list($this->cid, LDAP::fix($dn), "(objectClass=*)", array("objectClass"));
910 }
914 /* This funktion imports ldifs
916 If DeleteOldEntries is true, the destination entry will be deleted first.
917 If JustModify is true the destination entry will only be touched by the attributes specified in the ldif.
918 if JustMofify id false the destination dn will be overwritten by the new ldif.
919 */
921 function import_complete_ldif($srp, $str_attr,$error,$JustModify,$DeleteOldEntries)
922 {
923 if($this->reconnect) $this->connect();
925 /* First we have to splitt the string ito detect empty lines
926 An empty line indicates an new Entry */
927 $entries = split("\n",$str_attr);
929 $data = "";
930 $cnt = 0;
931 $current_line = 0;
933 /* FIX ldif */
934 $last = "";
935 $tmp = "";
936 $i = 0;
937 foreach($entries as $entry){
938 if(preg_match("/^ /",$entry)){
939 $tmp[$i] .= trim($entry);
940 }else{
941 $i ++;
942 $tmp[$i] = trim($entry);
943 }
944 }
946 /* Every single line ... */
947 foreach($tmp as $entry) {
948 $current_line ++;
950 /* Removing Spaces to ..
951 .. test if a new entry begins */
952 $tmp = str_replace(" ","",$data );
954 /* .. prevent empty lines in an entry */
955 $tmp2 = str_replace(" ","",$entry);
957 /* If the Block ends (Empty Line) */
958 if((empty($entry))&&(!empty($tmp))) {
959 /* Add collected lines as a complete block */
960 $all[$cnt] = $data;
961 $cnt ++;
962 $data ="";
963 } else {
965 /* Append lines ... */
966 if(!empty($tmp2)) {
967 /* check if we need base64_decode for this line */
968 if(ereg("::",$tmp2))
969 {
970 $encoded = split("::",$entry);
971 $attr = trim($encoded[0]);
972 $value = base64_decode(trim($encoded[1]));
973 /* Add linenumber */
974 $data .= $current_line."#".base64_encode($attr.":".$value)."\n";
975 }
976 else
977 {
978 /* Add Linenumber */
979 $data .= $current_line."#".base64_encode($entry)."\n";
980 }
981 }
982 }
983 }
985 /* The Data we collected is not in the array all[];
986 For example the Data is stored like this..
988 all[0] = "1#dn : .... \n
989 2#ObjectType: person \n ...."
991 Now we check every insertblock and try to insert */
992 foreach ( $all as $single) {
993 $lineone = split("\n",$single);
994 $ndn = split("#", $lineone[0]);
995 $line = base64_decode($ndn[1]);
997 $dnn = split (":",$line,2);
998 $current_line = $ndn[0];
999 $dn = $dnn[0];
1000 $value = $dnn[1];
1002 /* Every block must begin with a dn */
1003 if($dn != "dn") {
1004 $error= sprintf(_("This is not a valid DN: '%s'. A block for import should begin with 'dn: ...' in line %s"), $line, $current_line);
1005 return -2;
1006 }
1008 /* Should we use Modify instead of Add */
1009 $usemodify= false;
1011 /* Delete before insert */
1012 $usermdir= false;
1014 /* The dn address already exists, Don't delete destination entry, overwrite it */
1015 if (($this->dn_exists($value))&&((!$JustModify)&&(!$DeleteOldEntries))) {
1017 $usermdir = $usemodify = false;
1019 /* Delete old entry first, then add new */
1020 } elseif(($this->dn_exists($value))&&($DeleteOldEntries)){
1022 /* Delete first, then add */
1023 $usermdir = true;
1025 } elseif(($this->dn_exists($value))&&($JustModify)) {
1027 /* Modify instead of Add */
1028 $usemodify = true;
1029 }
1031 /* If we can't Import, return with a file error */
1032 if(!$this->import_single_entry($srp, $single,$usemodify,$usermdir) ) {
1033 $error= sprintf(_("Error while importing dn: '%s', please check your LDIF from line %s on!"), $line,
1034 $current_line);
1035 return UNKNOWN_TOKEN_IN_LDIF_FILE; }
1036 }
1038 return (INSERT_OK);
1039 }
1042 /* Imports a single entry
1043 If $delete is true; The old entry will be deleted if it exists.
1044 if $modify is true; All variables that are not touched by the new ldif will be kept.
1045 if $modify is false; The new ldif overwrites the old entry, and all untouched attributes get lost.
1046 */
1047 function import_single_entry($srp, $str_attr,$modify,$delete)
1048 {
1049 global $config;
1051 if(!$config){
1052 trigger_error("Can't import ldif, can't read config object.");
1053 }
1056 if($this->reconnect) $this->connect();
1058 $ret = false;
1059 $rows= split("\n",$str_attr);
1060 $data= false;
1062 foreach($rows as $row) {
1064 /* Check if we use Linenumbers (when import_complete_ldif is called we use
1065 Linenumbers) Linenumbers are use like this 123#attribute : value */
1066 if(!empty($row)) {
1067 if(strpos($row,"#")!=FALSE) {
1069 /* We are using line numbers
1070 Because there is a # before a : */
1071 $tmp1= split("#",$row);
1072 $current_line= $tmp1[0];
1073 $row= base64_decode($tmp1[1]);
1074 }
1076 /* Split the line into attribute and value */
1077 $attr = split(":", $row,2);
1078 $attr[0]= trim($attr[0]); /* attribute */
1079 $attr[1]= $attr[1]; /* value */
1081 /* Check :: was used to indicate base64_encoded strings */
1082 if($attr[1][0] == ":"){
1083 $attr[1]=trim(preg_replace("/^:/","",$attr[1]));
1084 $attr[1]=base64_decode($attr[1]);
1085 }
1087 $attr[1] = trim($attr[1]);
1089 /* Check for attributes that are used more than once */
1090 if(!isset($data[$attr[0]])) {
1091 $data[$attr[0]]=$attr[1];
1092 } else {
1093 $tmp = $data[$attr[0]];
1095 if(!is_array($tmp)) {
1096 $new[0]=$tmp;
1097 $new[1]=$attr[1];
1098 $datas[$attr[0]]['count']=1;
1099 $data[$attr[0]]=$new;
1100 } else {
1101 $cnt = $datas[$attr[0]]['count'];
1102 $cnt ++;
1103 $data[$attr[0]][$cnt]=$attr[1];
1104 $datas[$attr[0]]['count'] = $cnt;
1105 }
1106 }
1107 }
1108 }
1110 /* If dn is an index of data, we should try to insert the data */
1111 if(isset($data['dn'])) {
1113 /* Fix dn */
1114 $tmp = gosa_ldap_explode_dn($data['dn']);
1115 unset($tmp['count']);
1116 $newdn ="";
1117 foreach($tmp as $tm){
1118 $newdn.= trim($tm).",";
1119 }
1120 $newdn = preg_replace("/,$/","",$newdn);
1121 $data['dn'] = $newdn;
1123 /* Creating Entry */
1124 $this->cd($data['dn']);
1126 /* Delete existing entry */
1127 if($delete){
1128 $this->rmdir_recursive($srp, $data['dn']);
1129 }
1131 /* Create missing trees */
1132 $this->cd ($this->basedn);
1133 $this->cd($config->current['BASE']);
1134 $this->create_missing_trees($srp, preg_replace("/^[^,]+,/","",$data['dn']));
1135 $this->cd($data['dn']);
1137 $dn = $data['dn'];
1138 unset($data['dn']);
1140 if(!$modify){
1142 $this->cat($srp, $dn);
1143 if($this->count($srp)){
1145 /* The destination entry exists, overwrite it with the new entry */
1146 $attrs = $this->fetch($srp);
1147 foreach($attrs as $name => $value ){
1148 if(!is_numeric($name)){
1149 if(in_array($name,array("dn","count"))) continue;
1150 if(!isset($data[$name])){
1151 $data[$name] = array();
1152 }
1153 }
1154 }
1155 $ret = $this->modify($data);
1157 }else{
1159 /* The destination entry doesn't exists, create it */
1160 $ret = $this->add($data);
1161 }
1163 } else {
1165 /* Keep all vars that aren't touched by this ldif */
1166 $ret = $this->modify($data);
1167 }
1168 }
1170 if (!$this->success()){
1171 msg_dialog::display(_("LDAP error"), msgPool::ldaperror($this->get_error(), $dn, "", get_class()));
1172 }
1174 return($ret);
1175 }
1178 function importcsv($str)
1179 {
1180 $lines = split("\n",$str);
1181 foreach($lines as $line)
1182 {
1183 /* continue if theres a comment */
1184 if(substr(trim($line),0,1)=="#"){
1185 continue;
1186 }
1188 $line= str_replace ("\t\t","\t",$line);
1189 $line= str_replace ("\t" ,"," ,$line);
1190 echo $line;
1192 $cells = split(",",$line ) ;
1193 $linet= str_replace ("\t\t",",",$line);
1194 $cells = split("\t",$line);
1195 $count = count($cells);
1196 }
1198 }
1200 function get_objectclasses()
1201 {
1202 $objectclasses = array();
1203 global $config;
1205 /* Only read schema if it is allowed */
1206 if(isset($config) && preg_match("/config/i",get_class($config))){
1207 if ($config->get_cfg_value("schemaCheck") != "true"){
1208 return($objectclasses);
1209 }
1210 }
1212 /* Return the cached results. */
1213 if(class_available('session') && session::is_set("LDAP_CACHE::get_objectclasses")){
1214 $objectclasses = session::get("LDAP_CACHE::get_objectclasses");
1215 return($objectclasses);
1216 }
1218 # Get base to look for schema
1219 $sr = @ldap_read ($this->cid, "", "objectClass=*", array("subschemaSubentry"));
1220 $attr = @ldap_get_entries($this->cid,$sr);
1221 if (!isset($attr[0]['subschemasubentry'][0])){
1222 return array();
1223 }
1225 /* Get list of objectclasses and fill array */
1226 $nb= $attr[0]['subschemasubentry'][0];
1227 $objectclasses= array();
1228 $sr= ldap_read ($this->cid, $nb, "objectClass=*", array("objectclasses"));
1229 $attrs= ldap_get_entries($this->cid,$sr);
1230 if (!isset($attrs[0])){
1231 return array();
1232 }
1233 foreach ($attrs[0]['objectclasses'] as $val){
1234 if (preg_match('/^[0-9]+$/', $val)){
1235 continue;
1236 }
1237 $name= "OID";
1238 $pattern= split(' ', $val);
1239 $ocname= preg_replace("/^.* NAME\s+\(*\s*'([^']+)'\s*\)*.*$/", '\\1', $val);
1240 $objectclasses[$ocname]= array();
1242 foreach($pattern as $chunk){
1243 switch($chunk){
1245 case '(':
1246 $value= "";
1247 break;
1249 case ')': if ($name != ""){
1250 $objectclasses[$ocname][$name]= $this->value2container($value);
1251 }
1252 $name= "";
1253 $value= "";
1254 break;
1256 case 'NAME':
1257 case 'DESC':
1258 case 'SUP':
1259 case 'STRUCTURAL':
1260 case 'ABSTRACT':
1261 case 'AUXILIARY':
1262 case 'MUST':
1263 case 'MAY':
1264 if ($name != ""){
1265 $objectclasses[$ocname][$name]= $this->value2container($value);
1266 }
1267 $name= $chunk;
1268 $value= "";
1269 break;
1271 default: $value.= $chunk." ";
1272 }
1273 }
1275 }
1276 if(class_available("session")){
1277 session::set("LDAP_CACHE::get_objectclasses",$objectclasses);
1278 }
1280 return $objectclasses;
1281 }
1284 function value2container($value)
1285 {
1286 /* Set emtpy values to "true" only */
1287 if (preg_match('/^\s*$/', $value)){
1288 return true;
1289 }
1291 /* Remove ' and " if needed */
1292 $value= preg_replace('/^[\'"]/', '', $value);
1293 $value= preg_replace('/[\'"] *$/', '', $value);
1295 /* Convert to array if $ is inside... */
1296 if (preg_match('/\$/', $value)){
1297 $container= preg_split('/\s*\$\s*/', $value);
1298 } else {
1299 $container= chop($value);
1300 }
1302 return ($container);
1303 }
1306 function log($string)
1307 {
1308 if (session::is_set('config')){
1309 $cfg = session::get('config');
1310 if (isset($cfg->current['LDAPSTATS']) && preg_match('/true/i', $cfg->current['LDAPSTATS'])){
1311 syslog (LOG_INFO, $string);
1312 }
1313 }
1314 }
1316 /* added by Guido Serra aka Zeph <zeph@purotesto.it> */
1317 function getCn($dn){
1318 $simple= split(",", $dn);
1320 foreach($simple as $piece) {
1321 $partial= split("=", $piece);
1323 if($partial[0] == "cn"){
1324 return $partial[1];
1325 }
1326 }
1327 }
1330 function get_naming_contexts($server, $admin= "", $password= "")
1331 {
1332 /* Build LDAP connection */
1333 $ds= ldap_connect ($server);
1334 if (!$ds) {
1335 die ("Can't bind to LDAP. No check possible!");
1336 }
1337 ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
1338 $r= ldap_bind ($ds, $admin, $password);
1340 /* Get base to look for naming contexts */
1341 $sr = @ldap_read ($ds, "", "objectClass=*", array("+"));
1342 $attr= @ldap_get_entries($ds,$sr);
1344 return ($attr[0]['namingcontexts']);
1345 }
1348 function get_root_dse($server, $admin= "", $password= "")
1349 {
1350 /* Build LDAP connection */
1351 $ds= ldap_connect ($server);
1352 if (!$ds) {
1353 die ("Can't bind to LDAP. No check possible!");
1354 }
1355 ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
1356 $r= ldap_bind ($ds, $admin, $password);
1358 /* Get base to look for naming contexts */
1359 $sr = @ldap_read ($ds, "", "objectClass=*", array("+"));
1360 $attr= @ldap_get_entries($ds,$sr);
1362 /* Return empty array, if nothing was set */
1363 if (!isset($attr[0])){
1364 return array();
1365 }
1367 /* Rework array... */
1368 $result= array();
1369 for ($i= 0; $i<$attr[0]['count']; $i++){
1370 $result[$attr[0][$i]]= $attr[0][$attr[0][$i]];
1371 unset($result[$attr[0][$i]]['count']);
1372 }
1374 return ($result);
1375 }
1377 }
1378 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
1379 ?>