Code

Added remove multiple entries to macro list
[gosa.git] / plugins / addons / ldapmanager / class_csvimport.inc
1 <?php
3 class csvimport extends plugin
4 {
5   /* Definitions */
6   var $plHeadline= "LDIF export";
7   var $plDescription= "This does something";
8   var $access= "";
10   /* Array with csv informations*/
11   var $csvinfo=array();
13   /* attribute list for save action */
14   var $attributes= array();
15   var $objectclasses= array();
17   function csvimport ($config, $dn= NULL)
18   {
19     /* Include config object */
20     $this->config= $config;
22     $this->ui = get_userinfo();
23   }
25   function execute()
26   {
27     /* Call parent execute */
28     plugin::execute();
30     /* initiate smarty */
31     $smarty= get_smarty();
32     $smarty->assign("selectedattrs",array(0=>""));
33     $smarty->assign("data",array(0=>""));
34     $smarty->assign("head",array(0=>""));
35     $smarty->assign("sorted",0);
36     $smarty->assign("fileup",0);
38     /* Get the LDAP link, to generate the Export */
39     $ldap = $this->config->get_ldap_link();
41     $arrtemplates = array();
42     $tempvar =0;
44     /* Array to fill in Formfields */
45     $arrtemplates[$tempvar] = "None";
46     if(!is_array($this->csvinfo)){
47       $this->csvinfo=array();
48     }
50     /* Set Usertemplate information and get all Attribute from userclass */
51     unset ($this->csvinfo['arrtemplates']);
52     unset ($this->csvinfo['arrtempls']);
54     /* Generate Template Array, Attribute Array */
55     if(!isset($this->csvinfo['arrtempls'])){
57       /* Generating attributes */
58       $attrs = @get_class_vars("user");
59       $this->csvinfo['attr']  = $attrs['attributes'];
61       /* Attach the choise none to discard a csv col */
62       $new = array();
63       $new[0]="none";
64       $new[1]="userPassword";
65       for($c = 0; $c < count($this->csvinfo['attr']);$c++){
66         $new[$c+2]=$this->csvinfo['attr'][$c];
67       }
69       $this->csvinfo['attr'] = $new;
71       /* Search all Templates    */
72       $this->csvinfo['templates'] = $ldap->search("(objectClass=gosaUserTemplate)",array("*"));
74       /* Array to handle selected Form fiels */
75       $this->csvinfo['arrtempls'][$tempvar]['name'] = "";
76       $this->csvinfo['arrtempls'][$tempvar]['dn']   = "";
78       $this->csvinfo['arrtemplates'][]="None";
80       while($temp = $ldap->fetch($this->csvinfo['templates'])){
81         $tempvar ++;
82         $this->csvinfo['arrtemplates'][$tempvar] = $temp['sn'][0]." - ".$this->config->idepartments[preg_replace("/^[^,]+,".get_people_ou()."/i", "", $temp['dn'])];
83         $this->csvinfo['arrtempls']   [$tempvar]['name'] = $temp['sn'][0]; 
84         $this->csvinfo['arrtempls']   [$tempvar]['dn']   = $temp['dn'];
85       }
86     }
88     $arr_temp  = array_flip($this->csvinfo['attr']);
89     $this->csvinfo['arr_selected']= array($arr_temp['uid'],$arr_temp['sn'],$arr_temp['givenName'],$arr_temp['userPassword']);
91     $smarty->assign("templates",$this->csvinfo['arrtemplates']);
92     $smarty->assign("attrs",$this->csvinfo['attr']);
94     /* Check permissions for import */
95     $acl = $this->ui->get_permissions($this->config->current['BASE'],"all/all");
96     if(!preg_match("/w/",$acl)){
97       if(isset($_POST['userfile']) || isset($_POST['sorted']) || isset($_POST['fileup'])){
98         print_red(_("You've no permission to do CSV imports."));
99       }
100       return ($smarty->fetch (get_template_path('contentcsv.tpl', TRUE)));
101     }
103     /* If the given dat from the csv File are sorted by the attributes */
104     if(isset($_POST['sorted'])) {
106       /* Template Handling */
107       $smarty->assign("fileup",TRUE); 
108       $smarty->assign("sorted",TRUE); 
110       for($i = 0 ; $i < $this->csvinfo['rows'];$i++){
111         /* Preparing given Data */
112         $this->csvinfo['sorteddata'][$i]=array(); 
114         /* Go through every col */
115         for($a = 0; $a <= ($this->csvinfo['cols']); $a ++) {
116           /* Append a status col at last, to show possibly errors */
117           if($a==($this->csvinfo['cols'])){
118             $this->csvinfo['sorteddata'][$i]["status"]="-";            
119           } else {
120             $cc = ($i * ($this->csvinfo['cols']))+$a;
122             /* If theres a Attribut given for this col */
123             if(!empty($_POST[('row'.($a))])) {
124               $this->csvinfo['sorteddata'][$i][$this->csvinfo['attr'][$_POST[('row'.($a))]]]=$this->csvinfo['data'][($cc)]; 
125             }
126           }
127         }
128       } 
130       /* aleast one entry */
131       $rowcnt=0;      
132       if(isset($this->csvinfo['sorteddata'])){
133         $rowcnt ++;
135         /* Set the col count */
136         $tblcolcount= count ($this->csvinfo['cols']);
138         /* entrie count */
139         $tbl_entries= count ($this->csvinfo['count']);
141         /* row count */
142         $tbl_rows   = $tbl_entries / $tblcolcount;
144         /* No error occured */
145         $failing = FALSE;
147         /* For every row */
148         for($i = 0; $i < $this->csvinfo['rows']; $i++){
150           /* Get elemenet */
151           $dat = $this->csvinfo['sorteddata'][$i];
153           /* If not all needed vars set .... */
154           if(         ( empty($dat['sn']))||( empty($dat['givenName']))||( empty($dat['uid']))||
155               (!isset($dat['sn']))||(!isset($dat['givenName']))||(!isset($dat['uid']))){
157             /* Output Error */
159             print_red (_("Need 'sn','givenName' and 'uid' to create user."));
160           } else {
162             /* Register usertab to trigger edit dialog */
163             $this->usertab= new usertabs($this->config, $this->config->data['TABS']['USERTABS'], 'new');
164             $keys = array_keys($dat);
167             /* Set all submitted vars  */
168             if(is_array($keys))
169               foreach($keys as $key) {
170                 if($key != "status"){
171                   $this->usertab->$key = $dat[$key];
172                 }
173               }
175             /* Initialize template */
176             if($this->csvinfo['tplid']!=0){
177               $this->usertab->adapt_from_template($this->csvinfo['arrtempls'][$this->csvinfo['tplid']]['dn']);
178               $this->usertab->save_object();
179             } else {
181               /* Reset vars */
182               if(is_array($keys))
183                 foreach($keys as $key) {
184                   if($key != "status"){
185                     $this->usertab->by_object['user']->$key = $dat[$key];
186                   }
187                 }
188             }
190             // Setting user Password 
191             if((isset($dat['userPassword']))&&(!empty($dat['userPassword'])))
192               $password = $dat['userPassword']; 
193             else
194             {
195               $rand_str="";
196               $feed = "0123456789abcdefghijklmnopqrstuvwxyz";
197               for ($i=0; $i < 8; $i++)
198               {
199                 $rand_str .= substr($feed, rand(0, strlen($feed)-1), 1);
200               }
201               $password = $rand_str;
202             }
204             /* Insert in the LDAP tree */
205             if(count($this->usertab->check())) {
206               show_errors($this->usertab->check());
207               $this->csvinfo['sorteddata'][$i]['status']="<b>"._("failed")."</b>";
208               $failing = $i+1;
209               break;
210             } else {
211               $this->csvinfo['sorteddata'][$i]['status']=_("ok");
212               $this->usertab->save();
213               change_password($this->usertab->dn,$password); 
214             }
215           }
216         }
218         $pointsbefore = FALSE;
219         $pointsafter  = FALSE;
221         /* Get Attributs for Tableheadline  */
222         $this->csvinfo['colsstr'] = array();
223         for($i =0; $i <= $this->csvinfo['cols']; $i++) {
224           if(!empty($_POST[('row'.$i)])){
225             $this->csvinfo['colsstr'][$i] = $this->csvinfo['attr'][$_POST[('row'.$i)]];
226           }
227         }
229         /*Create array with data for the template */
230         if($failing == FALSE){
232           $dataouts= array();
233           for($i =1; $i <= $this->csvinfo['shownrowscount']; $i++) {
234             if(is_array($this->csvinfo['sorteddata'][($i-1)])){
235               foreach($this->csvinfo['sorteddata'][($i-1)] as $dat){
236                 $dataouts[]=$dat;
237               }
238             }
239           }
241           if($this->csvinfo['rows']> $this->csvinfo['shownrowscount']){
242             $pointsafter = TRUE;
243           }
244         } else {
245           $pointsbefore = TRUE;
246           $pointsafter  = TRUE;
248           $begin = $failing -3;
250           if($begin <0) {
251             $begin =0;
252             $pointsbefore = FALSE;
253           }
255           $end = $failing + 2;
257           if($end > $this->csvinfo['rows']) {
258             $end = $this->csvinfo['rows']+1;
259             $pointsafter = FALSE;
260           }
261           $this->csvinfo['shownrowscount']=$end - $begin;
263           if($this->csvinfo['shownrowscount']> $this->csvinfo['rows'])$this->csvinfo['shownrowscount']=$this->csvinfo['rows'];
265           $dataouts = array(); 
266           for($i =$begin; $i <= $end; $i++) {
267             if(is_array($this->csvinfo['sorteddata'][($i-1)])){
268               foreach($this->csvinfo['sorteddata'][($i-1)] as $dat){
269                 $dataouts[]=$dat;
270               }
271             }
272           }
273         }
274         $tmparr2  = $this->csvinfo['colsstr'];
275         $tmparr2[]=_("status");
277         /* Error? */
278         if ($failing){
279           print_red(sprintf(_("An Error Occured while inserting entry %s - process aborted"), $failing));
280         }
281         $smarty->assign("error",$failing);
283         /* Set vars to smarty */
284         $smarty->assign("cols",count($tmparr2));
285         $smarty->assign("anz" ,$this->csvinfo['count']);
286         $smarty->assign("rows",$this->csvinfo['shownrowscount']);
289         $cnt = 0 ;
290         $tmp2 = $tmp3 = array();
291         if(is_array($dataouts))
292           foreach($dataouts as $tmp){
293             $tmp2[] = $tmp;
294             $cnt ++ ;
295             if($cnt >= count($tmparr2)){
296               $tmp3[] = $tmp2;
297               $tmp2= array();
298               $cnt = 0; 
299             }
300           }  
301         $smarty->assign("head",$tmparr2);
302         $smarty->assign("data",$tmp3);
304         /* Set other vars  */
305         $smarty->assign("i",1);
306         $smarty->assign("ie",0);
307         $smarty->assign("tplid",$this->csvinfo['tplid']);
309         $smarty->assign("pointsafter",$pointsafter);
310         $smarty->assign("pointsbefore",$pointsbefore);
311       } else {
312         /* Set Template ID */
313         $tplid = $_POST['tplid'];
316         $smarty->assign("tpl",$arrtemplates[$tplid]);
317         print_red (_("Nothing to import!"));
318       }
320       /* If theres a File uploaded */
321     } else {
322       /* Check if theres a file uploaded */
323       if(!empty($_FILES['userfile']['name'])){
325         $handle = NULL;
327         if((!isset($_FILES['userfile']['name']))||(!isset($_POST['fileup'])))
328         {
329           print_red(_("There is no file uploaded."));
330           $smarty->assign("LDIFError",TRUE);
331         }
332         elseif(!$_FILES['userfile']['size'] > 0 )
333         {
334           print_red(_("The specified file is empty."));
335           $smarty->assign("LDIFError",TRUE);
336         }
337         /* Is there a tmp file, which we can use ? */
338         elseif(!file_exists($_FILES['userfile']['tmp_name']))
339         {
340           print_red(_("There is no file uploaded."));
341           $smarty->assign("LDIFError",TRUE);
342         }
343         elseif(!$handle = @fopen($_FILES['userfile']['tmp_name'],"r"))
344         {
345           print_red(_("There is no file uploaded."));
346           $smarty->assign("LDIFError",TRUE);
347         }
348         else
349         {
350           $smarty->assign("fileup",TRUE);
351           $str = "";
354           /* Reading content */
355           while(!feof($handle)) {
356             $str .= fread($handle,1024);
357           }
359           $lines = split("\n",$str);
360           $anz  = 0;
361           $rest = 0;
362           $data = array();
364           /* check colum count */
365           if(is_array($lines))
366             foreach($lines as $line) {
367               /* continue if theres a comment */
368               if(substr(trim($line),0,1)=="#"){
369                 continue;
370               }
372               $line= str_replace ("\t","",$line);
373               $cells  = split(",",$line )  ;
375               if(count($cells)> $anz ){
376                 $anz = count($cells);
377               }
378             }
380           /* At least one entry */
381           if($anz >1) {
383             /* Generate array with outpu info  */
384             if(is_array($lines))
385               foreach($lines as $line) {
386                 $rest = 0;
387                 $cnt  = 0;
389                 /* dont use comments or empty lines */
390                 if((substr(trim($line),0,1)=="#")||(empty($line))){
391                   continue;
392                 }
394                 /* replace \t to , */
395                 $line= str_replace ("\t"  ,"" ,$line);
397                 /* get all elements  */
398                 $cells  = split(",",$line )  ;
400                 /* attach all elements to data array */
401                 if(is_array($cells))
402                   foreach($cells as $cell) {
403                     if(!empty($cell)) {
404                       $cnt++; 
405                       $data[]=trim($cell);
406                     }
407                   }
409                 /* cell count less than anz, attach some empty fields */
410                 if(($cnt != $anz)&&(!empty($cnt))) {
411                   $rest = $anz - $cnt;
412                   for($i = 0 ; $i < $rest ; $i ++){
413                     $data[] = " ";
414                   }
415                 }
416               }    
418             unset($this->csvinfo['sorteddata']);
419             unset($this->csvinfo['colsstr']);
420             unset($this->csvinfo['sorteddata']);
422             $this->csvinfo['cols']        = $anz;
423             $this->csvinfo['data']        = array();
424             $this->csvinfo['data']        = $data;
425             $this->csvinfo['count']       = count($this->csvinfo['data']);
427             if($this->csvinfo['count']> (6* $this->csvinfo['cols'])) {
428               /* only show 6 rows in ouptuttablei */
429               $datouttemp =  array_chunk($this->csvinfo['data'],(6* $this->csvinfo['cols']));
430               $this->csvinfo['dataout']=$datouttemp[0];
431               $this->csvinfo['shownrowscount'] = 6;
432             } else {
433               $this->csvinfo['shownrowscount'] = (count($this->csvinfo['data']))/$this->csvinfo['cols'];
434               $this->csvinfo['dataout']= $this->csvinfo['data'];  
435             }
437             $this->csvinfo['tplid']       = $_POST['template'];
438             $this->csvinfo['templatestr'] = $this->csvinfo['arrtemplates' ][$this->csvinfo['tplid']];
439             $this->csvinfo['count']       = count($this->csvinfo['data']);
440             $this->csvinfo['rows']        = (count($this->csvinfo['data'])/$anz);
442             $i =  0; 
443             $tmp = $tmp2= array();
444             if(is_array($this->csvinfo['dataout']))
445               foreach($this->csvinfo['dataout'] as $dat){
446                 $tmp[]= $dat;
447                 $i++;
448                 if($i >=$this->csvinfo['cols']){
449                   $i = 0;
450                   $tmp2[] = $tmp;
451                   $tmp = array();
452                 }
454               }
456             /* Set Templateid  */
457             $smarty->assign("tplid",$this->csvinfo['tplid']);
459             /* Set Template  */
460             $smarty->assign("tpl",$this->csvinfo['templatestr']);
462             /* Temp var 1 */
463             $smarty->assign("ia",1); 
465             /* Temp var 2 */
466             $smarty->assign("i",0); 
468             /* Num rows    */
469             $smarty->assign("rows",$this->csvinfo['shownrowscount']);
472             for($i  = 0 ; $i < $anz; $i ++)
473               $this->csvinfo['arr_selected'][]="0";
475             $smarty->assign("selectedattrs",$this->csvinfo['arr_selected']);
477             /* Entrie count5 */
478             $smarty->assign("anz",$this->csvinfo['cols']);                                                    
480             /* Array with data */
481             $smarty->assign("data",$tmp2);   
483             @fclose($handle);
484           } else {
485             $smarty->assign("tpl",$this->csvinfo['attr'][$_POST['template']]);
486             $smarty->assign("LDIFError",TRUE);
487             $smarty->assign("fileup",FALSE);
488             print_red(_("The selected file does not contain any CSV Data..."));  
489           }
490         }
491       }
492     }                                              
494     /* Show main page */
495     return ($smarty->fetch (get_template_path('contentcsv.tpl', TRUE)));
496   }
500 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
501 ?>