Code

Updated password change for csvimport
[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     $this->initTime = microtime(TRUE);
21     /* Include config object */
22     $this->config= &$config;
24     $this->ui = get_userinfo();
25     stats::log('plugin', $class = get_class($this), $category = array($this->acl_category),  $action = 'open',
26             $amount = 1, $duration = (microtime(TRUE) - $this->initTime));
28   }
30   function execute()
31   {
32     /* Call parent execute */
33     plugin::execute();
35     /* Log view */
36     if(!$this->view_logged){
37       $this->view_logged = TRUE;
38       new log("view","all/".get_class($this),$this->dn);
39     }
41     /* initiate smarty */
42     $smarty= get_smarty();
43     $smarty->assign("selectedattrs",array(0=>""));
44     $smarty->assign("data",array(0=>""));
45     $smarty->assign("head",array(0=>""));
46     $smarty->assign("sorted",0);
47     $smarty->assign("fileup",0);
49     /* Get the LDAP link, to generate the Export */
50     $ldap = $this->config->get_ldap_link();
52     $arrtemplates = array();
53     $tempvar =0;
55     /* Array to fill in Formfields */
56     $arrtemplates[$tempvar] = "None";
57     if(!is_array($this->csvinfo)){
58       $this->csvinfo=array();
59     }
61     /* Set Usertemplate information and get all Attribute from userclass */
62     unset ($this->csvinfo['arrtemplates']);
63     unset ($this->csvinfo['arrtempls']);
65     /* Generate Template Array, Attribute Array */
66     if(!isset($this->csvinfo['arrtempls'])){
68       /* Generating attributes */
69       $attrs = @get_class_vars("user");
70       $this->csvinfo['attr']  = $attrs['attributes'];
72       /* Attach the choise none to discard a csv col */
73       $new = array();
74       $new[0]="none";
75       $new[1]="userPassword";
76       for($c = 0; $c < count($this->csvinfo['attr']);$c++){
77         $new[$c+2]=$this->csvinfo['attr'][$c];
78       }
80       $this->csvinfo['attr'] = $new;
82       /* Search all Templates    */
83       $this->csvinfo['templates'] = $ldap->search("(objectClass=gosaUserTemplate)",array("*"));
85       /* Array to handle selected Form fiels */
86       $this->csvinfo['arrtempls'][$tempvar]['name'] = "";
87       $this->csvinfo['arrtempls'][$tempvar]['dn']   = "";
89       $this->csvinfo['arrtemplates'][]="None";
91       while($temp = $ldap->fetch($this->csvinfo['templates'])){
92         $tempvar ++;
93         $this->csvinfo['arrtemplates'][$tempvar] = $temp['sn'][0]." - ".$this->config->idepartments[preg_replace("/^[^,]+,".preg_quote(get_people_ou(), '/')."/i", "", $temp['dn'])];
94         $this->csvinfo['arrtempls']   [$tempvar]['name'] = $temp['sn'][0]; 
95         $this->csvinfo['arrtempls']   [$tempvar]['dn']   = $temp['dn'];
96       }
97     }
99     $arr_temp  = array_flip($this->csvinfo['attr']);
100     $this->csvinfo['arr_selected']= array($arr_temp['uid'],$arr_temp['sn'],$arr_temp['givenName'],$arr_temp['userPassword']);
102     $smarty->assign("templates",$this->csvinfo['arrtemplates']);
103     $smarty->assign("attrs",$this->csvinfo['attr']);
105     /* Check permissions for import */
106     $acl = $this->ui->get_permissions($this->config->current['BASE'],"all/all");
107     if(!preg_match("/w/",$acl)){
108       if(isset($_POST['userfile']) || isset($_POST['sorted']) || isset($_POST['fileup'])){
109         msg_dialog::display(_("Permission error"), _("You've no permission to import CSV files!"), ERROR_DIALOG);
110       }
111       return ($smarty->fetch (get_template_path('contentcsv.tpl', TRUE)));
112     }
114     /* If the given dat from the csv File are sorted by the attributes */
115     if(isset($_POST['sorted'])) {
117       /* Template Handling */
118       $smarty->assign("fileup",TRUE); 
119       $smarty->assign("sorted",TRUE); 
121       for($i = 0 ; $i < $this->csvinfo['rows'];$i++){
122         /* Preparing given Data */
123         $this->csvinfo['sorteddata'][$i]=array(); 
125         /* Go through every col */
126         for($a = 0; $a <= ($this->csvinfo['cols']); $a ++) {
127           /* Append a status col at last, to show possibly errors */
128           if($a==($this->csvinfo['cols'])){
129             $this->csvinfo['sorteddata'][$i]["status"]="-";            
130           } else {
131             $cc = ($i * ($this->csvinfo['cols']))+$a;
133             /* If theres a Attribut given for this col */
134             if(!empty($_POST[('row'.($a))])) {
135               $this->csvinfo['sorteddata'][$i][$this->csvinfo['attr'][$_POST[('row'.($a))]]]=$this->csvinfo['data'][($cc)]; 
136             }
137           }
138         }
139       } 
141       /* aleast one entry */
142       $rowcnt=0;      
143       if(isset($this->csvinfo['sorteddata'])){
144         $rowcnt ++;
146         /* Set the col count */
147         $tblcolcount= count ($this->csvinfo['cols']);
149         /* entrie count */
150         $tbl_entries= count ($this->csvinfo['count']);
152         /* row count */
153         $tbl_rows   = $tbl_entries / $tblcolcount;
155         /* No error occurred */
156         $failing = FALSE;
158         /* For every row */
159         for($i = 0; $i < $this->csvinfo['rows']; $i++){
161           /* Get elemenet */
162           $dat = $this->csvinfo['sorteddata'][$i];
164           /* If not all needed vars set .... */
165           if(         ( empty($dat['sn']))||( empty($dat['givenName']))||( empty($dat['uid']))||
166               (!isset($dat['sn']))||(!isset($dat['givenName']))||(!isset($dat['uid']))){
168             /* Output Error */
169             msg_dialog::display(_("Error"), sprintf(_("Need at least %s, %s and %s to create users!"), bold("sn"), bold("givenName"), bold("uid")), ERROR_DIALOG);
170           } else {
172             /* Register usertab to trigger edit dialog */
173             $this->usertab= new usertabs($this->config, $this->config->data['TABS']['USERTABS'], 'new');
174             $keys = array_keys($dat);
177             /* Set all submitted vars  */
178             if(is_array($keys))
179               foreach($keys as $key) {
180                 if($key != "status"){
181                   $this->usertab->$key = $dat[$key];
182                 }
183               }
185             /* Initialize template */
186             if($this->csvinfo['tplid']!=0){
187               $this->usertab->adapt_from_template($this->csvinfo['arrtempls'][$this->csvinfo['tplid']]['dn']);
188               $this->usertab->save_object();
189             } else {
191               /* Reset vars */
192               if(is_array($keys))
193                 foreach($keys as $key) {
194                   if($key != "status"){
195                     $this->usertab->by_object['user']->$key = $dat[$key];
196                   }
197                 }
198             }
200             // Setting user Password 
201             if((isset($dat['userPassword']))&&(!empty($dat['userPassword'])))
202               $password = $dat['userPassword']; 
203             else
204             {
205               $rand_str="";
206               $feed = "0123456789abcdefghijklmnopqrstuvwxyz";
207               for ($i=0; $i < 8; $i++)
208               {
209                 $rand_str .= substr($feed, rand(0, strlen($feed)-1), 1);
210               }
211               $password = $rand_str;
212             }
214             /* Insert in the LDAP tree */
215             if(count($this->usertab->check())) {
216               msg_dialog::displayChecks($this->usertab->check());
217               $this->csvinfo['sorteddata'][$i]['status']="<b>"._("failed")."</b>";
218               $failing = $i+1;
219               break;
220             } else {
221               $this->csvinfo['sorteddata'][$i]['status']=_("OK");
222               $this->usertab->save();
223               if(!change_password($this->usertab->dn,$password,FALSE,'','', $message)){
224                 msg_dialog::displayChecks(array($message));
225               }
226             }
227           }
228         }
230         $pointsbefore = FALSE;
231         $pointsafter  = FALSE;
233         /* Get Attributs for Tableheadline  */
234         $this->csvinfo['colsstr'] = array();
235         for($i =0; $i <= $this->csvinfo['cols']; $i++) {
236           if(!empty($_POST[('row'.$i)])){
237             $this->csvinfo['colsstr'][$i] = $this->csvinfo['attr'][$_POST[('row'.$i)]];
238           }
239         }
241         /*Create array with data for the template */
242         if($failing == FALSE){
244           $dataouts= array();
245           for($i =1; $i <= $this->csvinfo['shownrowscount']; $i++) {
246             if(is_array($this->csvinfo['sorteddata'][($i-1)])){
247               foreach($this->csvinfo['sorteddata'][($i-1)] as $dat){
248                 $dataouts[]=$dat;
249               }
250             }
251           }
253           if($this->csvinfo['rows']> $this->csvinfo['shownrowscount']){
254             $pointsafter = TRUE;
255           }
256         } else {
257           $pointsbefore = TRUE;
258           $pointsafter  = TRUE;
260           $begin = $failing -3;
262           if($begin <0) {
263             $begin =0;
264             $pointsbefore = FALSE;
265           }
267           $end = $failing + 2;
269           if($end > $this->csvinfo['rows']) {
270             $end = $this->csvinfo['rows']+1;
271             $pointsafter = FALSE;
272           }
273           $this->csvinfo['shownrowscount']=$end - $begin;
275           if($this->csvinfo['shownrowscount']> $this->csvinfo['rows'])$this->csvinfo['shownrowscount']=$this->csvinfo['rows'];
277           $dataouts = array(); 
278           for($i =$begin; $i <= $end; $i++) {
279             if(is_array($this->csvinfo['sorteddata'][($i-1)])){
280               foreach($this->csvinfo['sorteddata'][($i-1)] as $dat){
281                 $dataouts[]=$dat;
282               }
283             }
284           }
285         }
286         $tmparr2  = $this->csvinfo['colsstr'];
287         $tmparr2[]=_("status");
289         /* Error? */
290         if ($failing){
291           msg_dialog::display(_("Error"), sprintf(_("Cannot add entry %s!"), bold($failing)), ERROR_DIALOG);
292         }
293         $smarty->assign("error",$failing);
295         /* Set vars to smarty */
296         $smarty->assign("cols",count($tmparr2));
297         $smarty->assign("anz" ,$this->csvinfo['count']);
298         $smarty->assign("rows",$this->csvinfo['shownrowscount']);
301         $cnt = 0 ;
302         $tmp2 = $tmp3 = array();
303         if(is_array($dataouts))
304           foreach($dataouts as $tmp){
305             $tmp2[] = $tmp;
306             $cnt ++ ;
307             if($cnt >= count($tmparr2)){
308               $tmp3[] = $tmp2;
309               $tmp2= array();
310               $cnt = 0; 
311             }
312           }  
313         $smarty->assign("head",$tmparr2);
314         $smarty->assign("data",$tmp3);
316         /* Set other vars  */
317         $smarty->assign("i",1);
318         $smarty->assign("ie",0);
319         $smarty->assign("tplid",$this->csvinfo['tplid']);
321         $smarty->assign("pointsafter",$pointsafter);
322         $smarty->assign("pointsbefore",$pointsbefore);
323       } else {
324         /* Set Template ID */
325         $tplid = $_POST['tplid'];
328         $smarty->assign("tpl",$arrtemplates[$tplid]);
329         msg_dialog::display(_("Information"), _("Nothing to import!"), INFO_DIALOG);
330       }
332       /* If theres a File uploaded */
333     } else {
334       /* Check if theres a file uploaded */
335       if(!empty($_FILES['userfile']['name'])){
337         $handle = NULL;
339         if((!isset($_FILES['userfile']['name']))||(!isset($_POST['fileup'])))
340         {
341           msg_dialog::display(_("Error"), sprintf(_("Cannot read uploaded file: %s"), _("file not found")), ERROR_DIALOG);
342           $smarty->assign("LDIFError",TRUE);
343         }
344         elseif(!$_FILES['userfile']['size'] > 0 )
345         {
346           msg_dialog::display(_("Error"), sprintf(_("Cannot read uploaded file: %s"), _("file is empty")), ERROR_DIALOG);
347           $smarty->assign("LDIFError",TRUE);
348         }
349         /* Is there a tmp file, which we can use ? */
350         elseif(!file_exists($_FILES['userfile']['tmp_name']))
351         {
352           msg_dialog::display(_("Error"), sprintf(_("Cannot read uploaded file: %s"), _("file not found")), ERROR_DIALOG);
353           $smarty->assign("LDIFError",TRUE);
354         }
355         elseif(!$handle = @fopen($_FILES['userfile']['tmp_name'],"r"))
356         {
357           msg_dialog::display(_("Error"), sprintf(_("Cannot read uploaded file: %s"), _("file not readable")), ERROR_DIALOG);
358           $smarty->assign("LDIFError",TRUE);
359         }
360         else
361         {
362           $smarty->assign("fileup",TRUE);
363           $str = "";
366           /* Reading content */
367           while(!feof($handle)) {
368             $str .= fread($handle,1024);
369           }
371           $lines = preg_split("/\n/",$str);
372           $anz  = 0;
373           $rest = 0;
374           $data = array();
376           /* check colum count */
377           if(is_array($lines))
378             foreach($lines as $line) {
379               /* continue if theres a comment */
380               if(substr(trim($line),0,1)=="#"){
381                 continue;
382               }
384               $line= str_replace ("\t","",$line);
385               $cells  = explode(",",$line )  ;
387               if(count($cells)> $anz ){
388                 $anz = count($cells);
389               }
390             }
392           /* At least one entry */
393           if($anz >1) {
395             /* Generate array with outpu info  */
396             if(is_array($lines))
397               foreach($lines as $line) {
398                 $rest = 0;
399                 $cnt  = 0;
401                 /* dont use comments or empty lines */
402                 if((substr(trim($line),0,1)=="#")||(empty($line))){
403                   continue;
404                 }
406                 /* replace \t to , */
407                 $line= str_replace ("\t"  ,"" ,$line);
409                 /* get all elements  */
410                 $cells  = explode(",",$line )  ;
412                 /* attach all elements to data array */
413                 if(is_array($cells))
414                   foreach($cells as $cell) {
415                     if(!empty($cell)) {
416                       $cnt++; 
417                       $data[]=trim($cell);
418                     }
419                   }
421                 /* cell count less than anz, attach some empty fields */
422                 if(($cnt != $anz)&&(!empty($cnt))) {
423                   $rest = $anz - $cnt;
424                   for($i = 0 ; $i < $rest ; $i ++){
425                     $data[] = " ";
426                   }
427                 }
428               }    
430             unset($this->csvinfo['sorteddata']);
431             unset($this->csvinfo['colsstr']);
432             unset($this->csvinfo['sorteddata']);
434             $this->csvinfo['cols']        = $anz;
435             $this->csvinfo['data']        = array();
436             $this->csvinfo['data']        = $data;
437             $this->csvinfo['count']       = count($this->csvinfo['data']);
439             if($this->csvinfo['count']> (6* $this->csvinfo['cols'])) {
440               /* only show 6 rows in ouptuttablei */
441               $datouttemp =  array_chunk($this->csvinfo['data'],(6* $this->csvinfo['cols']));
442               $this->csvinfo['dataout']=$datouttemp[0];
443               $this->csvinfo['shownrowscount'] = 6;
444             } else {
445               $this->csvinfo['shownrowscount'] = (count($this->csvinfo['data']))/$this->csvinfo['cols'];
446               $this->csvinfo['dataout']= $this->csvinfo['data'];  
447             }
449             $this->csvinfo['tplid']       = $_POST['template'];
450             $this->csvinfo['templatestr'] = $this->csvinfo['arrtemplates' ][$this->csvinfo['tplid']];
451             $this->csvinfo['count']       = count($this->csvinfo['data']);
452             $this->csvinfo['rows']        = (count($this->csvinfo['data'])/$anz);
454             $i =  0; 
455             $tmp = $tmp2= array();
456             if(is_array($this->csvinfo['dataout']))
457               foreach($this->csvinfo['dataout'] as $dat){
458                 $tmp[]= $dat;
459                 $i++;
460                 if($i >=$this->csvinfo['cols']){
461                   $i = 0;
462                   $tmp2[] = $tmp;
463                   $tmp = array();
464                 }
466               }
468             /* Set Templateid  */
469             $smarty->assign("tplid",$this->csvinfo['tplid']);
471             /* Set Template  */
472             $smarty->assign("tpl",$this->csvinfo['templatestr']);
474             /* Temp var 1 */
475             $smarty->assign("ia",1); 
477             /* Temp var 2 */
478             $smarty->assign("i",0); 
480             /* Num rows    */
481             $smarty->assign("rows",$this->csvinfo['shownrowscount']);
484             for($i  = 0 ; $i < $anz; $i ++)
485               $this->csvinfo['arr_selected'][]="0";
487             $smarty->assign("selectedattrs",$this->csvinfo['arr_selected']);
489             /* Entrie count5 */
490             $smarty->assign("anz",$this->csvinfo['cols']);                                                    
492             /* Array with data */
493             $smarty->assign("data",$tmp2);   
495             @fclose($handle);
496           } else {
497             $smarty->assign("tpl",$this->csvinfo['attr'][$_POST['template']]);
498             $smarty->assign("LDIFError",TRUE);
499             $smarty->assign("fileup",FALSE);
500             msg_dialog::display(_("Error"), _("Cannot find CSV data in the selected file!"), ERROR_DIALOG);
501           }
502         }
503       }
504     }                                              
506     /* Show main page */
507     return ($smarty->fetch (get_template_path('contentcsv.tpl', TRUE)));
508   }
512 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
513 ?>