Code

fb0c41db20615eac6009535d0c206d2564650d1d
[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);
172                         /* Set all submitted vars  */
173                         if(is_array($keys)){
174                             foreach($keys as $key) {
175                                 if($key != "status"){
176                                     $this->usertab->$key = $dat[$key];
177                                     foreach($this->usertab->by_object as $pname => $plugin){
178                                         if(isset($this->usertab->by_object[$pname]->$key)){
179                                             $this->usertab->by_object[$pname]->$key = $dat[$key];
180                                         }
181                                     }
182                                 }
183                             }
184                         }
186                         // Adapt template values.
187                         if($this->csvinfo['tplid']!=0){
188                             $tpl_dn = $this->csvinfo['arrtempls'][$this->csvinfo['tplid']]['dn'];
189                             $this->usertab->adapt_from_template($tpl_dn,array("uid","cn","givenName","sn"));
190                             $tpl_base  = preg_replace("/^[^,]+,".preg_quote(get_people_ou(), '/i')."/", '', $tpl_dn);
191                             $this->usertab->by_object['user']->base= $tpl_base;
192                         } 
194                         // Setting user Password 
195                         if((isset($dat['userPassword']))&&(!empty($dat['userPassword']))){
196                             $password = $dat['userPassword']; 
197                         }else{
198                             $rand_str="";
199                             $feed = "0123456789abcdefghijklmnopqrstuvwxyz";
200                             for ($e=0; $e < 8; $e++)
201                             {
202                                 $rand_str .= substr($feed, rand(0, strlen($feed)-1), 1);
203                             }
204                             $password = $rand_str;
205                         }
207                         /* Insert in the LDAP tree */
208                         if(count($this->usertab->check())) {
209                             msg_dialog::displayChecks($this->usertab->check());
210                             $this->csvinfo['sorteddata'][$i]['status']="<b>"._("failed")."</b>";
211                             $failing = $i+1;
212                             break;
213                         } else {
214                             $this->csvinfo['sorteddata'][$i]['status']=_("ok");
215                             $this->usertab->save();
216                             change_password($this->usertab->dn,$password); 
217                         }
218                     }
219                 }
221                 $pointsbefore = FALSE;
222                 $pointsafter  = FALSE;
224                 /* Get Attributs for Tableheadline  */
225                 $this->csvinfo['colsstr'] = array();
226                 for($i =0; $i <= $this->csvinfo['cols']; $i++) {
227                     if(!empty($_POST[('row'.$i)])){
228                         $this->csvinfo['colsstr'][$i] = $this->csvinfo['attr'][$_POST[('row'.$i)]];
229                     }
230                 }
232                 /*Create array with data for the template */
233                 if($failing == FALSE){
235                     $dataouts= array();
236                     for($i =1; $i <= $this->csvinfo['shownrowscount']; $i++) {
237                         if(is_array($this->csvinfo['sorteddata'][($i-1)])){
238                             foreach($this->csvinfo['sorteddata'][($i-1)] as $dat){
239                                 $dataouts[]=$dat;
240                             }
241                         }
242                     }
244                     if($this->csvinfo['rows']> $this->csvinfo['shownrowscount']){
245                         $pointsafter = TRUE;
246                     }
247                 } else {
248                     $pointsbefore = TRUE;
249                     $pointsafter  = TRUE;
251                     $begin = $failing -3;
253                     if($begin <0) {
254                         $begin =0;
255                         $pointsbefore = FALSE;
256                     }
258                     $end = $failing + 2;
260                     if($end > $this->csvinfo['rows']) {
261                         $end = $this->csvinfo['rows']+1;
262                         $pointsafter = FALSE;
263                     }
264                     $this->csvinfo['shownrowscount']=$end - $begin;
266                     if($this->csvinfo['shownrowscount']> $this->csvinfo['rows'])$this->csvinfo['shownrowscount']=$this->csvinfo['rows'];
268                     $dataouts = array(); 
269                     for($i =$begin; $i <= $end; $i++) {
270                         if(is_array($this->csvinfo['sorteddata'][($i)])){
271                             foreach($this->csvinfo['sorteddata'][($i)] as $dat){
272                                 $dataouts[]=$dat;
273                             }
274                         }
275                     }
276                 }
277                 $tmparr2  = $this->csvinfo['colsstr'];
278                 $tmparr2[]=_("status");
280                 /* Error? */
281                 if ($failing){
282                     msg_dialog::display(_("Error"), sprintf(_("Cannot insert entry '%s'!"), $failing), ERROR_DIALOG);
283                 }
284                 $smarty->assign("error",$failing);
286                 /* Set vars to smarty */
287                 $smarty->assign("cols",count($tmparr2));
288                 $smarty->assign("anz" ,$this->csvinfo['count']);
289                 $smarty->assign("rows",$this->csvinfo['shownrowscount']);
292                 $cnt = 0 ;
293                 $tmp2 = $tmp3 = array();
294                 if(is_array($dataouts))
295                     foreach($dataouts as $tmp){
296                         $tmp2[] = $tmp;
297                         $cnt ++ ;
298                         if($cnt >= count($tmparr2)){
299                             $tmp3[] = $tmp2;
300                             $tmp2= array();
301                             $cnt = 0; 
302                         }
303                     }  
304                 $smarty->assign("head",$tmparr2);
305                 $smarty->assign("data",$tmp3);
307                 /* Set other vars  */
308                 $smarty->assign("i",1);
309                 $smarty->assign("ie",0);
310                 $smarty->assign("tplid",$this->csvinfo['tplid']);
312                 $smarty->assign("pointsafter",$pointsafter);
313                 $smarty->assign("pointsbefore",$pointsbefore);
314             } else {
315                 /* Set Template ID */
316                 $tplid = $_POST['tplid'];
319                 $smarty->assign("tpl",$arrtemplates[$tplid]);
320                 msg_dialog::display(_("Information"), _("Nothing to import!"), INFO_DIALOG);
321             }
323             /* If theres a File uploaded */
324         } else {
325             /* Check if theres a file uploaded */
326             if(!empty($_FILES['userfile']['name'])){
328                 $handle = NULL;
330                 if((!isset($_FILES['userfile']['name']))||(!isset($_POST['fileup'])))
331                 {
332                     msg_dialog::display(_("Error"), sprintf(_("Cannot read uploaded file: %s"), _("file not found")), ERROR_DIALOG);
333                     $smarty->assign("LDIFError",TRUE);
334                 }
335                 elseif(!$_FILES['userfile']['size'] > 0 )
336                 {
337                     msg_dialog::display(_("Error"), sprintf(_("Cannot read uploaded file: %s"), _("file is empty")), ERROR_DIALOG);
338                     $smarty->assign("LDIFError",TRUE);
339                 }
340                 /* Is there a tmp file, which we can use ? */
341                 elseif(!file_exists($_FILES['userfile']['tmp_name']))
342                 {
343                     msg_dialog::display(_("Error"), sprintf(_("Cannot read uploaded file: %s"), _("file not found")), ERROR_DIALOG);
344                     $smarty->assign("LDIFError",TRUE);
345                 }
346                 elseif(!$handle = @fopen($_FILES['userfile']['tmp_name'],"r"))
347                 {
348                     msg_dialog::display(_("Error"), sprintf(_("Cannot read uploaded file: %s"), _("file not readable")), ERROR_DIALOG);
349                     $smarty->assign("LDIFError",TRUE);
350                 }
351                 else
352                 {
353                     $smarty->assign("fileup",TRUE);
354                     $str = "";
357                     /* Reading content */
358                     while(!feof($handle)) {
359                         $str .= fread($handle,1024);
360                     }
362                     $lines = preg_split("/\n/",$str);
363                     $anz  = 0;
364                     $rest = 0;
365                     $data = array();
367                     /* check colum count */
368                     if(is_array($lines))
369                         foreach($lines as $line) {
370                             /* continue if theres a comment */
371                             if(substr(trim($line),0,1)=="#"){
372                                 continue;
373                             }
375                             $line= str_replace ("\t","",$line);
376                             $cells  = explode(",",$line )  ;
378                             if(count($cells)> $anz ){
379                                 $anz = count($cells);
380                             }
381                         }
383                     /* At least one entry */
384                     if($anz >1) {
386                         /* Generate array with outpu info  */
387                         if(is_array($lines))
388                             foreach($lines as $line) {
389                                 $rest = 0;
390                                 $cnt  = 0;
392                                 /* dont use comments or empty lines */
393                                 if((substr(trim($line),0,1)=="#")||(empty($line))){
394                                     continue;
395                                 }
397                                 /* replace \t to , */
398                                 $line= str_replace ("\t"  ,"" ,$line);
400                                 /* get all elements  */
401                                 $cells  = explode(",",$line )  ;
403                                 /* attach all elements to data array */
404                                 if(is_array($cells))
405                                     foreach($cells as $cell) {
406                                         if(!empty($cell)) {
407                                             $cnt++; 
408                                             $data[]=trim($cell);
409                                         }
410                                     }
412                                 /* cell count less than anz, attach some empty fields */
413                                 if(($cnt != $anz)&&(!empty($cnt))) {
414                                     $rest = $anz - $cnt;
415                                     for($i = 0 ; $i < $rest ; $i ++){
416                                         $data[] = " ";
417                                     }
418                                 }
419                             }    
421                         unset($this->csvinfo['sorteddata']);
422                         unset($this->csvinfo['colsstr']);
423                         unset($this->csvinfo['sorteddata']);
425                         $this->csvinfo['cols']        = $anz;
426                         $this->csvinfo['data']        = array();
427                         $this->csvinfo['data']        = $data;
428                         $this->csvinfo['count']       = count($this->csvinfo['data']);
430                         if($this->csvinfo['count']> (6* $this->csvinfo['cols'])) {
431                             /* only show 6 rows in ouptuttablei */
432                             $datouttemp =  array_chunk($this->csvinfo['data'],(6* $this->csvinfo['cols']));
433                             $this->csvinfo['dataout']=$datouttemp[0];
434                             $this->csvinfo['shownrowscount'] = 6;
435                         } else {
436                             $this->csvinfo['shownrowscount'] = (count($this->csvinfo['data']))/$this->csvinfo['cols'];
437                             $this->csvinfo['dataout']= $this->csvinfo['data'];  
438                         }
440                         $this->csvinfo['tplid']       = $_POST['template'];
441                         $this->csvinfo['templatestr'] = $this->csvinfo['arrtemplates' ][$this->csvinfo['tplid']];
442                         $this->csvinfo['count']       = count($this->csvinfo['data']);
443                         $this->csvinfo['rows']        = (count($this->csvinfo['data'])/$anz);
445                         $i =  0; 
446                         $tmp = $tmp2= array();
447                         if(is_array($this->csvinfo['dataout']))
448                             foreach($this->csvinfo['dataout'] as $dat){
449                                 $tmp[]= $dat;
450                                 $i++;
451                                 if($i >=$this->csvinfo['cols']){
452                                     $i = 0;
453                                     $tmp2[] = $tmp;
454                                     $tmp = array();
455                                 }
457                             }
459                         /* Set Templateid  */
460                         $smarty->assign("tplid",$this->csvinfo['tplid']);
462                         /* Set Template  */
463                         $smarty->assign("tpl",$this->csvinfo['templatestr']);
465                         /* Temp var 1 */
466                         $smarty->assign("ia",1); 
468                         /* Temp var 2 */
469                         $smarty->assign("i",0); 
471                         /* Num rows    */
472                         $smarty->assign("rows",$this->csvinfo['shownrowscount']);
475                         for($i  = 0 ; $i < $anz; $i ++)
476                             $this->csvinfo['arr_selected'][]="0";
478                         $smarty->assign("selectedattrs",$this->csvinfo['arr_selected']);
480                         /* Entrie count5 */
481                         $smarty->assign("anz",$this->csvinfo['cols']);                                                    
483                         /* Array with data */
484                         $smarty->assign("data",$tmp2);   
486                         @fclose($handle);
487                     } else {
488                         $smarty->assign("tpl",$this->csvinfo['attr'][$_POST['template']]);
489                         $smarty->assign("LDIFError",TRUE);
490                         $smarty->assign("fileup",FALSE);
491                         msg_dialog::display(_("Error"), _("Cannot find CSV data in the selected file!"), ERROR_DIALOG);
492                     }
493                 }
494             }
495         }                                              
497         /* Show main page */
498         return ($smarty->fetch (get_template_path('contentcsv.tpl', TRUE)));
499     }
503 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
504 ?>