Code

c56d6b245d9ca62dc9a7335295980b7ebf133cdb
[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(!isset($dat['givenName']) || empty($dat['givenName']) || !isset($dat['sn']) || empty($dat['sn'])){
163                         /* Output Error */
164                         msg_dialog::display(_("Error"), _("Need at least 'sn' and 'givenName' to create users!"), ERROR_DIALOG);
165                         $this->csvinfo['sorteddata'][$i]['status']="<b>"._("failed")."</b>";
166                         $failing = $i+1;
167                         continue;
168                     } 
170                     /* Automatically generate 'uid' while it wasn't given yet. 
171                      */
172                     if(!isset($dat['uid']) || empty($dat['uid'])){
174                         // Generate uids and take the first result.
175                         $attributes= array('sn' => $dat['sn'], 'givenName' => $dat['givenName']);
176                         $uids = gen_uids ($this->config->get_cfg_value("idGenerator"), $attributes);
177                         if (!count($uids) || empty($uids[0])){
178                             $msgs = sprintf(_("Failed to generate 'uid' for entry '%s'!"), ($i+1));
179                             $this->csvinfo['sorteddata'][$i]['status']="<b>"._("failed")."</b>&nbsp;". $msgs;
180                             $failing = $i+1;
181                             continue;
182                         }else{
183                             $this->csvinfo['sorteddata'][$i]['uid'] = array_pop($uids);
184                             $dat['uid'] = $this->csvinfo['sorteddata'][$i]['uid'];
185                         }
186                     }
188                     /* Register usertab to trigger edit dialog */
189                     $this->usertab= new usertabs($this->config, $this->config->data['TABS']['USERTABS'], 'new');
190                     $keys = array_keys($dat);
192                     /* Set all submitted vars  */
193                     if(is_array($keys)){
194                         foreach($keys as $key) {
195                             if($key != "status"){
196                                 $this->usertab->$key = $dat[$key];
197                                 foreach($this->usertab->by_object as $pname => $plugin){
198                                     if(isset($this->usertab->by_object[$pname]->$key)){
199                                         $this->usertab->by_object[$pname]->$key = $dat[$key];
200                                     }
201                                 }
202                             }
203                         }
204                     }
206                     // Adapt template values.
207                     if($this->csvinfo['tplid']!=0){
208                         $tpl_dn = $this->csvinfo['arrtempls'][$this->csvinfo['tplid']]['dn'];
209                         $this->usertab->adapt_from_template($tpl_dn,array("uid","cn","givenName","sn"));
210                         $tpl_base  = preg_replace("/^[^,]+,".preg_quote(get_people_ou(), '/i')."/", '', $tpl_dn);
211                         $this->usertab->by_object['user']->base= $tpl_base;
212                     } 
214                     // Setting user Password 
215                     if((isset($dat['userPassword']))&&(!empty($dat['userPassword']))){
216                         $password = $dat['userPassword']; 
217                     }else{
218                         $rand_str="";
219                         $feed = "0123456789abcdefghijklmnopqrstuvwxyz";
220                         for ($e=0; $e < 8; $e++)
221                         {
222                             $rand_str .= substr($feed, rand(0, strlen($feed)-1), 1);
223                         }
224                         $password = $rand_str;
225                     }
227                     /* Insert in the LDAP tree */
228                     if(count($this->usertab->check())) {
229                         msg_dialog::displayChecks($this->usertab->check());
230                         $this->csvinfo['sorteddata'][$i]['status']="<b>"._("failed")."</b>";
231                         $failing = $i+1;
232                         break;
233                     } else {
234                         $this->csvinfo['sorteddata'][$i]['status']=_("ok");
235                         $this->usertab->save();
236                         change_password($this->usertab->dn,$password); 
237                     }
238                 }
240                 $pointsbefore = FALSE;
241                 $pointsafter  = FALSE;
243                 /* Get Attributs for Tableheadline  */
244                 $this->csvinfo['colsstr'] = array();
245                 for($i =0; $i <= $this->csvinfo['cols']; $i++) {
246                     if(!empty($_POST[('row'.$i)])){
247                         $this->csvinfo['colsstr'][$i] = $this->csvinfo['attr'][$_POST[('row'.$i)]];
248                     }
249                 }
251                 /*Create array with data for the template */
252                 if($failing == FALSE){
254                     $dataouts= array();
255                     for($i =1; $i <= $this->csvinfo['shownrowscount']; $i++) {
256                         if(is_array($this->csvinfo['sorteddata'][($i-1)])){
257                             foreach($this->csvinfo['sorteddata'][($i-1)] as $dat){
258                                 $dataouts[]=$dat;
259                             }
260                         }
261                     }
263                     if($this->csvinfo['rows']> $this->csvinfo['shownrowscount']){
264                         $pointsafter = TRUE;
265                     }
266                 } else {
267                     $pointsbefore = TRUE;
268                     $pointsafter  = TRUE;
270                     $begin = $failing -3;
272                     if($begin <0) {
273                         $begin =0;
274                         $pointsbefore = FALSE;
275                     }
277                     $end = $failing + 2;
279                     if($end > $this->csvinfo['rows']) {
280                         $end = $this->csvinfo['rows']+1;
281                         $pointsafter = FALSE;
282                     }
283                     $this->csvinfo['shownrowscount']=$end - $begin;
285                     if($this->csvinfo['shownrowscount']> $this->csvinfo['rows'])$this->csvinfo['shownrowscount']=$this->csvinfo['rows'];
287                     $dataouts = array(); 
288                     for($i =$begin; ($i <= $end) && (isset($this->csvinfo['sorteddata'][($i)])); $i++) {
289                         if(is_array($this->csvinfo['sorteddata'][($i)])){
290                             foreach($this->csvinfo['sorteddata'][($i)] as $dat){
291                                 $dataouts[]=$dat;
292                             }
293                         }
294                     }
295                 }
296                 $tmparr2  = $this->csvinfo['colsstr'];
297                 $tmparr2[]=_("status");
299                 /* Error? */
300                 if ($failing){
301                     msg_dialog::display(_("Error"), sprintf(_("Cannot insert entry '%s'!"), $failing), ERROR_DIALOG);
302                 }
303                 $smarty->assign("error",$failing);
305                 /* Set vars to smarty */
306                 $smarty->assign("cols",count($tmparr2));
307                 $smarty->assign("anz" ,$this->csvinfo['count']);
308                 $smarty->assign("rows",$this->csvinfo['shownrowscount']);
311                 $cnt = 0 ;
312                 $tmp2 = $tmp3 = array();
313                 if(is_array($dataouts))
314                     foreach($dataouts as $tmp){
315                         $tmp2[] = $tmp;
316                         $cnt ++ ;
317                         if($cnt >= count($tmparr2)){
318                             $tmp3[] = $tmp2;
319                             $tmp2= array();
320                             $cnt = 0; 
321                         }
322                     }  
323                 $smarty->assign("head",$tmparr2);
324                 $smarty->assign("data",$tmp3);
326                 /* Set other vars  */
327                 $smarty->assign("i",1);
328                 $smarty->assign("ie",0);
329                 $smarty->assign("tplid",$this->csvinfo['tplid']);
331                 $smarty->assign("pointsafter",$pointsafter);
332                 $smarty->assign("pointsbefore",$pointsbefore);
333             } else {
334                 /* Set Template ID */
335                 $tplid = $_POST['tplid'];
338                 $smarty->assign("tpl",$arrtemplates[$tplid]);
339                 msg_dialog::display(_("Information"), _("Nothing to import!"), INFO_DIALOG);
340             }
342             /* If theres a File uploaded */
343         } else {
344             /* Check if theres a file uploaded */
345             if(!empty($_FILES['userfile']['name'])){
347                 $handle = NULL;
349                 if((!isset($_FILES['userfile']['name']))||(!isset($_POST['fileup'])))
350                 {
351                     msg_dialog::display(_("Error"), sprintf(_("Cannot read uploaded file: %s"), _("file not found")), ERROR_DIALOG);
352                     $smarty->assign("LDIFError",TRUE);
353                 }
354                 elseif(!$_FILES['userfile']['size'] > 0 )
355                 {
356                     msg_dialog::display(_("Error"), sprintf(_("Cannot read uploaded file: %s"), _("file is empty")), ERROR_DIALOG);
357                     $smarty->assign("LDIFError",TRUE);
358                 }
359                 /* Is there a tmp file, which we can use ? */
360                 elseif(!file_exists($_FILES['userfile']['tmp_name']))
361                 {
362                     msg_dialog::display(_("Error"), sprintf(_("Cannot read uploaded file: %s"), _("file not found")), ERROR_DIALOG);
363                     $smarty->assign("LDIFError",TRUE);
364                 }
365                 elseif(!$handle = @fopen($_FILES['userfile']['tmp_name'],"r"))
366                 {
367                     msg_dialog::display(_("Error"), sprintf(_("Cannot read uploaded file: %s"), _("file not readable")), ERROR_DIALOG);
368                     $smarty->assign("LDIFError",TRUE);
369                 }
370                 else
371                 {
372                     $smarty->assign("fileup",TRUE);
373                     $str = "";
376                     /* Reading content */
377                     while(!feof($handle)) {
378                         $str .= fread($handle,1024);
379                     }
381                     $lines = preg_split("/\n/",$str);
382                     $anz  = 0;
383                     $rest = 0;
384                     $data = array();
386                     /* check colum count */
387                     if(is_array($lines))
388                         foreach($lines as $line) {
389                             /* continue if theres a comment */
390                             if(substr(trim($line),0,1)=="#"){
391                                 continue;
392                             }
394                             $line= str_replace ("\t","",$line);
395                             $cells  = explode(",",$line )  ;
397                             if(count($cells)> $anz ){
398                                 $anz = count($cells);
399                             }
400                         }
402                     /* At least one entry */
403                     if($anz >1) {
405                         /* Generate array with outpu info  */
406                         if(is_array($lines))
407                             foreach($lines as $line) {
408                                 $rest = 0;
409                                 $cnt  = 0;
411                                 /* dont use comments or empty lines */
412                                 if((substr(trim($line),0,1)=="#")||(empty($line))){
413                                     continue;
414                                 }
416                                 /* replace \t to , */
417                                 $line= str_replace ("\t"  ,"" ,$line);
419                                 /* get all elements  */
420                                 $cells  = explode(",",$line )  ;
422                                 /* attach all elements to data array */
423                                 if(is_array($cells))
424                                     foreach($cells as $cell) {
425                                         if(!empty($cell)) {
426                                             $cnt++; 
427                                             $data[]=trim($cell);
428                                         }
429                                     }
431                                 /* cell count less than anz, attach some empty fields */
432                                 if(($cnt != $anz)&&(!empty($cnt))) {
433                                     $rest = $anz - $cnt;
434                                     for($i = 0 ; $i < $rest ; $i ++){
435                                         $data[] = " ";
436                                     }
437                                 }
438                             }    
440                         unset($this->csvinfo['sorteddata']);
441                         unset($this->csvinfo['colsstr']);
442                         unset($this->csvinfo['sorteddata']);
444                         $this->csvinfo['cols']        = $anz;
445                         $this->csvinfo['data']        = array();
446                         $this->csvinfo['data']        = $data;
447                         $this->csvinfo['count']       = count($this->csvinfo['data']);
449                         if($this->csvinfo['count']> (6* $this->csvinfo['cols'])) {
450                             /* only show 6 rows in ouptuttablei */
451                             $datouttemp =  array_chunk($this->csvinfo['data'],(6* $this->csvinfo['cols']));
452                             $this->csvinfo['dataout']=$datouttemp[0];
453                             $this->csvinfo['shownrowscount'] = 6;
454                         } else {
455                             $this->csvinfo['shownrowscount'] = (count($this->csvinfo['data']))/$this->csvinfo['cols'];
456                             $this->csvinfo['dataout']= $this->csvinfo['data'];  
457                         }
459                         $this->csvinfo['tplid']       = $_POST['template'];
460                         $this->csvinfo['templatestr'] = $this->csvinfo['arrtemplates' ][$this->csvinfo['tplid']];
461                         $this->csvinfo['count']       = count($this->csvinfo['data']);
462                         $this->csvinfo['rows']        = (count($this->csvinfo['data'])/$anz);
464                         $i =  0; 
465                         $tmp = $tmp2= array();
466                         if(is_array($this->csvinfo['dataout']))
467                             foreach($this->csvinfo['dataout'] as $dat){
468                                 $tmp[]= $dat;
469                                 $i++;
470                                 if($i >=$this->csvinfo['cols']){
471                                     $i = 0;
472                                     $tmp2[] = $tmp;
473                                     $tmp = array();
474                                 }
476                             }
478                         /* Set Templateid  */
479                         $smarty->assign("tplid",$this->csvinfo['tplid']);
481                         /* Set Template  */
482                         $smarty->assign("tpl",$this->csvinfo['templatestr']);
484                         /* Temp var 1 */
485                         $smarty->assign("ia",1); 
487                         /* Temp var 2 */
488                         $smarty->assign("i",0); 
490                         /* Num rows    */
491                         $smarty->assign("rows",$this->csvinfo['shownrowscount']);
494                         for($i  = 0 ; $i < $anz; $i ++)
495                             $this->csvinfo['arr_selected'][]="0";
497                         $smarty->assign("selectedattrs",$this->csvinfo['arr_selected']);
499                         /* Entrie count5 */
500                         $smarty->assign("anz",$this->csvinfo['cols']);                                                    
502                         /* Array with data */
503                         $smarty->assign("data",$tmp2);   
505                         @fclose($handle);
506                     } else {
507                         $smarty->assign("tpl",$this->csvinfo['attr'][$_POST['template']]);
508                         $smarty->assign("LDIFError",TRUE);
509                         $smarty->assign("fileup",FALSE);
510                         msg_dialog::display(_("Error"), _("Cannot find CSV data in the selected file!"), ERROR_DIALOG);
511                     }
512                 }
513             }
514         }                                              
516         /* Show main page */
517         return ($smarty->fetch (get_template_path('contentcsv.tpl', TRUE)));
518     }
522 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
523 ?>