Code

8f64c9a8d0a5302e71d6d83fac044e82eb0623e7
[gosa.git] / include / class_ldap.inc
1 <?php
2 /*****************************************************************************
3   newldap.inc - version 1.0
4   Copyright (C) 2003 Alejandro Escanero Blanco <alex@ofmin.com>
5   Copyright (C) 2004 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("COLON_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();
34   function LDAP($binddn,$bindpw, $hostname, $follow_referral= FALSE, $tls= FALSE)
35   {
36     $this->follow_referral= $follow_referral;
37     $this->tls=$tls;
38     $this->binddn=$this->convert($binddn);
40     $this->bindpw=$bindpw;
41     $this->hostname=$hostname;
42     $this->connect();
43   }
46   function convert($dn)
47   {
48     if (COLON_OVERRIDE == TRUE){
49       $res= preg_replace("/\\\\,/", '###GOSAREPLACED###', $dn);
50       $res= preg_replace("/\\\\2C/", '###GOSAREPLACED###', $res);
51       $res= preg_replace("/\(/", '###OPENBRACE###', $res);
52       $res= preg_replace("/\)/", '###CLOSEBRACE###', $res);
53       $res= preg_replace("/\//", '###SLASH###', $res);
55       #if ($dn != $res){
56       #  echo "Conversation from '$dn' to '$res'<br>";
57       #}
58       return ($res);
59     } else {
60       return ($dn);
61     }
62   }
65   function fix($dn)
66   {
67     if (COLON_OVERRIDE == TRUE){
68       $res= preg_replace("/###GOSAREPLACED###/", '\,', $dn);
69       $res= preg_replace("/###OPENBRACE###/", '(', $res);
70       $res= preg_replace("/###CLOSEBRACE###/", ')', $res);
71       $res= preg_replace("/###SLASH###/", '/', $res);
73       #if ($dn != $res){
74       #  echo "Fix from '$dn' to '$res'<br>";
75       #}
76       return ($res);
77     } else {
78       return ($dn);
79     }
80   }
83   function connect()
84   {
85     $this->hascon=false;
86     $this->reconnect=false;
87     if ($this->cid= @ldap_connect($this->hostname)) {
88       @ldap_set_option($this->cid, LDAP_OPT_PROTOCOL_VERSION, 3);
89       if (function_exists("ldap_set_rebind_proc") && $this->follow_referral) {
90         @ldap_set_option($this->cid, LDAP_OPT_REFERRALS, 1);
91         @ldap_set_rebind_proc($this->cid, array(&$this, "rebind"));
92       }
93       if (function_exists("ldap_start_tls") && $this->tls){
94         @ldap_start_tls($this->cid);
95       }
97       $this->error = "No Error";
98       if ($bid = @ldap_bind($this->cid, $this->fix($this->binddn), $this->bindpw)) {
99         $this->error = "Success";
100         $this->hascon=true;
101       } else {
102         if ($this->reconnect){
103           if ($this->error != "Success"){
104             $this->error = "Could not rebind to " . $this->binddn;
105           }
106         } else {
107           $this->error = "Could not bind to " . $this->binddn;
108         }
109       }
110     } else {
111       $this->error = "Could not connect to LDAP server";
112     }
113   }
115   function rebind($ldap, $referral)
116   {
117     $credentials= $this->get_credentials($referral);
118     if (@ldap_bind($ldap, $this->fix($credentials['ADMIN']), $credentials['PASSWORD'])) {
119       $this->error = "Success";
120       $this->hascon=true;
121       $this->reconnect= true;
122       return (0);
123     } else {
124       $this->error = "Could not bind to " . $credentials['ADMIN'];
125       return NULL;
126     }
127   }
129   function reconnect()
130   {
131     if ($this->reconnect){
132       @ldap_unbind($this->cid);
133       $this->cid = NULL;
134     }
135   }
137   function unbind()
138   {
139     @ldap_unbind($this->cid);
140     $this->cid = NULL;
141   }
143   function disconnect()
144   {
145     if($this->hascon){
146       @ldap_close($this->cid);
147       $this->hascon=false;
148     }
149   }
151   function cd($dir)
152   {
153     if ($dir == "..")
154       $this->basedn = $this->getParentDir();
155     else
156       $this->basedn = $this->convert($dir);
157   }
159   function getParentDir($basedn = "")
160   {
161     if ($basedn=="")
162       $basedn = $this->basedn;
163     else
164       $basedn = $this->convert($this->basedn);
165     return(ereg_replace("[^,]*[,]*[ ]*(.*)", "\\1", $basedn));
166   }
168   function search($filter, $attrs= array())
169   {
170     if($this->hascon){
171       if ($this->reconnect) $this->connect();
172       $this->clearResult();
173       $this->sr = @ldap_search($this->cid, $this->fix($this->basedn), $filter, $attrs);
174       $this->error = @ldap_error($this->cid);
175       $this->resetResult();
176       $this->hasres=true;
177   
178       return($this->sr);
179     }else{
180       $this->error = "Could not connect to LDAP server";
181       return("");
182     }
183   }
185   function ls($filter = "(objectclass=*)", $basedn = "",$attrs = array("*"))
186   {
187     if($this->hascon){
188       if ($this->reconnect) $this->connect();
189       $this->clearResult();
190       if ($basedn == "")
191         $basedn = $this->basedn;
192       else
193         $basedn= $this->convert($basedn);
194       $this->sr = @ldap_list($this->cid, $this->fix($basedn), $filter,$attrs);
195       $this->error = @ldap_error($this->cid);
196       $this->resetResult();
197       $this->hasres=true;
198       return($this->sr);
199     }else{
200       $this->error = "Could not connect to LDAP server";
201       return("");
202     }
203   }
205   function cat($dn,$attrs= array("*"))
206   {
207     if($this->hascon){
208       if ($this->reconnect) $this->connect();
209       $this->clearResult();
210       $filter = "(objectclass=*)";
211       $this->sr = @ldap_read($this->cid, $this->fix($dn), $filter,$attrs);
212       $this->error = @ldap_error($this->cid);
213       $this->resetResult();
214       $this->hasres=true;
215       return($this->sr);
216     }else{
217       $this->error = "Could not connect to LDAP server";
218       return("");
219     }
220   }
222   function set_size_limit($size)
223   {
224     /* Ignore zero settings */
225     if ($size == 0){
226       @ldap_set_option($this->cid, LDAP_OPT_SIZELIMIT, 10000000);
227     }
228     if($this->hascon){
229       @ldap_set_option($this->cid, LDAP_OPT_SIZELIMIT, $size);
230     } else {
231       $this->error = "Could not connect to LDAP server";
232     }
233   }
235   function fetch()
236   {
237     if($this->hascon){
238       if($this->hasres){
239         if ($this->start == 0)
240         {
241           $this->start = 1;
242           $this->re= @ldap_first_entry($this->cid, $this->sr);
243         } else {
244           $this->re= @ldap_next_entry($this->cid, $this->re);
245         }
246         if ($this->re)
247         {
248           $att= @ldap_get_attributes($this->cid, $this->re);
249           $att['dn']= $this->convert(@ldap_get_dn($this->cid, $this->re));
250         }
251         $this->error = @ldap_error($this->cid);
252         if (!isset($att)){
253           $att= array();
254         }
255         return($att);
256       }else{
257         $this->error = "Perform a Fetch with no Search";
258         return("");
259       }
260     }else{
261       $this->error = "Could not connect to LDAP server";
262       return("");
263     }
264   }
266   function resetResult()
267   {
268     $this->start = 0;
269   }
271   function clearResult()
272   {
273     if($this->hasres){
274       $this->hasres = false;
275       @ldap_free_result($this->sr);
276     }
277   }
279   function getDN()
280   {
281     if($this->hascon){
282       if($this->hasres){
284         if(!$this->re)
285           {
286           $this->error = "Perform a Fetch with no valid Result";
287           }
288           else
289           {
290           $rv = @ldap_get_dn($this->cid, $this->re);
291         
292           $this->error = @ldap_error($this->cid);
293           return($this->convert($rv));
294            }
295       }else{
296         $this->error = "Perform a Fetch with no Search";
297         return("");
298       }
299     }else{
300       $this->error = "Could not connect to LDAP server";
301       return("");
302     }
303   }
305   function count()
306   {
307     if($this->hascon){
308       if($this->hasres){
309         $rv = @ldap_count_entries($this->cid, $this->sr);
310         $this->error = @ldap_error($this->cid);
311         return($rv);
312       }else{
313         $this->error = "Perform a Fetch with no Search";
314         return("");
315       }
316     }else{
317       $this->error = "Could not connect to LDAP server";
318       return("");
319     }
320   }
322   function rm($attrs = "", $dn = "")
323   {
324     if($this->hascon){
325       if ($this->reconnect) $this->connect();
326       if ($dn == "")
327         $dn = $this->basedn;
329       $r = @ldap_mod_del($this->cid, $this->fix($dn), $attrs);
330       $this->error = @ldap_error($this->cid);
331       return($r);
332     }else{
333       $this->error = "Could not connect to LDAP server";
334       return("");
335     }
336   }
338   function rename($attrs, $dn = "")
339   {
340     if($this->hascon){
341       if ($this->reconnect) $this->connect();
342       if ($dn == "")
343         $dn = $this->basedn;
345       $r = @ldap_mod_replace($this->cid, $this->fix($dn), $attrs);
346       $this->error = @ldap_error($this->cid);
347       return($r);
348     }else{
349       $this->error = "Could not connect to LDAP server";
350       return("");
351     }
352   }
354   function rmdir($deletedn)
355   {
356     if($this->hascon){
357       if ($this->reconnect) $this->connect();
358       $r = @ldap_delete($this->cid, $this->fix($deletedn));
359       $this->error = @ldap_error($this->cid);
360       return($r ? $r : 0);
361     }else{
362       $this->error = "Could not connect to LDAP server";
363       return("");
364     }
365   }
367   /**
368   *  Function rmdir_recursive
369   *
370   *  Description: Based in recursive_remove, adding two thing: full subtree remove, and delete own node.
371   *  Parameters:  The dn to delete
372   *  GiveBack:    True on sucessfull , 0 in error, and "" when we don't get a ldap conection
373   *
374   */
376   function rmdir_recursive($deletedn)
377   {
378     if($this->hascon){
379       if ($this->reconnect) $this->connect();
380       $delarray= array();
381         
382       /* Get sorted list of dn's to delete */
383       $this->ls ("(objectClass=*)",$deletedn);
384       while ($this->fetch()){
385         $deldn= $this->getDN();
386         $delarray[$deldn]= strlen($deldn);
387       }
388       arsort ($delarray);
389       reset ($delarray);
391       /* Really Delete ALL dn's in subtree */
392       foreach ($delarray as $key => $value){
393         $this->rmdir_recursive($key);
394       }
395       
396       /* Finally Delete own Node */
397       $r = @ldap_delete($this->cid, $this->fix($deletedn));
398       $this->error = @ldap_error($this->cid);
399       return($r ? $r : 0);
400     }else{
401       $this->error = "Could not connect to LDAP server";
402       return("");
403     }
404   }
406   /* Copy given attributes and sub-dns with attributes to destination dn 
407   */
408   function copy_FAI_resource_recursive($sourcedn,$destinationdn,$type="branch",$is_first = true,$depth=0)
409   {
410     error_reporting(E_ALL);
411     
412     if($is_first){
413       echo "<h2>".sprintf(_("Creating copy of %s"),"<i>".$sourcedn."</i>")."</h2>";
414     }else{
415       if(preg_match("/^ou=/",$sourcedn)){
416         echo "<h3>"._("Processing")." <i>$destinationdn</i></h3>";
417       }else{
418         $tmp = split(",",$sourcedn);
419         
420         echo "&nbsp;<b>"._("Object").":</b> ";
422         $deststr = $destinationdn;
423         if(strlen($deststr) > 96){
424           $deststr = substr($deststr,0,96)."...";
425         }
427         echo $deststr."<br>";
428       }
429     }
431     flush();
432     
433     if($this->hascon){
434       if ($this->reconnect) $this->connect();
436       /* Save base dn */
437       $basedn= $this->basedn;
438       $delarray= array();
439      
440       /* Check if destination entry already exists */
441       $this->cat($destinationdn);
443       if($this->count()){
444         return;
445       }else{
446         
447         $this->clearResult();
449         /* Get source entry */
450         $this->cd($basedn);
451         $this->cat($sourcedn);
452         $attr = $this->fetch();
454         /* Error while fetching object / attribute abort*/
455         if((!$attr) || (count($attr)) ==0) {
456           echo _("Error while fetching source dn - aborted!");
457           return;
458         }
459   
460         /* check if this is a department */
461         if(in_array("organizationalUnit",$attr['objectClass'])){
462           $attr['dn'] = $this->convert($destinationdn);
463           $this->cd($basedn);
464           $this->create_missing_trees($destinationdn);
465           $this->cd($destinationdn);
467           /* If is first entry, append FAIbranch to department entry */
468           if($is_first){
469             $this->cat($destinationdn);
470             $attr= $this->fetch();
472             /* Filter unneeded informations */
473             foreach($attr as $key => $value){
474               if(is_numeric($key)) unset($attr[$key]);
475               if(isset($attr[$key]['count'])){
476                 if(is_array($attr[$key])){
477                   unset($attr[$key]['count']);
478                 }
479               }
480             }
481             
482             unset($attr['count']);
483             unset($attr['dn']);
485             /* Add marking attribute */
486             $attr['objectClass'][] = "FAIbranch";
487             
488             /* Add this entry */
489             $this->modify($attr);
490           }
491         }else{
493           /* If this is no department */
494           foreach($attr as $key => $value){
495             if(in_array($key ,array("FAItemplateFile","FAIscript", "gotoLogonScript", "gosaApplicationIcon"))){
496               $sr= ldap_read($this->cid, $this->fix($sourcedn), "$key=*", array($key));
497               $ei= ldap_first_entry($this->cid, $sr);
498               if ($tmp= @ldap_get_values_len($this->cid, $ei,$key)){
499                 $attr[$key] = $tmp;
500               }
501             }
503             if(is_numeric($key)) unset($attr[$key]);
504             if(isset($attr[$key]['count'])){
505               if(is_array($attr[$key])){
506                 unset($attr[$key]['count']);
507               }
508             }
509           }
510           unset($attr['count']);
511           unset($attr['dn']);
513           if(!in_array("gosaApplication" , $attr['objectClass'])){
514             if($type=="branch"){
515               $attr['FAIstate'] ="branch";
516             }elseif($type=="freeze"){
517               $attr['FAIstate'] ="freeze";
518             }else{
519               print_red(_("Unknown FAIstate %s"),$type);
520             }
521           }
523           /* Add entry */
524           $this->cd($destinationdn);
525           $this->cat($destinationdn);
526           $a = $this->fetch();
527           if(!count($a)){
528             $this->add($attr);
529           }
531           if($this->error != "Success"){
532             /* Some error occured */
533             print "---------------------------------------------";
534             print $this->get_error()."<br>";
535             print $sourcedn."<br>";
536             print $destinationdn."<br>";
537             print_a( $attr);
538             exit();
539           }          
540         }
541       }
543       $this->ls ("(objectClass=*)",$sourcedn);
544       while ($this->fetch()){
545         $deldn= $this->getDN();
546         $delarray[$deldn]= strlen($deldn);
547       }
548       asort ($delarray);
549       reset ($delarray);
551        $depth ++;
552       foreach($delarray as $dn => $bla){
553         if($dn != $destinationdn){
554           $this->cd($basedn);
555           $item = $this->fetch($this->cat($dn));
556           if(!in_array("FAIbranch",$item['objectClass'])){
557             $this->copy_FAI_resource_recursive($dn,str_replace($sourcedn,$destinationdn,$dn),$type,false,$depth);
558           } 
559         }
560       }
561     }
562     if($is_first){
563       echo "<p class='seperator'>&nbsp;</p>";
564     }
566   }
568   function modify($attrs)
569   {
570     if(count($attrs) == 0){
571       return (0);
572     }
573     if($this->hascon){
574       if ($this->reconnect) $this->connect();
575       $r = @ldap_modify($this->cid, $this->fix($this->basedn), $attrs);
576       $this->error = @ldap_error($this->cid);
577       return($r ? $r : 0);
578     }else{
579       $this->error = "Could not connect to LDAP server";
580       return("");
581     }
582   }
584   function add($attrs)
585   {
586     if($this->hascon){
587       if ($this->reconnect) $this->connect();
588       $r = @ldap_add($this->cid, $this->fix($this->basedn), $attrs);
589       $this->error = @ldap_error($this->cid);
590       return($r ? $r : 0);
591     }else{
592       $this->error = "Could not connect to LDAP server";
593       return("");
594     }
595   }
597   function create_missing_trees($target)
598   {
599     /* Ignore create_missing trees if the base equals target */
600     if ($target == $this->basedn){
601      return;
602     }
604     $real_path= substr($target, 0, strlen($target) - strlen($this->basedn) -1 );
605     $l= array_reverse(ldap_explode_dn($real_path,0));
606     unset($l['count']);
607     $cdn= $this->basedn;
609     foreach ($l as $part){
610       $cdn= "$part,$cdn";
612       /* Ignore referrals */
613       $found= false;
614       foreach($this->referrals as $ref){
615         $base= preg_replace('!^[^:]+://[^/]+/([^?]+).*$!', '\\1', $ref['URL']);
616         if ($base == $cdn){
617           $found= true;
618           break;
619         }
620       }
621       if ($found){
622         continue;
623       }
625       $this->cat ($cdn);
626       $attrs= $this->fetch();
628       /* Create missing entry? */
629       if (!count ($attrs)){
630         $type= preg_replace('/^([^=]+)=.*$/', '\\1', $cdn);
631         $param= preg_replace('/^[^=]+=([^,]+),.*$/', '\\1', $cdn);
633         $na= array();
634         switch ($type){
635           case 'ou':
636             $na["objectClass"]= "organizationalUnit";
637             $na["ou"]= $param;
638             break;
639           case 'dc':
640             $na["objectClass"]= array("dcObject", "top", "locality");
641             $na["dc"]= $param;
642             break;
643           default:
644             print_red(sprintf(_("Autocreation of type '%s' is currently not supported. Please report to the GOsa team."), $type));
645             echo $_SESSION['errors'];
646             exit;
647         }
648         $this->cd($cdn);
649         $this->add($na);
650       }
651     }
652   }
654   function recursive_remove()
655   {
656     $delarray= array();
658     /* Get sorted list of dn's to delete */
659     $this->search ("(objectClass=*)");
660     while ($this->fetch()){
661       $deldn= $this->getDN();
662       $delarray[$deldn]= strlen($deldn);
663     }
664     arsort ($delarray);
665     reset ($delarray);
667     /* Delete all dn's in subtree */
668     foreach ($delarray as $key => $value){
669       $this->rmdir($key);
670     }
671   }
673   function get_attribute($dn, $name,$r_array=0)
674   {
675     $data= "";
676     if ($this->reconnect) $this->connect();
677     $sr= @ldap_read($this->cid, $this->fix($dn), "objectClass=*", array("$name"));
679     /* fill data from LDAP */
680     if ($sr) {
681       $ei= @ldap_first_entry($this->cid, $sr);
682       if ($ei) {
683         if ($info= @ldap_get_values_len($this->cid, $ei, "$name")){
684           $data= $info[0];
685         }
687       }
688     }
689     if($r_array==0)
690     return ($data);
691     else
692     return ($info);
693   
694   
695   }
696  
699   function get_additional_error()
700   {
701     $error= "";
702     @ldap_get_option ($this->cid, LDAP_OPT_ERROR_STRING, $error);
703     return ($error);
704   }
706   function get_error()
707   {
708     if ($this->error == 'Success'){
709       return $this->error;
710     } else {
711       $error= $this->error." (".$this->get_additional_error().")";
712       return $error;
713     }
714   }
716   function get_credentials($url, $referrals= NULL)
717   {
718     $ret= array();
719     $url= preg_replace('!\?\?.*$!', '', $url);
720     $server= preg_replace('!^([^:]+://[^/]+)/.*$!', '\\1', $url);
722     if ($referrals == NULL){
723       $referrals= $this->referrals;
724     }
726     if (isset($referrals[$server])){
727       return ($referrals[$server]);
728     } else {
729       $ret['ADMIN']= $this->fix($this->binddn);
730       $ret['PASSWORD']= $this->bindpw;
731     }
733     return ($ret);
734   }
737   function gen_ldif ($dn, $filter= "(objectClass=*)", $attributes= array('*'), $recursive= TRUE)
738   {
739     $display= "";
741     if ($recursive){
742       $this->cd($dn);
743       $this->search("$filter", array('dn'));
744       while ($attrs= $this->fetch()){
745         $display.= $this->gen_one_entry($attrs['dn'], $filter, $attributes);
746         $display.= "\n";
747       }
748     } else {
749       $display.= $this->gen_one_entry($dn);
750     }
752     return ($display);
753   }
755 function gen_xls ($dn, $filter= "(objectClass=*)", $attributes= array('*'), $recursive= TRUE,$r_array=0)
756   {
757     $display= "";
759       $this->cd($dn);
760       $this->search("$filter");
762       $i=0;
763       while ($attrs= $this->fetch()){
764         $j=0;
766         foreach ($attributes as $at){
767           $display[$i][$j]= $this->get_attribute($attrs['dn'], $at,$r_array);
768           $j++;
769         }
771         $i++;
772       }
774     return ($display);
775   }
778   function gen_one_entry($dn, $filter= "(objectClass=*)" , $name= array("*"))
779   {
780     $ret = "";
781     $data = "";
782     if($this->reconnect){
783       $this->connect();
784     }
786     /* Searching Ldap Tree */
787     $sr= @ldap_read($this->cid, $this->fix($dn), $filter, $name);
789     /* Get the first entry */   
790     $entry= @ldap_first_entry($this->cid, $sr);
792     /* Get all attributes related to that Objekt */
793     $atts = array();
794     
795     /* Assemble dn */
796     $atts[0]['name']  = "dn";
797     $atts[0]['value'] = array('count' => 1, 0 => $dn);
799     /* Reset index */
800     $i = 1 ; 
801   $identifier = array();
802     $attribute= @ldap_first_attribute($this->cid,$entry,$identifier);
803     while ($attribute) {
804       $i++;
805       $atts[$i]['name']  = $attribute;
806       $atts[$i]['value'] = @ldap_get_values_len($this->cid, $entry, "$attribute");
808       /* Next one */
809       $attribute= @ldap_next_attribute($this->cid,$entry,$identifier);
810     }
812     foreach($atts as $at)
813     {
814       for ($i= 0; $i<$at['value']['count']; $i++){
816         /* Check if we must encode the data */
817         if(!preg_match('/^[a-z0-9+@#.=, \/ -]+$/i', $at['value'][$i])) {
818           $ret .= $at['name'].":: ".base64_encode($at['value'][$i])."\n";
819         } else {
820           $ret .= $at['name'].": ".$at['value'][$i]."\n";
821         }
822       }
823     }
825     return($ret);
826   }
829   function dn_exists($dn)
830   {
831     return @ldap_list($this->cid, $this->fix($dn), "(objectClass=*)", array("objectClass"));
832   }
833   
836   function import_complete_ldif($str_attr,&$error,$overwrite,$cleanup)
837   {
838     if($this->reconnect) $this->connect();
840     /* First we have to splitt the string ito detect empty lines
841        An empty line indicates an new Entry */
842     $entries = split("\n",$str_attr);
844     $data = "";
845     $cnt = 0; 
846     $current_line = 0;
848     /* Every single line ... */
849     foreach($entries as $entry) {
850       $current_line ++;
852       /* Removing Spaces to .. 
853          .. test if a new entry begins */
854       $tmp  = str_replace(" ","",$data );
856       /* .. prevent empty lines in an entry */
857       $tmp2 = str_replace(" ","",$entry);
859       /* If the Block ends (Empty Line) */
860       if((empty($entry))&&(!empty($tmp))) {
861         /* Add collected lines as a complete block */
862         $all[$cnt] = $data;
863         $cnt ++;
864         $data ="";
865       } else {
867         /* Append lines ... */
868         if(!empty($tmp2)) {
869           /* check if we need base64_decode for this line */
870           if(ereg("::",$tmp2))
871           {
872             $encoded = split("::",$entry);
873             $attr  = $encoded[0];
874             $value = base64_decode($encoded[1]);
875             /* Add linenumber */
876             $data .= $current_line."#".$attr.":".$value."\n";
877           }
878           else
879           {
880             /* Add Linenumber */ 
881             $data .= $current_line."#".$entry."\n";
882           }
883         }
884       }
885     }
887     /* The Data we collected is not in the array all[];
888        For example the Data is stored like this..
890        all[0] = "1#dn : .... \n 
891        2#ObjectType: person \n ...."
892        
893        Now we check every insertblock and try to insert */
894     foreach ( $all as $single) {
895       $lineone = split("\n",$single);  
896       $ndn = split("#", $lineone[0]);
897       $line = $ndn[1];
899       $dnn = split (":",$line);
900       $current_line = $ndn[0];
901       $dn    = $dnn[0];
902       $value = $dnn[1];
904       /* Every block must begin with a dn */
905       if($dn != "dn") {
906         $error= sprintf(_("This is not a valid DN: '%s'. A block for import should begin with 'dn: ...' in line %s"), $line, $current_line);
907         return -2;  
908       }
910       /* Should we use Modify instead of Add */
911       $usemodify= false;
913       /* Delete before insert */
914       $usermdir= false;
915     
916       /* The dn address already exists! */
917       if (($this->dn_exists($value))&&((!$overwrite)&&(!$cleanup))) {
919         $error= sprintf(_("The dn: '%s' (from line %s) already exists in the LDAP database."), $line, $current_line);
920         return ALREADY_EXISTING_ENTRY;   
922       } elseif(($this->dn_exists($value))&&($cleanup)){
924         /* Delete first, then add */
925         $usermdir = true;        
927       } elseif(($this->dn_exists($value))&&($overwrite)) {
928         
929         /* Modify instead of Add */
930         $usemodify = true;
931       }
932      
933       /* If we can't Import, return with a file error */
934       if(!$this->import_single_entry($single,$usemodify,$usermdir) ) {
935         $error= sprintf(_("Error while importing dn: '%s', please check your LDIF from line %s on!"), $line,
936                         $current_line);
937         return UNKNOWN_TOKEN_IN_LDIF_FILE;      }
938     }
940     return (INSERT_OK);
941   }
944   /* Imports a single entry */
945   function import_single_entry($str_attr,$modify,$delete)
946   {
947     if($this->reconnect) $this->connect();
949     $ret = false;
950     $rows= split("\n",$str_attr);
951     $data= false;
953     foreach($rows as $row) {
954       
955       /* Check if we use Linenumbers (when import_complete_ldif is called we use
956          Linenumbers) Linenumbers are use like this 123#attribute : value */
957       if(!empty($row)) {
958         if((strpos($row,"#")!=FALSE)&&(strpos($row,"#")<strpos($row,":"))) {
960           /* We are using line numbers 
961              Because there is a # before a : */
962           $tmp1= split("#",$row);
963           $current_line= $tmp1[0];
964           $row= $tmp1[1];
965         }
967         /* Split the line into  attribute  and value */
968         $attr   = split(":", $row);
969         $attr[0]= trim($attr[0]);  /* attribute */
970         $attr[1]= trim($attr[1]);  /* value */
972         /* Check for attributes that are used more than once */
973         if(!isset($data[$attr[0]])) {
974           $data[$attr[0]]=$attr[1];
975         } else {
976           $tmp = $data[$attr[0]];
978           if(!is_array($tmp)) {
979             $new[0]=$tmp;
980             $new[1]=$attr[1];
981             $datas[$attr[0]]['count']=1;             
982             $data[$attr[0]]=$new;
983           } else {
984             $cnt = $datas[$attr[0]]['count'];           
985             $cnt ++;
986             $data[$attr[0]][$cnt]=$attr[1];
987             $datas[$attr[0]]['count'] = $cnt;
988           }
989         }
990       }
991     } 
992     
993     /* If dn is an index of data, we should try to insert the data */
994     if(isset($data['dn'])) {
995       /* Creating Entry */
996       $this->cd($data['dn']);
998       /* Delete existing entry */
999       if($delete){
1000         $this->rmdir($data['dn']);
1001       }
1002       
1003       /* Create missing trees */
1004       $this->create_missing_trees($data['dn']);
1005       unset($data['dn']);
1006       
1007       /* If entry exists use modify */
1008       if(!$modify){
1009         $ret = $this->add($data);
1010       } else {
1011         $ret = $this->modify($data);
1012       }
1013     }
1015     return($ret);
1016   }
1018   
1019   function importcsv($str)
1020   {
1021     $lines = split("\n",$str);
1022     foreach($lines as $line)
1023     {
1024       /* continue if theres a comment */
1025       if(substr(trim($line),0,1)=="#"){
1026         continue;
1027       }
1029       $line= str_replace ("\t\t","\t",$line);
1030       $line= str_replace ("\t"  ,"," ,$line);
1031       echo $line;
1033       $cells = split(",",$line )  ;
1034       $linet= str_replace ("\t\t",",",$line);
1035       $cells = split("\t",$line);
1036       $count = count($cells);  
1037     }
1039   }
1043 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
1044 ?>