Teil 1 von: Usability und Lokalisierung de und de_DE (neu)
[kivitendo-erp.git] / bin / mozilla / admin.pl
1 #=====================================================================
2 # LX-Office ERP
3 # Copyright (C) 2004
4 # Based on SQL-Ledger Version 2.1.9
5 # Web http://www.lx-office.org
6 #
7 #=====================================================================
8 # SQL-Ledger Accounting
9 # Copyright (c) 2002
10 #
11 #  Author: Dieter Simader
12 #   Email: dsimader@sql-ledger.org
13 #     Web: http://www.sql-ledger.org
14 #
15 #
16 # This program is free software; you can redistribute it and/or modify
17 # it under the terms of the GNU General Public License as published by
18 # the Free Software Foundation; either version 2 of the License, or
19 # (at your option) any later version.
20 #
21 # This program is distributed in the hope that it will be useful,
22 # but WITHOUT ANY WARRANTY; without even the implied warranty of
23 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
24 # GNU General Public License for more details.
25 # You should have received a copy of the GNU General Public License
26 # along with this program; if not, write to the Free Software
27 # Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
28 #======================================================================
29 #
30 # setup module
31 # add/edit/delete users
32 #
33 #======================================================================
34
35 use DBI;
36 use CGI;
37 use English qw(-no_match_vars);
38 use Fcntl;
39 use File::Copy;
40 use IO::File;
41 use POSIX qw(strftime);
42 use Sys::Hostname;
43
44 use SL::Auth;
45 use SL::Form;
46 use SL::Mailer;
47 use SL::User;
48 use SL::Common;
49 use SL::Inifile;
50 use SL::DBUpgrade2;
51 use SL::DBUtils;
52
53 require "bin/mozilla/common.pl";
54 require "bin/mozilla/admin_groups.pl";
55
56 use strict;
57
58 our $cgi;
59 our $form;
60 our $locale;
61 our $auth;
62
63 sub run {
64   $::lxdebug->enter_sub;
65   my $session_result = shift;
66
67   $cgi    = $::cgi;
68   $form   = $::form;
69   $locale = $::locale;
70   $auth   = $::auth;
71
72   $::auth->set_session_value('rpw', $::form->{rpw}) if $session_result == SL::Auth->SESSION_OK;
73
74   $form->{stylesheet} = "lx-office-erp.css";
75   $form->{favicon}    = "favicon.ico";
76
77   if ($form->{action}) {
78     if ($auth->authenticate_root($form->{rpw}, 0) != $auth->OK()) {
79       $form->{error_message} = $locale->text('Incorrect Password!');
80       adminlogin();
81     } else {
82       $auth->create_or_refresh_session() if ($auth->session_tables_present());
83       call_sub($locale->findsub($form->{action}));
84     }
85   } elsif ($auth->authenticate_root($form->{rpw}, 0) == $auth->OK()) {
86
87     $auth->create_or_refresh_session() if ($auth->session_tables_present());
88
89     login();
90   } else {
91     # if there are no drivers bail out
92     $form->error($locale->text('No Database Drivers available!'))
93       unless (User->dbdrivers);
94
95     adminlogin();
96   }
97   $::lxdebug->leave_sub;
98 }
99
100 sub adminlogin {
101   my $form   = $main::form;
102   my $locale = $main::locale;
103
104   $form->{title} = qq|Lx-Office ERP $form->{version} | . $locale->text('Administration');
105
106   $form->header();
107   print $form->parse_html_template('admin/adminlogin');
108 }
109
110 sub login {
111   check_auth_db_and_tables();
112   list_users();
113 }
114
115 sub logout {
116   $main::auth->destroy_session();
117   adminlogin();
118 }
119
120 sub check_auth_db_and_tables {
121   my $form   = $main::form;
122   my $locale = $main::locale;
123
124   my %params;
125
126   map { $params{"db_${_}"} = $main::auth->{DB_config}->{$_} } keys %{ $auth->{DB_config} };
127
128   if (!$main::auth->check_database()) {
129     $form->{title} = $locale->text('Authentification database creation');
130     $form->header();
131     print $form->parse_html_template('admin/check_auth_database', \%params);
132
133     ::end_of_request();
134   }
135
136   if (!$main::auth->check_tables()) {
137     $form->{title} = $locale->text('Authentification tables creation');
138     $form->header();
139     print $form->parse_html_template('admin/check_auth_tables', \%params);
140
141     ::end_of_request();
142   }
143
144   if (-f $main::memberfile) {
145     my $memberdir = "";
146
147     if ($main::memberfile =~ m|^.*/|) {
148       $memberdir = $&;
149     }
150
151     my $backupdir = "${memberdir}member-file-migration";
152
153     $form->{title} = $locale->text('User data migration');
154     $form->header();
155     print $form->parse_html_template('admin/user_migration', { 'memberfile' => $main::memberfile,
156                                                                'backupdir'  => $backupdir });
157
158     ::end_of_request();
159   }
160 }
161
162 sub create_auth_db {
163   my $form = $main::form;
164
165   $main::auth->create_database('superuser'          => $form->{db_superuser},
166                                'superuser_password' => $form->{db_superuser_password},
167                                'template'           => $form->{db_template});
168   login();
169 }
170
171 sub create_auth_tables {
172   my $form   = $main::form;
173   my $locale = $main::locale;
174
175   $main::auth->create_tables();
176   $main::auth->set_session_value('rpw', $form->{rpw});
177   $main::auth->create_or_refresh_session();
178
179   if (!-f $main::memberfile) {
180     # New installation -- create a standard group with full access
181     my %members;
182     my $group = {
183       'name'        => $locale->text('Full Access'),
184       'description' => $locale->text('Full access to all functions'),
185       'rights'      => { map { $_ => 1 } SL::Auth::all_rights() },
186       'members'     => [ map { $_->{id} } values %members ],
187     };
188
189     $main::auth->save_group($group);
190   }
191
192   login();
193 }
194
195 sub migrate_users {
196   $main::lxdebug->enter_sub();
197
198   my $form      = $main::form;
199   my $locale    = $main::locale;
200
201   my $memberdir = "";
202
203   if ($main::memberfile =~ m|^.*/|) {
204     $memberdir = $&;
205   }
206
207   my $backupdir = "${memberdir}member-file-migration";
208
209   if (! -d $backupdir && !mkdir $backupdir, 0700) {
210     $form->error(sprintf($locale->text('The directory "%s" could not be created:\n%s'), $backupdir, $!));
211   }
212
213   copy $main::memberfile, "users/member-file-migration/members";
214
215   my $in = IO::File->new($main::memberfile, "r");
216
217   $form->error($locale->text('Could not open the old memberfile.')) if (!$in);
218
219   my (%members, $login);
220
221   while (<$in>) {
222     chomp;
223
224     next if (m/^\s*\#/);
225
226     if (m/^\[.*\]/) {
227       $login = $_;
228       $login =~ s/(\[|\])//g;
229       $login =~ s/^\s*//;
230       $login =~ s/\s*$//;
231
232       $members{$login} = { "login" => $login };
233       next;
234     }
235
236     if ($login && m/=/) {
237       my ($key, $value) = split m/\s*=\s*/, $_, 2;
238       $key   =~ s|^\s*||;
239       $value =~ s|\s*$||;
240
241       $value =~ s|\\r||g;
242       $value =~ s|\\n|\n|g;
243
244       $members{$login}->{$key} = $value;
245     }
246   }
247
248   $in->close();
249
250   delete $members{"root login"};
251
252   map { $_->{dbpasswd} = unpack 'u', $_->{dbpasswd} } values %members;
253
254   while (my ($login, $params) = each %members) {
255     $main::auth->save_user($login, %{ $params });
256     $main::auth->change_password($login, $params->{password}, 1);
257
258     my $conf_file = "${memberdir}${login}.conf";
259
260     if (-f $conf_file) {
261       copy   $conf_file, "${backupdir}/${login}.conf";
262       unlink $conf_file;
263     }
264   }
265
266   unlink $main::memberfile;
267
268   my @member_list = sort { lc $a->{login} cmp lc $b->{login} } values %members;
269
270   $form->{title} = $locale->text('User data migration');
271   $form->header();
272   print $form->parse_html_template('admin/user_migration_done', { 'MEMBERS' => \@member_list });
273
274   $main::lxdebug->leave_sub();
275 }
276
277 sub create_standard_group_ask {
278   my $form   = $main::form;
279   my $locale = $main::locale;
280
281   $form->{title} = $locale->text('Create a standard group');
282
283   $form->header();
284   print $form->parse_html_template("admin/create_standard_group_ask");
285 }
286
287 sub create_standard_group {
288   my $form    = $main::form;
289   my $locale  = $main::locale;
290
291   my %members = $main::auth->read_all_users();
292
293   my $groups  = $main::auth->read_groups();
294
295   foreach my $group (values %{$groups}) {
296     if (($form->{group_id} != $group->{id})
297         && ($form->{name} eq $group->{name})) {
298       $form->show_generic_error($locale->text("A group with that name does already exist."));
299     }
300   }
301
302   my $group = {
303     'name'        => $locale->text('Full Access'),
304     'description' => $locale->text('Full access to all functions'),
305     'rights'      => { map { $_ => 1 } SL::Auth::all_rights() },
306     'members'     => [ map { $_->{id} } values %members ],
307   };
308
309   $main::auth->save_group($group);
310
311   user_migration_complete(1);
312 }
313
314 sub dont_create_standard_group {
315   user_migration_complete(0);
316 }
317
318 sub user_migration_complete {
319   my $standard_group_created = shift;
320
321   my $form                   = $main::form;
322   my $locale                 = $main::locale;
323
324   $form->{title} = $locale->text('User migration complete');
325   $form->header();
326
327   print $form->parse_html_template('admin/user_migration_complete', { 'standard_group_created' => $standard_group_created });
328 }
329
330 sub list_users {
331   my $form    = $main::form;
332   my $locale  = $main::locale;
333
334   my %members = $main::auth->read_all_users();
335
336   delete $members{"root login"};
337
338   map { $_->{templates} =~ s|.*/||; } values %members;
339
340   $form->{title}   = "Lx-Office ERP " . $locale->text('Administration');
341   $form->{LOCKED}  = -e "$main::userspath/nologin";
342   $form->{MEMBERS} = [ @members{sort { lc $a cmp lc $b } keys %members} ];
343
344   $form->header();
345   print $form->parse_html_template("admin/list_users");
346 }
347
348 sub add_user {
349   my $form         = $main::form;
350   my $locale       = $main::locale;
351
352   $form->{title}   = "Lx-Office ERP " . $locale->text('Administration') . " / " . $locale->text('Add User');
353
354 # Note: Menu Style 'v3' is not compatible to all browsers!
355 # "menustyle"    => "old" sets the HTML Menu to default.
356   my $myconfig     = {
357     "vclimit"      => 200,
358     "countrycode"  => "de",
359     "numberformat" => "1.000,00",
360     "dateformat"   => "dd.mm.yy",
361     "stylesheet"   => "lx-office-erp.css",
362     "menustyle"    => "old",
363   };
364
365   edit_user_form($myconfig);
366 }
367
368 sub edit_user {
369   my $form       = $main::form;
370   my $locale     = $main::locale;
371
372   $form->{title} = "Lx-Office ERP " . $locale->text('Administration') . " / " . $locale->text('Edit User');
373   $form->{edit}  = 1;
374
375   $form->isblank("login", $locale->text("The login is missing."));
376
377   # get user
378   my $myconfig = new User($form->{login});
379
380   # strip basedir from templates directory
381   $myconfig->{templates} =~ s|.*/||;
382
383   edit_user_form($myconfig);
384 }
385
386 sub edit_user_form {
387   my ($myconfig) = @_;
388
389   my $form       = $main::form;
390   my $locale     = $main::locale;
391
392   my @valid_dateformats = qw(mm-dd-yy mm/dd/yy dd-mm-yy dd/mm/yy dd.mm.yy yyyy-mm-dd);
393   $form->{ALL_DATEFORMATS} = [ map { { "format" => $_, "selected" => $_ eq $myconfig->{dateformat} } } @valid_dateformats ];
394
395   my @valid_numberformats = ('1,000.00', '1000.00', '1.000,00', '1000,00');
396   $form->{ALL_NUMBERFORMATS} = [ map { { "format" => $_, "selected" => $_ eq $myconfig->{numberformat} } } @valid_numberformats ];
397
398   my %countrycodes = User->country_codes;
399   $form->{ALL_COUNTRYCODES} = [];
400   foreach my $countrycode (sort { $countrycodes{$a} cmp $countrycodes{$b} } keys %countrycodes) {
401     push @{ $form->{ALL_COUNTRYCODES} }, { "value"    => $countrycode,
402                                            "name"     => $countrycodes{$countrycode},
403                                            "selected" => $countrycode eq $myconfig->{countrycode} };
404   }
405
406   # is there a templates basedir
407   if (!-d "$main::templates") {
408     $form->error(sprintf($locale->text("The directory %s does not exist."), $main::templates));
409   }
410
411   opendir TEMPLATEDIR, "$main::templates/." or $form->error("$main::templates : $ERRNO");
412   my @all     = readdir(TEMPLATEDIR);
413   my @alldir  = sort grep { -d "$main::templates/$_" && !/^\.\.?$/ } @all;
414   my @allhtml = sort grep { -f "$main::templates/$_" && /\.html$/ } @all;
415   closedir TEMPLATEDIR;
416
417   @alldir = grep !/\.(html|tex|sty|odt|xml|txb)$/, @alldir;
418   @alldir = grep !/^(webpages|\.svn)$/, @alldir;
419
420   @allhtml = reverse grep !/Default/, @allhtml;
421   push @allhtml, 'Default';
422   @allhtml = reverse @allhtml;
423
424   $form->{ALL_TEMPLATES} = [ map { { "name", => $_, "selected" => $_ eq $myconfig->{templates} } } @alldir ];
425
426   my $lastitem = $allhtml[0];
427   $lastitem =~ s/-.*//g;
428   $form->{ALL_MASTER_TEMPLATES} = [ { "name" => $lastitem, "selected" => $lastitem eq "German" } ];
429   foreach my $item (@allhtml) {
430     $item =~ s/-.*//g;
431     next if ($item eq $lastitem);
432
433     push @{ $form->{ALL_MASTER_TEMPLATES} }, { "name" => $item, "selected" => $item eq "German" };
434     $lastitem = $item;
435   }
436
437   # css dir has styles that are not intended as general layouts.
438   # reverting to hardcoded list
439   $form->{ALL_STYLESHEETS} = [ map { { "name" => $_, "selected" => $_ eq $myconfig->{stylesheet} } } qw(lx-office-erp.css Win2000.css) ];
440
441   $form->{"menustyle_" . $myconfig->{menustyle} } = 1;
442
443   map { $form->{"myc_${_}"} = $myconfig->{$_} } keys %{ $myconfig };
444
445   my $groups = [];
446
447   if ($form->{edit}) {
448     my $user_id    = $main::auth->get_user_id($form->{login});
449     my $all_groups = $main::auth->read_groups();
450
451     foreach my $group (values %{ $all_groups }) {
452       push @{ $groups }, $group if (grep { $user_id == $_ } @{ $group->{members} });
453     }
454
455     $groups = [ sort { lc $a->{name} cmp lc $b->{name} } @{ $groups } ];
456   }
457
458   $form->{CAN_CHANGE_PASSWORD} = $main::auth->can_change_password();
459
460   $form->header();
461   print $form->parse_html_template("admin/edit_user", { 'GROUPS' => $groups });
462 }
463
464 sub save_user {
465   my $form          = $main::form;
466   my $locale        = $main::locale;
467
468   $form->{dbdriver} = 'Pg';
469
470   # no spaces allowed in login name
471   $form->{login} =~ s|\s||g;
472   $form->isblank("login", $locale->text('Login name missing!'));
473
474   # check for duplicates
475   if (!$form->{edit}) {
476     my %members = $main::auth->read_all_users();
477     if ($members{$form->{login}}) {
478       $form->show_generic_error($locale->text('Another user with the login #1 does already exist.', $form->{login}), 'back_button' => 1);
479     }
480   }
481
482   # no spaces allowed in directories
483   ($form->{newtemplates}) = split / /, $form->{newtemplates};
484
485   if ($form->{newtemplates}) {
486     $form->{templates} = $form->{newtemplates};
487   } else {
488     $form->{templates} =
489       ($form->{usetemplates}) ? $form->{usetemplates} : $form->{login};
490   }
491
492   # is there a basedir
493   if (!-d "$main::templates") {
494     $form->error(sprintf($locale->text("The directory %s does not exist."), $main::templates));
495   }
496
497   # add base directory to $form->{templates}
498   $form->{templates} =~ s|.*/||;
499   $form->{templates} =  "$main::templates/$form->{templates}";
500
501   my $myconfig = new User($form->{login});
502
503   $form->isblank("dbname", $locale->text('Dataset missing!'));
504   $form->isblank("dbuser", $locale->text('Database User missing!'));
505
506   foreach my $item (keys %{$form}) {
507     $myconfig->{$item} = $form->{$item};
508   }
509
510   delete $myconfig->{stylesheet};
511   if ($form->{userstylesheet}) {
512     $myconfig->{stylesheet} = $form->{userstylesheet};
513   }
514
515   $myconfig->save_member();
516
517   if ($main::auth->can_change_password()
518       && defined $form->{new_password}
519       && ($form->{new_password} ne '********')) {
520     $main::auth->change_password($form->{login}, $form->{new_password});
521   }
522
523   $form->{templates}       =~ s|.*/||;
524   $form->{templates}       =  "$main::templates/$form->{templates}";
525   $form->{mastertemplates} =~ s|.*/||;
526
527   # create user template directory and copy master files
528   if (!-d "$form->{templates}") {
529     umask(002);
530
531     if (mkdir "$form->{templates}", oct("771")) {
532
533       umask(007);
534
535       # copy templates to the directory
536       opendir TEMPLATEDIR, "$main::templates/." or $form->error("$main::templates : $ERRNO");
537       my @templates = grep /$form->{mastertemplates}.*?\.(html|tex|sty|odt|xml|txb)$/,
538         readdir TEMPLATEDIR;
539       closedir TEMPLATEDIR;
540
541       foreach my $file (@templates) {
542         open(TEMP, "$main::templates/$file")
543           or $form->error("$main::templates/$file : $ERRNO");
544
545         $file =~ s/\Q$form->{mastertemplates}\E-//;
546         open(NEW, ">$form->{templates}/$file")
547           or $form->error("$form->{templates}/$file : $ERRNO");
548
549         while (my $line = <TEMP>) {
550           print NEW $line;
551         }
552         close(TEMP);
553         close(NEW);
554       }
555     } else {
556       $form->error("$ERRNO: $form->{templates}");
557     }
558   }
559
560   # Add new user to his groups.
561   if (ref $form->{new_user_group_ids} eq 'ARRAY') {
562     my $all_groups = $main::auth->read_groups();
563     my %user       = $main::auth->read_user($form->{login});
564
565     foreach my $group_id (@{ $form->{new_user_group_ids} }) {
566       my $group = $all_groups->{$group_id};
567
568       next if !$group;
569
570       push @{ $group->{members} }, $user{id};
571       $main::auth->save_group($group);
572     }
573   }
574
575   $form->redirect($locale->text('User saved!'));
576
577 }
578
579 sub save_user_as_new {
580   my $form       = $main::form;
581
582   $form->{login} = $form->{new_user_login};
583   delete @{$form}{qw(edit new_user_login)};
584
585   save_user();
586 }
587
588 sub delete_user {
589   my $form      = $main::form;
590   my $locale    = $main::locale;
591
592   my %members   = $main::auth->read_all_users();
593   my $templates = $members{$form->{login}}->{templates};
594
595   $main::auth->delete_user($form->{login});
596
597   if ($templates) {
598     my $templates_in_use = 0;
599
600     foreach my $login (keys %members) {
601       next if $form->{login} eq $login;
602       next if $members{$login}->{templates} ne $templates;
603       $templates_in_use = 1;
604       last;
605     }
606
607     if (!$templates_in_use && -d $templates) {
608       unlink <$templates/*>;
609       rmdir $templates;
610     }
611   }
612
613   $form->redirect($locale->text('User deleted!'));
614
615 }
616
617 sub login_name {
618   my $login = shift;
619
620   $login =~ s/\[\]//g;
621   return ($login) ? $login : undef;
622
623 }
624
625 sub get_value {
626   my $line           = shift;
627   my ($null, $value) = split(/=/, $line, 2);
628
629   # remove comments
630   $value =~ s/\s#.*//g;
631
632   # remove any trailing whitespace
633   $value =~ s/^\s*(.*?)\s*$/$1/;
634
635   $value;
636 }
637
638 sub pg_database_administration {
639   my $form = $main::form;
640
641   $form->{dbdriver} = 'Pg';
642   dbselect_source();
643
644 }
645
646 sub dbselect_source {
647   my $form           = $main::form;
648   my $locale         = $main::locale;
649
650   $form->{dbport}    = '5432';
651   $form->{dbuser}    = 'lxoffice';
652   $form->{dbdefault} = 'template1';
653   $form->{dbhost}    = 'localhost';
654
655   $form->{title}     = "Lx-Office ERP / " . $locale->text('Database Administration');
656
657   # Intentionnaly disabled unless fixed to work with the authentication DB.
658   $form->{ALLOW_DBBACKUP} = 0; # "$pg_dump_exe" ne "DISABLED";
659
660   $form->header();
661   print $form->parse_html_template("admin/dbadmin");
662 }
663
664 sub test_db_connection {
665   my $form   = $main::form;
666   my $locale = $main::locale;
667
668   $form->{dbdriver} = 'Pg';
669   User::dbconnect_vars($form, $form->{dbname});
670
671   my $dbh = DBI->connect($form->{dbconnect}, $form->{dbuser}, $form->{dbpasswd});
672
673   $form->{connection_ok} = $dbh ? 1 : 0;
674   $form->{errstr}        = $DBI::errstr;
675
676   $dbh->disconnect() if ($dbh);
677
678   $form->{title} = $locale->text('Database Connection Test');
679   $form->header();
680   print $form->parse_html_template("admin/test_db_connection");
681 }
682
683 sub continue {
684   call_sub($main::form->{"nextsub"});
685 }
686
687 sub update_dataset {
688   my $form              = $main::form;
689   my $locale            = $main::locale;
690
691   $form->{title}        = "Lx-Office ERP " . $locale->text('Database Administration') . " / " . $locale->text('Update Dataset');
692
693   my @need_updates      = User->dbneedsupdate($form);
694   $form->{NEED_UPDATES} = \@need_updates;
695   $form->{ALL_UPDATED}  = !scalar @need_updates;
696
697   $form->header();
698   print $form->parse_html_template("admin/update_dataset");
699 }
700
701 sub dbupdate {
702   my $form            = $main::form;
703   my $locale          = $main::locale;
704
705   $form->{stylesheet} = "lx-office-erp.css";
706   $form->{title}      = $locale->text("Dataset upgrade");
707   $form->header();
708
709   my $rowcount           = $form->{rowcount} * 1;
710   my @update_rows        = grep { $form->{"update_$_"} } (1 .. $rowcount);
711   $form->{NOTHING_TO_DO} = !scalar @update_rows;
712   my $saved_form         = save_form();
713
714   $| = 1;
715
716   print $form->parse_html_template("admin/dbupgrade_all_header");
717
718   foreach my $i (@update_rows) {
719     restore_form($saved_form);
720
721     map { $form->{$_} = $form->{"${_}_${i}"} } qw(dbname dbdriver dbhost dbport dbuser dbpasswd);
722
723     my $controls = parse_dbupdate_controls($form, $form->{dbdriver});
724
725     print $form->parse_html_template("admin/dbupgrade_header");
726
727     $form->{dbupdate}        = $form->{dbname};
728     $form->{$form->{dbname}} = 1;
729
730     User->dbupdate($form);
731     User->dbupdate2($form, $controls);
732
733     print $form->parse_html_template("admin/dbupgrade_footer");
734   }
735
736   print $form->parse_html_template("admin/dbupgrade_all_done");
737 }
738
739 sub create_dataset {
740   my $form           = $main::form;
741   my $locale         = $main::locale;
742
743   $form->{dbsources} = join " ", map { "[${_}]" } sort User->dbsources($form);
744
745   $form->{CHARTS}    = [];
746
747   opendir SQLDIR, "sql/." or $form->error($ERRNO);
748   foreach my $item (sort grep /-chart\.sql\z/, readdir SQLDIR) {
749     next if ($item eq 'Default-chart.sql');
750     $item =~ s/-chart\.sql//;
751     push @{ $form->{CHARTS} }, { "name"     => $item,
752                                  "selected" => $item eq "Germany-DATEV-SKR03EU" };
753   }
754   closedir SQLDIR;
755
756   my $default_charset = $main::dbcharset;
757   $default_charset ||= Common::DEFAULT_CHARSET;
758
759   my $cluster_encoding = User->dbclusterencoding($form);
760   if ($cluster_encoding && ($cluster_encoding =~ m/^(?:UTF-?8|UNICODE)$/i)) {
761     if ($main::dbcharset !~ m/^UTF-?8$/i) {
762       $form->show_generic_error($locale->text('The selected  PostgreSQL installation uses UTF-8 as its encoding. ' .
763                                               'Therefore you have to configure Lx-Office to use UTF-8 as well.'),
764                                 'back_button' => 1);
765     }
766
767     $form->{FORCE_DBENCODING} = 'UNICODE';
768
769   } else {
770     $form->{DBENCODINGS} = [];
771
772     foreach my $encoding (@Common::db_encodings) {
773       push @{ $form->{DBENCODINGS} }, { "dbencoding" => $encoding->{dbencoding},
774                                         "label"      => $encoding->{label},
775                                         "selected"   => $encoding->{charset} eq $default_charset };
776     }
777   }
778
779   $form->{title} = "Lx-Office ERP " . $locale->text('Database Administration') . " / " . $locale->text('Create Dataset');
780
781   $form->header();
782   print $form->parse_html_template("admin/create_dataset");
783 }
784
785 sub dbcreate {
786   my $form   = $main::form;
787   my $locale = $main::locale;
788
789   $form->isblank("db", $locale->text('Dataset missing!'));
790
791   User->dbcreate(\%$form);
792
793   $form->{title} = "Lx-Office ERP " . $locale->text('Database Administration') . " / " . $locale->text('Create Dataset');
794
795   $form->header();
796   print $form->parse_html_template("admin/dbcreate");
797 }
798
799 sub delete_dataset {
800   my $form      = $main::form;
801   my $locale    = $main::locale;
802
803   my @dbsources = User->dbsources_unused($form);
804   $form->error($locale->text('Nothing to delete!')) unless @dbsources;
805
806   $form->{title}     = "Lx-Office ERP " . $locale->text('Database Administration') . " / " . $locale->text('Delete Dataset');
807   $form->{DBSOURCES} = [ map { { "name", $_ } } sort @dbsources ];
808
809   $form->header();
810   print $form->parse_html_template("admin/delete_dataset");
811 }
812
813 sub dbdelete {
814   my $form   = $main::form;
815   my $locale = $main::locale;
816
817   if (!$form->{db}) {
818     $form->error($locale->text('No Dataset selected!'));
819   }
820
821   User->dbdelete(\%$form);
822
823   $form->{title} = "Lx-Office ERP " . $locale->text('Database Administration') . " / " . $locale->text('Delete Dataset');
824   $form->header();
825   print $form->parse_html_template("admin/dbdelete");
826 }
827
828 sub backup_dataset {
829   my $form       = $main::form;
830   my $locale     = $main::locale;
831
832   $form->{title} = "Lx-Office ERP " . $locale->text('Database Administration') . " / " . $locale->text('Backup Dataset');
833
834   if ("$main::pg_dump_exe" eq "DISABLED") {
835     $form->error($locale->text('Database backups and restorations are disabled in lx-erp.conf.'));
836   }
837
838   my @dbsources         = sort User->dbsources($form);
839   $form->{DATABASES}    = [ map { { "dbname" => $_ } } @dbsources ];
840   $form->{NO_DATABASES} = !scalar @dbsources;
841
842   my $username  = getpwuid $UID || "unknown-user";
843   my $hostname  = hostname() || "unknown-host";
844   $form->{from} = "Lx-Office Admin <${username}\@${hostname}>";
845
846   $form->header();
847   print $form->parse_html_template("admin/backup_dataset");
848 }
849
850 sub backup_dataset_start {
851   my $form       = $main::form;
852   my $locale     = $main::locale;
853
854   $form->{title} = "Lx-Office ERP " . $locale->text('Database Administration') . " / " . $locale->text('Backup Dataset');
855
856   $main::pg_dump_exe ||= "pg_dump";
857
858   if ("$main::pg_dump_exe" eq "DISABLED") {
859     $form->error($locale->text('Database backups and restorations are disabled in lx-erp.conf.'));
860   }
861
862   $form->isblank("dbname", $locale->text('The dataset name is missing.'));
863   $form->isblank("to", $locale->text('The email address is missing.')) if $form->{destination} eq "email";
864
865   my $tmpdir = "/tmp/lx_office_backup_" . Common->unique_id();
866   mkdir $tmpdir, 0700 || $form->error($locale->text('A temporary directory could not be created:') . " $ERRNO");
867
868   my $pgpass = IO::File->new("${tmpdir}/.pgpass", O_WRONLY | O_CREAT, 0600);
869
870   if (!$pgpass) {
871     unlink $tmpdir;
872     $form->error($locale->text('A temporary file could not be created:') . " $ERRNO");
873   }
874
875   print $pgpass "$form->{dbhost}:$form->{dbport}:$form->{dbname}:$form->{dbuser}:$form->{dbpasswd}\n";
876   $pgpass->close();
877
878   $ENV{HOME} = $tmpdir;
879
880   my @args = ("-Ft", "-c", "-o", "-h", $form->{dbhost}, "-U", $form->{dbuser});
881   push @args, ("-p", $form->{dbport}) if ($form->{dbport});
882   push @args, $form->{dbname};
883
884   my $cmd  = "$main::pg_dump_exe " . join(" ", map { s/\\/\\\\/g; s/\"/\\\"/g; $_ } @args);
885   my $name = "dataset_backup_$form->{dbname}_" . strftime("%Y%m%d", localtime()) . ".tar";
886
887   if ($form->{destination} ne "email") {
888     my $in = IO::File->new("$cmd |");
889
890     if (!$in) {
891       unlink "${tmpdir}/.pgpass";
892       rmdir $tmpdir;
893
894       $form->error($locale->text('The pg_dump process could not be started.'));
895     }
896
897     print "content-type: application/x-tar\n";
898     print "content-disposition: attachment; filename=\"${name}\"\n\n";
899
900     while (my $line = <$in>) {
901       print $line;
902     }
903
904     $in->close();
905
906     unlink "${tmpdir}/.pgpass";
907     rmdir $tmpdir;
908
909   } else {
910     my $tmp = $tmpdir . "/dump_" . Common::unique_id();
911
912     if (system("$cmd > $tmp") != 0) {
913       unlink "${tmpdir}/.pgpass", $tmp;
914       rmdir $tmpdir;
915
916       $form->error($locale->text('The pg_dump process could not be started.'));
917     }
918
919     my $mail = new Mailer;
920
921     map { $mail->{$_} = $form->{$_} } qw(from to cc subject message);
922
923     $mail->{charset}     = $main::dbcharset ? $main::dbcharset : Common::DEFAULT_CHARSET;
924     $mail->{attachments} = [ { "filename" => $tmp, "name" => $name } ];
925     $mail->send();
926
927     unlink "${tmpdir}/.pgpass", $tmp;
928     rmdir $tmpdir;
929
930     $form->{title} = "Lx-Office ERP " . $locale->text('Database Administration') . " / " . $locale->text('Backup Dataset');
931
932     $form->header();
933     print $form->parse_html_template("admin/backup_dataset_email_done");
934   }
935 }
936
937 sub restore_dataset {
938   my $form       = $main::form;
939   my $locale     = $main::locale;
940
941   $form->{title} = "Lx-Office ERP " . $locale->text('Database Administration') . " / " . $locale->text('Restore Dataset');
942
943   if ("$main::pg_restore_exe" eq "DISABLED") {
944     $form->error($locale->text('Database backups and restorations are disabled in lx-erp.conf.'));
945   }
946
947   my $default_charset   = $main::dbcharset;
948   $default_charset    ||= Common::DEFAULT_CHARSET;
949
950   $form->{DBENCODINGS}  = [];
951
952   foreach my $encoding (@Common::db_encodings) {
953     push @{ $form->{DBENCODINGS} }, { "dbencoding" => $encoding->{dbencoding},
954                                       "label"      => $encoding->{label},
955                                       "selected"   => $encoding->{charset} eq $default_charset };
956   }
957
958   $form->header();
959   print $form->parse_html_template("admin/restore_dataset");
960 }
961
962 sub restore_dataset_start {
963   my $form       = $main::form;
964   my $locale     = $main::locale;
965
966   $form->{title} = "Lx-Office ERP " . $locale->text('Database Administration') . " / " . $locale->text('Restore Dataset');
967
968   $main::pg_restore_exe ||= "pg_restore";
969
970   if ("$main::pg_restore_exe" eq "DISABLED") {
971     $form->error($locale->text('Database backups and restorations are disabled in lx-erp.conf.'));
972   }
973
974   $form->isblank("new_dbname", $locale->text('The dataset name is missing.'));
975   $form->isblank("content", $locale->text('No backup file has been uploaded.'));
976
977   # Create temporary directories. Write the backup file contents to a temporary
978   # file. Create a .pgpass file with the username and password for the pg_restore
979   # utility.
980
981   my $tmpdir = "/tmp/lx_office_backup_" . Common->unique_id();
982   mkdir $tmpdir, 0700 || $form->error($locale->text('A temporary directory could not be created:') . " $ERRNO");
983
984   my $pgpass = IO::File->new("${tmpdir}/.pgpass", O_WRONLY | O_CREAT, 0600);
985
986   if (!$pgpass) {
987     unlink $tmpdir;
988     $form->error($locale->text('A temporary file could not be created:') . " $ERRNO");
989   }
990
991   print $pgpass "$form->{dbhost}:$form->{dbport}:$form->{new_dbname}:$form->{dbuser}:$form->{dbpasswd}\n";
992   $pgpass->close();
993
994   $ENV{HOME} = $tmpdir;
995
996   my $tmp = $tmpdir . "/dump_" . Common::unique_id();
997   my $tmpfile;
998
999   if (substr($form->{content}, 0, 2) eq "\037\213") {
1000     $tmpfile = IO::File->new("| gzip -d > $tmp");
1001     $tmpfile->binary();
1002
1003   } else {
1004     $tmpfile = IO::File->new($tmp, O_WRONLY | O_CREAT | O_BINARY, 0600);
1005   }
1006
1007   if (!$tmpfile) {
1008     unlink "${tmpdir}/.pgpass";
1009     rmdir $tmpdir;
1010
1011     $form->error($locale->text('A temporary file could not be created:') . " $ERRNO");
1012   }
1013
1014   print $tmpfile $form->{content};
1015   $tmpfile->close();
1016
1017   delete $form->{content};
1018
1019   # Try to connect to the database. Find out if a database with the same name exists.
1020   # If yes, then drop the existing database. Create a new one with the name and encoding
1021   # given by the user.
1022
1023   User::dbconnect_vars($form, "template1");
1024
1025   my %myconfig = map { $_ => $form->{$_} } grep /^db/, keys %{ $form };
1026   my $dbh      = $form->dbconnect(\%myconfig) || $form->dberror();
1027
1028   my ($query, $sth);
1029
1030   $form->{new_dbname} =~ s|[^a-zA-Z0-9_\-]||g;
1031
1032   $query = qq|SELECT COUNT(*) FROM pg_database WHERE datname = ?|;
1033   my ($count) = selectrow_query($form, $dbh, $query, $form->{new_dbname});
1034   if ($count) {
1035     do_query($form, $dbh, qq|DROP DATABASE $form->{new_dbname}|);
1036   }
1037
1038   my $found = 0;
1039   foreach my $item (@Common::db_encodings) {
1040     if ($item->{dbencoding} eq $form->{dbencoding}) {
1041       $found = 1;
1042       last;
1043     }
1044   }
1045   $form->{dbencoding} = "LATIN9" unless $form->{dbencoding};
1046
1047   do_query($form, $dbh, qq|CREATE DATABASE $form->{new_dbname} ENCODING ? TEMPLATE template0|, $form->{dbencoding});
1048
1049   $dbh->disconnect();
1050
1051   # Spawn pg_restore on the temporary file.
1052
1053   my @args = ("-h", $form->{dbhost}, "-U", $form->{dbuser}, "-d", $form->{new_dbname});
1054   push @args, ("-p", $form->{dbport}) if ($form->{dbport});
1055   push @args, $tmp;
1056
1057   my $cmd = "$main::pg_restore_exe " . join(" ", map { s/\\/\\\\/g; s/\"/\\\"/g; $_ } @args);
1058
1059   my $in = IO::File->new("$cmd 2>&1 |");
1060
1061   if (!$in) {
1062     unlink "${tmpdir}/.pgpass", $tmp;
1063     rmdir $tmpdir;
1064
1065     $form->error($locale->text('The pg_restore process could not be started.'));
1066   }
1067
1068   $English::AUTOFLUSH = 1;
1069
1070   $form->header();
1071   print $form->parse_html_template("admin/restore_dataset_start_header");
1072
1073   while (my $line = <$in>) {
1074     print $line;
1075   }
1076   $in->close();
1077
1078   $form->{retval} = $CHILD_ERROR >> 8;
1079   print $form->parse_html_template("admin/restore_dataset_start_footer");
1080
1081   unlink "${tmpdir}/.pgpass", $tmp;
1082   rmdir $tmpdir;
1083 }
1084
1085 sub unlock_system {
1086   my $form   = $main::form;
1087   my $locale = $main::locale;
1088
1089   unlink "$main::userspath/nologin";
1090
1091   $form->{callback} = "admin.pl?action=list_users";
1092
1093   $form->redirect($locale->text('Lockfile removed!'));
1094
1095 }
1096
1097 sub lock_system {
1098   my $form   = $main::form;
1099   my $locale = $main::locale;
1100
1101   open(FH, ">$main::userspath/nologin")
1102     or $form->error($locale->text('Cannot create Lock!'));
1103   close(FH);
1104
1105   $form->{callback} = "admin.pl?action=list_users";
1106
1107   $form->redirect($locale->text('Lockfile created!'));
1108
1109 }
1110
1111 sub yes {
1112   call_sub($main::form->{yes_nextsub});
1113 }
1114
1115 sub no {
1116   call_sub($main::form->{no_nextsub});
1117 }
1118
1119 sub add {
1120   call_sub($main::form->{add_nextsub});
1121 }
1122
1123 sub edit {
1124   my $form = $main::form;
1125
1126   $form->{edit_nextsub} ||= 'edit_user';
1127
1128   call_sub($form->{edit_nextsub});
1129 }
1130
1131 sub delete {
1132   my $form     = $main::form;
1133
1134   $form->{delete_nextsub} ||= 'delete_user';
1135
1136   call_sub($form->{delete_nextsub});
1137 }
1138
1139 sub save {
1140   my $form = $main::form;
1141
1142   $form->{save_nextsub} ||= 'save_user';
1143
1144   call_sub($form->{save_nextsub});
1145 }
1146
1147 sub back {
1148   call_sub($main::form->{back_nextsub});
1149 }
1150
1151 sub dispatcher {
1152   my $form   = $main::form;
1153   my $locale = $main::locale;
1154
1155   foreach my $action (qw(create_standard_group dont_create_standard_group
1156                          save_user delete_user save_user_as_new)) {
1157     if ($form->{"action_${action}"}) {
1158       call_sub($action);
1159       return;
1160     }
1161   }
1162
1163   call_sub($form->{default_action}) if ($form->{default_action});
1164
1165   $form->error($locale->text('No action defined.'));
1166 }
1167
1168 1;