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