Code

Removed comment
[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     /* set permissions */
23     $ui= get_userinfo();
24     $acl= get_permissions ($ui->dn, $ui->subtreeACL);
25     $this->acl= get_module_permission($acl, "ldapmanager", $ui->dn);
28   }
30   function execute()
31   {
32     /* Call parent execute */
33     plugin::execute();
35     /* initiate smarty */
36     $smarty= get_smarty();
37     $smarty->assign("selectedattrs",array(0=>""));
38     $smarty->assign("data",array(0=>""));
39     $smarty->assign("head",array(0=>""));
40     $smarty->assign("sorted",0);
41     $smarty->assign("fileup",0);
43     /* Get the LDAP link, to generate the Export */
44     $ldap = $this->config->get_ldap_link();
46     $arrtemplates = array();
47     $tempvar =0;
49     /* Array to fill in Formfields */
50     $arrtemplates[$tempvar] = "None";
51     if(!is_array($this->csvinfo)){
52       $this->csvinfo=array();
53     }
55     /* Set Usertemplate information and get all Attribute from userclass */
56     unset ($this->csvinfo['arrtemplates']);
57     unset ($this->csvinfo['arrtempls']);
59     /* Generate Template Array, Attribute Array */
60     if(!isset($this->csvinfo['arrtempls'])){
62       /* Generating attributes */
63       $attrs = @get_class_vars("user");
64       $this->csvinfo['attr']  = $attrs['attributes'];
66       /* Attach the choise none to discard a csv col */
67       $new = array();
68       $new[0]="none";
69       $new[1]="userPassword";
70       for($c = 0; $c < count($this->csvinfo['attr']);$c++){
71         $new[$c+2]=$this->csvinfo['attr'][$c];
72       }
74       $this->csvinfo['attr'] = $new;
76       /* Search all Templates    */
77       $this->csvinfo['templates'] = $ldap->search("(objectClass=gosaUserTemplate)",array("*"));
79       /* Array to handle selected Form fiels */
80       $this->csvinfo['arrtempls'][$tempvar]['name'] = "";
81       $this->csvinfo['arrtempls'][$tempvar]['dn']   = "";
83       $this->csvinfo['arrtemplates'][]="None";
85       while($temp = $ldap->fetch($this->csvinfo['templates'])){
86         $tempvar ++;
87         $this->csvinfo['arrtemplates'][$tempvar] = $temp['sn'][0]." - ".$this->config->idepartments[preg_replace("/^[^,]+,".get_people_ou()."/", "", $temp['dn'])];
88         $this->csvinfo['arrtempls']   [$tempvar]['name'] = $temp['sn'][0]; 
89         $this->csvinfo['arrtempls']   [$tempvar]['dn']   = $temp['dn'];
90       }
91     }
93     $arr_temp  = array_flip($this->csvinfo['attr']);
94     $this->csvinfo['arr_selected']= array($arr_temp['uid'],$arr_temp['sn'],$arr_temp['givenName'],$arr_temp['userPassword']);
96     $smarty->assign("templates",$this->csvinfo['arrtemplates']);
97     $smarty->assign("attrs",$this->csvinfo['attr']);
99     /* Check permissions for import */
100     if (chkacl($this->acl,"csvimport")!=""){
101       print_red(_("You've no permission to do CSV imports."));
102       return ($smarty->fetch (get_template_path('contentcsv.tpl', TRUE)));
103     }
105     /* If the given dat from the csv File are sorted by the attributes */
106     if(isset($_POST['sorted'])) {
108       /* Template Handling */
109       $smarty->assign("fileup",TRUE); 
110       $smarty->assign("sorted",TRUE); 
112       for($i = 0 ; $i < $this->csvinfo['rows'];$i++){
113         /* Preparing given Data */
114         $this->csvinfo['sorteddata'][$i]=array(); 
116         /* Go through every col */
117         for($a = 0; $a <= ($this->csvinfo['cols']); $a ++) {
118           /* Append a status col at last, to show possibly errors */
119           if($a==($this->csvinfo['cols'])){
120             $this->csvinfo['sorteddata'][$i]["status"]="-";            
121           } else {
122             $cc = ($i * ($this->csvinfo['cols']))+$a;
124             /* If theres a Attribut given for this col */
125             if(!empty($_POST[('row'.($a))])) {
126               $this->csvinfo['sorteddata'][$i][$this->csvinfo['attr'][$_POST[('row'.($a))]]]=$this->csvinfo['data'][($cc)]; 
127             }
128           }
129         }
130       } 
132       /* aleast one entry */
133       $rowcnt=0;      
134       if(isset($this->csvinfo['sorteddata'])){
135         $rowcnt ++;
137         /* Set the col count */
138         $tblcolcount= count ($this->csvinfo['cols']);
140         /* entrie count */
141         $tbl_entries= count ($this->csvinfo['count']);
143         /* row count */
144         $tbl_rows   = $tbl_entries / $tblcolcount;
146         /* No error occured */
147         $failing = FALSE;
149         /* For every row */
150         for($i = 0; $i < $this->csvinfo['rows']; $i++){
152           /* Get elemenet */
153           $dat = $this->csvinfo['sorteddata'][$i];
155           /* If not all needed vars set .... */
156           if(         ( empty($dat['sn']))||( empty($dat['givenName']))||( empty($dat['uid']))||
157               (!isset($dat['sn']))||(!isset($dat['givenName']))||(!isset($dat['uid']))){
159             /* Output Error */
161             print_red (_("Need 'sn','givenName' and 'uid' to create user."));
162           } else {
164             /* Register usertab to trigger edit dialog */
165             $this->usertab= new usertabs($this->config, $this->config->data['TABS']['USERTABS'], 'new');
166             $keys = array_keys($dat);
169             /* Set all submitted vars  */
170             if(is_array($keys))
171               foreach($keys as $key) {
172                 if($key != "status"){
173                   $this->usertab->$key = $dat[$key];
174                 }
175               }
177             /* Initialize template */
178             if($this->csvinfo['tplid']!=0){
179               $this->usertab->adapt_from_template($this->csvinfo['arrtempls'][$this->csvinfo['tplid']]['dn']);
180               $this->usertab->save_object();
181             } else {
183               /* Reset vars */
184               if(is_array($keys))
185                 foreach($keys as $key) {
186                   if($key != "status"){
187                     $this->usertab->by_object['user']->$key = $dat[$key];
188                   }
189                 }
190             }
192             // Setting user Password 
193             if((isset($dat['userPassword']))&&(!empty($dat['userPassword'])))
194               $password = $dat['userPassword']; 
195             else
196             {
197               $rand_str="";
198               $feed = "0123456789abcdefghijklmnopqrstuvwxyz";
199               for ($i=0; $i < 8; $i++)
200               {
201                 $rand_str .= substr($feed, rand(0, strlen($feed)-1), 1);
202               }
203               $password = $rand_str;
204             }
206             /* Insert in the LDAP tree */
207             if(count($this->usertab->check())) {
208               show_errors($this->usertab->check());
209               $this->csvinfo['sorteddata'][$i]['status']="<b>"._("failed")."</b>";
210               $failing = $i+1;
211               break;
212             } else {
213               $this->csvinfo['sorteddata'][$i]['status']=_("ok");
214               $this->usertab->save();
215               change_password($this->usertab->dn,$password); 
216             }
217           }
218         }
220         $pointsbefore = FALSE;
221         $pointsafter  = FALSE;
223         /* Get Attributs for Tableheadline  */
224         $this->csvinfo['colsstr'] = array();
225         for($i =0; $i <= $this->csvinfo['cols']; $i++) {
226           if(!empty($_POST[('row'.$i)])){
227             $this->csvinfo['colsstr'][$i] = $this->csvinfo['attr'][$_POST[('row'.$i)]];
228           }
229         }
231         /*Create array with data for the template */
232         if($failing == FALSE){
234           $dataouts= array();
235           for($i =1; $i <= $this->csvinfo['shownrowscount']; $i++) {
236             if(is_array($this->csvinfo['sorteddata'][($i-1)])){
237               foreach($this->csvinfo['sorteddata'][($i-1)] as $dat){
238                 $dataouts[]=$dat;
239               }
240             }
241           }
243           if($this->csvinfo['rows']> $this->csvinfo['shownrowscount']){
244             $pointsafter = TRUE;
245           }
246         } else {
247           $pointsbefore = TRUE;
248           $pointsafter  = TRUE;
250           $begin = $failing -3;
252           if($begin <0) {
253             $begin =0;
254             $pointsbefore = FALSE;
255           }
257           $end = $failing + 2;
259           if($end > $this->csvinfo['rows']) {
260             $end = $this->csvinfo['rows']+1;
261             $pointsafter = FALSE;
262           }
263           $this->csvinfo['shownrowscount']=$end - $begin;
265           if($this->csvinfo['shownrowscount']> $this->csvinfo['rows'])$this->csvinfo['shownrowscount']=$this->csvinfo['rows'];
267           $dataouts = array(); 
268           for($i =$begin; $i <= $end; $i++) {
269             if(is_array($this->csvinfo['sorteddata'][($i-1)])){
270               foreach($this->csvinfo['sorteddata'][($i-1)] as $dat){
271                 $dataouts[]=$dat;
272               }
273             }
274           }
275         }
276         $tmparr2  = $this->csvinfo['colsstr'];
277         $tmparr2[]=_("status");
279         /* Error? */
280         if ($failing){
281           print_red(sprintf(_("An Error Occured while inserting entry %s - process aborted"), $failing));
282         }
283         $smarty->assign("error",$failing);
285         /* Set vars to smarty */
286         $smarty->assign("cols",count($tmparr2));
287         $smarty->assign("anz" ,$this->csvinfo['count']);
288         $smarty->assign("rows",$this->csvinfo['shownrowscount']);
291         $cnt = 0 ;
292         $tmp2 = $tmp3 = array();
293         if(is_array($dataouts))
294           foreach($dataouts as $tmp){
295             $tmp2[] = $tmp;
296             $cnt ++ ;
297             if($cnt >= count($tmparr2)){
298               $tmp3[] = $tmp2;
299               $tmp2= array();
300               $cnt = 0; 
301             }
302           }  
303         $smarty->assign("head",$tmparr2);
304         $smarty->assign("data",$tmp3);
306         /* Set other vars  */
307         $smarty->assign("i",1);
308         $smarty->assign("ie",0);
309         $smarty->assign("tplid",$this->csvinfo['tplid']);
311         $smarty->assign("pointsafter",$pointsafter);
312         $smarty->assign("pointsbefore",$pointsbefore);
313       } else {
314         /* Set Template ID */
315         $tplid = $_POST['tplid'];
318         $smarty->assign("tpl",$arrtemplates[$tplid]);
319         print_red (_("Nothing to import!"));
320       }
322       /* If theres a File uploaded */
323     } else {
324       /* Check if theres a file uploaded */
325       if(!empty($_FILES['userfile']['name'])){
327         $handle = NULL;
329         if((!isset($_FILES['userfile']['name']))||(!isset($_POST['fileup'])))
330         {
331           print_red(_("There is no file uploaded."));
332           $smarty->assign("LDIFError",TRUE);
333         }
334         elseif(!$_FILES['userfile']['size'] > 0 )
335         {
336           print_red(_("The specified file is empty."));
337           $smarty->assign("LDIFError",TRUE);
338         }
339         /* Is there a tmp file, which we can use ? */
340         elseif(!file_exists($_FILES['userfile']['tmp_name']))
341         {
342           print_red(_("There is no file uploaded."));
343           $smarty->assign("LDIFError",TRUE);
344         }
345         elseif(!$handle = @fopen($_FILES['userfile']['tmp_name'],"r"))
346         {
347           print_red(_("There is no file uploaded."));
348           $smarty->assign("LDIFError",TRUE);
349         }
350         else
351         {
352           $smarty->assign("fileup",TRUE);
353           $str = "";
356           /* Reading content */
357           while(!feof($handle)) {
358             $str .= fread($handle,1024);
359           }
361           $lines = split("\n",$str);
362           $anz  = 0;
363           $rest = 0;
364           $data = array();
366           /* check colum count */
367           if(is_array($lines))
368             foreach($lines as $line) {
369               /* continue if theres a comment */
370               if(substr(trim($line),0,1)=="#"){
371                 continue;
372               }
374               $line= str_replace ("\t","",$line);
375               $cells  = split(",",$line )  ;
377               if(count($cells)> $anz ){
378                 $anz = count($cells);
379               }
380             }
382           /* At least one entry */
383           if($anz >1) {
385             /* Generate array with outpu info  */
386             if(is_array($lines))
387               foreach($lines as $line) {
388                 $rest = 0;
389                 $cnt  = 0;
391                 /* dont use comments or empty lines */
392                 if((substr(trim($line),0,1)=="#")||(empty($line))){
393                   continue;
394                 }
396                 /* replace \t to , */
397                 $line= str_replace ("\t"  ,"" ,$line);
399                 /* get all elements  */
400                 $cells  = split(",",$line )  ;
402                 /* attach all elements to data array */
403                 if(is_array($cells))
404                   foreach($cells as $cell) {
405                     if(!empty($cell)) {
406                       $cnt++; 
407                       $data[]=trim($cell);
408                     }
409                   }
411                 /* cell count less than anz, attach some empty fields */
412                 if(($cnt != $anz)&&(!empty($cnt))) {
413                   $rest = $anz - $cnt;
414                   for($i = 0 ; $i < $rest ; $i ++){
415                     $data[] = " ";
416                   }
417                 }
418               }    
420             unset($this->csvinfo['sorteddata']);
421             unset($this->csvinfo['colsstr']);
422             unset($this->csvinfo['sorteddata']);
424             $this->csvinfo['cols']        = $anz;
425             $this->csvinfo['data']        = array();
426             $this->csvinfo['data']        = $data;
427             $this->csvinfo['count']       = count($this->csvinfo['data']);
429             if($this->csvinfo['count']> (6* $this->csvinfo['cols'])) {
430               /* only show 6 rows in ouptuttablei */
431               $datouttemp =  array_chunk($this->csvinfo['data'],(6* $this->csvinfo['cols']));
432               $this->csvinfo['dataout']=$datouttemp[0];
433               $this->csvinfo['shownrowscount'] = 6;
434             } else {
435               $this->csvinfo['shownrowscount'] = (count($this->csvinfo['data']))/$this->csvinfo['cols'];
436               $this->csvinfo['dataout']= $this->csvinfo['data'];  
437             }
439             $this->csvinfo['tplid']       = $_POST['template'];
440             $this->csvinfo['templatestr'] = $this->csvinfo['arrtemplates' ][$this->csvinfo['tplid']];
441             $this->csvinfo['count']       = count($this->csvinfo['data']);
442             $this->csvinfo['rows']        = (count($this->csvinfo['data'])/$anz);
444             $i =  0; 
445             $tmp = $tmp2= array();
446             if(is_array($this->csvinfo['dataout']))
447               foreach($this->csvinfo['dataout'] as $dat){
448                 $tmp[]= $dat;
449                 $i++;
450                 if($i >=$this->csvinfo['cols']){
451                   $i = 0;
452                   $tmp2[] = $tmp;
453                   $tmp = array();
454                 }
456               }
458             /* Set Templateid  */
459             $smarty->assign("tplid",$this->csvinfo['tplid']);
461             /* Set Template  */
462             $smarty->assign("tpl",$this->csvinfo['templatestr']);
464             /* Temp var 1 */
465             $smarty->assign("ia",1); 
467             /* Temp var 2 */
468             $smarty->assign("i",0); 
470             /* Num rows    */
471             $smarty->assign("rows",$this->csvinfo['shownrowscount']);
474             for($i  = 0 ; $i < $anz; $i ++)
475               $this->csvinfo['arr_selected'][]="0";
477             $smarty->assign("selectedattrs",$this->csvinfo['arr_selected']);
479             /* Entrie count5 */
480             $smarty->assign("anz",$this->csvinfo['cols']);                                                    
482             /* Array with data */
483             $smarty->assign("data",$tmp2);   
485             @fclose($handle);
486           } else {
487             $smarty->assign("tpl",$this->csvinfo['attr'][$_POST['template']]);
488             $smarty->assign("LDIFError",TRUE);
489             $smarty->assign("fileup",FALSE);
490             print_red(_("The selected file does not contain any CSV Data..."));  
491           }
492         }
493       }
494     }                                              
496     /* Show main page */
497     return ($smarty->fetch (get_template_path('contentcsv.tpl', TRUE)));
498   }
501 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
502 ?>