Code

20ff04037656c808190024ed349790aedc04d7b2
[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);
16 define("INSERT_OK",10000);
20 class LDAP{
22   var $hascon   =false;
23   var $hasres   =false;
24   var $reconnect=false;
25   var $tls      = false;
26   var $basedn   ="";
27   var $cid;
28   var $error    = ""; // Any error messages to be returned can be put here
29   var $start    = 0; // 0 if we are fetching the first entry, otherwise 1
30   var $objectClasses = array(); // Information read from slapd.oc.conf
31   var $binddn   = "";
32   var $bindpw   = "";
33   var $hostname = "";
34   var $follow_referral = FALSE;
35   var $referrals= array();
37   function LDAP($binddn,$bindpw, $hostname, $follow_referral= FALSE, $tls= FALSE)
38   {
39     $this->follow_referral= $follow_referral;
40     $this->tls=$tls;
41     $this->binddn=$binddn;
42     $this->bindpw=$bindpw;
43     $this->hostname=$hostname;
44     $this->connect();
45   }
47   function connect()
48   {
49     $this->hascon=false;
50     $this->reconnect=false;
51     if ($this->cid= @ldap_connect($this->hostname)) {
52       @ldap_set_option($this->cid, LDAP_OPT_PROTOCOL_VERSION, 3);
53       if (function_exists("ldap_set_rebind_proc") && $this->follow_referral) {
54         @ldap_set_option($this->cid, LDAP_OPT_REFERRALS, 1);
55         @ldap_set_rebind_proc($this->cid, array(&$this, "rebind"));
56       }
57       if (function_exists("ldap_start_tls") && $this->tls){
58         @ldap_start_tls($this->cid);
59       }
61       $this->error = "No Error";
62       if ($bid = @ldap_bind($this->cid, $this->binddn, $this->bindpw)) {
63         $this->error = "Success";
64         $this->hascon=true;
65       } else {
66         if ($this->reconnect){
67           if ($this->error != "Success"){
68             $this->error = "Could not rebind to " . $this->binddn;
69           }
70         } else {
71           $this->error = "Could not bind to " . $this->binddn;
72         }
73       }
74     } else {
75       $this->error = "Could not connect to LDAP server";
76     }
77   }
79   function rebind($ldap, $referral)
80   {
81     $credentials= $this->get_credentials($referral);
82     if (@ldap_bind($ldap, $credentials['ADMIN'], $credentials['PASSWORD'])) {
83       $this->error = "Success";
84       $this->hascon=true;
85       $this->reconnect= true;
86       return (0);
87     } else {
88       $this->error = "Could not bind to " . $credentials['ADMIN'];
89       return NULL;
90     }
91   }
93   function reconnect()
94   {
95     if ($this->reconnect){
96       @ldap_unbind($this->cid);
97       $this->cid = NULL;
98     }
99   }
101   function unbind()
102   {
103     @ldap_unbind($this->cid);
104     $this->cid = NULL;
105   }
107   function disconnect()
108   {
109     if($this->hascon){
110       @ldap_close($this->cid);
111       $this->hascon=false;
112     }
113   }
115   function cd($dir)
116   {
117     if ($dir == "..")
118       $this->basedn = $this->getParentDir();
119     else
120       $this->basedn = $dir;
121   }
123   function getParentDir($basedn = "")
124   {
125     if ($basedn=="")
126       $basedn = $this->basedn;
127     return(ereg_replace("[^,]*[,]*[ ]*(.*)", "\\1", $basedn));
128   }
130   function search($filter, $attrs= array())
131   {
132     $start = microtime();
134     if($this->hascon){
135       if ($this->reconnect) $this->connect();
136       $this->clearResult();
137       $this->sr = @ldap_search($this->cid, $this->basedn, $filter, $attrs);
138       $this->error = @ldap_error($this->cid);
139       $this->resetResult();
140       $this->hasres=true;
141   
142       /* Time management */
143       $r = split(" ",$start);
144       $ms = $r[0];
145       $s= $r[1];
147       $re = split(" ",microtime());
148       $mse = $re[0];
149       $se= $re[1];
151       $add = 0;
152       if(($mse -$ms)<0){
153         $se --;
154         $add = 1;
155       }
156       $secs =  ($se -$s);
157       $msecs = (int)(($add+($mse -$ms))*1000);
158       $time = $secs +($msecs/1000);
159       if($time > .2){
160         $Sattrs = "";
161         foreach($attrs as $att){
162           $Sattrs .= " ".$att;
163         }
164         print_red(sprintf(_("Ldap search took about %s seconds, used filter '%s' with following attributes '%s '. Please check for performance improvements."),$time,htmlentities($filter),$Sattrs));
165       }
166       return($this->sr);
167     }else{
168       $this->error = "Could not connect to LDAP server";
169       return("");
170     }
171   }
173   function ls($filter = "(objectclass=*)", $basedn = "",$attrs = array("*"))
174   {
175     if($this->hascon){
176       if ($this->reconnect) $this->connect();
177       $this->clearResult();
178       if ($basedn == "")
179         $basedn = $this->basedn;
180       $this->sr = @ldap_list($this->cid, $basedn, $filter,$attrs);
181       $this->error = @ldap_error($this->cid);
182       $this->resetResult();
183       $this->hasres=true;
184       return($this->sr);
185     }else{
186       $this->error = "Could not connect to LDAP server";
187       return("");
188     }
189   }
191   function cat($dn)
192   {
193     if($this->hascon){
194       if ($this->reconnect) $this->connect();
195       $this->clearResult();
196       $filter = "(objectclass=*)";
197       $this->sr = @ldap_read($this->cid, $dn, $filter);
198       $this->error = @ldap_error($this->cid);
199       $this->resetResult();
200       $this->hasres=true;
201       return($this->sr);
202     }else{
203       $this->error = "Could not connect to LDAP server";
204       return("");
205     }
206   }
208   function set_size_limit($size)
209   {
210     /* Ignore zero settings */
211     if ($size == 0){
212       @ldap_set_option($this->cid, LDAP_OPT_SIZELIMIT, 10000000);
213     }
214     if($this->hascon){
215       @ldap_set_option($this->cid, LDAP_OPT_SIZELIMIT, $size);
216     } else {
217       $this->error = "Could not connect to LDAP server";
218     }
219   }
221   function fetch()
222   {
223     if($this->hascon){
224       if($this->hasres){
225         if ($this->start == 0)
226         {
227           $this->start = 1;
228           $this->re= @ldap_first_entry($this->cid, $this->sr);
229         } else {
230           $this->re= @ldap_next_entry($this->cid, $this->re);
231         }
232         if ($this->re)
233         {
234           $att= @ldap_get_attributes($this->cid, $this->re);
235           $att['dn']= @ldap_get_dn($this->cid, $this->re);
236         }
237         $this->error = @ldap_error($this->cid);
238         if (!isset($att)){
239           $att= array();
240         }
241         return($att);
242       }else{
243         $this->error = "Perform a Fetch with no Search";
244         return("");
245       }
246     }else{
247       $this->error = "Could not connect to LDAP server";
248       return("");
249     }
250   }
252   function resetResult()
253   {
254     $this->start = 0;
255   }
257   function clearResult()
258   {
259     if($this->hasres){
260       $this->hasres = false;
261       @ldap_free_result($this->sr);
262     }
263   }
265   function getDN()
266   {
267     if($this->hascon){
268       if($this->hasres){
270         if(!$this->re)
271           {
272           $this->error = "Perform a Fetch with no valid Result";
273           }
274           else
275           {
276           $rv = @ldap_get_dn($this->cid, $this->re);
277         
278           $this->error = @ldap_error($this->cid);
279           $rv= clean_dn($rv);
280           return($rv);
281            }
282       }else{
283         $this->error = "Perform a Fetch with no Search";
284         return("");
285       }
286     }else{
287       $this->error = "Could not connect to LDAP server";
288       return("");
289     }
290   }
292   function count()
293   {
294     if($this->hascon){
295       if($this->hasres){
296         $rv = @ldap_count_entries($this->cid, $this->sr);
297         $this->error = @ldap_error($this->cid);
298         return($rv);
299       }else{
300         $this->error = "Perform a Fetch with no Search";
301         return("");
302       }
303     }else{
304       $this->error = "Could not connect to LDAP server";
305       return("");
306     }
307   }
309   function rm($attrs = "", $dn = "")
310   {
311     if($this->hascon){
312       if ($this->reconnect) $this->connect();
313       if ($dn == "")
314         $dn = $this->basedn;
316       $r = @ldap_mod_del($this->cid, $dn, $attrs);
317       $this->error = @ldap_error($this->cid);
318       return($r);
319     }else{
320       $this->error = "Could not connect to LDAP server";
321       return("");
322     }
323   }
325   function rename($attrs, $dn = "")
326   {
327     if($this->hascon){
328       if ($this->reconnect) $this->connect();
329       if ($dn == "")
330         $dn = $this->basedn;
332       $r = @ldap_mod_replace($this->cid, $dn, $attrs);
333       $this->error = @ldap_error($this->cid);
334       return($r);
335     }else{
336       $this->error = "Could not connect to LDAP server";
337       return("");
338     }
339   }
341   function rmdir($deletedn)
342   {
343     if($this->hascon){
344       if ($this->reconnect) $this->connect();
345       $r = @ldap_delete($this->cid, $deletedn);
346       $this->error = @ldap_error($this->cid);
347       return($r ? $r : 0);
348     }else{
349       $this->error = "Could not connect to LDAP server";
350       return("");
351     }
352   }
354   /**
355   *  Function rmdir_recursive
356   *
357   *  Description: Based in recursive_remove, adding two thing: full subtree remove, and delete own node.
358   *  Parameters:  The dn to delete
359   *  GiveBack:    True on sucessfull , 0 in error, and "" when we don't get a ldap conection
360   *
361   */
363   function rmdir_recursive($deletedn)
364   {
365     if($this->hascon){
366       if ($this->reconnect) $this->connect();
367       $delarray= array();
368         
369       /* Get sorted list of dn's to delete */
370       $this->ls ("(objectClass=*)",$deletedn);
371       while ($this->fetch()){
372         $deldn= $this->getDN();
373         $delarray[$deldn]= strlen($deldn);
374       }
375       arsort ($delarray);
376       reset ($delarray);
378       /* Really Delete ALL dn's in subtree */
379       foreach ($delarray as $key => $value){
380         $this->rmdir_recursive($key);
381       }
382       
383       /* Finally Delete own Node */
384       $r = @ldap_delete($this->cid, $deletedn);
385       $this->error = @ldap_error($this->cid);
386       return($r ? $r : 0);
387     }else{
388       $this->error = "Could not connect to LDAP server";
389       return("");
390     }
391   }
393   /* Copy given attributes and sub-dns with attributes to destination dn 
394       
395   */
396   function copy_FAI_resource_recursive($sourcedn,$destinationdn,$type="branch",$is_first = false)
397   {
398     error_reporting(E_ALL);
399     if($this->hascon){
400       if ($this->reconnect) $this->connect();
402       /* Save base dn */
403       $basedn= $this->basedn;
404       $delarray= array();
405       
406       /* Check if destination entry already exists */
407       if($this->count($this->fetch($this->cat($destinationdn)))){
408         return;
409       }else{
411         /* Get source entrie */
412         $this->cd($basedn);
413         $attr = $this->fetch($this->cat($sourcedn));
415         /* check if this is a department */
416         if(in_array("organizationalUnit",$attr['objectClass'])){
417           $attr['dn'] = $destinationdn;
418           $this->cd($basedn);
419           $this->create_missing_trees($destinationdn);
420           $this->cd($destinationdn);
422           /* If is first entry, append FAIbranch to department entry */
423           if($is_first){
424             $attr= $this->fetch($this->cat($destinationdn));
426             /* Filter unneeded informations */
427             foreach($attr as $key => $value){
428               if(is_numeric($key)) unset($attr[$key]);
429               if(isset($attr[$key]['count'])){
430                 if(($attr[$key]['count']==1)&&($key!="objectClass")){
431                   $attr[$key] = $attr[$key][0];
432                 }
433               }
434               
435               if(isset($attr[$key]['count'])){
436                 if(is_array($attr[$key])){
437                   unset($attr[$key]['count']);
438                 }
439               }
440             }
441             unset($attr['count']);
442             unset($attr['dn']);
444             /* Add marking attribute */
445             $attr['objectClass'][] = "FAIbranch";
446             
447             /* Add this entry */
448             $this->modify($attr);
449           }
450           
451         }else{
452         /* If this is no department */
453           foreach($attr as $key => $value){
454             if(is_numeric($key)) unset($attr[$key]);
455             if(isset($attr[$key]['count'])){
456               if(($attr[$key]['count']==1)&&($key!="objectClass")){
457                 $attr[$key] = $attr[$key][0];
458               }
459             }
460             if(isset($attr[$key]['count'])){
461               if(is_array($attr[$key])){
462                 unset($attr[$key]['count']);
463               }
464             }
465           }
466           unset($attr['count']);
467           unset($attr['dn']);
468  
469           if($type=="branch"){
470             $attr['FAIstate'] ="branch";
471           }elseif($type=="freeze"){
472             $attr['FAIstate'] ="freeze";
473           }else{
474             print_red(_("Unknown FAIstate %s"),$type);
475           }
476  
477           /* Add entry */
478           $this->cd($destinationdn);
479           $a = $this->fetch($this->cat($destinationdn));
480           if(!count($a)){
481             $this->add($attr);
482           }
484           if($this->error != "Success"){
485             /* Some error occured */
486             print "---------------------------------------------";
487             print $this->get_error()."<br>";
488             print $sourcedn."<br>";
489             print $destinationdn."<br>";
490             print_a( $attr);
491             exit();
492           }          
493         }
494       }
496       $this->ls ("(objectClass=*)",$sourcedn);
497       while ($this->fetch()){
498         $deldn= $this->getDN();
499         $delarray[$deldn]= strlen($deldn);
500       }
501       asort ($delarray);
502       reset ($delarray);
504       foreach($delarray as $dn => $bla){
505         if($dn != $destinationdn){
506           $this->cd($basedn);
507           $item = $this->fetch($this->cat($dn));
508           if(!in_array("FAIbranch",$item['objectClass'])){
509             $this->copy_FAI_resource_recursive($dn,str_replace($sourcedn,$destinationdn,$dn),$type);
510           } 
511         }
512       }
513     }
514   }
516   function modify($attrs)
517   {
518     if($this->hascon){
519       if ($this->reconnect) $this->connect();
520       $r = @ldap_modify($this->cid, $this->basedn, $attrs);
521       $this->error = @ldap_error($this->cid);
522       return($r ? $r : 0);
523     }else{
524       $this->error = "Could not connect to LDAP server";
525       return("");
526     }
527   }
529   function add($attrs)
530   {
531     if($this->hascon){
532       if ($this->reconnect) $this->connect();
533       $r = @ldap_add($this->cid, $this->basedn, $attrs);
534       $this->error = @ldap_error($this->cid);
535       return($r ? $r : 0);
536     }else{
537       $this->error = "Could not connect to LDAP server";
538       return("");
539     }
540   }
542   function create_missing_trees($target)
543   {
544     /* Ignore create_missing trees if the base equals target */
545     if ($target == $this->basedn){
546      return;
547     }
548     $l= array_reverse(explode(",", preg_replace("/,".$this->basedn."/", "", $target)));
549     $cdn= $this->basedn;
550     foreach ($l as $part){
551       $cdn= "$part,$cdn";
553       /* Ignore referrals */
554       $found= false;
555       foreach($this->referrals as $ref){
556         $base= preg_replace('!^[^:]+://[^/]+/([^?]+).*$!', '\\1', $ref['URL']);
557         if ($base == $cdn){
558           $found= true;
559           break;
560         }
561       }
562       if ($found){
563         continue;
564       }
566       $this->cat ($cdn);
567       $attrs= $this->fetch();
569       /* Create missing entry? */
570       if (!count ($attrs)){
571         $type= preg_replace('/^([^=]+)=.*$/', '\\1', $cdn);
572         $param= preg_replace('/^[^=]+=([^,]+),.*$/', '\\1', $cdn);
574         $na= array();
575         switch ($type){
576           case 'ou':
577             $na["objectClass"]= "organizationalUnit";
578             $na["ou"]= $param;
579             break;
580           case 'dc':
581             $na["objectClass"]= array("dcObject", "top", "locality");
582             $na["dc"]= $param;
583             break;
584           default:
585             print_red(sprintf(_("Autocreation of type '%s' is currently not supported. Please report to the GOsa team."), $type));
586             echo $_SESSION['errors'];
587             exit;
588         }
589         $this->cd($cdn);
590         $this->add($na);
591       }
592     }
593   }
595   function recursive_remove()
596   {
597     $delarray= array();
599     /* Get sorted list of dn's to delete */
600     $this->search ("(objectClass=*)");
601     while ($this->fetch()){
602       $deldn= $this->getDN();
603       $delarray[$deldn]= strlen($deldn);
604     }
605     arsort ($delarray);
606     reset ($delarray);
608     /* Delete all dn's in subtree */
609     foreach ($delarray as $key => $value){
610       $this->rmdir($key);
611     }
612   }
614   function get_attribute($dn, $name,$r_array=0)
615   {
616     $data= "";
617     if ($this->reconnect) $this->connect();
618     $sr= @ldap_read($this->cid, $dn, "objectClass=*", array("$name"));
620     /* fill data from LDAP */
621     if ($sr) {
622       $ei= @ldap_first_entry($this->cid, $sr);
623       if ($ei) {
624         if ($info= @ldap_get_values_len($this->cid, $ei, "$name")){
625           $data= $info[0];
626         }
628       }
629     }
630     if($r_array==0)
631     return ($data);
632     else
633     return ($info);
634   
635   
636   }
637  
640   function get_additional_error()
641   {
642     $error= "";
643     @ldap_get_option ($this->cid, LDAP_OPT_ERROR_STRING, $error);
644     return ($error);
645   }
647   function get_error()
648   {
649     if ($this->error == 'Success'){
650       return $this->error;
651     } else {
652       $error= $this->error." (".$this->get_additional_error().")";
653       return $error;
654     }
655   }
657   function get_credentials($url, $referrals= NULL)
658   {
659     $ret= array();
660     $url= preg_replace('!\?\?.*$!', '', $url);
661     $server= preg_replace('!^([^:]+://[^/]+)/.*$!', '\\1', $url);
663     if ($referrals == NULL){
664       $referrals= $this->referrals;
665     }
667     if (isset($referrals[$server])){
668       return ($referrals[$server]);
669     } else {
670       $ret['ADMIN']= $this->binddn;
671       $ret['PASSWORD']= $this->bindpw;
672     }
674     return ($ret);
675   }
678   function gen_ldif ($dn, $filter= "(objectClass=*)", $attributes= array('*'), $recursive= TRUE)
679   {
680     $display= "";
682     if ($recursive){
683       $this->cd($dn);
684       $this->search("$filter", array('dn'));
685       while ($attrs= $this->fetch()){
686         $display.= $this->gen_one_entry($attrs['dn'], $filter, $attributes);
687         $display.= "\n";
688       }
689     } else {
690       $display.= $this->gen_one_entry($dn);
691     }
693     return ($display);
694   }
696 function gen_xls ($dn, $filter= "(objectClass=*)", $attributes= array('*'), $recursive= TRUE,$r_array=0)
697   {
698     $display= "";
700       $this->cd($dn);
701       $this->search("$filter");
703       $i=0;
704       while ($attrs= $this->fetch()){
705         $j=0;
707         foreach ($attributes as $at){
708           $display[$i][$j]= $this->get_attribute($attrs['dn'], $at,$r_array);
709           $j++;
710         }
712         $i++;
713       }
715     return ($display);
716   }
719   function gen_one_entry($dn, $filter= "(objectClass=*)" , $name= array("*"))
720   {
721     $ret = "";
722     $data = "";
723     if($this->reconnect){
724       $this->connect();
725     }
727     /* Searching Ldap Tree */
728     $sr= @ldap_read($this->cid, $dn, $filter, $name);
730     /* Get the first entry */   
731     $entry= @ldap_first_entry($this->cid, $sr);
733     /* Get all attributes related to that Objekt */
734     $atts = array();
735     
736     /* Assemble dn */
737     $atts[0]['name']  = "dn";
738     $atts[0]['value'] = array('count' => 1, 0 => $dn);
740     /* Reset index */
741     $i = 1 ; 
742   $identifier = array();
743     $attribute= @ldap_first_attribute($this->cid,$entry,$identifier);
744     while ($attribute) {
745       $i++;
746       $atts[$i]['name']  = $attribute;
747       $atts[$i]['value'] = @ldap_get_values_len($this->cid, $entry, "$attribute");
749       /* Next one */
750       $attribute= @ldap_next_attribute($this->cid,$entry,$identifier);
751     }
753     foreach($atts as $at)
754     {
755       for ($i= 0; $i<$at['value']['count']; $i++){
757         /* Check if we must encode the data */
758         if(!preg_match('/^[a-z0-9+@#.=, \/ -]+$/i', $at['value'][$i])) {
759           $ret .= $at['name'].":: ".base64_encode($at['value'][$i])."\n";
760         } else {
761           $ret .= $at['name'].": ".$at['value'][$i]."\n";
762         }
763       }
764     }
766     return($ret);
767   }
770   function dn_exists($dn)
771   {
772     return @ldap_list($this->cid, $dn, "(objectClass=*)", array("objectClass"));
773   }
774   
777   function import_complete_ldif($str_attr,&$error,$overwrite,$cleanup)
778   {
779     if($this->reconnect) $this->connect();
781     /* First we have to splitt the string ito detect empty lines
782        An empty line indicates an new Entry */
783     $entries = split("\n",$str_attr);
785     $data = "";
786     $cnt = 0; 
787     $current_line = 0;
789     /* Every single line ... */
790     foreach($entries as $entry) {
791       $current_line ++;
793       /* Removing Spaces to .. 
794          .. test if a new entry begins */
795       $tmp  = str_replace(" ","",$data );
797       /* .. prevent empty lines in an entry */
798       $tmp2 = str_replace(" ","",$entry);
800       /* If the Block ends (Empty Line) */
801       if((empty($entry))&&(!empty($tmp))) {
802         /* Add collected lines as a complete block */
803         $all[$cnt] = $data;
804         $cnt ++;
805         $data ="";
806       } else {
808         /* Append lines ... */
809         if(!empty($tmp2)) {
810           /* check if we need base64_decode for this line */
811           if(ereg("::",$tmp2))
812           {
813             $encoded = split("::",$entry);
814             $attr  = $encoded[0];
815             $value = base64_decode($encoded[1]);
816             /* Add linenumber */
817             $data .= $current_line."#".$attr.":".$value."\n";
818           }
819           else
820           {
821             /* Add Linenumber */ 
822             $data .= $current_line."#".$entry."\n";
823           }
824         }
825       }
826     }
828     /* The Data we collected is not in the array all[];
829        For example the Data is stored like this..
831        all[0] = "1#dn : .... \n 
832        2#ObjectType: person \n ...."
833        
834        Now we check every insertblock and try to insert */
835     foreach ( $all as $single) {
836       $lineone = split("\n",$single);  
837       $ndn = split("#", $lineone[0]);
838       $line = $ndn[1];
840       $dnn = split (":",$line);
841       $current_line = $ndn[0];
842       $dn    = $dnn[0];
843       $value = $dnn[1];
845       /* Every block must begin with a dn */
846       if($dn != "dn") {
847         $error= sprintf(_("This is not a valid DN: '%s'. A block for import should begin with 'dn: ...' in line %s"), $line, $current_line);
848         return -2;  
849       }
851       /* Should we use Modify instead of Add */
852       $usemodify= false;
854       /* Delete before insert */
855       $usermdir= false;
856     
857       /* The dn address already exists! */
858       if (($this->dn_exists($value))&&((!$overwrite)&&(!$cleanup))) {
860         $error= sprintf(_("The dn: '%s' (from line %s) already exists in the LDAP database."), $line, $current_line);
861         return ALREADY_EXISTING_ENTRY;   
863       } elseif(($this->dn_exists($value))&&($cleanup)){
865         /* Delete first, then add */
866         $usermdir = true;        
868       } elseif(($this->dn_exists($value))&&($overwrite)) {
869         
870         /* Modify instead of Add */
871         $usemodify = true;
872       }
873      
874       /* If we can't Import, return with a file error */
875       if(!$this->import_single_entry($single,$usemodify,$usermdir) ) {
876         $error= sprintf(_("Error while importing dn: '%s', please check your LDIF from line %s on!"), $line,
877                         $current_line);
878         return UNKNOWN_TOKEN_IN_LDIF_FILE;      }
879     }
881     return (INSERT_OK);
882   }
885   /* Imports a single entry */
886   function import_single_entry($str_attr,$modify,$delete)
887   {
888     if($this->reconnect) $this->connect();
890     $ret = false;
891     $rows= split("\n",$str_attr);
892     $data= false;
894     foreach($rows as $row) {
895       
896       /* Check if we use Linenumbers (when import_complete_ldif is called we use
897          Linenumbers) Linenumbers are use like this 123#attribute : value */
898       if(!empty($row)) {
899         if((strpos($row,"#")!=FALSE)&&(strpos($row,"#")<strpos($row,":"))) {
901           /* We are using line numbers 
902              Because there is a # before a : */
903           $tmp1= split("#",$row);
904           $current_line= $tmp1[0];
905           $row= $tmp1[1];
906         }
908         /* Split the line into  attribute  and value */
909         $attr   = split(":", $row);
910         $attr[0]= trim($attr[0]);  /* attribute */
911         $attr[1]= trim($attr[1]);  /* value */
913         /* Check for attributes that are used more than once */
914         if(!isset($data[$attr[0]])) {
915           $data[$attr[0]]=$attr[1];
916         } else {
917           $tmp = $data[$attr[0]];
919           if(!is_array($tmp)) {
920             $new[0]=$tmp;
921             $new[1]=$attr[1];
922             $datas[$attr[0]]['count']=1;             
923             $data[$attr[0]]=$new;
924           } else {
925             $cnt = $datas[$attr[0]]['count'];           
926             $cnt ++;
927             $data[$attr[0]][$cnt]=$attr[1];
928             $datas[$attr[0]]['count'] = $cnt;
929           }
930         }
931       }
932     } 
933     
934     /* If dn is an index of data, we should try to insert the data */
935     if(isset($data['dn'])) {
936       /* Creating Entry */
937       $this->cd($data['dn']);
939       /* Delete existing entry */
940       if($delete){
941         $this->rmdir($data['dn']);
942       }
943       
944       /* Create missing trees */
945       $this->create_missing_trees($data['dn']);
946       unset($data['dn']);
947       
948       /* If entry exists use modify */
949       if(!$modify){
950         $ret = $this->add($data);
951       } else {
952         $ret = $this->modify($data);
953       }
954     }
956     return($ret);
957   }
959   
960   function importcsv($str)
961   {
962     $lines = split("\n",$str);
963     foreach($lines as $line)
964     {
965       /* continue if theres a comment */
966       if(substr(trim($line),0,1)=="#"){
967         continue;
968       }
970       $line= str_replace ("\t\t","\t",$line);
971       $line= str_replace ("\t"  ,"," ,$line);
972       echo $line;
974       $cells = split(",",$line )  ;
975       $linet= str_replace ("\t\t",",",$line);
976       $cells = split("\t",$line);
977       $count = count($cells);  
978     }
980   }
984 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
985 ?>