Code

Only display C&P - SnapShot functionality if user has full access to current object...
[gosa.git] / include / class_ldap.inc
1 <?php
2 /*****************************************************************************
3   newldap.inc - version 1.0
4   Copyright (C) 2003 Alejandro Escanero Blanco <aescanero@chaosdimension.org>
5   Copyright (C) 2004-2006 Cajus Pollmeier <pollmeier@gonicus.de>
7   Based in code of ldap.inc of
8   Copyright (C) 1998  Eric Kilfoil <eric@ipass.net>
9  *****************************************************************************/
11 define("ALREADY_EXISTING_ENTRY",-10001);
12 define("UNKNOWN_TOKEN_IN_LDIF_FILE",-10002);
13 define("NO_FILE_UPLOADED",10003);
14 define("INSERT_OK",10000);
15 define("SPECIALS_OVERRIDE", TRUE);
17 class LDAP{
19   var $hascon   =false;
20   var $hasres   =false;
21   var $reconnect=false;
22   var $tls      = false;
23   var $basedn   ="";
24   var $cid;
25   var $error    = ""; // Any error messages to be returned can be put here
26   var $start    = 0; // 0 if we are fetching the first entry, otherwise 1
27   var $objectClasses = array(); // Information read from slapd.oc.conf
28   var $binddn   = "";
29   var $bindpw   = "";
30   var $hostname = "";
31   var $follow_referral = FALSE;
32   var $referrals= array();
33   var $max_ldap_query_time = 0;   // 0, empty or negative values will disable this check 
35   function LDAP($binddn,$bindpw, $hostname, $follow_referral= FALSE, $tls= FALSE)
36   {
37     global $config;
38     $this->follow_referral= $follow_referral;
39     $this->tls=$tls;
40     $this->binddn=$this->convert($binddn);
42     $this->bindpw=$bindpw;
43     $this->hostname=$hostname;
45     /* Check if MAX_LDAP_QUERY_TIME is defined */ 
46     if(isset($config->data['MAIN']['MAX_LDAP_QUERY_TIME'])){
47       $str = $config->data['MAIN']['MAX_LDAP_QUERY_TIME'];
48       $this->max_ldap_query_time = (float)($str);
49     }
51     $this->connect();
52   }
55   /* Function to replace all problematic characters inside a DN by \001XX, where
56      \001 is decoded to chr(1) [ctrl+a]. It is not impossible, but very unlikely
57      that this character is inside a DN.
58      
59      Currently used codes:
60       ,   => CO
61       \2C => CO
62       (   => OB
63       )   => CB
64       /   => SL                                                                  */
65   function convert($dn)
66   {
67     if (SPECIALS_OVERRIDE == TRUE){
68       $tmp= preg_replace(array("/\\\\,/", "/\\\\2C/", "/\(/", "/\)/", "/\//"),
69                            array("\001CO", "\001CO", "\001OB", "\001CB", "\001SL"),
70                            $dn);
71       return (preg_replace('/,\s+/', ',', $tmp));
72     } else {
73       return ($dn);
74     }
75   }
78   /* Function to fix all problematic characters inside a DN by replacing \001XX
79      codes to their original values. See "convert" for mor information. 
80      ',' characters are always expanded to \, (not \2C), since all tested LDAP
81      servers seem to take it the correct way.                                  */
82   function fix($dn)
83   {
84     if (SPECIALS_OVERRIDE == TRUE){
85       return (preg_replace(array("/\001CO/", "/\001OB/", "/\001CB/", "/\001SL/"),
86                            array("\,", "(", ")", "/"),
87                            $dn));
88     } else {
89       return ($dn);
90     }
91   }
94   function connect()
95   {
96     $this->hascon=false;
97     $this->reconnect=false;
98     if ($this->cid= @ldap_connect($this->hostname)) {
99       @ldap_set_option($this->cid, LDAP_OPT_PROTOCOL_VERSION, 3);
100       if (function_exists("ldap_set_rebind_proc") && $this->follow_referral) {
101         @ldap_set_option($this->cid, LDAP_OPT_REFERRALS, 1);
102         @ldap_set_rebind_proc($this->cid, array(&$this, "rebind"));
103       }
104       if (function_exists("ldap_start_tls") && $this->tls){
105         @ldap_start_tls($this->cid);
106       }
108       $this->error = "No Error";
109       if ($bid = @ldap_bind($this->cid, $this->fix($this->binddn), $this->bindpw)) {
110         $this->error = "Success";
111         $this->hascon=true;
112       } else {
113         if ($this->reconnect){
114           if ($this->error != "Success"){
115             $this->error = "Could not rebind to " . $this->binddn;
116           }
117         } else {
118           $this->error = "Could not bind to " . $this->binddn;
119         }
120       }
121     } else {
122       $this->error = "Could not connect to LDAP server";
123     }
124   }
126   function rebind($ldap, $referral)
127   {
128     $credentials= $this->get_credentials($referral);
129     if (@ldap_bind($ldap, $this->fix($credentials['ADMIN']), $credentials['PASSWORD'])) {
130       $this->error = "Success";
131       $this->hascon=true;
132       $this->reconnect= true;
133       return (0);
134     } else {
135       $this->error = "Could not bind to " . $credentials['ADMIN'];
136       return NULL;
137     }
138   }
140   function reconnect()
141   {
142     if ($this->reconnect){
143       @ldap_unbind($this->cid);
144       $this->cid = NULL;
145     }
146   }
148   function unbind()
149   {
150     @ldap_unbind($this->cid);
151     $this->cid = NULL;
152   }
154   function disconnect()
155   {
156     if($this->hascon){
157       @ldap_close($this->cid);
158       $this->hascon=false;
159     }
160   }
162   function cd($dir)
163   {
164     if ($dir == "..")
165       $this->basedn = $this->getParentDir();
166     else
167       $this->basedn = $this->convert($dir);
168   }
170   function getParentDir($basedn = "")
171   {
172     if ($basedn=="")
173       $basedn = $this->basedn;
174     else
175       $basedn = $this->convert($this->basedn);
176     return(ereg_replace("[^,]*[,]*[ ]*(.*)", "\\1", $basedn));
177   }
179   function search($filter, $attrs= array())
180   {
181     if($this->hascon){
182       if ($this->reconnect) $this->connect();
184       $start = microtime();
185    
186       $this->clearResult();
187       $this->sr = @ldap_search($this->cid, $this->fix($this->basedn), $filter, $attrs);
188       $this->error = @ldap_error($this->cid);
189       $this->resetResult();
190       $this->hasres=true;
191    
192       /* Check if query took longer as specified in max_ldap_query_time */
193       if($this->max_ldap_query_time){
194         $diff = get_MicroTimeDiff($start,microtime());
195         if($diff > $this->max_ldap_query_time){
196           print_red(sprintf(_("The LDAP server is slow (%.2fs for the last query). This may be responsible for performance breakdowns."),$diff)) ;
197         }
198       }
200       $this->log("LDAP operation: time=".get_MicroTimeDiff($start,microtime())." operation=search('".$this->fix($this->basedn)."', '$filter')");
201       return($this->sr);
202     }else{
203       $this->error = "Could not connect to LDAP server";
204       return("");
205     }
206   }
208   function ls($filter = "(objectclass=*)", $basedn = "",$attrs = array("*"))
209   {
210     if($this->hascon){
211       if ($this->reconnect) $this->connect();
212       $this->clearResult();
213       if ($basedn == "")
214         $basedn = $this->basedn;
215       else
216         $basedn= $this->convert($basedn);
217   
218       $start = microtime();
220       $this->sr = @ldap_list($this->cid, $this->fix($basedn), $filter,$attrs);
221       $this->error = @ldap_error($this->cid);
222       $this->resetResult();
223       $this->hasres=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           print_red(sprintf(_("The ldapserver is answering very slow (%.2f), this may be responsible for performance breakdowns."),$diff)) ;
230         }
231       }
233       $this->log("LDAP operation: time=".get_MicroTimeDiff($start,microtime())." operation=ls('".$this->fix($basedn)."', '$filter')");
235       return($this->sr);
236     }else{
237       $this->error = "Could not connect to LDAP server";
238       return("");
239     }
240   }
242   function cat($dn,$attrs= array("*"))
243   {
244     if($this->hascon){
245       if ($this->reconnect) $this->connect();
246       $this->clearResult();
247       $filter = "(objectclass=*)";
248       $this->sr = @ldap_read($this->cid, $this->fix($dn), $filter,$attrs);
249       $this->error = @ldap_error($this->cid);
250       $this->resetResult();
251       $this->hasres=true;
252       return($this->sr);
253     }else{
254       $this->error = "Could not connect to LDAP server";
255       return("");
256     }
257   }
259   function set_size_limit($size)
260   {
261     /* Ignore zero settings */
262     if ($size == 0){
263       @ldap_set_option($this->cid, LDAP_OPT_SIZELIMIT, 10000000);
264     }
265     if($this->hascon){
266       @ldap_set_option($this->cid, LDAP_OPT_SIZELIMIT, $size);
267     } else {
268       $this->error = "Could not connect to LDAP server";
269     }
270   }
272   function fetch()
273   {
274     $att= array();
275     if($this->hascon){
276       if($this->hasres){
277         if ($this->start == 0)
278         {
279           $this->start = 1;
280           $this->re= @ldap_first_entry($this->cid, $this->sr);
281         } else {
282           $this->re= @ldap_next_entry($this->cid, $this->re);
283         }
284         if ($this->re)
285         {
286           $att= @ldap_get_attributes($this->cid, $this->re);
287           $att['dn']= trim($this->convert(@ldap_get_dn($this->cid, $this->re)));
288         }
289         $this->error = @ldap_error($this->cid);
290         if (!isset($att)){
291           $att= array();
292         }
293         return($att);
294       }else{
295         $this->error = "Perform a Fetch with no Search";
296         return("");
297       }
298     }else{
299       $this->error = "Could not connect to LDAP server";
300       return("");
301     }
302   }
304   function resetResult()
305   {
306     $this->start = 0;
307   }
309   function clearResult()
310   {
311     if($this->hasres){
312       $this->hasres = false;
313       @ldap_free_result($this->sr);
314     }
315   }
317   function getDN()
318   {
319     if($this->hascon){
320       if($this->hasres){
322         if(!$this->re)
323           {
324           $this->error = "Perform a Fetch with no valid Result";
325           }
326           else
327           {
328           $rv = @ldap_get_dn($this->cid, $this->re);
329         
330           $this->error = @ldap_error($this->cid);
331           return(trim($this->convert($rv)));
332            }
333       }else{
334         $this->error = "Perform a Fetch with no Search";
335         return("");
336       }
337     }else{
338       $this->error = "Could not connect to LDAP server";
339       return("");
340     }
341   }
343   function count()
344   {
345     if($this->hascon){
346       if($this->hasres){
347         $rv = @ldap_count_entries($this->cid, $this->sr);
348         $this->error = @ldap_error($this->cid);
349         return($rv);
350       }else{
351         $this->error = "Perform a Fetch with no Search";
352         return("");
353       }
354     }else{
355       $this->error = "Could not connect to LDAP server";
356       return("");
357     }
358   }
360   function rm($attrs = "", $dn = "")
361   {
362     if($this->hascon){
363       if ($this->reconnect) $this->connect();
364       if ($dn == "")
365         $dn = $this->basedn;
367       $r = @ldap_mod_del($this->cid, $this->fix($dn), $attrs);
368       $this->error = @ldap_error($this->cid);
369       return($r);
370     }else{
371       $this->error = "Could not connect to LDAP server";
372       return("");
373     }
374   }
376   function rename($attrs, $dn = "")
377   {
378     if($this->hascon){
379       if ($this->reconnect) $this->connect();
380       if ($dn == "")
381         $dn = $this->basedn;
383       $r = @ldap_mod_replace($this->cid, $this->fix($dn), $attrs);
384       $this->error = @ldap_error($this->cid);
385       return($r);
386     }else{
387       $this->error = "Could not connect to LDAP server";
388       return("");
389     }
390   }
392   function rmdir($deletedn)
393   {
394     if($this->hascon){
395       if ($this->reconnect) $this->connect();
396       $r = @ldap_delete($this->cid, $this->fix($deletedn));
397       $this->error = @ldap_error($this->cid);
398       return($r ? $r : 0);
399     }else{
400       $this->error = "Could not connect to LDAP server";
401       return("");
402     }
403   }
405   /**
406   *  Function rmdir_recursive
407   *
408   *  Description: Based in recursive_remove, adding two thing: full subtree remove, and delete own node.
409   *  Parameters:  The dn to delete
410   *  GiveBack:    True on sucessfull , 0 in error, and "" when we don't get a ldap conection
411   *
412   */
414   function rmdir_recursive($deletedn)
415   {
416     if($this->hascon){
417       if ($this->reconnect) $this->connect();
418       $delarray= array();
419         
420       /* Get sorted list of dn's to delete */
421       $this->ls ("(objectClass=*)",$deletedn);
422       while ($this->fetch()){
423         $deldn= $this->getDN();
424         $delarray[$deldn]= strlen($deldn);
425       }
426       arsort ($delarray);
427       reset ($delarray);
429       /* Really Delete ALL dn's in subtree */
430       foreach ($delarray as $key => $value){
431         $this->rmdir_recursive($key);
432       }
433       
434       /* Finally Delete own Node */
435       $r = @ldap_delete($this->cid, $this->fix($deletedn));
436       $this->error = @ldap_error($this->cid);
437       return($r ? $r : 0);
438     }else{
439       $this->error = "Could not connect to LDAP server";
440       return("");
441     }
442   }
444   /* Copy given attributes and sub-dns with attributes to destination dn 
445   */
446   function copy_FAI_resource_recursive($sourcedn,$destinationdn,$destinationName,$type="branch",$is_first = true,$depth=0)
447   {
448     error_reporting(E_ALL);
449     
450     if($is_first){
451       echo "<h2>".sprintf(_("Creating copy of %s"),"<i>".@LDAP::fix($sourcedn)."</i>")."</h2>";
452     }else{
453       if(preg_match("/^ou=/",$sourcedn)){
454         echo "<h3>"._("Processing")." <i>".@LDAP::fix($destinationdn)."</i></h3>";
455       }else{
456         $tmp = split(",",$sourcedn);
457         
458         echo "&nbsp;<b>"._("Object").":</b> ";
460         $deststr = @LDAP::fix($destinationdn);
461         if(strlen($deststr) > 96){
462           $deststr = substr($deststr,0,96)."...";
463         }
465         echo $deststr."<br>";
466       }
467     }
469     flush();
470     
471     if($this->hascon){
472       if ($this->reconnect) $this->connect();
474       /* Save base dn */
475       $basedn= $this->basedn;
476       $delarray= array();
477      
478       /* Check if destination entry already exists */
479       $this->cat($destinationdn);
481       if($this->count()){
482         return;
483       }else{
484         
485         $this->clearResult();
487         /* Get source entry */
488         $this->cd($basedn);
489         $this->cat($sourcedn);
490         $attr = $this->fetch();
492         /* Error while fetching object / attribute abort*/
493         if((!$attr) || (count($attr)) ==0) {
494           echo _("Error while fetching source dn - aborted!");
495           return;
496         }
497   
498         /* check if this is a department */
499         if(in_array("organizationalUnit",$attr['objectClass'])){
500           $attr['dn'] = $this->convert($destinationdn);
501           $this->cd($basedn);
502           $this->create_missing_trees($destinationdn);
503           $this->cd($destinationdn);
505           /* If is first entry, append FAIbranch to department entry */
506           if($is_first){
507             $this->cat($destinationdn);
508             $attr= $this->fetch();
510             /* Filter unneeded informations */
511             foreach($attr as $key => $value){
512               if(is_numeric($key)) unset($attr[$key]);
513               if(isset($attr[$key]['count'])){
514                 if(is_array($attr[$key])){
515                   unset($attr[$key]['count']);
516                 }
517               }
518             }
519             
520             unset($attr['count']);
521             unset($attr['dn']);
523             /* Add marking attribute */
524             $attr['objectClass'][] = "FAIbranch";
525             
526             /* Add this entry */
527             $this->modify($attr);
528           }
529         }else{
531           /* If this is no department */
532           foreach($attr as $key => $value){
533             if(in_array($key ,array("FAItemplateFile","FAIscript", "gotoLogonScript", "gosaApplicationIcon","gotoMimeIcon"))){
534               $sr= ldap_read($this->cid, $this->fix($sourcedn), "$key=*", array($key));
535               $ei= ldap_first_entry($this->cid, $sr);
536               if ($tmp= @ldap_get_values_len($this->cid, $ei,$key)){
537                 $attr[$key] = $tmp;
538               }
539             }
541             if(is_numeric($key)) unset($attr[$key]);
542             if(isset($attr[$key]['count'])){
543               if(is_array($attr[$key])){
544                 unset($attr[$key]['count']);
545               }
546             }
547           }
548           unset($attr['count']);
549           unset($attr['dn']);
551           if((!in_array("gosaApplication" , $attr['objectClass'])) && (!in_array("gotoMimeType", $attr['objectClass']))){
552             if($type=="branch"){
553               $attr['FAIstate'] ="branch";
554             }elseif($type=="freeze"){
555               $attr['FAIstate'] ="freeze";
556             }else{
557               print_red(_("Unknown FAIstate %s"),$type);
558             }
559           }
561           /* Replace FAIdebianRelease with new release name */
562           if(in_array("FAIpackageList" , $attr['objectClass'])){
563             $attr['FAIdebianRelease'] = $destinationName; 
564           }
566           /* Add entry */
567           $this->cd($destinationdn);
568           $this->cat($destinationdn);
569           $a = $this->fetch();
570           if(!count($a)){
571             $this->add($attr);
572           }
574           if($this->error != "Success"){
575             /* Some error occured */
576             print "---------------------------------------------";
577             print $this->get_error()."<br>";
578             print $sourcedn."<br>";
579             print $destinationdn."<br>";
580             print_a( $attr);
581             exit();
582           }          
583         }
584       }
586       $this->ls ("(objectClass=*)",$sourcedn);
587       while ($this->fetch()){
588         $deldn= $this->getDN();
589         $delarray[$deldn]= strlen($deldn);
590       }
591       asort ($delarray);
592       reset ($delarray);
594        $depth ++;
595       foreach($delarray as $dn => $bla){
596         if($dn != $destinationdn){
597           $this->cd($basedn);
598           $item = $this->fetch($this->cat($dn));
599           if(!in_array("FAIbranch",$item['objectClass'])){
600             $this->copy_FAI_resource_recursive($dn,str_replace($sourcedn,$destinationdn,$dn),$destinationName,$type,false,$depth);
601           } 
602         }
603       }
604     }
605     if($is_first){
606       echo "<p class='seperator'>&nbsp;</p>";
607     }
609   }
611   function modify($attrs)
612   {
613     if(count($attrs) == 0){
614       return (0);
615     }
616     if($this->hascon){
617       if ($this->reconnect) $this->connect();
618       $r = @ldap_modify($this->cid, $this->fix($this->basedn), $attrs);
619       $this->error = @ldap_error($this->cid);
620       return($r ? $r : 0);
621     }else{
622       $this->error = "Could not connect to LDAP server";
623       return("");
624     }
625   }
627   function add($attrs)
628   {
629     if($this->hascon){
630       if ($this->reconnect) $this->connect();
631       $r = @ldap_add($this->cid, $this->fix($this->basedn), $attrs);
632       $this->error = @ldap_error($this->cid);
633       return($r ? $r : 0);
634     }else{
635       $this->error = "Could not connect to LDAP server";
636       return("");
637     }
638   }
640   function create_missing_trees($target)
641   {
642     /* Ignore create_missing trees if the base equals target */
643     if ($target == $this->basedn){
644      return;
645     }
647     $real_path= substr($target, 0, strlen($target) - strlen($this->basedn) -1 );
648     $l= array_reverse(gosa_ldap_explode_dn($real_path));
649     unset($l['count']);
650     $cdn= $this->basedn;
651     $tag= "";
653     foreach ($l as $part){
654       $cdn= "$part,$cdn";
656       /* Ignore referrals */
657       $found= false;
658       foreach($this->referrals as $ref){
659         $base= preg_replace('!^[^:]+://[^/]+/([^?]+).*$!', '\\1', $ref['URL']);
660         if ($base == $cdn){
661           $found= true;
662           break;
663         }
664       }
665       if ($found){
666         continue;
667       }
669       $this->cat ($cdn);
670       $attrs= $this->fetch();
672       /* Create missing entry? */
673       if (count ($attrs)){
674       
675         /* Catch the tag - if present */
676         if (isset($attrs['gosaUnitTag'][0])){
677           $tag= $attrs['gosaUnitTag'][0];
678         }
680       } else {
681         $type= preg_replace('/^([^=]+)=.*$/', '\\1', $cdn);
682         $param= preg_replace('/^[^=]+=([^,]+),.*$/', '\\1', $cdn);
684         $na= array();
685         switch ($type){
686           case 'ou':
687             if ($tag != ""){
688               $na["objectClass"]= array("organizationalUnit", "gosaAdministrativeUnitTag");
689               $na["gosaUnitTag"]= $tag;
690             } else {
691               $na["objectClass"]= "organizationalUnit";
692             }
693             $na["ou"]= $param;
694             break;
695           case 'dc':
696             if ($tag != ""){
697               $na["objectClass"]= array("dcObject", "top", "locality", "gosaAdministrativeUnitTag");
698               $na["gosaUnitTag"]= $tag;
699             } else {
700               $na["objectClass"]= array("dcObject", "top", "locality");
701             }
702             $na["dc"]= $param;
703             break;
704           default:
705             print_red(sprintf(_("Autocreation of type '%s' is currently not supported. Please report to the GOsa team."), $type));
706             echo $_SESSION['errors'];
707             exit;
708         }
709         $this->cd($cdn);
710         $this->add($na);
711       }
712     }
713   }
715   function recursive_remove()
716   {
717     $delarray= array();
719     /* Get sorted list of dn's to delete */
720     $this->search ("(objectClass=*)");
721     while ($this->fetch()){
722       $deldn= $this->getDN();
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, $this->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         }
748       }
749     }
750     if($r_array==0)
751     return ($data);
752     else
753     return ($info);
754   
755   
756   }
757  
760   function get_additional_error()
761   {
762     $error= "";
763     @ldap_get_option ($this->cid, LDAP_OPT_ERROR_STRING, $error);
764     return ($error);
765   }
767   function get_error()
768   {
769     if ($this->error == 'Success'){
770       return $this->error;
771     } else {
772       $adderror= $this->get_additional_error();
773       if ($adderror != ""){
774         $error= $this->error." (".$this->get_additional_error().", ".sprintf(_("while operating on '%s' using LDAP server '%s'"), $this->basedn, $this->hostname).")";
775       } else {
776         $error= $this->error." (".sprintf(_("while operating on LDAP server %s"), $this->hostname).")";
777       }
778       return $error;
779     }
780   }
782   function get_credentials($url, $referrals= NULL)
783   {
784     $ret= array();
785     $url= preg_replace('!\?\?.*$!', '', $url);
786     $server= preg_replace('!^([^:]+://[^/]+)/.*$!', '\\1', $url);
788     if ($referrals == NULL){
789       $referrals= $this->referrals;
790     }
792     if (isset($referrals[$server])){
793       return ($referrals[$server]);
794     } else {
795       $ret['ADMIN']= $this->fix($this->binddn);
796       $ret['PASSWORD']= $this->bindpw;
797     }
799     return ($ret);
800   }
803   function gen_ldif ($dn, $filter= "(objectClass=*)", $attributes= array('*'), $recursive= TRUE)
804   {
805     $display= "";
807     if ($recursive){
808       $this->cd($dn);
809       $this->ls($filter,$dn, array('dn','objectClass'));
810       $deps = array();
812       $display .= $this->gen_one_entry($dn)."\n";
814       while ($attrs= $this->fetch()){
815         $deps[] = $attrs['dn'];
816       }
817       foreach($deps as $dn){
818         $display .= $this->gen_ldif($dn, $filter,$attributes,$recursive);
819       }
820     } else {
821       $display.= $this->gen_one_entry($dn);
822     }
823     return ($display);
824   }
827   function gen_xls ($dn, $filter= "(objectClass=*)", $attributes= array('*'), $recursive= TRUE,$r_array=0)
828   {
829     $display= array();
831       $this->cd($dn);
832       $this->search("$filter");
834       $i=0;
835       while ($attrs= $this->fetch()){
836         $j=0;
838         foreach ($attributes as $at){
839           $display[$i][$j]= $this->get_attribute($attrs['dn'], $at,$r_array);
840           $j++;
841         }
843         $i++;
844       }
846     return ($display);
847   }
850   function gen_one_entry($dn, $filter= "(objectClass=*)" , $name= array("*"))
851   {
852     $ret = "";
853     $data = "";
854     if($this->reconnect){
855       $this->connect();
856     }
858     /* Searching Ldap Tree */
859     $sr= @ldap_read($this->cid, $this->fix($dn), $filter, $name);
861     /* Get the first entry */   
862     $entry= @ldap_first_entry($this->cid, $sr);
864     /* Get all attributes related to that Objekt */
865     $atts = array();
866     
867     /* Assemble dn */
868     $atts[0]['name']  = "dn";
869     $atts[0]['value'] = array('count' => 1, 0 => $dn);
871     /* Reset index */
872     $i = 1 ; 
873   $identifier = array();
874     $attribute= @ldap_first_attribute($this->cid,$entry,$identifier);
875     while ($attribute) {
876       $i++;
877       $atts[$i]['name']  = $attribute;
878       $atts[$i]['value'] = @ldap_get_values_len($this->cid, $entry, "$attribute");
880       /* Next one */
881       $attribute= @ldap_next_attribute($this->cid,$entry,$identifier);
882     }
884     foreach($atts as $at)
885     {
886       for ($i= 0; $i<$at['value']['count']; $i++){
888         /* Check if we must encode the data */
889         if(!preg_match('/^[a-z0-9+@#.=, \/ -]+$/i', $at['value'][$i])) {
890           $ret .= $at['name'].":: ".base64_encode($at['value'][$i])."\n";
891         } else {
892           $ret .= $at['name'].": ".$at['value'][$i]."\n";
893         }
894       }
895     }
897     return($ret);
898   }
901   function dn_exists($dn)
902   {
903     return @ldap_list($this->cid, $this->fix($dn), "(objectClass=*)", array("objectClass"));
904   }
905   
908   /*  This funktion imports ldifs 
909         
910       If DeleteOldEntries is true, the destination entry will be deleted first. 
911       If JustModify is true the destination entry will only be touched by the attributes specified in the ldif.
912       if JustMofify id false the destination dn will be overwritten by the new ldif. 
913     */
915   function import_complete_ldif($str_attr,&$error,$JustModify,$DeleteOldEntries)
916   {
917     if($this->reconnect) $this->connect();
919     /* First we have to splitt the string ito detect empty lines
920        An empty line indicates an new Entry */
921     $entries = split("\n",$str_attr);
923     $data = "";
924     $cnt = 0; 
925     $current_line = 0;
927     /* FIX ldif */
928     $last = "";
929     $tmp  = "";
930     $i = 0;
931     foreach($entries as $entry){
932       if(preg_match("/^ /",$entry)){
933         $tmp[$i] .= trim($entry);
934       }else{
935         $i ++;
936         $tmp[$i] = trim($entry);
937       }
938     }
940     /* Every single line ... */
941     foreach($tmp as $entry) {
942       $current_line ++;
944       /* Removing Spaces to .. 
945          .. test if a new entry begins */
946       $tmp  = str_replace(" ","",$data );
948       /* .. prevent empty lines in an entry */
949       $tmp2 = str_replace(" ","",$entry);
951       /* If the Block ends (Empty Line) */
952       if((empty($entry))&&(!empty($tmp))) {
953         /* Add collected lines as a complete block */
954         $all[$cnt] = $data;
955         $cnt ++;
956         $data ="";
957       } else {
959         /* Append lines ... */
960         if(!empty($tmp2)) {
961           /* check if we need base64_decode for this line */
962           if(ereg("::",$tmp2))
963           {
964             $encoded = split("::",$entry);
965             $attr  = trim($encoded[0]);
966             $value = base64_decode(trim($encoded[1]));
967             /* Add linenumber */
968             $data .= $current_line."#".base64_encode($attr.":".$value)."\n";
969           }
970           else
971           {
972             /* Add Linenumber */ 
973             $data .= $current_line."#".base64_encode($entry)."\n";
974           }
975         }
976       }
977     }
979     /* The Data we collected is not in the array all[];
980        For example the Data is stored like this..
982        all[0] = "1#dn : .... \n 
983        2#ObjectType: person \n ...."
984        
985        Now we check every insertblock and try to insert */
986     foreach ( $all as $single) {
987       $lineone = split("\n",$single);  
988       $ndn = split("#", $lineone[0]);
989       $line = base64_decode($ndn[1]);
991       $dnn = split (":",$line);
992       $current_line = $ndn[0];
993       $dn    = $dnn[0];
994       $value = $dnn[1];
996       /* Every block must begin with a dn */
997       if($dn != "dn") {
998         $error= sprintf(_("This is not a valid DN: '%s'. A block for import should begin with 'dn: ...' in line %s"), $line, $current_line);
999         return -2;  
1000       }
1002       /* Should we use Modify instead of Add */
1003       $usemodify= false;
1005       /* Delete before insert */
1006       $usermdir= false;
1007     
1008       /* The dn address already exists, Don't delete destination entry, overwrite it */
1009       if (($this->dn_exists($value))&&((!$JustModify)&&(!$DeleteOldEntries))) {
1011         $usermdir = $usemodify = false;
1013       /* Delete old entry first, then add new */
1014       } elseif(($this->dn_exists($value))&&($DeleteOldEntries)){
1016         /* Delete first, then add */
1017         $usermdir = true;        
1019       } elseif(($this->dn_exists($value))&&($JustModify)) {
1020         
1021         /* Modify instead of Add */
1022         $usemodify = true;
1023       }
1024      
1025       /* If we can't Import, return with a file error */
1026       if(!$this->import_single_entry($single,$usemodify,$usermdir) ) {
1027         $error= sprintf(_("Error while importing dn: '%s', please check your LDIF from line %s on!"), $line,
1028                         $current_line);
1029         return UNKNOWN_TOKEN_IN_LDIF_FILE;      }
1030     }
1032     return (INSERT_OK);
1033   }
1036   /* Imports a single entry 
1037       If $delete is true;  The old entry will be deleted if it exists.
1038       if $modify is true;  All variables that are not touched by the new ldif will be kept.
1039       if $modify is false; The new ldif overwrites the old entry, and all untouched attributes get lost.
1040   */
1041   function import_single_entry($str_attr,$modify,$delete)
1042   {
1043     if($this->reconnect) $this->connect();
1045     $ret = false;
1046     $rows= split("\n",$str_attr);
1047     $data= false;
1049     foreach($rows as $row) {
1050       
1051       /* Check if we use Linenumbers (when import_complete_ldif is called we use
1052          Linenumbers) Linenumbers are use like this 123#attribute : value */
1053       if(!empty($row)) {
1054         if(strpos($row,"#")!=FALSE) {
1056           /* We are using line numbers 
1057              Because there is a # before a : */
1058           $tmp1= split("#",$row);
1059           $current_line= $tmp1[0];
1060           $row= base64_decode($tmp1[1]);
1061         }
1063         /* Split the line into  attribute  and value */
1064         $attr   = split(":", $row,2);
1065         $attr[0]= trim($attr[0]);  /* attribute */
1066         $attr[1]= $attr[1];  /* value */
1068         /* Check :: was used to indicate base64_encoded strings */
1069         if($attr[1][0] == ":"){
1070           $attr[1]=trim(preg_replace("/^:/","",$attr[1]));
1071           $attr[1]=base64_decode($attr[1]);
1072         }
1074         $attr[1] = trim($attr[1]);
1076         /* Check for attributes that are used more than once */
1077         if(!isset($data[$attr[0]])) {
1078           $data[$attr[0]]=$attr[1];
1079         } else {
1080           $tmp = $data[$attr[0]];
1082           if(!is_array($tmp)) {
1083             $new[0]=$tmp;
1084             $new[1]=$attr[1];
1085             $datas[$attr[0]]['count']=1;             
1086             $data[$attr[0]]=$new;
1087           } else {
1088             $cnt = $datas[$attr[0]]['count'];           
1089             $cnt ++;
1090             $data[$attr[0]][$cnt]=$attr[1];
1091             $datas[$attr[0]]['count'] = $cnt;
1092           }
1093         }
1094       }
1095     }
1097     /* If dn is an index of data, we should try to insert the data */
1098     if(isset($data['dn'])) {
1100       /* Fix dn */
1101       $tmp = gosa_ldap_explode_dn($data['dn']);
1102       unset($tmp['count']);
1103       $newdn ="";
1104       foreach($tmp as $tm){
1105         $newdn.= trim($tm).",";
1106       }
1107       $newdn = preg_replace("/,$/","",$newdn);
1108       $data['dn'] = $newdn;
1109    
1110       /* Creating Entry */
1111       $this->cd($data['dn']);
1113       /* Delete existing entry */
1114       if($delete){
1115         $this->rmdir_recursive($data['dn']);
1116       }
1117      
1118       /* Create missing trees */
1119       $this->cd ($this->basedn);
1120       $this->create_missing_trees($data['dn']);
1121       $this->cd($data['dn']);
1123       $dn = $data['dn'];
1124       unset($data['dn']);
1125       
1126       if(!$modify){
1128         $this->cat($dn);
1129         if($this->count()){
1130         
1131           /* The destination entry exists, overwrite it with the new entry */
1132           $attrs = $this->fetch();
1133           foreach($attrs as $name => $value ){
1134             if(!is_numeric($name)){
1135               if(in_array($name,array("dn","count"))) continue;
1136               if(!isset($data[$name])){
1137                 $data[$name] = array();
1138               }
1139             }
1140           }
1141           $ret = $this->modify($data);
1142     
1143         }else{
1144     
1145           /* The destination entry doesn't exists, create it */
1146           $ret = $this->add($data);
1147         }
1149       } else {
1150         
1151         /* Keep all vars that aren't touched by this ldif */
1152         $ret = $this->modify($data);
1153       }
1154     }
1155     show_ldap_error($this->get_error(), sprintf(_("Ldap import with dn '%s' failed."),$dn));
1156     return($ret);
1157   }
1159   
1160   function importcsv($str)
1161   {
1162     $lines = split("\n",$str);
1163     foreach($lines as $line)
1164     {
1165       /* continue if theres a comment */
1166       if(substr(trim($line),0,1)=="#"){
1167         continue;
1168       }
1170       $line= str_replace ("\t\t","\t",$line);
1171       $line= str_replace ("\t"  ,"," ,$line);
1172       echo $line;
1174       $cells = split(",",$line )  ;
1175       $linet= str_replace ("\t\t",",",$line);
1176       $cells = split("\t",$line);
1177       $count = count($cells);  
1178     }
1180   }
1181   
1182   function get_objectclasses()
1183   {
1184           $objectclasses = array();
1185         
1186           # Get base to look for schema 
1187           $sr = @ldap_read ($this->cid, NULL, "objectClass=*", array("subschemaSubentry"));
1188           $attr = @ldap_get_entries($this->cid,$sr);
1189           if (!isset($attr[0]['subschemasubentry'][0])){
1190             return array();
1191           }
1192         
1193           # Get list of objectclasses
1194           $nb= $attr[0]['subschemasubentry'][0];
1195           $objectclasses= array();
1196           $sr= ldap_read ($this->cid, $nb, "objectClass=*", array("objectclasses"));
1197           $attrs= ldap_get_entries($this->cid,$sr);
1198           if (!isset($attrs[0])){
1199             return array();
1200           }
1201           foreach ($attrs[0]['objectclasses'] as $val){
1202             $name= preg_replace("/^.* NAME\s+\(*\s*'([^']+)'\s*\)*.*$/", '\\1', $val);
1203             if ($name != $val){
1204               $objectclasses[$name]= $val;
1205             }
1206           }
1207           
1208           return $objectclasses;
1209   }
1211   function log($string)
1212   {
1213     if (isset($_SESSION['config'])){
1214       $cfg= $_SESSION['config'];
1215       if (isset($cfg->current['LDAPSTATS']) && preg_match('/true/i', $cfg->current['LDAPSTATS'])){
1216         syslog (LOG_INFO, $string);
1217       }
1218     }
1219   }
1222 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
1223 ?>