Code

Updated error Messages
[gosa.git] / gosa-plugins / ldapmanager / 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("/^[^,]+,".preg_quote(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                 msg_dialog::display(_("Permission error"), _("You've no permission to import CSV files."), ERROR_DIALOG);
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 occurred */
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 */
165                         msg_dialog::display(_("Error"), _("Need at least 'sn', 'givenName' and 'uid' to create users."), ERROR_DIALOG);
166                     } else {
168                         /* Register usertab to trigger edit dialog */
169                         $this->usertab= new usertabs($this->config, $this->config->data['TABS']['USERTABS'], 'new');
170                         $keys = array_keys($dat);
173                         /* Set all submitted vars  */
174                         if(is_array($keys))
175                             foreach($keys as $key) {
176                                 if($key != "status"){
177                                     $this->usertab->$key = $dat[$key];
178                                 }
179                             }
181                         /* Initialize template */
182                         if($this->csvinfo['tplid']!=0){
183                             $this->usertab->adapt_from_template($this->csvinfo['arrtempls'][$this->csvinfo['tplid']]['dn']);
184                             $this->usertab->save_object();
185                         } else {
187                             /* Reset vars */
188                             if(is_array($keys))
189                                 foreach($keys as $key) {
190                                     if($key != "status"){
191                                         $this->usertab->by_object['user']->$key = $dat[$key];
192                                     }
193                                 }
194                         }
196                         // Setting user Password 
197                         if((isset($dat['userPassword']))&&(!empty($dat['userPassword']))){
198                             $password = $dat['userPassword']; 
199                         }else{
200                             $rand_str="";
201                             $feed = "0123456789abcdefghijklmnopqrstuvwxyz";
202                             for ($e=0; $e < 8; $e++)
203                             {
204                                 $rand_str .= substr($feed, rand(0, strlen($feed)-1), 1);
205                             }
206                             $password = $rand_str;
207                         }
209                         /* Insert in the LDAP tree */
210                         if(count($this->usertab->check())) {
211                             msg_dialog::displayChecks($this->usertab->check());
212                             $this->csvinfo['sorteddata'][$i]['status']="<b>"._("failed")."</b>";
213                             $failing = $i+1;
214                             break;
215                         } else {
216                             $this->csvinfo['sorteddata'][$i]['status']=_("ok");
217                             $this->usertab->save();
218                             change_password($this->usertab->dn,$password); 
219                         }
220                     }
221                 }
223                 $pointsbefore = FALSE;
224                 $pointsafter  = FALSE;
226                 /* Get Attributs for Tableheadline  */
227                 $this->csvinfo['colsstr'] = array();
228                 for($i =0; $i <= $this->csvinfo['cols']; $i++) {
229                     if(!empty($_POST[('row'.$i)])){
230                         $this->csvinfo['colsstr'][$i] = $this->csvinfo['attr'][$_POST[('row'.$i)]];
231                     }
232                 }
234                 /*Create array with data for the template */
235                 if($failing == FALSE){
237                     $dataouts= array();
238                     for($i =1; $i <= $this->csvinfo['shownrowscount']; $i++) {
239                         if(is_array($this->csvinfo['sorteddata'][($i-1)])){
240                             foreach($this->csvinfo['sorteddata'][($i-1)] as $dat){
241                                 $dataouts[]=$dat;
242                             }
243                         }
244                     }
246                     if($this->csvinfo['rows']> $this->csvinfo['shownrowscount']){
247                         $pointsafter = TRUE;
248                     }
249                 } else {
250                     $pointsbefore = TRUE;
251                     $pointsafter  = TRUE;
253                     $begin = $failing -3;
255                     if($begin <0) {
256                         $begin =0;
257                         $pointsbefore = FALSE;
258                     }
260                     $end = $failing + 2;
262                     if($end > $this->csvinfo['rows']) {
263                         $end = $this->csvinfo['rows']+1;
264                         $pointsafter = FALSE;
265                     }
266                     $this->csvinfo['shownrowscount']=$end - $begin;
268                     if($this->csvinfo['shownrowscount']> $this->csvinfo['rows'])$this->csvinfo['shownrowscount']=$this->csvinfo['rows'];
270                     $dataouts = array(); 
271                     for($i =$begin; $i <= $end; $i++) {
272                         if(is_array($this->csvinfo['sorteddata'][($i)])){
273                             foreach($this->csvinfo['sorteddata'][($i)] as $dat){
274                                 $dataouts[]=$dat;
275                             }
276                         }
277                     }
278                 }
279                 $tmparr2  = $this->csvinfo['colsstr'];
280                 $tmparr2[]=_("status");
282                 /* Error? */
283                 if ($failing){
284                     msg_dialog::display(_("Error"), sprintf(_("Cannot insert entry '%s'!"), $failing), ERROR_DIALOG);
285                 }
286                 $smarty->assign("error",$failing);
288                 /* Set vars to smarty */
289                 $smarty->assign("cols",count($tmparr2));
290                 $smarty->assign("anz" ,$this->csvinfo['count']);
291                 $smarty->assign("rows",$this->csvinfo['shownrowscount']);
294                 $cnt = 0 ;
295                 $tmp2 = $tmp3 = array();
296                 if(is_array($dataouts))
297                     foreach($dataouts as $tmp){
298                         $tmp2[] = $tmp;
299                         $cnt ++ ;
300                         if($cnt >= count($tmparr2)){
301                             $tmp3[] = $tmp2;
302                             $tmp2= array();
303                             $cnt = 0; 
304                         }
305                     }  
306                 $smarty->assign("head",$tmparr2);
307                 $smarty->assign("data",$tmp3);
309                 /* Set other vars  */
310                 $smarty->assign("i",1);
311                 $smarty->assign("ie",0);
312                 $smarty->assign("tplid",$this->csvinfo['tplid']);
314                 $smarty->assign("pointsafter",$pointsafter);
315                 $smarty->assign("pointsbefore",$pointsbefore);
316             } else {
317                 /* Set Template ID */
318                 $tplid = $_POST['tplid'];
321                 $smarty->assign("tpl",$arrtemplates[$tplid]);
322                 msg_dialog::display(_("Information"), _("Nothing to import!"), INFO_DIALOG);
323             }
325             /* If theres a File uploaded */
326         } else {
327             /* Check if theres a file uploaded */
328             if(!empty($_FILES['userfile']['name'])){
330                 $handle = NULL;
332                 if((!isset($_FILES['userfile']['name']))||(!isset($_POST['fileup'])))
333                 {
334                     msg_dialog::display(_("Error"), sprintf(_("Cannot read uploaded file: %s"), _("file not found")), ERROR_DIALOG);
335                     $smarty->assign("LDIFError",TRUE);
336                 }
337                 elseif(!$_FILES['userfile']['size'] > 0 )
338                 {
339                     msg_dialog::display(_("Error"), sprintf(_("Cannot read uploaded file: %s"), _("file is empty")), ERROR_DIALOG);
340                     $smarty->assign("LDIFError",TRUE);
341                 }
342                 /* Is there a tmp file, which we can use ? */
343                 elseif(!file_exists($_FILES['userfile']['tmp_name']))
344                 {
345                     msg_dialog::display(_("Error"), sprintf(_("Cannot read uploaded file: %s"), _("file not found")), ERROR_DIALOG);
346                     $smarty->assign("LDIFError",TRUE);
347                 }
348                 elseif(!$handle = @fopen($_FILES['userfile']['tmp_name'],"r"))
349                 {
350                     msg_dialog::display(_("Error"), sprintf(_("Cannot read uploaded file: %s"), _("file not readable")), ERROR_DIALOG);
351                     $smarty->assign("LDIFError",TRUE);
352                 }
353                 else
354                 {
355                     $smarty->assign("fileup",TRUE);
356                     $str = "";
359                     /* Reading content */
360                     while(!feof($handle)) {
361                         $str .= fread($handle,1024);
362                     }
364                     $lines = preg_split("/\n/",$str);
365                     $anz  = 0;
366                     $rest = 0;
367                     $data = array();
369                     /* check colum count */
370                     if(is_array($lines))
371                         foreach($lines as $line) {
372                             /* continue if theres a comment */
373                             if(substr(trim($line),0,1)=="#"){
374                                 continue;
375                             }
377                             $line= str_replace ("\t","",$line);
378                             $cells  = explode(",",$line )  ;
380                             if(count($cells)> $anz ){
381                                 $anz = count($cells);
382                             }
383                         }
385                     /* At least one entry */
386                     if($anz >1) {
388                         /* Generate array with outpu info  */
389                         if(is_array($lines))
390                             foreach($lines as $line) {
391                                 $rest = 0;
392                                 $cnt  = 0;
394                                 /* dont use comments or empty lines */
395                                 if((substr(trim($line),0,1)=="#")||(empty($line))){
396                                     continue;
397                                 }
399                                 /* replace \t to , */
400                                 $line= str_replace ("\t"  ,"" ,$line);
402                                 /* get all elements  */
403                                 $cells  = explode(",",$line )  ;
405                                 /* attach all elements to data array */
406                                 if(is_array($cells))
407                                     foreach($cells as $cell) {
408                                         if(!empty($cell)) {
409                                             $cnt++; 
410                                             $data[]=trim($cell);
411                                         }
412                                     }
414                                 /* cell count less than anz, attach some empty fields */
415                                 if(($cnt != $anz)&&(!empty($cnt))) {
416                                     $rest = $anz - $cnt;
417                                     for($i = 0 ; $i < $rest ; $i ++){
418                                         $data[] = " ";
419                                     }
420                                 }
421                             }    
423                         unset($this->csvinfo['sorteddata']);
424                         unset($this->csvinfo['colsstr']);
425                         unset($this->csvinfo['sorteddata']);
427                         $this->csvinfo['cols']        = $anz;
428                         $this->csvinfo['data']        = array();
429                         $this->csvinfo['data']        = $data;
430                         $this->csvinfo['count']       = count($this->csvinfo['data']);
432                         if($this->csvinfo['count']> (6* $this->csvinfo['cols'])) {
433                             /* only show 6 rows in ouptuttablei */
434                             $datouttemp =  array_chunk($this->csvinfo['data'],(6* $this->csvinfo['cols']));
435                             $this->csvinfo['dataout']=$datouttemp[0];
436                             $this->csvinfo['shownrowscount'] = 6;
437                         } else {
438                             $this->csvinfo['shownrowscount'] = (count($this->csvinfo['data']))/$this->csvinfo['cols'];
439                             $this->csvinfo['dataout']= $this->csvinfo['data'];  
440                         }
442                         $this->csvinfo['tplid']       = $_POST['template'];
443                         $this->csvinfo['templatestr'] = $this->csvinfo['arrtemplates' ][$this->csvinfo['tplid']];
444                         $this->csvinfo['count']       = count($this->csvinfo['data']);
445                         $this->csvinfo['rows']        = (count($this->csvinfo['data'])/$anz);
447                         $i =  0; 
448                         $tmp = $tmp2= array();
449                         if(is_array($this->csvinfo['dataout']))
450                             foreach($this->csvinfo['dataout'] as $dat){
451                                 $tmp[]= $dat;
452                                 $i++;
453                                 if($i >=$this->csvinfo['cols']){
454                                     $i = 0;
455                                     $tmp2[] = $tmp;
456                                     $tmp = array();
457                                 }
459                             }
461                         /* Set Templateid  */
462                         $smarty->assign("tplid",$this->csvinfo['tplid']);
464                         /* Set Template  */
465                         $smarty->assign("tpl",$this->csvinfo['templatestr']);
467                         /* Temp var 1 */
468                         $smarty->assign("ia",1); 
470                         /* Temp var 2 */
471                         $smarty->assign("i",0); 
473                         /* Num rows    */
474                         $smarty->assign("rows",$this->csvinfo['shownrowscount']);
477                         for($i  = 0 ; $i < $anz; $i ++)
478                             $this->csvinfo['arr_selected'][]="0";
480                         $smarty->assign("selectedattrs",$this->csvinfo['arr_selected']);
482                         /* Entrie count5 */
483                         $smarty->assign("anz",$this->csvinfo['cols']);                                                    
485                         /* Array with data */
486                         $smarty->assign("data",$tmp2);   
488                         @fclose($handle);
489                     } else {
490                         $smarty->assign("tpl",$this->csvinfo['attr'][$_POST['template']]);
491                         $smarty->assign("LDIFError",TRUE);
492                         $smarty->assign("fileup",FALSE);
493                         msg_dialog::display(_("Error"), _("Cannot find CSV data in the selected file!"), ERROR_DIALOG);
494                     }
495                 }
496             }
497         }                                              
499         /* Show main page */
500         return ($smarty->fetch (get_template_path('contentcsv.tpl', TRUE)));
501     }
505 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
506 ?>