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(isset($config->data['MAIN']['MAX_LDAP_QUERY_TIME'])){
64 $str = $config->data['MAIN']['MAX_LDAP_QUERY_TIME'];
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 }
120 /* Function to fix problematic characters in DN's that are used for search
121 requests. I.e. member=.... */
122 static function prepare4filter($dn)
123 {
124 return normalizeLdap(preg_replace('/\\\\/', '\\\\\\', LDAP::fix($dn)));
125 }
128 function connect()
129 {
130 $this->hascon=false;
131 $this->reconnect=false;
132 if ($this->cid= @ldap_connect($this->hostname)) {
133 @ldap_set_option($this->cid, LDAP_OPT_PROTOCOL_VERSION, 3);
134 if (function_exists("ldap_set_rebind_proc") && $this->follow_referral) {
135 @ldap_set_option($this->cid, LDAP_OPT_REFERRALS, 1);
136 @ldap_set_rebind_proc($this->cid, array(&$this, "rebind"));
137 }
138 if (function_exists("ldap_start_tls") && $this->tls){
139 @ldap_start_tls($this->cid);
140 }
142 $this->error = "No Error";
143 if ($bid = @ldap_bind($this->cid, LDAP::fix($this->binddn), $this->bindpw)) {
144 $this->error = "Success";
145 $this->hascon=true;
146 } else {
147 if ($this->reconnect){
148 if ($this->error != "Success"){
149 $this->error = "Could not rebind to " . $this->binddn;
150 }
151 } else {
152 $this->error = "Could not bind to " . $this->binddn;
153 }
154 }
155 } else {
156 $this->error = "Could not connect to LDAP server";
157 }
158 }
160 function rebind($ldap, $referral)
161 {
162 $credentials= $this->get_credentials($referral);
163 if (@ldap_bind($ldap, LDAP::fix($credentials['ADMIN']), $credentials['PASSWORD'])) {
164 $this->error = "Success";
165 $this->hascon=true;
166 $this->reconnect= true;
167 return (0);
168 } else {
169 $this->error = "Could not bind to " . $credentials['ADMIN'];
170 return NULL;
171 }
172 }
174 function reconnect()
175 {
176 if ($this->reconnect){
177 @ldap_unbind($this->cid);
178 $this->cid = NULL;
179 }
180 }
182 function unbind()
183 {
184 @ldap_unbind($this->cid);
185 $this->cid = NULL;
186 }
188 function disconnect()
189 {
190 if($this->hascon){
191 @ldap_close($this->cid);
192 $this->hascon=false;
193 }
194 }
196 function cd($dir)
197 {
198 if ($dir == ".."){
199 $this->basedn = $this->getParentDir();
200 } else {
201 $this->basedn = LDAP::convert($dir);
202 }
203 }
205 function getParentDir($basedn = "")
206 {
207 if ($basedn==""){
208 $basedn = $this->basedn;
209 } else {
210 $basedn = LDAP::convert($this->basedn);
211 }
212 return(ereg_replace("[^,]*[,]*[ ]*(.*)", "\\1", $basedn));
213 }
216 function search($srp, $filter, $attrs= array())
217 {
218 if($this->hascon){
219 if ($this->reconnect) $this->connect();
221 $start = microtime();
222 $this->clearResult($srp);
223 $this->sr[$srp] = @ldap_search($this->cid, LDAP::fix($this->basedn), $filter, $attrs);
224 $this->error = @ldap_error($this->cid);
225 $this->resetResult($srp);
226 $this->hasres[$srp]=true;
228 /* Check if query took longer as specified in max_ldap_query_time */
229 if($this->max_ldap_query_time){
230 $diff = get_MicroTimeDiff($start,microtime());
231 if($diff > $this->max_ldap_query_time){
232 msg_dialog::display(_("Performance warning"), sprintf(_("LDAP performance is poor: last query took about %.2fs!"), $diff), WARNING_DIALOG);
233 }
234 }
236 $this->log("LDAP operation: time=".get_MicroTimeDiff($start,microtime())." operation=search('".LDAP::fix($this->basedn)."', '$filter')");
237 return($this->sr[$srp]);
238 }else{
239 $this->error = "Could not connect to LDAP server";
240 return("");
241 }
242 }
244 function ls($srp, $filter = "(objectclass=*)", $basedn = "",$attrs = array("*"))
245 {
246 if($this->hascon){
247 if ($this->reconnect) $this->connect();
249 $this->clearResult($srp);
250 if ($basedn == "")
251 $basedn = $this->basedn;
252 else
253 $basedn= LDAP::convert($basedn);
255 $start = microtime();
256 $this->sr[$srp] = @ldap_list($this->cid, LDAP::fix($basedn), $filter,$attrs);
257 $this->error = @ldap_error($this->cid);
258 $this->resetResult($srp);
259 $this->hasres[$srp]=true;
261 /* Check if query took longer as specified in max_ldap_query_time */
262 if($this->max_ldap_query_time){
263 $diff = get_MicroTimeDiff($start,microtime());
264 if($diff > $this->max_ldap_query_time){
265 msg_dialog::display(_("Performance warning"), sprintf(_("LDAP performance is poor: last query took about %.2fs!"), $diff), WARNING_DIALOG);
266 }
267 }
269 $this->log("LDAP operation: time=".get_MicroTimeDiff($start,microtime())." operation=ls('".LDAP::fix($basedn)."', '$filter')");
271 return($this->sr[$srp]);
272 }else{
273 $this->error = "Could not connect to LDAP server";
274 return("");
275 }
276 }
278 function cat($srp, $dn,$attrs= array("*"))
279 {
280 if($this->hascon){
281 if ($this->reconnect) $this->connect();
283 $this->clearResult($srp);
284 $filter = "(objectclass=*)";
285 $this->sr[$srp] = @ldap_read($this->cid, LDAP::fix($dn), $filter,$attrs);
286 $this->error = @ldap_error($this->cid);
287 $this->resetResult($srp);
288 $this->hasres[$srp]=true;
289 return($this->sr[$srp]);
290 }else{
291 $this->error = "Could not connect to LDAP server";
292 return("");
293 }
294 }
296 function set_size_limit($size)
297 {
298 /* Ignore zero settings */
299 if ($size == 0){
300 @ldap_set_option($this->cid, LDAP_OPT_SIZELIMIT, 10000000);
301 }
302 if($this->hascon){
303 @ldap_set_option($this->cid, LDAP_OPT_SIZELIMIT, $size);
304 } else {
305 $this->error = "Could not connect to LDAP server";
306 }
307 }
309 function fetch($srp)
310 {
311 $att= array();
312 if($this->hascon){
313 if($this->hasres[$srp]){
314 if ($this->start[$srp] == 0)
315 {
316 if ($this->sr[$srp]){
317 $this->start[$srp] = 1;
318 $this->re[$srp]= @ldap_first_entry($this->cid, $this->sr[$srp]);
319 } else {
320 return array();
321 }
322 } else {
323 $this->re[$srp]= @ldap_next_entry($this->cid, $this->re[$srp]);
324 }
325 if ($this->re[$srp])
326 {
327 $att= @ldap_get_attributes($this->cid, $this->re[$srp]);
328 $att['dn']= trim(LDAP::convert(@ldap_get_dn($this->cid, $this->re[$srp])));
329 }
330 $this->error = @ldap_error($this->cid);
331 if (!isset($att)){
332 $att= array();
333 }
334 return($att);
335 }else{
336 $this->error = "Perform a fetch with no search";
337 return("");
338 }
339 }else{
340 $this->error = "Could not connect to LDAP server";
341 return("");
342 }
343 }
345 function resetResult($srp)
346 {
347 $this->start[$srp] = 0;
348 }
350 function clearResult($srp)
351 {
352 if($this->hasres[$srp]){
353 $this->hasres[$srp] = false;
354 @ldap_free_result($this->sr[$srp]);
355 }
356 }
358 function getDN($srp)
359 {
360 if($this->hascon){
361 if($this->hasres[$srp]){
363 if(!$this->re[$srp])
364 {
365 $this->error = "Perform a Fetch with no valid Result";
366 }
367 else
368 {
369 $rv = @ldap_get_dn($this->cid, $this->re[$srp]);
371 $this->error = @ldap_error($this->cid);
372 return(trim(LDAP::convert($rv)));
373 }
374 }else{
375 $this->error = "Perform a Fetch with no Search";
376 return("");
377 }
378 }else{
379 $this->error = "Could not connect to LDAP server";
380 return("");
381 }
382 }
384 function count($srp)
385 {
386 if($this->hascon){
387 if($this->hasres[$srp]){
388 $rv = @ldap_count_entries($this->cid, $this->sr[$srp]);
389 $this->error = @ldap_error($this->cid);
390 return($rv);
391 }else{
392 $this->error = "Perform a Fetch with no Search";
393 return("");
394 }
395 }else{
396 $this->error = "Could not connect to LDAP server";
397 return("");
398 }
399 }
401 function rm($attrs = "", $dn = "")
402 {
403 if($this->hascon){
404 if ($this->reconnect) $this->connect();
405 if ($dn == "")
406 $dn = $this->basedn;
408 $r = @ldap_mod_del($this->cid, LDAP::fix($dn), $attrs);
409 $this->error = @ldap_error($this->cid);
410 return($r);
411 }else{
412 $this->error = "Could not connect to LDAP server";
413 return("");
414 }
415 }
417 function rename($attrs, $dn = "")
418 {
419 if($this->hascon){
420 if ($this->reconnect) $this->connect();
421 if ($dn == "")
422 $dn = $this->basedn;
424 $r = @ldap_mod_replace($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 rmdir($deletedn)
434 {
435 if($this->hascon){
436 if ($this->reconnect) $this->connect();
437 $r = @ldap_delete($this->cid, LDAP::fix($deletedn));
438 $this->error = @ldap_error($this->cid);
439 return($r ? $r : 0);
440 }else{
441 $this->error = "Could not connect to LDAP server";
442 return("");
443 }
444 }
447 /*! \brief Move the given Ldap entry from $source to $dest
448 @param String $source The source dn.
449 @param String $dest The destination dn.
450 @return Boolean TRUE on success else FALSE.
451 */
452 function rename_dn($source,$dest)
453 {
454 /* Check if source and destination are the same entry */
455 if(strtolower($source) == strtolower($dest)){
456 trigger_error("Source and destination can't be the same entry.");
457 $this->error = "Source and destination can't be the same entry.";
458 return(FALSE);
459 }
461 /* Check if destination entry exists */
462 if($this->dn_exists($dest)){
463 trigger_error("Destination '$dest' already exists.");
464 $this->error = "Destination '$dest' already exists.";
465 return(FALSE);
466 }
468 /* Extract the name and the parent part out ouf source dn.
469 e.g. cn=herbert,ou=department,dc=...
470 parent => ou=department,dc=...
471 dest_rdn => cn=herbert
472 */
473 $parent = preg_replace("/^[^,]+,/","",$dest);
474 $dest_rdn = preg_replace("/,.*$/","",$dest);
476 if($this->hascon){
477 if ($this->reconnect) $this->connect();
478 $r= ldap_rename($this->cid,$source,$dest_rdn,$parent,TRUE);
479 $this->error = ldap_error($this->cid);
481 /* Check if destination dn exists, if not the
482 server may not support this operation */
483 $r &= is_resource($this->dn_exists($dest));
484 return($r);
485 }else{
486 $this->error = "Could not connect to LDAP server";
487 return(FALSE);
488 }
489 }
492 /**
493 * Function rmdir_recursive
494 *
495 * Description: Based in recursive_remove, adding two thing: full subtree remove, and delete own node.
496 * Parameters: The dn to delete
497 * GiveBack: True on sucessfull , 0 in error, and "" when we don't get a ldap conection
498 *
499 */
500 function rmdir_recursive($srp, $deletedn)
501 {
502 if($this->hascon){
503 if ($this->reconnect) $this->connect();
504 $delarray= array();
506 /* Get sorted list of dn's to delete */
507 $this->ls ($srp, "(objectClass=*)",$deletedn);
508 while ($this->fetch($srp)){
509 $deldn= $this->getDN($srp);
510 $delarray[$deldn]= strlen($deldn);
511 }
512 arsort ($delarray);
513 reset ($delarray);
515 /* Really Delete ALL dn's in subtree */
516 foreach ($delarray as $key => $value){
517 $this->rmdir_recursive($srp, $key);
518 }
520 /* Finally Delete own Node */
521 $r = @ldap_delete($this->cid, LDAP::fix($deletedn));
522 $this->error = @ldap_error($this->cid);
523 return($r ? $r : 0);
524 }else{
525 $this->error = "Could not connect to LDAP server";
526 return("");
527 }
528 }
531 function modify($attrs)
532 {
533 if(count($attrs) == 0){
534 return (0);
535 }
536 if($this->hascon){
537 if ($this->reconnect) $this->connect();
538 $r = @ldap_modify($this->cid, LDAP::fix($this->basedn), $attrs);
539 $this->error = @ldap_error($this->cid);
540 return($r ? $r : 0);
541 }else{
542 $this->error = "Could not connect to LDAP server";
543 return("");
544 }
545 }
547 function add($attrs)
548 {
549 if($this->hascon){
550 if ($this->reconnect) $this->connect();
551 $r = @ldap_add($this->cid, LDAP::fix($this->basedn), $attrs);
552 $this->error = @ldap_error($this->cid);
553 return($r ? $r : 0);
554 }else{
555 $this->error = "Could not connect to LDAP server";
556 return("");
557 }
558 }
560 function create_missing_trees($srp, $target)
561 {
562 global $config;
564 $real_path= substr($target, 0, strlen($target) - strlen($this->basedn) -1 );
566 if ($target == $this->basedn){
567 $l= array("dummy");
568 } else {
569 $l= array_reverse(gosa_ldap_explode_dn($real_path));
570 }
571 unset($l['count']);
572 $cdn= $this->basedn;
573 $tag= "";
575 /* Load schema if available... */
576 $classes= $this->get_objectclasses();
578 foreach ($l as $part){
579 if ($part != "dummy"){
580 $cdn= "$part,$cdn";
581 }
583 /* Ignore referrals */
584 $found= false;
585 foreach($this->referrals as $ref){
586 $base= preg_replace('!^[^:]+://[^/]+/([^?]+).*$!', '\\1', $ref['URL']);
587 if ($base == $cdn){
588 $found= true;
589 break;
590 }
591 }
592 if ($found){
593 continue;
594 }
596 $this->cat ($srp, $cdn);
597 $attrs= $this->fetch($srp);
599 /* Create missing entry? */
600 if (count ($attrs)){
602 /* Catch the tag - if present */
603 if (isset($attrs['gosaUnitTag'][0])){
604 $tag= $attrs['gosaUnitTag'][0];
605 }
607 } else {
608 $type= preg_replace('/^([^=]+)=.*$/', '\\1', $cdn);
609 $param= preg_replace('/^[^=]+=([^,]+),.*$/', '\\1', $cdn);
611 $na= array();
613 /* Automatic or traditional? */
614 if(count($classes)){
616 /* Get name of first matching objectClass */
617 $ocname= "";
618 foreach($classes as $class){
619 if (isset($class['MUST']) && $class['MUST'] == "$type"){
621 /* Look for first classes that is structural... */
622 if (isset($class['STRUCTURAL'])){
623 $ocname= $class['NAME'];
624 break;
625 }
627 /* Look for classes that are auxiliary... */
628 if (isset($class['AUXILIARY'])){
629 $ocname= $class['NAME'];
630 }
631 }
632 }
634 /* Bail out, if we've nothing to do... */
635 if ($ocname == ""){
636 msg_dialog::display(_("Internal error"), sprintf(_("Cannot automatically create subtrees with RDN '%s': no object class found!"),$type), FATAL_ERROR_DIALOG);
637 exit();
638 }
640 /* Assemble_entry */
641 if ($tag != ""){
642 $na['objectClass']= array($ocname, "gosaAdministrativeUnitTag");
643 $na["gosaUnitTag"]= $tag;
644 } else {
645 $na['objectClass']= array($ocname);
646 }
647 if (isset($classes[$ocname]['AUXILIARY'])){
648 $na['objectClass'][]= $classes[$ocname]['SUP'];
649 }
650 if ($type == "dc"){
651 /* This is bad actually, but - tell me a better way? */
652 $na['objectClass'][]= 'locality';
653 }
654 $na[$type]= $param;
655 if (is_array($classes[$ocname]['MUST'])){
656 foreach($classes[$ocname]['MUST'] as $attr){
657 $na[$attr]= "filled";
658 }
659 }
661 } else {
663 /* Use alternative add... */
664 switch ($type){
665 case 'ou':
666 if ($tag != ""){
667 $na["objectClass"]= array("organizationalUnit", "gosaAdministrativeUnitTag");
668 $na["gosaUnitTag"]= $tag;
669 } else {
670 $na["objectClass"]= "organizationalUnit";
671 }
672 $na["ou"]= $param;
673 break;
674 case 'dc':
675 if ($tag != ""){
676 $na["objectClass"]= array("dcObject", "top", "locality", "gosaAdministrativeUnitTag");
677 $na["gosaUnitTag"]= $tag;
678 } else {
679 $na["objectClass"]= array("dcObject", "top", "locality");
680 }
681 $na["dc"]= $param;
682 break;
683 default:
684 msg_dialog::display(_("Internal error"), sprintf(_("Cannot automatically create subtrees with RDN '%s': not supported"),$type), FATAL_ERROR_DIALOG);
685 exit();
686 }
688 }
689 $this->cd($cdn);
690 $this->add($na);
692 if (!$this->success()){
693 msg_dialog::display(_("LDAP error"), msgPool::ldaperror($this->get_error(), $cdn, LDAP_ADD, get_class()));
694 return FALSE;
695 }
696 }
697 }
699 return TRUE;
700 }
703 function recursive_remove($srp)
704 {
705 $delarray= array();
707 /* Get sorted list of dn's to delete */
708 $this->search ($srp, "(objectClass=*)");
709 while ($this->fetch($srp)){
710 $deldn= $this->getDN($srp);
711 $delarray[$deldn]= strlen($deldn);
712 }
713 arsort ($delarray);
714 reset ($delarray);
716 /* Delete all dn's in subtree */
717 foreach ($delarray as $key => $value){
718 $this->rmdir($key);
719 }
720 }
722 function get_attribute($dn, $name,$r_array=0)
723 {
724 $data= "";
725 if ($this->reconnect) $this->connect();
726 $sr= @ldap_read($this->cid, LDAP::fix($dn), "objectClass=*", array("$name"));
728 /* fill data from LDAP */
729 if ($sr) {
730 $ei= @ldap_first_entry($this->cid, $sr);
731 if ($ei) {
732 if ($info= @ldap_get_values_len($this->cid, $ei, "$name")){
733 $data= $info[0];
734 }
735 }
736 }
737 if($r_array==0)
738 return ($data);
739 else
740 return ($info);
743 }
747 function get_additional_error()
748 {
749 $error= "";
750 @ldap_get_option ($this->cid, LDAP_OPT_ERROR_STRING, $error);
751 return ($error);
752 }
755 function success()
756 {
757 return (preg_match('/Success/i', $this->error));
758 }
761 function get_error()
762 {
763 if ($this->error == 'Success'){
764 return $this->error;
765 } else {
766 $adderror= $this->get_additional_error();
767 if ($adderror != ""){
768 $error= $this->error." (".$this->get_additional_error().", ".sprintf(_("while operating on '%s' using LDAP server '%s'"), $this->basedn, $this->hostname).")";
769 } else {
770 $error= $this->error." (".sprintf(_("while operating on LDAP server %s"), $this->hostname).")";
771 }
772 return $error;
773 }
774 }
776 function get_credentials($url, $referrals= NULL)
777 {
778 $ret= array();
779 $url= preg_replace('!\?\?.*$!', '', $url);
780 $server= preg_replace('!^([^:]+://[^/]+)/.*$!', '\\1', $url);
782 if ($referrals === NULL){
783 $referrals= $this->referrals;
784 }
786 if (isset($referrals[$server])){
787 return ($referrals[$server]);
788 } else {
789 $ret['ADMIN']= LDAP::fix($this->binddn);
790 $ret['PASSWORD']= $this->bindpw;
791 }
793 return ($ret);
794 }
797 function gen_ldif ($srp, $dn, $filter= "(objectClass=*)", $attributes= array('*'), $recursive= TRUE)
798 {
799 $display= "";
801 if ($recursive){
802 $this->cd($dn);
803 $this->ls($srp, $filter,$dn, array('dn','objectClass'));
804 $deps = array();
806 $display .= $this->gen_one_entry($dn)."\n";
808 while ($attrs= $this->fetch($srp)){
809 $deps[] = $attrs['dn'];
810 }
811 foreach($deps as $dn){
812 $display .= $this->gen_ldif($srp, $dn, $filter,$attributes,$recursive);
813 }
814 } else {
815 $display.= $this->gen_one_entry($dn);
816 }
817 return ($display);
818 }
821 function gen_xls ($srp, $dn, $filter= "(objectClass=*)", $attributes= array('*'), $recursive= TRUE,$r_array=0)
822 {
823 $display= array();
825 $this->cd($dn);
826 $this->search($srp, "$filter");
828 $i=0;
829 while ($attrs= $this->fetch($srp)){
830 $j=0;
832 foreach ($attributes as $at){
833 $display[$i][$j]= $this->get_attribute($attrs['dn'], $at,$r_array);
834 $j++;
835 }
837 $i++;
838 }
840 return ($display);
841 }
844 function gen_one_entry($dn, $filter= "(objectClass=*)" , $name= array("*"))
845 {
846 $ret = "";
847 $data = "";
848 if($this->reconnect){
849 $this->connect();
850 }
852 /* Searching Ldap Tree */
853 $sr= @ldap_read($this->cid, LDAP::fix($dn), $filter, $name);
855 /* Get the first entry */
856 $entry= @ldap_first_entry($this->cid, $sr);
858 /* Get all attributes related to that Objekt */
859 $atts = array();
861 /* Assemble dn */
862 $atts[0]['name'] = "dn";
863 $atts[0]['value'] = array('count' => 1, 0 => $dn);
865 /* Reset index */
866 $i = 1 ;
867 $identifier = array();
868 $attribute= @ldap_first_attribute($this->cid,$entry,$identifier);
869 while ($attribute) {
870 $i++;
871 $atts[$i]['name'] = $attribute;
872 $atts[$i]['value'] = @ldap_get_values_len($this->cid, $entry, "$attribute");
874 /* Next one */
875 $attribute= @ldap_next_attribute($this->cid,$entry,$identifier);
876 }
878 foreach($atts as $at)
879 {
880 for ($i= 0; $i<$at['value']['count']; $i++){
882 /* Check if we must encode the data */
883 if(!preg_match('/^[a-z0-9+@#.=, \/ -]+$/i', $at['value'][$i])) {
884 $ret .= $at['name'].":: ".base64_encode($at['value'][$i])."\n";
885 } else {
886 $ret .= $at['name'].": ".$at['value'][$i]."\n";
887 }
888 }
889 }
891 return($ret);
892 }
895 function dn_exists($dn)
896 {
897 return @ldap_list($this->cid, LDAP::fix($dn), "(objectClass=*)", array("objectClass"));
898 }
902 /* This funktion imports ldifs
904 If DeleteOldEntries is true, the destination entry will be deleted first.
905 If JustModify is true the destination entry will only be touched by the attributes specified in the ldif.
906 if JustMofify id false the destination dn will be overwritten by the new ldif.
907 */
909 function import_complete_ldif($srp, $str_attr,$error,$JustModify,$DeleteOldEntries)
910 {
911 if($this->reconnect) $this->connect();
913 /* First we have to splitt the string ito detect empty lines
914 An empty line indicates an new Entry */
915 $entries = split("\n",$str_attr);
917 $data = "";
918 $cnt = 0;
919 $current_line = 0;
921 /* FIX ldif */
922 $last = "";
923 $tmp = "";
924 $i = 0;
925 foreach($entries as $entry){
926 if(preg_match("/^ /",$entry)){
927 $tmp[$i] .= trim($entry);
928 }else{
929 $i ++;
930 $tmp[$i] = trim($entry);
931 }
932 }
934 /* Every single line ... */
935 foreach($tmp as $entry) {
936 $current_line ++;
938 /* Removing Spaces to ..
939 .. test if a new entry begins */
940 $tmp = str_replace(" ","",$data );
942 /* .. prevent empty lines in an entry */
943 $tmp2 = str_replace(" ","",$entry);
945 /* If the Block ends (Empty Line) */
946 if((empty($entry))&&(!empty($tmp))) {
947 /* Add collected lines as a complete block */
948 $all[$cnt] = $data;
949 $cnt ++;
950 $data ="";
951 } else {
953 /* Append lines ... */
954 if(!empty($tmp2)) {
955 /* check if we need base64_decode for this line */
956 if(ereg("::",$tmp2))
957 {
958 $encoded = split("::",$entry);
959 $attr = trim($encoded[0]);
960 $value = base64_decode(trim($encoded[1]));
961 /* Add linenumber */
962 $data .= $current_line."#".base64_encode($attr.":".$value)."\n";
963 }
964 else
965 {
966 /* Add Linenumber */
967 $data .= $current_line."#".base64_encode($entry)."\n";
968 }
969 }
970 }
971 }
973 /* The Data we collected is not in the array all[];
974 For example the Data is stored like this..
976 all[0] = "1#dn : .... \n
977 2#ObjectType: person \n ...."
979 Now we check every insertblock and try to insert */
980 foreach ( $all as $single) {
981 $lineone = split("\n",$single);
982 $ndn = split("#", $lineone[0]);
983 $line = base64_decode($ndn[1]);
985 $dnn = split (":",$line,2);
986 $current_line = $ndn[0];
987 $dn = $dnn[0];
988 $value = $dnn[1];
990 /* Every block must begin with a dn */
991 if($dn != "dn") {
992 $error= sprintf(_("This is not a valid DN: '%s'. A block for import should begin with 'dn: ...' in line %s"), $line, $current_line);
993 return -2;
994 }
996 /* Should we use Modify instead of Add */
997 $usemodify= false;
999 /* Delete before insert */
1000 $usermdir= false;
1002 /* The dn address already exists, Don't delete destination entry, overwrite it */
1003 if (($this->dn_exists($value))&&((!$JustModify)&&(!$DeleteOldEntries))) {
1005 $usermdir = $usemodify = false;
1007 /* Delete old entry first, then add new */
1008 } elseif(($this->dn_exists($value))&&($DeleteOldEntries)){
1010 /* Delete first, then add */
1011 $usermdir = true;
1013 } elseif(($this->dn_exists($value))&&($JustModify)) {
1015 /* Modify instead of Add */
1016 $usemodify = true;
1017 }
1019 /* If we can't Import, return with a file error */
1020 if(!$this->import_single_entry($srp, $single,$usemodify,$usermdir) ) {
1021 $error= sprintf(_("Error while importing dn: '%s', please check your LDIF from line %s on!"), $line,
1022 $current_line);
1023 return UNKNOWN_TOKEN_IN_LDIF_FILE; }
1024 }
1026 return (INSERT_OK);
1027 }
1030 /* Imports a single entry
1031 If $delete is true; The old entry will be deleted if it exists.
1032 if $modify is true; All variables that are not touched by the new ldif will be kept.
1033 if $modify is false; The new ldif overwrites the old entry, and all untouched attributes get lost.
1034 */
1035 function import_single_entry($srp, $str_attr,$modify,$delete)
1036 {
1037 global $config;
1039 if(!$config){
1040 trigger_error("Can't import ldif, can't read config object.");
1041 }
1044 if($this->reconnect) $this->connect();
1046 $ret = false;
1047 $rows= split("\n",$str_attr);
1048 $data= false;
1050 foreach($rows as $row) {
1052 /* Check if we use Linenumbers (when import_complete_ldif is called we use
1053 Linenumbers) Linenumbers are use like this 123#attribute : value */
1054 if(!empty($row)) {
1055 if(strpos($row,"#")!=FALSE) {
1057 /* We are using line numbers
1058 Because there is a # before a : */
1059 $tmp1= split("#",$row);
1060 $current_line= $tmp1[0];
1061 $row= base64_decode($tmp1[1]);
1062 }
1064 /* Split the line into attribute and value */
1065 $attr = split(":", $row,2);
1066 $attr[0]= trim($attr[0]); /* attribute */
1067 $attr[1]= $attr[1]; /* value */
1069 /* Check :: was used to indicate base64_encoded strings */
1070 if($attr[1][0] == ":"){
1071 $attr[1]=trim(preg_replace("/^:/","",$attr[1]));
1072 $attr[1]=base64_decode($attr[1]);
1073 }
1075 $attr[1] = trim($attr[1]);
1077 /* Check for attributes that are used more than once */
1078 if(!isset($data[$attr[0]])) {
1079 $data[$attr[0]]=$attr[1];
1080 } else {
1081 $tmp = $data[$attr[0]];
1083 if(!is_array($tmp)) {
1084 $new[0]=$tmp;
1085 $new[1]=$attr[1];
1086 $datas[$attr[0]]['count']=1;
1087 $data[$attr[0]]=$new;
1088 } else {
1089 $cnt = $datas[$attr[0]]['count'];
1090 $cnt ++;
1091 $data[$attr[0]][$cnt]=$attr[1];
1092 $datas[$attr[0]]['count'] = $cnt;
1093 }
1094 }
1095 }
1096 }
1098 /* If dn is an index of data, we should try to insert the data */
1099 if(isset($data['dn'])) {
1101 /* Fix dn */
1102 $tmp = gosa_ldap_explode_dn($data['dn']);
1103 unset($tmp['count']);
1104 $newdn ="";
1105 foreach($tmp as $tm){
1106 $newdn.= trim($tm).",";
1107 }
1108 $newdn = preg_replace("/,$/","",$newdn);
1109 $data['dn'] = $newdn;
1111 /* Creating Entry */
1112 $this->cd($data['dn']);
1114 /* Delete existing entry */
1115 if($delete){
1116 $this->rmdir_recursive($srp, $data['dn']);
1117 }
1119 /* Create missing trees */
1120 $this->cd ($this->basedn);
1121 $this->cd($config->current['BASE']);
1122 $this->create_missing_trees($srp, preg_replace("/^[^,]+,/","",$data['dn']));
1123 $this->cd($data['dn']);
1125 $dn = $data['dn'];
1126 unset($data['dn']);
1128 if(!$modify){
1130 $this->cat($srp, $dn);
1131 if($this->count($srp)){
1133 /* The destination entry exists, overwrite it with the new entry */
1134 $attrs = $this->fetch($srp);
1135 foreach($attrs as $name => $value ){
1136 if(!is_numeric($name)){
1137 if(in_array($name,array("dn","count"))) continue;
1138 if(!isset($data[$name])){
1139 $data[$name] = array();
1140 }
1141 }
1142 }
1143 $ret = $this->modify($data);
1145 }else{
1147 /* The destination entry doesn't exists, create it */
1148 $ret = $this->add($data);
1149 }
1151 } else {
1153 /* Keep all vars that aren't touched by this ldif */
1154 $ret = $this->modify($data);
1155 }
1156 }
1158 if (!$this->success()){
1159 msg_dialog::display(_("LDAP error"), msgPool::ldaperror($this->get_error(), $dn, "", get_class()));
1160 }
1162 return($ret);
1163 }
1166 function importcsv($str)
1167 {
1168 $lines = split("\n",$str);
1169 foreach($lines as $line)
1170 {
1171 /* continue if theres a comment */
1172 if(substr(trim($line),0,1)=="#"){
1173 continue;
1174 }
1176 $line= str_replace ("\t\t","\t",$line);
1177 $line= str_replace ("\t" ,"," ,$line);
1178 echo $line;
1180 $cells = split(",",$line ) ;
1181 $linet= str_replace ("\t\t",",",$line);
1182 $cells = split("\t",$line);
1183 $count = count($cells);
1184 }
1186 }
1188 function get_objectclasses()
1189 {
1190 $objectclasses = array();
1191 global $config;
1193 /* Only read schema if it is allowed */
1194 if(isset($config) && preg_match("/config/i",get_class($config))){
1195 if(!isset($config->data['MAIN']['SCHEMA_CHECK']) || !preg_match("/true/i",$config->data['MAIN']['SCHEMA_CHECK'])){
1196 return($objectclasses);
1197 }
1198 }
1200 /* Return the cached results. */
1201 if(class_available('session') && session::is_set("LDAP_CACHE::get_objectclasses")){
1202 $objectclasses = session::get("LDAP_CACHE::get_objectclasses");
1203 return($objectclasses);
1204 }
1206 # Get base to look for schema
1207 $sr = @ldap_read ($this->cid, NULL, "objectClass=*", array("subschemaSubentry"));
1208 if(!$sr){
1209 $sr = @ldap_read ($this->cid, "", "objectClass=*", array("subschemaSubentry"));
1210 }
1212 $attr = @ldap_get_entries($this->cid,$sr);
1213 if (!isset($attr[0]['subschemasubentry'][0])){
1214 return array();
1215 }
1217 /* Get list of objectclasses and fill array */
1218 $nb= $attr[0]['subschemasubentry'][0];
1219 $objectclasses= array();
1220 $sr= ldap_read ($this->cid, $nb, "objectClass=*", array("objectclasses"));
1221 $attrs= ldap_get_entries($this->cid,$sr);
1222 if (!isset($attrs[0])){
1223 return array();
1224 }
1225 foreach ($attrs[0]['objectclasses'] as $val){
1226 if (preg_match('/^[0-9]+$/', $val)){
1227 continue;
1228 }
1229 $name= "OID";
1230 $pattern= split(' ', $val);
1231 $ocname= preg_replace("/^.* NAME\s+\(*\s*'([^']+)'\s*\)*.*$/", '\\1', $val);
1232 $objectclasses[$ocname]= array();
1234 foreach($pattern as $chunk){
1235 switch($chunk){
1237 case '(':
1238 $value= "";
1239 break;
1241 case ')': if ($name != ""){
1242 $objectclasses[$ocname][$name]= $this->value2container($value);
1243 }
1244 $name= "";
1245 $value= "";
1246 break;
1248 case 'NAME':
1249 case 'DESC':
1250 case 'SUP':
1251 case 'STRUCTURAL':
1252 case 'ABSTRACT':
1253 case 'AUXILIARY':
1254 case 'MUST':
1255 case 'MAY':
1256 if ($name != ""){
1257 $objectclasses[$ocname][$name]= $this->value2container($value);
1258 }
1259 $name= $chunk;
1260 $value= "";
1261 break;
1263 default: $value.= $chunk." ";
1264 }
1265 }
1267 }
1268 if(class_available("session")){
1269 session::set("LDAP_CACHE::get_objectclasses",$objectclasses);
1270 }
1271 return $objectclasses;
1272 }
1275 function value2container($value)
1276 {
1277 /* Set emtpy values to "true" only */
1278 if (preg_match('/^\s*$/', $value)){
1279 return true;
1280 }
1282 /* Remove ' and " if needed */
1283 $value= preg_replace('/^[\'"]/', '', $value);
1284 $value= preg_replace('/[\'"] *$/', '', $value);
1286 /* Convert to array if $ is inside... */
1287 if (preg_match('/\$/', $value)){
1288 $container= preg_split('/\s*\$\s*/', $value);
1289 } else {
1290 $container= chop($value);
1291 }
1293 return ($container);
1294 }
1297 function log($string)
1298 {
1299 if (session::is_set('config')){
1300 $cfg = session::get('config');
1301 if (isset($cfg->current['LDAPSTATS']) && preg_match('/true/i', $cfg->current['LDAPSTATS'])){
1302 syslog (LOG_INFO, $string);
1303 }
1304 }
1305 }
1307 /* added by Guido Serra aka Zeph <zeph@purotesto.it> */
1308 function getCn($dn){
1309 $simple= split(",", $dn);
1311 foreach($simple as $piece) {
1312 $partial= split("=", $piece);
1314 if($partial[0] == "cn"){
1315 return $partial[1];
1316 }
1317 }
1318 }
1321 function get_naming_contexts($server, $admin= "", $password= "")
1322 {
1323 /* Build LDAP connection */
1324 $ds= ldap_connect ($server);
1325 if (!$ds) {
1326 die ("Can't bind to LDAP. No check possible!");
1327 }
1328 ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
1329 $r= ldap_bind ($ds, $admin, $password);
1331 /* Get base to look for naming contexts */
1332 $sr = @ldap_read ($ds, "", "objectClass=*", array("+"));
1333 $attr= @ldap_get_entries($ds,$sr);
1335 return ($attr[0]['namingcontexts']);
1336 }
1339 function get_root_dse($server, $admin= "", $password= "")
1340 {
1341 /* Build LDAP connection */
1342 $ds= ldap_connect ($server);
1343 if (!$ds) {
1344 die ("Can't bind to LDAP. No check possible!");
1345 }
1346 ldap_set_option($ds, LDAP_OPT_PROTOCOL_VERSION, 3);
1347 $r= ldap_bind ($ds, $admin, $password);
1349 /* Get base to look for naming contexts */
1350 $sr = @ldap_read ($ds, "", "objectClass=*", array("+"));
1351 $attr= @ldap_get_entries($ds,$sr);
1353 /* Return empty array, if nothing was set */
1354 if (!isset($attr[0])){
1355 return array();
1356 }
1358 /* Rework array... */
1359 $result= array();
1360 for ($i= 0; $i<$attr[0]['count']; $i++){
1361 $result[$attr[0][$i]]= $attr[0][$attr[0][$i]];
1362 unset($result[$attr[0][$i]]['count']);
1363 }
1365 return ($result);
1366 }
1368 }
1369 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
1370 ?>