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 change_password($this->usertab->dn,$password);
224 }
225 }
226 }
228 $pointsbefore = FALSE;
229 $pointsafter = FALSE;
231 /* Get Attributs for Tableheadline */
232 $this->csvinfo['colsstr'] = array();
233 for($i =0; $i <= $this->csvinfo['cols']; $i++) {
234 if(!empty($_POST[('row'.$i)])){
235 $this->csvinfo['colsstr'][$i] = $this->csvinfo['attr'][$_POST[('row'.$i)]];
236 }
237 }
239 /*Create array with data for the template */
240 if($failing == FALSE){
242 $dataouts= array();
243 for($i =1; $i <= $this->csvinfo['shownrowscount']; $i++) {
244 if(is_array($this->csvinfo['sorteddata'][($i-1)])){
245 foreach($this->csvinfo['sorteddata'][($i-1)] as $dat){
246 $dataouts[]=$dat;
247 }
248 }
249 }
251 if($this->csvinfo['rows']> $this->csvinfo['shownrowscount']){
252 $pointsafter = TRUE;
253 }
254 } else {
255 $pointsbefore = TRUE;
256 $pointsafter = TRUE;
258 $begin = $failing -3;
260 if($begin <0) {
261 $begin =0;
262 $pointsbefore = FALSE;
263 }
265 $end = $failing + 2;
267 if($end > $this->csvinfo['rows']) {
268 $end = $this->csvinfo['rows']+1;
269 $pointsafter = FALSE;
270 }
271 $this->csvinfo['shownrowscount']=$end - $begin;
273 if($this->csvinfo['shownrowscount']> $this->csvinfo['rows'])$this->csvinfo['shownrowscount']=$this->csvinfo['rows'];
275 $dataouts = array();
276 for($i =$begin; $i <= $end; $i++) {
277 if(is_array($this->csvinfo['sorteddata'][($i-1)])){
278 foreach($this->csvinfo['sorteddata'][($i-1)] as $dat){
279 $dataouts[]=$dat;
280 }
281 }
282 }
283 }
284 $tmparr2 = $this->csvinfo['colsstr'];
285 $tmparr2[]=_("status");
287 /* Error? */
288 if ($failing){
289 msg_dialog::display(_("Error"), sprintf(_("Cannot add entry %s!"), bold($failing)), ERROR_DIALOG);
290 }
291 $smarty->assign("error",$failing);
293 /* Set vars to smarty */
294 $smarty->assign("cols",count($tmparr2));
295 $smarty->assign("anz" ,$this->csvinfo['count']);
296 $smarty->assign("rows",$this->csvinfo['shownrowscount']);
299 $cnt = 0 ;
300 $tmp2 = $tmp3 = array();
301 if(is_array($dataouts))
302 foreach($dataouts as $tmp){
303 $tmp2[] = $tmp;
304 $cnt ++ ;
305 if($cnt >= count($tmparr2)){
306 $tmp3[] = $tmp2;
307 $tmp2= array();
308 $cnt = 0;
309 }
310 }
311 $smarty->assign("head",$tmparr2);
312 $smarty->assign("data",$tmp3);
314 /* Set other vars */
315 $smarty->assign("i",1);
316 $smarty->assign("ie",0);
317 $smarty->assign("tplid",$this->csvinfo['tplid']);
319 $smarty->assign("pointsafter",$pointsafter);
320 $smarty->assign("pointsbefore",$pointsbefore);
321 } else {
322 /* Set Template ID */
323 $tplid = $_POST['tplid'];
326 $smarty->assign("tpl",$arrtemplates[$tplid]);
327 msg_dialog::display(_("Information"), _("Nothing to import!"), INFO_DIALOG);
328 }
330 /* If theres a File uploaded */
331 } else {
332 /* Check if theres a file uploaded */
333 if(!empty($_FILES['userfile']['name'])){
335 $handle = NULL;
337 if((!isset($_FILES['userfile']['name']))||(!isset($_POST['fileup'])))
338 {
339 msg_dialog::display(_("Error"), sprintf(_("Cannot read uploaded file: %s"), _("file not found")), ERROR_DIALOG);
340 $smarty->assign("LDIFError",TRUE);
341 }
342 elseif(!$_FILES['userfile']['size'] > 0 )
343 {
344 msg_dialog::display(_("Error"), sprintf(_("Cannot read uploaded file: %s"), _("file is empty")), ERROR_DIALOG);
345 $smarty->assign("LDIFError",TRUE);
346 }
347 /* Is there a tmp file, which we can use ? */
348 elseif(!file_exists($_FILES['userfile']['tmp_name']))
349 {
350 msg_dialog::display(_("Error"), sprintf(_("Cannot read uploaded file: %s"), _("file not found")), ERROR_DIALOG);
351 $smarty->assign("LDIFError",TRUE);
352 }
353 elseif(!$handle = @fopen($_FILES['userfile']['tmp_name'],"r"))
354 {
355 msg_dialog::display(_("Error"), sprintf(_("Cannot read uploaded file: %s"), _("file not readable")), ERROR_DIALOG);
356 $smarty->assign("LDIFError",TRUE);
357 }
358 else
359 {
360 $smarty->assign("fileup",TRUE);
361 $str = "";
364 /* Reading content */
365 while(!feof($handle)) {
366 $str .= fread($handle,1024);
367 }
369 $lines = preg_split("/\n/",$str);
370 $anz = 0;
371 $rest = 0;
372 $data = array();
374 /* check colum count */
375 if(is_array($lines))
376 foreach($lines as $line) {
377 /* continue if theres a comment */
378 if(substr(trim($line),0,1)=="#"){
379 continue;
380 }
382 $line= str_replace ("\t","",$line);
383 $cells = explode(",",$line ) ;
385 if(count($cells)> $anz ){
386 $anz = count($cells);
387 }
388 }
390 /* At least one entry */
391 if($anz >1) {
393 /* Generate array with outpu info */
394 if(is_array($lines))
395 foreach($lines as $line) {
396 $rest = 0;
397 $cnt = 0;
399 /* dont use comments or empty lines */
400 if((substr(trim($line),0,1)=="#")||(empty($line))){
401 continue;
402 }
404 /* replace \t to , */
405 $line= str_replace ("\t" ,"" ,$line);
407 /* get all elements */
408 $cells = explode(",",$line ) ;
410 /* attach all elements to data array */
411 if(is_array($cells))
412 foreach($cells as $cell) {
413 if(!empty($cell)) {
414 $cnt++;
415 $data[]=trim($cell);
416 }
417 }
419 /* cell count less than anz, attach some empty fields */
420 if(($cnt != $anz)&&(!empty($cnt))) {
421 $rest = $anz - $cnt;
422 for($i = 0 ; $i < $rest ; $i ++){
423 $data[] = " ";
424 }
425 }
426 }
428 unset($this->csvinfo['sorteddata']);
429 unset($this->csvinfo['colsstr']);
430 unset($this->csvinfo['sorteddata']);
432 $this->csvinfo['cols'] = $anz;
433 $this->csvinfo['data'] = array();
434 $this->csvinfo['data'] = $data;
435 $this->csvinfo['count'] = count($this->csvinfo['data']);
437 if($this->csvinfo['count']> (6* $this->csvinfo['cols'])) {
438 /* only show 6 rows in ouptuttablei */
439 $datouttemp = array_chunk($this->csvinfo['data'],(6* $this->csvinfo['cols']));
440 $this->csvinfo['dataout']=$datouttemp[0];
441 $this->csvinfo['shownrowscount'] = 6;
442 } else {
443 $this->csvinfo['shownrowscount'] = (count($this->csvinfo['data']))/$this->csvinfo['cols'];
444 $this->csvinfo['dataout']= $this->csvinfo['data'];
445 }
447 $this->csvinfo['tplid'] = $_POST['template'];
448 $this->csvinfo['templatestr'] = $this->csvinfo['arrtemplates' ][$this->csvinfo['tplid']];
449 $this->csvinfo['count'] = count($this->csvinfo['data']);
450 $this->csvinfo['rows'] = (count($this->csvinfo['data'])/$anz);
452 $i = 0;
453 $tmp = $tmp2= array();
454 if(is_array($this->csvinfo['dataout']))
455 foreach($this->csvinfo['dataout'] as $dat){
456 $tmp[]= $dat;
457 $i++;
458 if($i >=$this->csvinfo['cols']){
459 $i = 0;
460 $tmp2[] = $tmp;
461 $tmp = array();
462 }
464 }
466 /* Set Templateid */
467 $smarty->assign("tplid",$this->csvinfo['tplid']);
469 /* Set Template */
470 $smarty->assign("tpl",$this->csvinfo['templatestr']);
472 /* Temp var 1 */
473 $smarty->assign("ia",1);
475 /* Temp var 2 */
476 $smarty->assign("i",0);
478 /* Num rows */
479 $smarty->assign("rows",$this->csvinfo['shownrowscount']);
482 for($i = 0 ; $i < $anz; $i ++)
483 $this->csvinfo['arr_selected'][]="0";
485 $smarty->assign("selectedattrs",$this->csvinfo['arr_selected']);
487 /* Entrie count5 */
488 $smarty->assign("anz",$this->csvinfo['cols']);
490 /* Array with data */
491 $smarty->assign("data",$tmp2);
493 @fclose($handle);
494 } else {
495 $smarty->assign("tpl",$this->csvinfo['attr'][$_POST['template']]);
496 $smarty->assign("LDIFError",TRUE);
497 $smarty->assign("fileup",FALSE);
498 msg_dialog::display(_("Error"), _("Cannot find CSV data in the selected file!"), ERROR_DIALOG);
499 }
500 }
501 }
502 }
504 /* Show main page */
505 return ($smarty->fetch (get_template_path('contentcsv.tpl', TRUE)));
506 }
508 }
510 // vim:tabstop=2:expandtab:shiftwidth=2:filetype=php:syntax:ruler:
511 ?>