Code

Added initial (NOT WORKING) logging classes
[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();
16   var $view_logged = FALSE;
18   function csvimport ($config, $dn= NULL)
19   {
20     /* Include config object */
21     $this->config= $config;
23     $this->ui = get_userinfo();
24   }
26   function execute()
27   {
28     /* Call parent execute */
29     plugin::execute();
31     /* Log view */
32     if(!$this->view_logged){
33       $this->view_logged = TRUE;
34       new log("view","all/".get_class($this),$this->dn);
35     }
37     /* initiate smarty */
38     $smarty= get_smarty();
39     $smarty->assign("selectedattrs",array(0=>""));
40     $smarty->assign("data",array(0=>""));
41     $smarty->assign("head",array(0=>""));
42     $smarty->assign("sorted",0);
43     $smarty->assign("fileup",0);
45     /* Get the LDAP link, to generate the Export */
46     $ldap = $this->config->get_ldap_link();
48     $arrtemplates = array();
49     $tempvar =0;
51     /* Array to fill in Formfields */
52     $arrtemplates[$tempvar] = "None";
53     if(!is_array($this->csvinfo)){
54       $this->csvinfo=array();
55     }
57     /* Set Usertemplate information and get all Attribute from userclass */
58     unset ($this->csvinfo['arrtemplates']);
59     unset ($this->csvinfo['arrtempls']);
61     /* Generate Template Array, Attribute Array */
62     if(!isset($this->csvinfo['arrtempls'])){
64       /* Generating attributes */
65       $attrs = @get_class_vars("user");
66       $this->csvinfo['attr']  = $attrs['attributes'];
68       /* Attach the choise none to discard a csv col */
69       $new = array();
70       $new[0]="none";
71       $new[1]="userPassword";
72       for($c = 0; $c < count($this->csvinfo['attr']);$c++){
73         $new[$c+2]=$this->csvinfo['attr'][$c];
74       }
76       $this->csvinfo['attr'] = $new;
78       /* Search all Templates    */
79       $this->csvinfo['templates'] = $ldap->search("(objectClass=gosaUserTemplate)",array("*"));
81       /* Array to handle selected Form fiels */
82       $this->csvinfo['arrtempls'][$tempvar]['name'] = "";
83       $this->csvinfo['arrtempls'][$tempvar]['dn']   = "";
85       $this->csvinfo['arrtemplates'][]="None";
87       while($temp = $ldap->fetch($this->csvinfo['templates'])){
88         $tempvar ++;
89         $this->csvinfo['arrtemplates'][$tempvar] = $temp['sn'][0]." - ".$this->config->idepartments[preg_replace("/^[^,]+,".get_people_ou()."/i", "", $temp['dn'])];
90         $this->csvinfo['arrtempls']   [$tempvar]['name'] = $temp['sn'][0]; 
91         $this->csvinfo['arrtempls']   [$tempvar]['dn']   = $temp['dn'];
92       }
93     }
95     $arr_temp  = array_flip($this->csvinfo['attr']);
96     $this->csvinfo['arr_selected']= array($arr_temp['uid'],$arr_temp['sn'],$arr_temp['givenName'],$arr_temp['userPassword']);
98     $smarty->assign("templates",$this->csvinfo['arrtemplates']);
99     $smarty->assign("attrs",$this->csvinfo['attr']);
101     /* Check permissions for import */
102     $acl = $this->ui->get_permissions($this->config->current['BASE'],"all/all");
103     if(!preg_match("/w/",$acl)){
104       if(isset($_POST['userfile']) || isset($_POST['sorted']) || isset($_POST['fileup'])){
105         print_red(_("You've no permission to do CSV imports."));
106       }
107       return ($smarty->fetch (get_template_path('contentcsv.tpl', TRUE)));
108     }
110     /* If the given dat from the csv File are sorted by the attributes */
111     if(isset($_POST['sorted'])) {
113       /* Template Handling */
114       $smarty->assign("fileup",TRUE); 
115       $smarty->assign("sorted",TRUE); 
117       for($i = 0 ; $i < $this->csvinfo['rows'];$i++){
118         /* Preparing given Data */
119         $this->csvinfo['sorteddata'][$i]=array(); 
121         /* Go through every col */
122         for($a = 0; $a <= ($this->csvinfo['cols']); $a ++) {
123           /* Append a status col at last, to show possibly errors */
124           if($a==($this->csvinfo['cols'])){
125             $this->csvinfo['sorteddata'][$i]["status"]="-";            
126           } else {
127             $cc = ($i * ($this->csvinfo['cols']))+$a;
129             /* If theres a Attribut given for this col */
130             if(!empty($_POST[('row'.($a))])) {
131               $this->csvinfo['sorteddata'][$i][$this->csvinfo['attr'][$_POST[('row'.($a))]]]=$this->csvinfo['data'][($cc)]; 
132             }
133           }
134         }
135       } 
137       /* aleast one entry */
138       $rowcnt=0;      
139       if(isset($this->csvinfo['sorteddata'])){
140         $rowcnt ++;
142         /* Set the col count */
143         $tblcolcount= count ($this->csvinfo['cols']);
145         /* entrie count */
146         $tbl_entries= count ($this->csvinfo['count']);
148         /* row count */
149         $tbl_rows   = $tbl_entries / $tblcolcount;
151         /* No error occured */
152         $failing = FALSE;
154         /* For every row */
155         for($i = 0; $i < $this->csvinfo['rows']; $i++){
157           /* Get elemenet */
158           $dat = $this->csvinfo['sorteddata'][$i];
160           /* If not all needed vars set .... */
161           if(         ( empty($dat['sn']))||( empty($dat['givenName']))||( empty($dat['uid']))||
162               (!isset($dat['sn']))||(!isset($dat['givenName']))||(!isset($dat['uid']))){
164             /* Output Error */
166             print_red (_("Need 'sn','givenName' and 'uid' to create user."));
167           } else {
169             /* Register usertab to trigger edit dialog */
170             $this->usertab= new usertabs($this->config, $this->config->data['TABS']['USERTABS'], 'new');
171             $keys = array_keys($dat);
174             /* Set all submitted vars  */
175             if(is_array($keys))
176               foreach($keys as $key) {
177                 if($key != "status"){
178                   $this->usertab->$key = $dat[$key];
179                 }
180               }
182             /* Initialize template */
183             if($this->csvinfo['tplid']!=0){
184               $this->usertab->adapt_from_template($this->csvinfo['arrtempls'][$this->csvinfo['tplid']]['dn']);
185               $this->usertab->save_object();
186             } else {
188               /* Reset vars */
189               if(is_array($keys))
190                 foreach($keys as $key) {
191                   if($key != "status"){
192                     $this->usertab->by_object['user']->$key = $dat[$key];
193                   }
194                 }
195             }
197             // Setting user Password 
198             if((isset($dat['userPassword']))&&(!empty($dat['userPassword'])))
199               $password = $dat['userPassword']; 
200             else
201             {
202               $rand_str="";
203               $feed = "0123456789abcdefghijklmnopqrstuvwxyz";
204               for ($i=0; $i < 8; $i++)
205               {
206                 $rand_str .= substr($feed, rand(0, strlen($feed)-1), 1);
207               }
208               $password = $rand_str;
209             }
211             /* Insert in the LDAP tree */
212             if(count($this->usertab->check())) {
213               show_errors($this->usertab->check());
214               $this->csvinfo['sorteddata'][$i]['status']="<b>"._("failed")."</b>";
215               $failing = $i+1;
216               break;
217             } else {
218               $this->csvinfo['sorteddata'][$i]['status']=_("ok");
219               $this->usertab->save();
220               change_password($this->usertab->dn,$password); 
221             }
222           }
223         }
225         $pointsbefore = FALSE;
226         $pointsafter  = FALSE;
228         /* Get Attributs for Tableheadline  */
229         $this->csvinfo['colsstr'] = array();
230         for($i =0; $i <= $this->csvinfo['cols']; $i++) {
231           if(!empty($_POST[('row'.$i)])){
232             $this->csvinfo['colsstr'][$i] = $this->csvinfo['attr'][$_POST[('row'.$i)]];
233           }
234         }
236         /*Create array with data for the template */
237         if($failing == FALSE){
239           $dataouts= array();
240           for($i =1; $i <= $this->csvinfo['shownrowscount']; $i++) {
241             if(is_array($this->csvinfo['sorteddata'][($i-1)])){
242               foreach($this->csvinfo['sorteddata'][($i-1)] as $dat){
243                 $dataouts[]=$dat;
244               }
245             }
246           }
248           if($this->csvinfo['rows']> $this->csvinfo['shownrowscount']){
249             $pointsafter = TRUE;
250           }
251         } else {
252           $pointsbefore = TRUE;
253           $pointsafter  = TRUE;
255           $begin = $failing -3;
257           if($begin <0) {
258             $begin =0;
259             $pointsbefore = FALSE;
260           }
262           $end = $failing + 2;
264           if($end > $this->csvinfo['rows']) {
265             $end = $this->csvinfo['rows']+1;
266             $pointsafter = FALSE;
267           }
268           $this->csvinfo['shownrowscount']=$end - $begin;
270           if($this->csvinfo['shownrowscount']> $this->csvinfo['rows'])$this->csvinfo['shownrowscount']=$this->csvinfo['rows'];
272           $dataouts = array(); 
273           for($i =$begin; $i <= $end; $i++) {
274             if(is_array($this->csvinfo['sorteddata'][($i-1)])){
275               foreach($this->csvinfo['sorteddata'][($i-1)] as $dat){
276                 $dataouts[]=$dat;
277               }
278             }
279           }
280         }
281         $tmparr2  = $this->csvinfo['colsstr'];
282         $tmparr2[]=_("status");
284         /* Error? */
285         if ($failing){
286           print_red(sprintf(_("An Error Occured while inserting entry %s - process aborted"), $failing));
287         }
288         $smarty->assign("error",$failing);
290         /* Set vars to smarty */
291         $smarty->assign("cols",count($tmparr2));
292         $smarty->assign("anz" ,$this->csvinfo['count']);
293         $smarty->assign("rows",$this->csvinfo['shownrowscount']);
296         $cnt = 0 ;
297         $tmp2 = $tmp3 = array();
298         if(is_array($dataouts))
299           foreach($dataouts as $tmp){
300             $tmp2[] = $tmp;
301             $cnt ++ ;
302             if($cnt >= count($tmparr2)){
303               $tmp3[] = $tmp2;
304               $tmp2= array();
305               $cnt = 0; 
306             }
307           }  
308         $smarty->assign("head",$tmparr2);
309         $smarty->assign("data",$tmp3);
311         /* Set other vars  */
312         $smarty->assign("i",1);
313         $smarty->assign("ie",0);
314         $smarty->assign("tplid",$this->csvinfo['tplid']);
316         $smarty->assign("pointsafter",$pointsafter);
317         $smarty->assign("pointsbefore",$pointsbefore);
318       } else {
319         /* Set Template ID */
320         $tplid = $_POST['tplid'];
323         $smarty->assign("tpl",$arrtemplates[$tplid]);
324         print_red (_("Nothing to import!"));
325       }
327       /* If theres a File uploaded */
328     } else {
329       /* Check if theres a file uploaded */
330       if(!empty($_FILES['userfile']['name'])){
332         $handle = NULL;
334         if((!isset($_FILES['userfile']['name']))||(!isset($_POST['fileup'])))
335         {
336           print_red(_("There is no file uploaded."));
337           $smarty->assign("LDIFError",TRUE);
338         }
339         elseif(!$_FILES['userfile']['size'] > 0 )
340         {
341           print_red(_("The specified file is empty."));
342           $smarty->assign("LDIFError",TRUE);
343         }
344         /* Is there a tmp file, which we can use ? */
345         elseif(!file_exists($_FILES['userfile']['tmp_name']))
346         {
347           print_red(_("There is no file uploaded."));
348           $smarty->assign("LDIFError",TRUE);
349         }
350         elseif(!$handle = @fopen($_FILES['userfile']['tmp_name'],"r"))
351         {
352           print_red(_("There is no file uploaded."));
353           $smarty->assign("LDIFError",TRUE);
354         }
355         else
356         {
357           $smarty->assign("fileup",TRUE);
358           $str = "";
361           /* Reading content */
362           while(!feof($handle)) {
363             $str .= fread($handle,1024);
364           }
366           $lines = split("\n",$str);
367           $anz  = 0;
368           $rest = 0;
369           $data = array();
371           /* check colum count */
372           if(is_array($lines))
373             foreach($lines as $line) {
374               /* continue if theres a comment */
375               if(substr(trim($line),0,1)=="#"){
376                 continue;
377               }
379               $line= str_replace ("\t","",$line);
380               $cells  = split(",",$line )  ;
382               if(count($cells)> $anz ){
383                 $anz = count($cells);
384               }
385             }
387           /* At least one entry */
388           if($anz >1) {
390             /* Generate array with outpu info  */
391             if(is_array($lines))
392               foreach($lines as $line) {
393                 $rest = 0;
394                 $cnt  = 0;
396                 /* dont use comments or empty lines */
397                 if((substr(trim($line),0,1)=="#")||(empty($line))){
398                   continue;
399                 }
401                 /* replace \t to , */
402                 $line= str_replace ("\t"  ,"" ,$line);
404                 /* get all elements  */
405                 $cells  = split(",",$line )  ;
407                 /* attach all elements to data array */
408                 if(is_array($cells))
409                   foreach($cells as $cell) {
410                     if(!empty($cell)) {
411                       $cnt++; 
412                       $data[]=trim($cell);
413                     }
414                   }
416                 /* cell count less than anz, attach some empty fields */
417                 if(($cnt != $anz)&&(!empty($cnt))) {
418                   $rest = $anz - $cnt;
419                   for($i = 0 ; $i < $rest ; $i ++){
420                     $data[] = " ";
421                   }
422                 }
423               }    
425             unset($this->csvinfo['sorteddata']);
426             unset($this->csvinfo['colsstr']);
427             unset($this->csvinfo['sorteddata']);
429             $this->csvinfo['cols']        = $anz;
430             $this->csvinfo['data']        = array();
431             $this->csvinfo['data']        = $data;
432             $this->csvinfo['count']       = count($this->csvinfo['data']);
434             if($this->csvinfo['count']> (6* $this->csvinfo['cols'])) {
435               /* only show 6 rows in ouptuttablei */
436               $datouttemp =  array_chunk($this->csvinfo['data'],(6* $this->csvinfo['cols']));
437               $this->csvinfo['dataout']=$datouttemp[0];
438               $this->csvinfo['shownrowscount'] = 6;
439             } else {
440               $this->csvinfo['shownrowscount'] = (count($this->csvinfo['data']))/$this->csvinfo['cols'];
441               $this->csvinfo['dataout']= $this->csvinfo['data'];  
442             }
444             $this->csvinfo['tplid']       = $_POST['template'];
445             $this->csvinfo['templatestr'] = $this->csvinfo['arrtemplates' ][$this->csvinfo['tplid']];
446             $this->csvinfo['count']       = count($this->csvinfo['data']);
447             $this->csvinfo['rows']        = (count($this->csvinfo['data'])/$anz);
449             $i =  0; 
450             $tmp = $tmp2= array();
451             if(is_array($this->csvinfo['dataout']))
452               foreach($this->csvinfo['dataout'] as $dat){
453                 $tmp[]= $dat;
454                 $i++;
455                 if($i >=$this->csvinfo['cols']){
456                   $i = 0;
457                   $tmp2[] = $tmp;
458                   $tmp = array();
459                 }
461               }
463             /* Set Templateid  */
464             $smarty->assign("tplid",$this->csvinfo['tplid']);
466             /* Set Template  */
467             $smarty->assign("tpl",$this->csvinfo['templatestr']);
469             /* Temp var 1 */
470             $smarty->assign("ia",1); 
472             /* Temp var 2 */
473             $smarty->assign("i",0); 
475             /* Num rows    */
476             $smarty->assign("rows",$this->csvinfo['shownrowscount']);
479             for($i  = 0 ; $i < $anz; $i ++)
480               $this->csvinfo['arr_selected'][]="0";
482             $smarty->assign("selectedattrs",$this->csvinfo['arr_selected']);
484             /* Entrie count5 */
485             $smarty->assign("anz",$this->csvinfo['cols']);                                                    
487             /* Array with data */
488             $smarty->assign("data",$tmp2);   
490             @fclose($handle);
491           } else {
492             $smarty->assign("tpl",$this->csvinfo['attr'][$_POST['template']]);
493             $smarty->assign("LDIFError",TRUE);
494             $smarty->assign("fileup",FALSE);
495             print_red(_("The selected file does not contain any CSV Data..."));  
496           }
497         }
498       }
499     }                                              
501     /* Show main page */
502     return ($smarty->fetch (get_template_path('contentcsv.tpl', TRUE)));
503   }
507 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
508 ?>