Upgradescripte für auth.* nur ausführen, wenn Authentifizierungstabellen bereits...
[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::Iconv;
47 use SL::Mailer;
48 use SL::User;
49 use SL::Common;
50 use SL::Inifile;
51 use SL::DBUpgrade2;
52 use SL::DBUtils;
53
54 require "bin/mozilla/common.pl";
55 require "bin/mozilla/admin_groups.pl";
56 require "bin/mozilla/admin_printer.pl";
57
58 use strict;
59
60 our $cgi;
61 our $form;
62 our $locale;
63 our $auth;
64
65 sub run {
66   $::lxdebug->enter_sub;
67   my $session_result = shift;
68
69   $cgi    = $::cgi;
70   $form   = $::form;
71   $locale = $::locale;
72   $auth   = $::auth;
73
74   $::auth->set_session_value('rpw', $::form->{rpw}) if $session_result == SL::Auth->SESSION_OK;
75
76   $form->{stylesheet} = "lx-office-erp.css";
77   $form->{favicon}    = "favicon.ico";
78
79   if ($form->{action}) {
80     if ($auth->authenticate_root($form->{rpw}, 0) != $auth->OK()) {
81       $form->{error_message} = $locale->text('Incorrect Password!');
82       adminlogin();
83     } else {
84       if ($auth->session_tables_present()) {
85         $::auth->set_session_value('rpw', $::form->{rpw});
86         $::auth->create_or_refresh_session();
87         _apply_dbupgrade_scripts();
88       }
89
90       call_sub($locale->findsub($form->{action}));
91     }
92   } else {
93     # if there are no drivers bail out
94     $form->error($locale->text('No Database Drivers available!'))
95       unless (User->dbdrivers);
96
97     adminlogin();
98   }
99   $::lxdebug->leave_sub;
100 }
101
102 sub adminlogin {
103   my $form   = $main::form;
104   my $locale = $main::locale;
105
106   $form->{title} = qq|Lx-Office ERP $form->{version} | . $locale->text('Administration');
107
108   $form->header();
109   print $form->parse_html_template('admin/adminlogin');
110 }
111
112 sub login {
113   check_auth_db_and_tables();
114   list_users();
115 }
116
117 sub logout {
118   $main::auth->destroy_session();
119   adminlogin();
120 }
121
122 sub check_auth_db_and_tables {
123   my $form   = $main::form;
124   my $locale = $main::locale;
125
126   my %params;
127
128   map { $params{"db_${_}"} = $main::auth->{DB_config}->{$_} } keys %{ $auth->{DB_config} };
129
130   if (!$main::auth->check_database()) {
131     $form->{title} = $locale->text('Authentification database creation');
132     $form->header();
133     print $form->parse_html_template('admin/check_auth_database', \%params);
134
135     ::end_of_request();
136   }
137
138   if (!$main::auth->check_tables()) {
139     $form->{title} = $locale->text('Authentification tables creation');
140     $form->header();
141     print $form->parse_html_template('admin/check_auth_tables', \%params);
142
143     ::end_of_request();
144   }
145
146   if (-f $main::memberfile) {
147     my $memberdir = "";
148
149     if ($main::memberfile =~ m|^.*/|) {
150       $memberdir = $&;
151     }
152
153     my $backupdir = "${memberdir}member-file-migration";
154
155     $form->{title} = $locale->text('User data migration');
156     $form->header();
157     print $form->parse_html_template('admin/user_migration', { 'memberfile' => $main::memberfile,
158                                                                'backupdir'  => $backupdir });
159
160     ::end_of_request();
161   }
162 }
163
164 sub create_auth_db {
165   my $form = $main::form;
166
167   $main::auth->create_database('superuser'          => $form->{db_superuser},
168                                'superuser_password' => $form->{db_superuser_password},
169                                'template'           => $form->{db_template});
170   login();
171 }
172
173 sub create_auth_tables {
174   my $form   = $main::form;
175   my $locale = $main::locale;
176
177   $main::auth->create_tables();
178   $main::auth->set_session_value('rpw', $form->{rpw});
179   $main::auth->create_or_refresh_session();
180
181   if (!-f $main::memberfile) {
182     # New installation -- create a standard group with full access
183     my %members;
184     my $group = {
185       'name'        => $locale->text('Full Access'),
186       'description' => $locale->text('Full access to all functions'),
187       'rights'      => { map { $_ => 1 } SL::Auth::all_rights() },
188       'members'     => [ map { $_->{id} } values %members ],
189     };
190
191     $main::auth->save_group($group);
192   }
193
194   login();
195 }
196
197 sub migrate_users {
198   $main::lxdebug->enter_sub();
199
200   my $form      = $main::form;
201   my $locale    = $main::locale;
202
203   my $memberdir = "";
204
205   if ($main::memberfile =~ m|^.*/|) {
206     $memberdir = $&;
207   }
208
209   my $backupdir = "${memberdir}member-file-migration";
210
211   if (! -d $backupdir && !mkdir $backupdir, 0700) {
212     $form->error(sprintf($locale->text('The directory "%s" could not be created:\n%s'), $backupdir, $!));
213   }
214
215   copy $main::memberfile, "users/member-file-migration/members";
216
217   my $in = IO::File->new($main::memberfile, "r");
218
219   $form->error($locale->text('Could not open the old memberfile.')) if (!$in);
220
221   my (%members, $login);
222
223   while (<$in>) {
224     chomp;
225
226     next if (m/^\s*\#/);
227
228     if (m/^\[.*\]/) {
229       $login = $_;
230       $login =~ s/(\[|\])//g;
231       $login =~ s/^\s*//;
232       $login =~ s/\s*$//;
233
234       $members{$login} = { "login" => $login };
235       next;
236     }
237
238     if ($login && m/=/) {
239       my ($key, $value) = split m/\s*=\s*/, $_, 2;
240       $key   =~ s|^\s*||;
241       $value =~ s|\s*$||;
242
243       $value =~ s|\\r||g;
244       $value =~ s|\\n|\n|g;
245
246       $members{$login}->{$key} = $value;
247     }
248   }
249
250   $in->close();
251
252   delete $members{"root login"};
253
254   map { $_->{dbpasswd} = unpack 'u', $_->{dbpasswd} } values %members;
255
256   while (my ($login, $params) = each %members) {
257     $main::auth->save_user($login, %{ $params });
258     $main::auth->change_password($login, $params->{password}, 1);
259
260     my $conf_file = "${memberdir}${login}.conf";
261
262     if (-f $conf_file) {
263       copy   $conf_file, "${backupdir}/${login}.conf";
264       unlink $conf_file;
265     }
266   }
267
268   unlink $main::memberfile;
269
270   my @member_list = sort { lc $a->{login} cmp lc $b->{login} } values %members;
271
272   $form->{title} = $locale->text('User data migration');
273   $form->header();
274   print $form->parse_html_template('admin/user_migration_done', { 'MEMBERS' => \@member_list });
275
276   $main::lxdebug->leave_sub();
277 }
278
279 sub create_standard_group_ask {
280   my $form   = $main::form;
281   my $locale = $main::locale;
282
283   $form->{title} = $locale->text('Create a standard group');
284
285   $form->header();
286   print $form->parse_html_template("admin/create_standard_group_ask");
287 }
288
289 sub create_standard_group {
290   my $form    = $main::form;
291   my $locale  = $main::locale;
292
293   my %members = $main::auth->read_all_users();
294
295   my $groups  = $main::auth->read_groups();
296
297   foreach my $group (values %{$groups}) {
298     if (($form->{group_id} != $group->{id})
299         && ($form->{name} eq $group->{name})) {
300       $form->show_generic_error($locale->text("A group with that name does already exist."));
301     }
302   }
303
304   my $group = {
305     'name'        => $locale->text('Full Access'),
306     'description' => $locale->text('Full access to all functions'),
307     'rights'      => { map { $_ => 1 } SL::Auth::all_rights() },
308     'members'     => [ map { $_->{id} } values %members ],
309   };
310
311   $main::auth->save_group($group);
312
313   user_migration_complete(1);
314 }
315
316 sub dont_create_standard_group {
317   user_migration_complete(0);
318 }
319
320 sub user_migration_complete {
321   my $standard_group_created = shift;
322
323   my $form                   = $main::form;
324   my $locale                 = $main::locale;
325
326   $form->{title} = $locale->text('User migration complete');
327   $form->header();
328
329   print $form->parse_html_template('admin/user_migration_complete', { 'standard_group_created' => $standard_group_created });
330 }
331
332 sub list_users {
333   my $form    = $main::form;
334   my $locale  = $main::locale;
335
336   my %members = $main::auth->read_all_users();
337
338   delete $members{"root login"};
339
340   map { $_->{templates} =~ s|.*/||; } values %members;
341
342   $form->{title}   = "Lx-Office ERP " . $locale->text('Administration');
343   $form->{LOCKED}  = -e "$main::userspath/nologin";
344   $form->{MEMBERS} = [ @members{sort { lc $a cmp lc $b } keys %members} ];
345
346   $form->header();
347   print $form->parse_html_template("admin/list_users");
348 }
349
350 sub add_user {
351   my $form         = $main::form;
352   my $locale       = $main::locale;
353
354   $form->{title}   = "Lx-Office ERP " . $locale->text('Administration') . " / " . $locale->text('Add User');
355
356 # Note: Menu Style 'v3' is not compatible to all browsers!
357 # "menustyle"    => "old" sets the HTML Menu to default.
358   my $myconfig     = {
359     "vclimit"      => 200,
360     "countrycode"  => "de",
361     "numberformat" => "1.000,00",
362     "dateformat"   => "dd.mm.yy",
363     "stylesheet"   => "lx-office-erp.css",
364     "menustyle"    => "old",
365   };
366
367   edit_user_form($myconfig);
368 }
369
370 sub edit_user {
371   my $form       = $main::form;
372   my $locale     = $main::locale;
373
374   $form->{title} = "Lx-Office ERP " . $locale->text('Administration') . " / " . $locale->text('Edit User');
375   $form->{edit}  = 1;
376
377   $form->isblank("login", $locale->text("The login is missing."));
378
379   # get user
380   my $myconfig = new User($form->{login});
381
382   # strip basedir from templates directory
383   $myconfig->{templates} =~ s|.*/||;
384
385   edit_user_form($myconfig);
386 }
387
388 sub edit_user_form {
389   my ($myconfig) = @_;
390
391   my $form       = $main::form;
392   my $locale     = $main::locale;
393
394   my @valid_dateformats = qw(mm-dd-yy mm/dd/yy dd-mm-yy dd/mm/yy dd.mm.yy yyyy-mm-dd);
395   $form->{ALL_DATEFORMATS} = [ map { { "format" => $_, "selected" => $_ eq $myconfig->{dateformat} } } @valid_dateformats ];
396
397   my @valid_numberformats = ('1,000.00', '1000.00', '1.000,00', '1000,00');
398   $form->{ALL_NUMBERFORMATS} = [ map { { "format" => $_, "selected" => $_ eq $myconfig->{numberformat} } } @valid_numberformats ];
399
400   my %countrycodes = User->country_codes;
401   $form->{ALL_COUNTRYCODES} = [];
402   foreach my $countrycode (sort { $countrycodes{$a} cmp $countrycodes{$b} } keys %countrycodes) {
403     push @{ $form->{ALL_COUNTRYCODES} }, { "value"    => $countrycode,
404                                            "name"     => $countrycodes{$countrycode},
405                                            "selected" => $countrycode eq $myconfig->{countrycode} };
406   }
407
408   # is there a templates basedir
409   if (!-d "$main::templates") {
410     $form->error(sprintf($locale->text("The directory %s does not exist."), $main::templates));
411   }
412
413   opendir TEMPLATEDIR, "$main::templates/." or $form->error("$main::templates : $ERRNO");
414   my @all     = readdir(TEMPLATEDIR);
415   my @alldir  = sort grep { -d "$main::templates/$_" && !/^\.\.?$/ } @all;
416   my @allhtml = sort grep { -f "$main::templates/$_" && /\.html$/ } @all;
417   closedir TEMPLATEDIR;
418
419   @alldir = grep !/\.(html|tex|sty|odt|xml|txb)$/, @alldir;
420   @alldir = grep !/^(webpages|\.svn)$/, @alldir;
421
422   @allhtml = reverse grep !/Default/, @allhtml;
423   push @allhtml, 'Default';
424   @allhtml = reverse @allhtml;
425
426   $form->{ALL_TEMPLATES} = [ map { { "name", => $_, "selected" => $_ eq $myconfig->{templates} } } @alldir ];
427
428   my $lastitem = $allhtml[0];
429   $lastitem =~ s/-.*//g;
430   $form->{ALL_MASTER_TEMPLATES} = [ { "name" => $lastitem, "selected" => $lastitem eq "German" } ];
431   foreach my $item (@allhtml) {
432     $item =~ s/-.*//g;
433     next if ($item eq $lastitem);
434
435     push @{ $form->{ALL_MASTER_TEMPLATES} }, { "name" => $item, "selected" => $item eq "German" };
436     $lastitem = $item;
437   }
438
439   # css dir has styles that are not intended as general layouts.
440   # reverting to hardcoded list
441   $form->{ALL_STYLESHEETS} = [ map { { "name" => $_, "selected" => $_ eq $myconfig->{stylesheet} } } qw(lx-office-erp.css Win2000.css) ];
442
443   $form->{"menustyle_" . $myconfig->{menustyle} } = 1;
444
445   map { $form->{"myc_${_}"} = $myconfig->{$_} } keys %{ $myconfig };
446
447   my $groups = [];
448
449   if ($form->{edit}) {
450     my $user_id    = $main::auth->get_user_id($form->{login});
451     my $all_groups = $main::auth->read_groups();
452
453     foreach my $group (values %{ $all_groups }) {
454       push @{ $groups }, $group if (grep { $user_id == $_ } @{ $group->{members} });
455     }
456
457     $groups = [ sort { lc $a->{name} cmp lc $b->{name} } @{ $groups } ];
458   }
459
460   $form->{CAN_CHANGE_PASSWORD} = $main::auth->can_change_password();
461
462   $form->header();
463   print $form->parse_html_template("admin/edit_user", { 'GROUPS' => $groups });
464 }
465
466 sub save_user {
467   my $form          = $main::form;
468   my $locale        = $main::locale;
469
470   $form->{dbdriver} = 'Pg';
471
472   # no spaces allowed in login name
473   $form->{login} =~ s|\s||g;
474   $form->isblank("login", $locale->text('Login name missing!'));
475
476   # check for duplicates
477   if (!$form->{edit}) {
478     my %members = $main::auth->read_all_users();
479     if ($members{$form->{login}}) {
480       $form->show_generic_error($locale->text('Another user with the login #1 does already exist.', $form->{login}), 'back_button' => 1);
481     }
482   }
483
484   # no spaces allowed in directories
485   ($form->{newtemplates}) = split / /, $form->{newtemplates};
486
487   if ($form->{newtemplates}) {
488     $form->{templates} = $form->{newtemplates};
489   } else {
490     $form->{templates} =
491       ($form->{usetemplates}) ? $form->{usetemplates} : $form->{login};
492   }
493
494   # is there a basedir
495   if (!-d "$main::templates") {
496     $form->error(sprintf($locale->text("The directory %s does not exist."), $main::templates));
497   }
498
499   # add base directory to $form->{templates}
500   $form->{templates} =~ s|.*/||;
501   $form->{templates} =  "$main::templates/$form->{templates}";
502
503   my $myconfig = new User($form->{login});
504
505   $form->isblank("dbname", $locale->text('Dataset missing!'));
506   $form->isblank("dbuser", $locale->text('Database User missing!'));
507
508   foreach my $item (keys %{$form}) {
509     $myconfig->{$item} = $form->{$item};
510   }
511
512   delete $myconfig->{stylesheet};
513   if ($form->{userstylesheet}) {
514     $myconfig->{stylesheet} = $form->{userstylesheet};
515   }
516
517   $myconfig->save_member();
518
519   if ($main::auth->can_change_password()
520       && defined $form->{new_password}
521       && ($form->{new_password} ne '********')) {
522     $main::auth->change_password($form->{login}, $form->{new_password});
523   }
524
525   $form->{templates}       =~ s|.*/||;
526   $form->{templates}       =  "$main::templates/$form->{templates}";
527   $form->{mastertemplates} =~ s|.*/||;
528
529   # create user template directory and copy master files
530   if (!-d "$form->{templates}") {
531     umask(002);
532
533     if (mkdir "$form->{templates}", oct("771")) {
534
535       umask(007);
536
537       # copy templates to the directory
538       opendir TEMPLATEDIR, "$main::templates/." or $form->error("$main::templates : $ERRNO");
539       my @templates = grep /$form->{mastertemplates}.*?\.(html|tex|sty|odt|xml|txb)$/,
540         readdir TEMPLATEDIR;
541       closedir TEMPLATEDIR;
542
543       foreach my $file (@templates) {
544         open(TEMP, "$main::templates/$file")
545           or $form->error("$main::templates/$file : $ERRNO");
546
547         $file =~ s/\Q$form->{mastertemplates}\E-//;
548         open(NEW, ">$form->{templates}/$file")
549           or $form->error("$form->{templates}/$file : $ERRNO");
550
551         while (my $line = <TEMP>) {
552           print NEW $line;
553         }
554         close(TEMP);
555         close(NEW);
556       }
557     } else {
558       $form->error("$ERRNO: $form->{templates}");
559     }
560   }
561
562   # Add new user to his groups.
563   if (ref $form->{new_user_group_ids} eq 'ARRAY') {
564     my $all_groups = $main::auth->read_groups();
565     my %user       = $main::auth->read_user($form->{login});
566
567     foreach my $group_id (@{ $form->{new_user_group_ids} }) {
568       my $group = $all_groups->{$group_id};
569
570       next if !$group;
571
572       push @{ $group->{members} }, $user{id};
573       $main::auth->save_group($group);
574     }
575   }
576
577   $form->redirect($locale->text('User saved!'));
578
579 }
580
581 sub save_user_as_new {
582   my $form       = $main::form;
583
584   $form->{login} = $form->{new_user_login};
585   delete @{$form}{qw(edit new_user_login)};
586
587   save_user();
588 }
589
590 sub delete_user {
591   my $form      = $main::form;
592   my $locale    = $main::locale;
593
594   my %members   = $main::auth->read_all_users();
595   my $templates = $members{$form->{login}}->{templates};
596
597   $main::auth->delete_user($form->{login});
598
599   if ($templates) {
600     my $templates_in_use = 0;
601
602     foreach my $login (keys %members) {
603       next if $form->{login} eq $login;
604       next if $members{$login}->{templates} ne $templates;
605       $templates_in_use = 1;
606       last;
607     }
608
609     if (!$templates_in_use && -d $templates) {
610       unlink <$templates/*>;
611       rmdir $templates;
612     }
613   }
614
615   $form->redirect($locale->text('User deleted!'));
616
617 }
618
619 sub login_name {
620   my $login = shift;
621
622   $login =~ s/\[\]//g;
623   return ($login) ? $login : undef;
624
625 }
626
627 sub get_value {
628   my $line           = shift;
629   my ($null, $value) = split(/=/, $line, 2);
630
631   # remove comments
632   $value =~ s/\s#.*//g;
633
634   # remove any trailing whitespace
635   $value =~ s/^\s*(.*?)\s*$/$1/;
636
637   $value;
638 }
639
640 sub pg_database_administration {
641   my $form = $main::form;
642
643   $form->{dbdriver} = 'Pg';
644   dbselect_source();
645
646 }
647
648 sub dbselect_source {
649   my $form           = $main::form;
650   my $locale         = $main::locale;
651
652   $form->{dbport}    = $::auth->{DB_config}->{port} || 5432;
653   $form->{dbuser}    = $::auth->{DB_config}->{user} || 'lxoffice';
654   $form->{dbdefault} = 'template1';
655   $form->{dbhost}    = $::auth->{DB_config}->{host} || 'localhost';
656
657   $form->{title}     = "Lx-Office ERP / " . $locale->text('Database Administration');
658
659   # Intentionnaly disabled unless fixed to work with the authentication DB.
660   $form->{ALLOW_DBBACKUP} = 0; # "$pg_dump_exe" ne "DISABLED";
661
662   $form->header();
663   print $form->parse_html_template("admin/dbadmin");
664 }
665
666 sub test_db_connection {
667   my $form   = $main::form;
668   my $locale = $main::locale;
669
670   $form->{dbdriver} = 'Pg';
671   User::dbconnect_vars($form, $form->{dbname});
672
673   my $dbh = DBI->connect($form->{dbconnect}, $form->{dbuser}, $form->{dbpasswd});
674
675   $form->{connection_ok} = $dbh ? 1 : 0;
676   $form->{errstr}        = $DBI::errstr;
677
678   $dbh->disconnect() if ($dbh);
679
680   $form->{title} = $locale->text('Database Connection Test');
681   $form->header();
682   print $form->parse_html_template("admin/test_db_connection");
683 }
684
685 sub continue {
686   call_sub($main::form->{"nextsub"});
687 }
688
689 sub update_dataset {
690   my $form              = $main::form;
691   my $locale            = $main::locale;
692
693   $form->{title}        = "Lx-Office ERP " . $locale->text('Database Administration') . " / " . $locale->text('Update Dataset');
694
695   my @need_updates      = User->dbneedsupdate($form);
696   $form->{NEED_UPDATES} = \@need_updates;
697   $form->{ALL_UPDATED}  = !scalar @need_updates;
698
699   $form->header();
700   print $form->parse_html_template("admin/update_dataset");
701 }
702
703 sub dbupdate {
704   my $form            = $main::form;
705   my $locale          = $main::locale;
706
707   $form->{stylesheet} = "lx-office-erp.css";
708   $form->{title}      = $locale->text("Dataset upgrade");
709   $form->header();
710
711   my $rowcount           = $form->{rowcount} * 1;
712   my @update_rows        = grep { $form->{"update_$_"} } (1 .. $rowcount);
713   $form->{NOTHING_TO_DO} = !scalar @update_rows;
714   my $saved_form         = save_form();
715
716   $| = 1;
717
718   print $form->parse_html_template("admin/dbupgrade_all_header");
719
720   foreach my $i (@update_rows) {
721     restore_form($saved_form);
722
723     map { $form->{$_} = $form->{"${_}_${i}"} } qw(dbname dbdriver dbhost dbport dbuser dbpasswd);
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, SL::DBUpgrade2->new(form => $form, dbdriver => $form->{dbdriver})->parse_dbupdate_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 sub _apply_dbupgrade_scripts {
1169   ::end_of_request() if SL::DBUpgrade2->new(form => $::form, dbdriver => 'Pg', auth => 1)->apply_admin_dbupgrade_scripts(1);
1170 }
1171
1172 1;