a0c46a7cc6de9d16ee098c506bd0b41569e23df7
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 return preg_replace('/,\s+/', ',', str_replace(array('\\\\,', '\\\\2C', '\(/', '/\)', '\/'),
95 array("\001CO", "\001CO", "\001OB", "\001CB", "\001SL"), $dn));
96 } else {
97 return ($dn);
98 }
99 }
102 /* Function to fix all problematic characters inside a DN by replacing \001XX
103 codes to their original values. See "convert" for mor information.
104 ',' characters are always expanded to \, (not \2C), since all tested LDAP
105 servers seem to take it the correct way. */
106 static function fix($dn)
107 {
108 if (SPECIALS_OVERRIDE === TRUE){
109 return (str_replace(array('\001CO', '\001OB', '\001CB', '\001SL'),
110 array('\,', '(', ')', '/'), $dn));
111 } else {
112 return ($dn);
113 }
114 }
117 /* Function to fix problematic characters in DN's that are used for search
118 requests. I.e. member=.... */
119 static function prepare4filter($dn)
120 {
121 return normalizeLdap(str_replace('\\\\', '\\\\\\', LDAP::fix($dn)));
122 }
125 function connect()
126 {
127 $this->hascon=false;
128 $this->reconnect=false;
129 if ($this->cid= @ldap_connect($this->hostname)) {
130 @ldap_set_option($this->cid, LDAP_OPT_PROTOCOL_VERSION, 3);
131 if (function_exists("ldap_set_rebind_proc") && $this->follow_referral) {
132 @ldap_set_option($this->cid, LDAP_OPT_REFERRALS, 1);
133 @ldap_set_rebind_proc($this->cid, array(&$this, "rebind"));
134 }
135 if (function_exists("ldap_start_tls") && $this->tls){
136 @ldap_start_tls($this->cid);
137 }
139 $this->error = "No Error";
140 if ($bid = @ldap_bind($this->cid, LDAP::fix($this->binddn), $this->bindpw)) {
141 $this->error = "Success";
142 $this->hascon=true;
143 } else {
144 if ($this->reconnect){
145 if ($this->error != "Success"){
146 $this->error = "Could not rebind to " . $this->binddn;
147 }
148 } else {
149 $this->error = "Could not bind to " . $this->binddn;
150 }
151 }
152 } else {
153 $this->error = "Could not connect to LDAP server";
154 }
155 }
157 function rebind($ldap, $referral)
158 {
159 $credentials= $this->get_credentials($referral);
160 if (@ldap_bind($ldap, LDAP::fix($credentials['ADMINDN']), $credentials['ADMINPASSWORD'])) {
161 $this->error = "Success";
162 $this->hascon=true;
163 $this->reconnect= true;
164 return (0);
165 } else {
166 $this->error = "Could not bind to " . $credentials['ADMINDN'];
167 return NULL;
168 }
169 }
171 function reconnect()
172 {
173 if ($this->reconnect){
174 @ldap_unbind($this->cid);
175 $this->cid = NULL;
176 }
177 }
179 function unbind()
180 {
181 @ldap_unbind($this->cid);
182 $this->cid = NULL;
183 }
185 function disconnect()
186 {
187 if($this->hascon){
188 @ldap_close($this->cid);
189 $this->hascon=false;
190 }
191 }
193 function cd($dir)
194 {
195 if ($dir == ".."){
196 $this->basedn = $this->getParentDir();
197 } else {
198 $this->basedn = LDAP::convert($dir);
199 }
200 }
202 function getParentDir($basedn = "")
203 {
204 if ($basedn==""){
205 $basedn = $this->basedn;
206 } else {
207 $basedn = LDAP::convert($this->basedn);
208 }
209 return(ereg_replace("[^,]*[,]*[ ]*(.*)", "\\1", $basedn));
210 }
213 function search($srp, $filter, $attrs= array())
214 {
215 if($this->hascon){
216 if ($this->reconnect) $this->connect();
218 $start = microtime();
219 $this->clearResult($srp);
220 $this->sr[$srp] = @ldap_search($this->cid, LDAP::fix($this->basedn), $filter, $attrs);
221 $this->error = @ldap_error($this->cid);
222 $this->resetResult($srp);
223 $this->hasres[$srp]=true;
225 /* Check if query took longer as specified in max_ldap_query_time */
226 if($this->max_ldap_query_time){
227 $diff = get_MicroTimeDiff($start,microtime());
228 if($diff > $this->max_ldap_query_time){
229 msg_dialog::display(_("Performance warning"), sprintf(_("LDAP performance is poor: last query took about %.2fs!"), $diff), WARNING_DIALOG);
230 }
231 }
233 $this->log("LDAP operation: time=".get_MicroTimeDiff($start,microtime())." operation=search('".LDAP::fix($this->basedn)."', '$filter')");
234 return($this->sr[$srp]);
235 }else{
236 $this->error = "Could not connect to LDAP server";
237 return("");
238 }
239 }
241 function ls($srp, $filter = "(objectclass=*)", $basedn = "",$attrs = array("*"))
242 {
243 if($this->hascon){
244 if ($this->reconnect) $this->connect();
246 $this->clearResult($srp);
247 if ($basedn == "")
248 $basedn = $this->basedn;
249 else
250 $basedn= LDAP::convert($basedn);
252 $start = microtime();
253 $this->sr[$srp] = @ldap_list($this->cid, LDAP::fix($basedn), $filter,$attrs);
254 $this->error = @ldap_error($this->cid);
255 $this->resetResult($srp);
256 $this->hasres[$srp]=true;
258 /* Check if query took longer as specified in max_ldap_query_time */
259 if($this->max_ldap_query_time){
260 $diff = get_MicroTimeDiff($start,microtime());
261 if($diff > $this->max_ldap_query_time){
262 msg_dialog::display(_("Performance warning"), sprintf(_("LDAP performance is poor: last query took about %.2fs!"), $diff), WARNING_DIALOG);
263 }
264 }
266 $this->log("LDAP operation: time=".get_MicroTimeDiff($start,microtime())." operation=ls('".LDAP::fix($basedn)."', '$filter')");
268 return($this->sr[$srp]);
269 }else{
270 $this->error = "Could not connect to LDAP server";
271 return("");
272 }
273 }
275 function cat($srp, $dn,$attrs= array("*"))
276 {
277 if($this->hascon){
278 if ($this->reconnect) $this->connect();
280 $this->clearResult($srp);
281 $filter = "(objectclass=*)";
282 $this->sr[$srp] = @ldap_read($this->cid, LDAP::fix($dn), $filter,$attrs);
283 $this->error = @ldap_error($this->cid);
284 $this->resetResult($srp);
285 $this->hasres[$srp]=true;
286 return($this->sr[$srp]);
287 }else{
288 $this->error = "Could not connect to LDAP server";
289 return("");
290 }
291 }
293 function object_match_filter($dn,$filter)
294 {
295 if($this->hascon){
296 if ($this->reconnect) $this->connect();
297 $res = @ldap_read($this->cid, LDAP::fix($dn), $filter, array("objectClass"));
298 $rv = @ldap_count_entries($this->cid, $res);
299 return($rv);
300 }else{
301 $this->error = "Could not connect to LDAP server";
302 return(FALSE);
303 }
304 }
306 function set_size_limit($size)
307 {
308 /* Ignore zero settings */
309 if ($size == 0){
310 @ldap_set_option($this->cid, LDAP_OPT_SIZELIMIT, 10000000);
311 }
312 if($this->hascon){
313 @ldap_set_option($this->cid, LDAP_OPT_SIZELIMIT, $size);
314 } else {
315 $this->error = "Could not connect to LDAP server";
316 }
317 }
319 function fetch($srp)
320 {
321 $att= array();
322 if($this->hascon){
323 if($this->hasres[$srp]){
324 if ($this->start[$srp] == 0)
325 {
326 if ($this->sr[$srp]){
327 $this->start[$srp] = 1;
328 $this->re[$srp]= @ldap_first_entry($this->cid, $this->sr[$srp]);
329 } else {
330 return array();
331 }
332 } else {
333 $this->re[$srp]= @ldap_next_entry($this->cid, $this->re[$srp]);
334 }
335 if ($this->re[$srp])
336 {
337 $att= @ldap_get_attributes($this->cid, $this->re[$srp]);
338 $att['dn']= trim(LDAP::convert(@ldap_get_dn($this->cid, $this->re[$srp])));
339 }
340 $this->error = @ldap_error($this->cid);
341 if (!isset($att)){
342 $att= array();
343 }
344 return($att);
345 }else{
346 $this->error = "Perform a fetch with no search";
347 return("");
348 }
349 }else{
350 $this->error = "Could not connect to LDAP server";
351 return("");
352 }
353 }
355 function resetResult($srp)
356 {
357 $this->start[$srp] = 0;
358 }
360 function clearResult($srp)
361 {
362 if($this->hasres[$srp]){
363 $this->hasres[$srp] = false;
364 @ldap_free_result($this->sr[$srp]);
365 }
366 }
368 function getDN($srp)
369 {
370 if($this->hascon){
371 if($this->hasres[$srp]){
373 if(!$this->re[$srp])
374 {
375 $this->error = "Perform a Fetch with no valid Result";
376 }
377 else
378 {
379 $rv = @ldap_get_dn($this->cid, $this->re[$srp]);
381 $this->error = @ldap_error($this->cid);
382 return(trim(LDAP::convert($rv)));
383 }
384 }else{
385 $this->error = "Perform a Fetch with no Search";
386 return("");
387 }
388 }else{
389 $this->error = "Could not connect to LDAP server";
390 return("");
391 }
392 }
394 function count($srp)
395 {
396 if($this->hascon){
397 if($this->hasres[$srp]){
398 $rv = @ldap_count_entries($this->cid, $this->sr[$srp]);
399 $this->error = @ldap_error($this->cid);
400 return($rv);
401 }else{
402 $this->error = "Perform a Fetch with no Search";
403 return("");
404 }
405 }else{
406 $this->error = "Could not connect to LDAP server";
407 return("");
408 }
409 }
411 function rm($attrs = "", $dn = "")
412 {
413 if($this->hascon){
414 if ($this->reconnect) $this->connect();
415 if ($dn == "")
416 $dn = $this->basedn;
418 $r = @ldap_mod_del($this->cid, LDAP::fix($dn), $attrs);
419 $this->error = @ldap_error($this->cid);
420 return($r);
421 }else{
422 $this->error = "Could not connect to LDAP server";
423 return("");
424 }
425 }
427 function rename($attrs, $dn = "")
428 {
429 if($this->hascon){
430 if ($this->reconnect) $this->connect();
431 if ($dn == "")
432 $dn = $this->basedn;
434 $r = @ldap_mod_replace($this->cid, LDAP::fix($dn), $attrs);
435 $this->error = @ldap_error($this->cid);
436 return($r);
437 }else{
438 $this->error = "Could not connect to LDAP server";
439 return("");
440 }
441 }
443 function rmdir($deletedn)
444 {
445 if($this->hascon){
446 if ($this->reconnect) $this->connect();
447 $r = @ldap_delete($this->cid, LDAP::fix($deletedn));
448 $this->error = @ldap_error($this->cid);
449 return($r ? $r : 0);
450 }else{
451 $this->error = "Could not connect to LDAP server";
452 return("");
453 }
454 }
457 /*! \brief Move the given Ldap entry from $source to $dest
458 @param String $source The source dn.
459 @param String $dest The destination dn.
460 @return Boolean TRUE on success else FALSE.
461 */
462 function rename_dn($source,$dest)
463 {
464 /* Check if source and destination are the same entry */
465 if(strtolower($source) == strtolower($dest)){
466 trigger_error("Source and destination can't be the same entry.");
467 $this->error = "Source and destination can't be the same entry.";
468 return(FALSE);
469 }
471 /* Check if destination entry exists */
472 if($this->dn_exists($dest)){
473 trigger_error("Destination '$dest' already exists.");
474 $this->error = "Destination '$dest' already exists.";
475 return(FALSE);
476 }
478 /* Extract the name and the parent part out ouf source dn.
479 e.g. cn=herbert,ou=department,dc=...
480 parent => ou=department,dc=...
481 dest_rdn => cn=herbert
482 */
483 $parent = @LDAP::fix(preg_replace("/^[^,]+,/","", @LDAP::convert($dest)));
484 $dest_rdn = @LDAP::fix(preg_replace("/,.*$/","",@LDAP::convert($dest)));
486 if($this->hascon){
487 if ($this->reconnect) $this->connect();
488 $r= ldap_rename($this->cid,$source,$dest_rdn,$parent,TRUE);
489 $this->error = ldap_error($this->cid);
491 /* Check if destination dn exists, if not the
492 server may not support this operation */
493 $r &= is_resource($this->dn_exists($dest));
494 return($r);
495 }else{
496 $this->error = "Could not connect to LDAP server";
497 return(FALSE);
498 }
499 }
502 /**
503 * Function rmdir_recursive
504 *
505 * Description: Based in recursive_remove, adding two thing: full subtree remove, and delete own node.
506 * Parameters: The dn to delete
507 * GiveBack: True on sucessfull , 0 in error, and "" when we don't get a ldap conection
508 *
509 */
510 function rmdir_recursive($srp, $deletedn)
511 {
512 if($this->hascon){
513 if ($this->reconnect) $this->connect();
514 $delarray= array();
516 /* Get sorted list of dn's to delete */
517 $this->ls ($srp, "(objectClass=*)",$deletedn);
518 while ($this->fetch($srp)){
519 $deldn= $this->getDN($srp);
520 $delarray[$deldn]= strlen($deldn);
521 }
522 arsort ($delarray);
523 reset ($delarray);
525 /* Really Delete ALL dn's in subtree */
526 foreach ($delarray as $key => $value){
527 $this->rmdir_recursive($srp, $key);
528 }
530 /* Finally Delete own Node */
531 $r = @ldap_delete($this->cid, LDAP::fix($deletedn));
532 $this->error = @ldap_error($this->cid);
533 return($r ? $r : 0);
534 }else{
535 $this->error = "Could not connect to LDAP server";
536 return("");
537 }
538 }
541 function modify($attrs)
542 {
543 if(count($attrs) == 0){
544 return (0);
545 }
546 if($this->hascon){
547 if ($this->reconnect) $this->connect();
548 $r = @ldap_modify($this->cid, LDAP::fix($this->basedn), $attrs);
549 $this->error = @ldap_error($this->cid);
550 return($r ? $r : 0);
551 }else{
552 $this->error = "Could not connect to LDAP server";
553 return("");
554 }
555 }
557 function add($attrs)
558 {
559 if($this->hascon){
560 if ($this->reconnect) $this->connect();
561 $r = @ldap_add($this->cid, LDAP::fix($this->basedn), $attrs);
562 $this->error = @ldap_error($this->cid);
563 return($r ? $r : 0);
564 }else{
565 $this->error = "Could not connect to LDAP server";
566 return("");
567 }
568 }
570 function create_missing_trees($srp, $target)
571 {
572 global $config;
574 $real_path= substr($target, 0, strlen($target) - strlen($this->basedn) -1 );
576 if ($target == $this->basedn){
577 $l= array("dummy");
578 } else {
579 $l= array_reverse(gosa_ldap_explode_dn($real_path));
580 }
581 unset($l['count']);
582 $cdn= $this->basedn;
583 $tag= "";
585 /* Load schema if available... */
586 $classes= $this->get_objectclasses();
588 foreach ($l as $part){
589 if ($part != "dummy"){
590 $cdn= "$part,$cdn";
591 }
593 /* Ignore referrals */
594 $found= false;
595 foreach($this->referrals as $ref){
596 $base= preg_replace('!^[^:]+://[^/]+/([^?]+).*$!', '\\1', $ref['URI']);
597 if ($base == $cdn){
598 $found= true;
599 break;
600 }
601 }
602 if ($found){
603 continue;
604 }
606 $this->cat ($srp, $cdn);
607 $attrs= $this->fetch($srp);
609 /* Create missing entry? */
610 if (count ($attrs)){
612 /* Catch the tag - if present */
613 if (isset($attrs['gosaUnitTag'][0])){
614 $tag= $attrs['gosaUnitTag'][0];
615 }
617 } else {
618 $type= preg_replace('/^([^=]+)=.*$/', '\\1', $cdn);
619 $param= preg_replace('/^[^=]+=([^,]+),.*$/', '\\1', $cdn);
621 $na= array();
623 /* Automatic or traditional? */
624 if(count($classes)){
626 /* Get name of first matching objectClass */
627 $ocname= "";
628 foreach($classes as $class){
629 if (isset($class['MUST']) && $class['MUST'] == "$type"){
631 /* Look for first classes that is structural... */
632 if (isset($class['STRUCTURAL'])){
633 $ocname= $class['NAME'];
634 break;
635 }
637 /* Look for classes that are auxiliary... */
638 if (isset($class['AUXILIARY'])){
639 $ocname= $class['NAME'];
640 }
641 }
642 }
644 /* Bail out, if we've nothing to do... */
645 if ($ocname == ""){
646 msg_dialog::display(_("Internal error"), sprintf(_("Cannot automatically create subtrees with RDN '%s': no object class found!"),$type), FATAL_ERROR_DIALOG);
647 exit();
648 }
650 /* Assemble_entry */
651 if ($tag != ""){
652 $na['objectClass']= array($ocname, "gosaAdministrativeUnitTag");
653 $na["gosaUnitTag"]= $tag;
654 } else {
655 $na['objectClass']= array($ocname);
656 }
657 if (isset($classes[$ocname]['AUXILIARY'])){
658 $na['objectClass'][]= $classes[$ocname]['SUP'];
659 }
660 if ($type == "dc"){
661 /* This is bad actually, but - tell me a better way? */
662 $na['objectClass'][]= 'locality';
663 }
664 $na[$type]= $param;
665 if (is_array($classes[$ocname]['MUST'])){
666 foreach($classes[$ocname]['MUST'] as $attr){
667 $na[$attr]= "filled";
668 }
669 }
671 } else {
673 /* Use alternative add... */
674 switch ($type){
675 case 'ou':
676 if ($tag != ""){
677 $na["objectClass"]= array("organizationalUnit", "gosaAdministrativeUnitTag");
678 $na["gosaUnitTag"]= $tag;
679 } else {
680 $na["objectClass"]= "organizationalUnit";
681 }
682 $na["ou"]= $param;
683 break;
684 case 'dc':
685 if ($tag != ""){
686 $na["objectClass"]= array("dcObject", "top", "locality", "gosaAdministrativeUnitTag");
687 $na["gosaUnitTag"]= $tag;
688 } else {
689 $na["objectClass"]= array("dcObject", "top", "locality");
690 }
691 $na["dc"]= $param;
692 break;
693 default:
694 msg_dialog::display(_("Internal error"), sprintf(_("Cannot automatically create subtrees with RDN '%s': not supported"),$type), FATAL_ERROR_DIALOG);
695 exit();
696 }
698 }
699 $this->cd($cdn);
700 $this->add($na);
702 if (!$this->success()){
703 msg_dialog::display(_("LDAP error"), msgPool::ldaperror($this->get_error(), $cdn, LDAP_ADD, get_class()));
704 return FALSE;
705 }
706 }
707 }
709 return TRUE;
710 }
713 function recursive_remove($srp)
714 {
715 $delarray= array();
717 /* Get sorted list of dn's to delete */
718 $this->search ($srp, "(objectClass=*)");
719 while ($this->fetch($srp)){
720 $deldn= $this->getDN($srp);
721 $delarray[$deldn]= strlen($deldn);
722 }
723 arsort ($delarray);
724 reset ($delarray);
726 /* Delete all dn's in subtree */
727 foreach ($delarray as $key => $value){
728 $this->rmdir($key);
729 }
730 }
732 function get_attribute($dn, $name,$r_array=0)
733 {
734 $data= "";
735 if ($this->reconnect) $this->connect();
736 $sr= @ldap_read($this->cid, LDAP::fix($dn), "objectClass=*", array("$name"));
738 /* fill data from LDAP */
739 if ($sr) {
740 $ei= @ldap_first_entry($this->cid, $sr);
741 if ($ei) {
742 if ($info= @ldap_get_values_len($this->cid, $ei, "$name")){
743 $data= $info[0];
744 }
745 }
746 }
747 if($r_array==0)
748 return ($data);
749 else
750 return ($info);
753 }
757 function get_additional_error()
758 {
759 $error= "";
760 @ldap_get_option ($this->cid, LDAP_OPT_ERROR_STRING, $error);
761 return ($error);
762 }
765 function success()
766 {
767 return (preg_match('/Success/i', $this->error));
768 }
771 function get_error()
772 {
773 if ($this->error == 'Success'){
774 return $this->error;
775 } else {
776 $adderror= $this->get_additional_error();
777 if ($adderror != ""){
778 $error= $this->error." (".$this->get_additional_error().", ".sprintf(_("while operating on '%s' using LDAP server '%s'"), $this->basedn, $this->hostname).")";
779 } else {
780 $error= $this->error." (".sprintf(_("while operating on LDAP server %s"), $this->hostname).")";
781 }
782 return $error;
783 }
784 }
786 function get_credentials($url, $referrals= NULL)
787 {
788 $ret= array();
789 $url= preg_replace('!\?\?.*$!', '', $url);
790 $server= preg_replace('!^([^:]+://[^/]+)/.*$!', '\\1', $url);
792 if ($referrals === NULL){
793 $referrals= $this->referrals;
794 }
796 if (isset($referrals[$server])){
797 return ($referrals[$server]);
798 } else {
799 $ret['ADMINDN']= LDAP::fix($this->binddn);
800 $ret['ADMINPASSWORD']= $this->bindpw;
801 }
803 return ($ret);
804 }
807 function gen_ldif ($srp, $dn, $filter= "(objectClass=*)", $attributes= array('*'), $recursive= TRUE)
808 {
809 $display= "";
811 if ($recursive){
812 $this->cd($dn);
813 $this->ls($srp, $filter,$dn, array('dn','objectClass'));
814 $deps = array();
816 $display .= $this->gen_one_entry($dn)."\n";
818 while ($attrs= $this->fetch($srp)){
819 $deps[] = $attrs['dn'];
820 }
821 foreach($deps as $dn){
822 $display .= $this->gen_ldif($srp, $dn, $filter,$attributes,$recursive);
823 }
824 } else {
825 $display.= $this->gen_one_entry($dn);
826 }
827 return ($display);
828 }
831 function gen_xls ($srp, $dn, $filter= "(objectClass=*)", $attributes= array('*'), $recursive= TRUE,$r_array=0)
832 {
833 $display= array();
835 $this->cd($dn);
836 $this->search($srp, "$filter");
838 $i=0;
839 while ($attrs= $this->fetch($srp)){
840 $j=0;
842 foreach ($attributes as $at){
843 $display[$i][$j]= $this->get_attribute($attrs['dn'], $at,$r_array);
844 $j++;
845 }
847 $i++;
848 }
850 return ($display);
851 }
854 function gen_one_entry($dn, $filter= "(objectClass=*)" , $name= array("*"))
855 {
856 $ret = "";
857 $data = "";
858 if($this->reconnect){
859 $this->connect();
860 }
862 /* Searching Ldap Tree */
863 $sr= @ldap_read($this->cid, LDAP::fix($dn), $filter, $name);
865 /* Get the first entry */
866 $entry= @ldap_first_entry($this->cid, $sr);
868 /* Get all attributes related to that Objekt */
869 $atts = array();
871 /* Assemble dn */
872 $atts[0]['name'] = "dn";
873 $atts[0]['value'] = array('count' => 1, 0 => $dn);
875 /* Reset index */
876 $i = 1 ;
877 $identifier = array();
878 $attribute= @ldap_first_attribute($this->cid,$entry,$identifier);
879 while ($attribute) {
880 $i++;
881 $atts[$i]['name'] = $attribute;
882 $atts[$i]['value'] = @ldap_get_values_len($this->cid, $entry, "$attribute");
884 /* Next one */
885 $attribute= @ldap_next_attribute($this->cid,$entry,$identifier);
886 }
888 foreach($atts as $at)
889 {
890 for ($i= 0; $i<$at['value']['count']; $i++){
892 /* Check if we must encode the data */
893 if(!preg_match('/^[a-z0-9+@#.=, \/ -]+$/i', $at['value'][$i])) {
894 $ret .= $at['name'].":: ".base64_encode($at['value'][$i])."\n";
895 } else {
896 $ret .= $at['name'].": ".$at['value'][$i]."\n";
897 }
898 }
899 }
901 return($ret);
902 }
905 function dn_exists($dn)
906 {
907 return @ldap_list($this->cid, LDAP::fix($dn), "(objectClass=*)", array("objectClass"));
908 }
912 /* This funktion imports ldifs
914 If DeleteOldEntries is true, the destination entry will be deleted first.
915 If JustModify is true the destination entry will only be touched by the attributes specified in the ldif.
916 if JustMofify id false the destination dn will be overwritten by the new ldif.
917 */
919 function import_complete_ldif($srp, $str_attr,$error,$JustModify,$DeleteOldEntries)
920 {
921 if($this->reconnect) $this->connect();
923 /* First we have to splitt the string ito detect empty lines
924 An empty line indicates an new Entry */
925 $entries = split("\n",$str_attr);
927 $data = "";
928 $cnt = 0;
929 $current_line = 0;
931 /* FIX ldif */
932 $last = "";
933 $tmp = "";
934 $i = 0;
935 foreach($entries as $entry){
936 if(preg_match("/^ /",$entry)){
937 $tmp[$i] .= trim($entry);
938 }else{
939 $i ++;
940 $tmp[$i] = trim($entry);
941 }
942 }
944 /* Every single line ... */
945 foreach($tmp as $entry) {
946 $current_line ++;
948 /* Removing Spaces to ..
949 .. test if a new entry begins */
950 $tmp = str_replace(" ","",$data );
952 /* .. prevent empty lines in an entry */
953 $tmp2 = str_replace(" ","",$entry);
955 /* If the Block ends (Empty Line) */
956 if((empty($entry))&&(!empty($tmp))) {
957 /* Add collected lines as a complete block */
958 $all[$cnt] = $data;
959 $cnt ++;
960 $data ="";
961 } else {
963 /* Append lines ... */
964 if(!empty($tmp2)) {
965 /* check if we need base64_decode for this line */
966 if(ereg("::",$tmp2))
967 {
968 $encoded = split("::",$entry);
969 $attr = trim($encoded[0]);
970 $value = base64_decode(trim($encoded[1]));
971 /* Add linenumber */
972 $data .= $current_line."#".base64_encode($attr.":".$value)."\n";
973 }
974 else
975 {
976 /* Add Linenumber */
977 $data .= $current_line."#".base64_encode($entry)."\n";
978 }
979 }
980 }
981 }
983 /* The Data we collected is not in the array all[];
984 For example the Data is stored like this..
986 all[0] = "1#dn : .... \n
987 2#ObjectType: person \n ...."
989 Now we check every insertblock and try to insert */
990 foreach ( $all as $single) {
991 $lineone = split("\n",$single);
992 $ndn = split("#", $lineone[0]);
993 $line = base64_decode($ndn[1]);
995 $dnn = split (":",$line,2);
996 $current_line = $ndn[0];
997 $dn = $dnn[0];
998 $value = $dnn[1];
1000 /* Every block must begin with a dn */
1001 if($dn != "dn") {
1002 $error= sprintf(_("This is not a valid DN: '%s'. A block for import should begin with 'dn: ...' in line %s"), $line, $current_line);
1003 return -2;
1004 }
1006 /* Should we use Modify instead of Add */
1007 $usemodify= false;
1009 /* Delete before insert */
1010 $usermdir= false;
1012 /* The dn address already exists, Don't delete destination entry, overwrite it */
1013 if (($this->dn_exists($value))&&((!$JustModify)&&(!$DeleteOldEntries))) {
1015 $usermdir = $usemodify = false;
1017 /* Delete old entry first, then add new */
1018 } elseif(($this->dn_exists($value))&&($DeleteOldEntries)){
1020 /* Delete first, then add */
1021 $usermdir = true;
1023 } elseif(($this->dn_exists($value))&&($JustModify)) {
1025 /* Modify instead of Add */
1026 $usemodify = true;
1027 }
1029 /* If we can't Import, return with a file error */
1030 if(!$this->import_single_entry($srp, $single,$usemodify,$usermdir) ) {
1031 $error= sprintf(_("Error while importing dn: '%s', please check your LDIF from line %s on!"), $line,
1032 $current_line);
1033 return UNKNOWN_TOKEN_IN_LDIF_FILE; }
1034 }
1036 return (INSERT_OK);
1037 }
1040 /* Imports a single entry
1041 If $delete is true; The old entry will be deleted if it exists.
1042 if $modify is true; All variables that are not touched by the new ldif will be kept.
1043 if $modify is false; The new ldif overwrites the old entry, and all untouched attributes get lost.
1044 */
1045 function import_single_entry($srp, $str_attr,$modify,$delete)
1046 {
1047 global $config;
1049 if(!$config){
1050 trigger_error("Can't import ldif, can't read config object.");
1051 }
1054 if($this->reconnect) $this->connect();
1056 $ret = false;
1057 $rows= split("\n",$str_attr);
1058 $data= false;
1060 foreach($rows as $row) {
1062 /* Check if we use Linenumbers (when import_complete_ldif is called we use
1063 Linenumbers) Linenumbers are use like this 123#attribute : value */
1064 if(!empty($row)) {
1065 if(strpos($row,"#")!=FALSE) {
1067 /* We are using line numbers
1068 Because there is a # before a : */
1069 $tmp1= split("#",$row);
1070 $current_line= $tmp1[0];
1071 $row= base64_decode($tmp1[1]);
1072 }
1074 /* Split the line into attribute and value */
1075 $attr = split(":", $row,2);
1076 $attr[0]= trim($attr[0]); /* attribute */
1077 $attr[1]= $attr[1]; /* value */
1079 /* Check :: was used to indicate base64_encoded strings */
1080 if($attr[1][0] == ":"){
1081 $attr[1]=trim(preg_replace("/^:/","",$attr[1]));
1082 $attr[1]=base64_decode($attr[1]);
1083 }
1085 $attr[1] = trim($attr[1]);
1087 /* Check for attributes that are used more than once */
1088 if(!isset($data[$attr[0]])) {
1089 $data[$attr[0]]=$attr[1];
1090 } else {
1091 $tmp = $data[$attr[0]];
1093 if(!is_array($tmp)) {
1094 $new[0]=$tmp;
1095 $new[1]=$attr[1];
1096 $datas[$attr[0]]['count']=1;
1097 $data[$attr[0]]=$new;
1098 } else {
1099 $cnt = $datas[$attr[0]]['count'];
1100 $cnt ++;
1101 $data[$attr[0]][$cnt]=$attr[1];
1102 $datas[$attr[0]]['count'] = $cnt;
1103 }
1104 }
1105 }
1106 }
1108 /* If dn is an index of data, we should try to insert the data */
1109 if(isset($data['dn'])) {
1111 /* Fix dn */
1112 $tmp = gosa_ldap_explode_dn($data['dn']);
1113 unset($tmp['count']);
1114 $newdn ="";
1115 foreach($tmp as $tm){
1116 $newdn.= trim($tm).",";
1117 }
1118 $newdn = preg_replace("/,$/","",$newdn);
1119 $data['dn'] = $newdn;
1121 /* Creating Entry */
1122 $this->cd($data['dn']);
1124 /* Delete existing entry */
1125 if($delete){
1126 $this->rmdir_recursive($srp, $data['dn']);
1127 }
1129 /* Create missing trees */
1130 $this->cd ($this->basedn);
1131 $this->cd($config->current['BASE']);
1132 $this->create_missing_trees($srp, preg_replace("/^[^,]+,/","",$data['dn']));
1133 $this->cd($data['dn']);
1135 $dn = $data['dn'];
1136 unset($data['dn']);
1138 if(!$modify){
1140 $this->cat($srp, $dn);
1141 if($this->count($srp)){
1143 /* The destination entry exists, overwrite it with the new entry */
1144 $attrs = $this->fetch($srp);
1145 foreach($attrs as $name => $value ){
1146 if(!is_numeric($name)){
1147 if(in_array($name,array("dn","count"))) continue;
1148 if(!isset($data[$name])){
1149 $data[$name] = array();
1150 }
1151 }
1152 }
1153 $ret = $this->modify($data);
1155 }else{
1157 /* The destination entry doesn't exists, create it */
1158 $ret = $this->add($data);
1159 }
1161 } else {
1163 /* Keep all vars that aren't touched by this ldif */
1164 $ret = $this->modify($data);
1165 }
1166 }
1168 if (!$this->success()){
1169 msg_dialog::display(_("LDAP error"), msgPool::ldaperror($this->get_error(), $dn, "", get_class()));
1170 }
1172 return($ret);
1173 }
1176 function importcsv($str)
1177 {
1178 $lines = split("\n",$str);
1179 foreach($lines as $line)
1180 {
1181 /* continue if theres a comment */
1182 if(substr(trim($line),0,1)=="#"){
1183 continue;
1184 }
1186 $line= str_replace ("\t\t","\t",$line);
1187 $line= str_replace ("\t" ,"," ,$line);
1188 echo $line;
1190 $cells = split(",",$line ) ;
1191 $linet= str_replace ("\t\t",",",$line);
1192 $cells = split("\t",$line);
1193 $count = count($cells);
1194 }
1196 }
1198 function get_objectclasses()
1199 {
1200 $objectclasses = array();
1201 global $config;
1203 /* Only read schema if it is allowed */
1204 if(isset($config) && preg_match("/config/i",get_class($config))){
1205 if ($config->get_cfg_value("schemaCheck") != "true"){
1206 return($objectclasses);
1207 }
1208 }
1210 /* Return the cached results. */
1211 if(class_available('session') && session::is_set("LDAP_CACHE::get_objectclasses")){
1212 $objectclasses = session::get("LDAP_CACHE::get_objectclasses");
1213 return($objectclasses);
1214 }
1216 # Get base to look for schema
1217 $sr = @ldap_read ($this->cid, "", "objectClass=*", array("subschemaSubentry"));
1218 $attr = @ldap_get_entries($this->cid,$sr);
1219 if (!isset($attr[0]['subschemasubentry'][0])){
1220 return array();
1221 }
1223 /* Get list of objectclasses and fill array */
1224 $nb= $attr[0]['subschemasubentry'][0];
1225 $objectclasses= array();
1226 $sr= ldap_read ($this->cid, $nb, "objectClass=*", array("objectclasses"));
1227 $attrs= ldap_get_entries($this->cid,$sr);
1228 if (!isset($attrs[0])){
1229 return array();
1230 }
1231 foreach ($attrs[0]['objectclasses'] as $val){
1232 if (preg_match('/^[0-9]+$/', $val)){
1233 continue;
1234 }
1235 $name= "OID";
1236 $pattern= split(' ', $val);
1237 $ocname= preg_replace("/^.* NAME\s+\(*\s*'([^']+)'\s*\)*.*$/", '\\1', $val);
1238 $objectclasses[$ocname]= array();
1240 foreach($pattern as $chunk){
1241 switch($chunk){
1243 case '(':
1244 $value= "";
1245 break;
1247 case ')': if ($name != ""){
1248 $objectclasses[$ocname][$name]= $this->value2container($value);
1249 }
1250 $name= "";
1251 $value= "";
1252 break;
1254 case 'NAME':
1255 case 'DESC':
1256 case 'SUP':
1257 case 'STRUCTURAL':
1258 case 'ABSTRACT':
1259 case 'AUXILIARY':
1260 case 'MUST':
1261 case 'MAY':
1262 if ($name != ""){
1263 $objectclasses[$ocname][$name]= $this->value2container($value);
1264 }
1265 $name= $chunk;
1266 $value= "";
1267 break;
1269 default: $value.= $chunk." ";
1270 }
1271 }
1273 }
1274 if(class_available("session")){
1275 session::set("LDAP_CACHE::get_objectclasses",$objectclasses);
1276 }
1278 return $objectclasses;
1279 }
1282 function value2container($value)
1283 {
1284 /* Set emtpy values to "true" only */
1285 if (preg_match('/^\s*$/', $value)){
1286 return true;
1287 }
1289 /* Remove ' and " if needed */
1290 $value= preg_replace('/^[\'"]/', '', $value);
1291 $value= preg_replace('/[\'"] *$/', '', $value);
1293 /* Convert to array if $ is inside... */
1294 if (preg_match('/\$/', $value)){
1295 $container= preg_split('/\s*\$\s*/', $value);
1296 } else {
1297 $container= chop($value);
1298 }
1300 return ($container);
1301 }
1304 function log($string)
1305 {
1306 if (session::is_set('config')){
1307 $cfg = session::get('config');
1308 if (isset($cfg->current['LDAPSTATS']) && preg_match('/true/i', $cfg->current['LDAPSTATS'])){
1309 syslog (LOG_INFO, $string);
1310 }
1311 }
1312 }
1314 /* added by Guido Serra aka Zeph <zeph@purotesto.it> */
1315 function getCn($dn){
1316 $simple= split(",", $dn);
1318 foreach($simple as $piece) {
1319 $partial= split("=", $piece);
1321 if($partial[0] == "cn"){
1322 return $partial[1];
1323 }
1324 }
1325 }
1328 function get_naming_contexts($server, $admin= "", $password= "")
1329 {
1330 /* Build LDAP connection */
1331 $ds= ldap_connect ($server);
1332 if (!$ds) {
1333 die ("Can't bind to LDAP. No check possible!");
1334 }
1335 ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
1336 $r= ldap_bind ($ds, $admin, $password);
1338 /* Get base to look for naming contexts */
1339 $sr = @ldap_read ($ds, "", "objectClass=*", array("+"));
1340 $attr= @ldap_get_entries($ds,$sr);
1342 return ($attr[0]['namingcontexts']);
1343 }
1346 function get_root_dse($server, $admin= "", $password= "")
1347 {
1348 /* Build LDAP connection */
1349 $ds= ldap_connect ($server);
1350 if (!$ds) {
1351 die ("Can't bind to LDAP. No check possible!");
1352 }
1353 ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
1354 $r= ldap_bind ($ds, $admin, $password);
1356 /* Get base to look for naming contexts */
1357 $sr = @ldap_read ($ds, "", "objectClass=*", array("+"));
1358 $attr= @ldap_get_entries($ds,$sr);
1360 /* Return empty array, if nothing was set */
1361 if (!isset($attr[0])){
1362 return array();
1363 }
1365 /* Rework array... */
1366 $result= array();
1367 for ($i= 0; $i<$attr[0]['count']; $i++){
1368 $result[$attr[0][$i]]= $attr[0][$attr[0][$i]];
1369 unset($result[$attr[0][$i]]['count']);
1370 }
1372 return ($result);
1373 }
1375 }
1376 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
1377 ?>