Aufrufe von 'exit' durch eigene Funktion '::end_of_request()' ersetzt.
[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;
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       $auth->create_or_refresh_session() if ($auth->session_tables_present());
85       call_sub($locale->findsub($form->{action}));
86     }
87   } elsif ($auth->authenticate_root($form->{rpw}, 0) == $auth->OK()) {
88
89     $auth->create_or_refresh_session() if ($auth->session_tables_present());
90
91     login();
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
352   my $form     = $main::form;
353   my $locale   = $main::locale;
354
355   $form->{title} =
356       "Lx-Office ERP "
357     . $locale->text('Administration') . " / "
358     . $locale->text('Add User');
359
360   my $myconfig = {
361     "vclimit"      => 200,
362     "countrycode"  => "de",
363     "numberformat" => "1.000,00",
364     "dateformat"   => "dd.mm.yy",
365     "stylesheet"   => "lx-office-erp.css",
366     "menustyle"    => "v3",
367   };
368
369   edit_user_form($myconfig);
370 }
371
372 sub edit_user {
373   my $form     = $main::form;
374   my $locale   = $main::locale;
375
376
377   $form->{title} =
378       "Lx-Office ERP "
379     . $locale->text('Administration') . " / "
380     . $locale->text('Edit User');
381   $form->{edit} = 1;
382
383   $form->isblank("login", $locale->text("The login is missing."));
384
385   # get user
386   my $myconfig = new User($form->{login});
387
388   # strip basedir from templates directory
389   $myconfig->{templates} =~ s|.*/||;
390
391   edit_user_form($myconfig);
392 }
393
394 sub edit_user_form {
395   my ($myconfig) = @_;
396
397   my $form     = $main::form;
398   my $locale   = $main::locale;
399
400   my @valid_dateformats = qw(mm-dd-yy mm/dd/yy dd-mm-yy dd/mm/yy dd.mm.yy yyyy-mm-dd);
401   $form->{ALL_DATEFORMATS} = [ map { { "format" => $_, "selected" => $_ eq $myconfig->{dateformat} } } @valid_dateformats ];
402
403   my @valid_numberformats = ('1,000.00', '1000.00', '1.000,00', '1000,00');
404   $form->{ALL_NUMBERFORMATS} = [ map { { "format" => $_, "selected" => $_ eq $myconfig->{numberformat} } } @valid_numberformats ];
405
406   my %countrycodes = User->country_codes;
407   $form->{ALL_COUNTRYCODES} = [];
408   foreach my $countrycode (sort { $countrycodes{$a} cmp $countrycodes{$b} } keys %countrycodes) {
409     push @{ $form->{ALL_COUNTRYCODES} }, { "value"    => $countrycode,
410                                            "name"     => $countrycodes{$countrycode},
411                                            "selected" => $countrycode eq $myconfig->{countrycode} };
412   }
413
414   # is there a templates basedir
415   if (!-d "$main::templates") {
416     $form->error(sprintf($locale->text("The directory %s does not exist."), $main::templates));
417   }
418
419   opendir TEMPLATEDIR, "$main::templates/." or $form->error("$main::templates : $ERRNO");
420   my @all     = readdir(TEMPLATEDIR);
421   my @alldir  = sort grep { -d "$main::templates/$_" && !/^\.\.?$/ } @all;
422   my @allhtml = sort grep { -f "$main::templates/$_" && /\.html$/ } @all;
423   closedir TEMPLATEDIR;
424
425   @alldir = grep !/\.(html|tex|sty|odt|xml|txb)$/, @alldir;
426   @alldir = grep !/^(webpages|\.svn)$/, @alldir;
427
428   @allhtml = reverse grep !/Default/, @allhtml;
429   push @allhtml, 'Default';
430   @allhtml = reverse @allhtml;
431
432   $form->{ALL_TEMPLATES} = [ map { { "name", => $_, "selected" => $_ eq $myconfig->{templates} } } @alldir ];
433
434   my $lastitem = $allhtml[0];
435   $lastitem =~ s/-.*//g;
436   $form->{ALL_MASTER_TEMPLATES} = [ { "name" => $lastitem, "selected" => $lastitem eq "German" } ];
437   foreach my $item (@allhtml) {
438     $item =~ s/-.*//g;
439     next if ($item eq $lastitem);
440
441     push @{ $form->{ALL_MASTER_TEMPLATES} }, { "name" => $item, "selected" => $item eq "German" };
442     $lastitem = $item;
443   }
444
445   # css dir has styles that are not intended as general layouts.
446   # reverting to hardcoded list
447   $form->{ALL_STYLESHEETS} = [ map { { "name" => $_, "selected" => $_ eq $myconfig->{stylesheet} } } qw(lx-office-erp.css Win2000.css) ];
448
449   $form->{"menustyle_" . $myconfig->{menustyle} } = 1;
450
451   map { $form->{"myc_${_}"} = $myconfig->{$_} } keys %{ $myconfig };
452
453   my $groups = [];
454
455   if ($form->{edit}) {
456     my $user_id    = $main::auth->get_user_id($form->{login});
457     my $all_groups = $main::auth->read_groups();
458
459     foreach my $group (values %{ $all_groups }) {
460       push @{ $groups }, $group if (grep { $user_id == $_ } @{ $group->{members} });
461     }
462
463     $groups = [ sort { lc $a->{name} cmp lc $b->{name} } @{ $groups } ];
464   }
465
466   $form->{CAN_CHANGE_PASSWORD} = $main::auth->can_change_password();
467
468   $form->header();
469   print $form->parse_html_template("admin/edit_user", { 'GROUPS' => $groups });
470 }
471
472 sub save_user {
473   my $form     = $main::form;
474   my $locale   = $main::locale;
475
476   $form->{dbdriver} = 'Pg';
477
478   # no spaces allowed in login name
479   $form->{login} =~ s|\s||g;
480   $form->isblank("login", $locale->text('Login name missing!'));
481
482   # check for duplicates
483   if (!$form->{edit}) {
484     my %members = $main::auth->read_all_users();
485     if ($members{$form->{login}}) {
486       $form->show_generic_error($locale->text('Another user with the login #1 does already exist.', $form->{login}), 'back_button' => 1);
487     }
488   }
489
490   # no spaces allowed in directories
491   ($form->{newtemplates}) = split / /, $form->{newtemplates};
492
493   if ($form->{newtemplates}) {
494     $form->{templates} = $form->{newtemplates};
495   } else {
496     $form->{templates} =
497       ($form->{usetemplates}) ? $form->{usetemplates} : $form->{login};
498   }
499
500   # is there a basedir
501   if (!-d "$main::templates") {
502     $form->error(sprintf($locale->text("The directory %s does not exist."), $main::templates));
503   }
504
505   # add base directory to $form->{templates}
506   $form->{templates} =~ s|.*/||;
507   $form->{templates} =  "$main::templates/$form->{templates}";
508
509   my $myconfig = new User($form->{login});
510
511   $form->isblank("dbname", $locale->text('Dataset missing!'));
512   $form->isblank("dbuser", $locale->text('Database User missing!'));
513
514   foreach my $item (keys %{$form}) {
515     $myconfig->{$item} = $form->{$item};
516   }
517
518   delete $myconfig->{stylesheet};
519   if ($form->{userstylesheet}) {
520     $myconfig->{stylesheet} = $form->{userstylesheet};
521   }
522
523   $myconfig->save_member();
524
525   if ($main::auth->can_change_password()
526       && defined $form->{new_password}
527       && ($form->{new_password} ne '********')) {
528     $main::auth->change_password($form->{login}, $form->{new_password});
529   }
530
531   $form->{templates}       =~ s|.*/||;
532   $form->{templates}       =  "$main::templates/$form->{templates}";
533   $form->{mastertemplates} =~ s|.*/||;
534
535   # create user template directory and copy master files
536   if (!-d "$form->{templates}") {
537     umask(002);
538
539     if (mkdir "$form->{templates}", oct("771")) {
540
541       umask(007);
542
543       # copy templates to the directory
544       opendir TEMPLATEDIR, "$main::templates/." or $form->error("$main::templates : $ERRNO");
545       my @templates = grep /$form->{mastertemplates}.*?\.(html|tex|sty|odt|xml|txb)$/,
546         readdir TEMPLATEDIR;
547       closedir TEMPLATEDIR;
548
549       foreach my $file (@templates) {
550         open(TEMP, "$main::templates/$file")
551           or $form->error("$main::templates/$file : $ERRNO");
552
553         $file =~ s/\Q$form->{mastertemplates}\E-//;
554         open(NEW, ">$form->{templates}/$file")
555           or $form->error("$form->{templates}/$file : $ERRNO");
556
557         while (my $line = <TEMP>) {
558           print NEW $line;
559         }
560         close(TEMP);
561         close(NEW);
562       }
563     } else {
564       $form->error("$ERRNO: $form->{templates}");
565     }
566   }
567
568   # Add new user to his groups.
569   if (ref $form->{new_user_group_ids} eq 'ARRAY') {
570     my $all_groups = $main::auth->read_groups();
571     my %user       = $main::auth->read_user($form->{login});
572
573     foreach my $group_id (@{ $form->{new_user_group_ids} }) {
574       my $group = $all_groups->{$group_id};
575
576       next if !$group;
577
578       push @{ $group->{members} }, $user{id};
579       $main::auth->save_group($group);
580     }
581   }
582
583   $form->redirect($locale->text('User saved!'));
584
585 }
586
587 sub save_user_as_new {
588   my $form     = $main::form;
589
590   $form->{login} = $form->{new_user_login};
591   delete @{$form}{qw(edit new_user_login)};
592
593   save_user();
594 }
595
596 sub delete_user {
597   my $form     = $main::form;
598   my $locale   = $main::locale;
599
600   my %members   = $main::auth->read_all_users();
601   my $templates = $members{$form->{login}}->{templates};
602
603   $main::auth->delete_user($form->{login});
604
605   if ($templates) {
606     my $templates_in_use = 0;
607
608     foreach my $login (keys %members) {
609       next if $form->{login} eq $login;
610       next if $members{$login}->{templates} ne $templates;
611       $templates_in_use = 1;
612       last;
613     }
614
615     if (!$templates_in_use && -d $templates) {
616       unlink <$templates/*>;
617       rmdir $templates;
618     }
619   }
620
621   $form->redirect($locale->text('User deleted!'));
622
623 }
624
625 sub login_name {
626   my $login = shift;
627
628   $login =~ s/\[\]//g;
629   return ($login) ? $login : undef;
630
631 }
632
633 sub get_value {
634   my $line = shift;
635
636   my $form     = $main::form;
637
638   my ($null, $value) = split(/=/, $line, 2);
639
640   # remove comments
641   $value =~ s/\s#.*//g;
642
643   # remove any trailing whitespace
644   $value =~ s/^\s*(.*?)\s*$/$1/;
645
646   $value;
647 }
648
649 sub pg_database_administration {
650   my $form     = $main::form;
651
652   $form->{dbdriver} = 'Pg';
653   dbselect_source();
654
655 }
656
657 sub dbselect_source {
658   my $form     = $main::form;
659   my $locale   = $main::locale;
660
661   $form->{dbport}    = '5432';
662   $form->{dbuser}    = 'postgres';
663   $form->{dbdefault} = 'template1';
664   $form->{dbhost}    = 'localhost';
665
666   $form->{title}     = "Lx-Office ERP / " . $locale->text('Database Administration');
667
668   # Intentionnaly disabled unless fixed to work with the authentication DB.
669   $form->{ALLOW_DBBACKUP} = 0; # "$pg_dump_exe" ne "DISABLED";
670
671   $form->header();
672   print $form->parse_html_template("admin/dbadmin");
673 }
674
675 sub test_db_connection {
676   my $form     = $main::form;
677   my $locale   = $main::locale;
678
679   $form->{dbdriver} = 'Pg';
680   User::dbconnect_vars($form, $form->{dbname});
681
682   my $dbh = DBI->connect($form->{dbconnect}, $form->{dbuser}, $form->{dbpasswd});
683
684   $form->{connection_ok} = $dbh ? 1 : 0;
685   $form->{errstr}        = $DBI::errstr;
686
687   $dbh->disconnect() if ($dbh);
688
689   $form->{title} = $locale->text('Database Connection Test');
690   $form->header();
691   print $form->parse_html_template("admin/test_db_connection");
692 }
693
694 sub continue {
695   call_sub($main::form->{"nextsub"});
696 }
697
698 sub update_dataset {
699   my $form     = $main::form;
700   my $locale   = $main::locale;
701
702   $form->{title} =
703       "Lx-Office ERP "
704     . $locale->text('Database Administration') . " / "
705     . $locale->text('Update Dataset');
706
707   my @need_updates      = User->dbneedsupdate($form);
708   $form->{NEED_UPDATES} = \@need_updates;
709   $form->{ALL_UPDATED}  = !scalar @need_updates;
710
711   $form->header();
712   print $form->parse_html_template("admin/update_dataset");
713 }
714
715 sub dbupdate {
716   my $form     = $main::form;
717   my $locale   = $main::locale;
718
719   $form->{stylesheet} = "lx-office-erp.css";
720   $form->{title}      = $locale->text("Dataset upgrade");
721   $form->header();
722
723   my $rowcount           = $form->{rowcount} * 1;
724   my @update_rows        = grep { $form->{"update_$_"} } (1 .. $rowcount);
725   $form->{NOTHING_TO_DO} = !scalar @update_rows;
726   my $saved_form         = save_form();
727
728   $| = 1;
729
730   print $form->parse_html_template("admin/dbupgrade_all_header");
731
732   foreach my $i (@update_rows) {
733     restore_form($saved_form);
734
735     map { $form->{$_} = $form->{"${_}_${i}"} } qw(dbname dbdriver dbhost dbport dbuser dbpasswd);
736
737     my $controls = parse_dbupdate_controls($form, $form->{dbdriver});
738
739     print $form->parse_html_template("admin/dbupgrade_header");
740
741     $form->{dbupdate}        = $form->{dbname};
742     $form->{$form->{dbname}} = 1;
743
744     User->dbupdate($form);
745     User->dbupdate2($form, $controls);
746
747     print $form->parse_html_template("admin/dbupgrade_footer");
748   }
749
750   print $form->parse_html_template("admin/dbupgrade_all_done");
751 }
752
753 sub create_dataset {
754   my $form     = $main::form;
755   my $locale   = $main::locale;
756
757   $form->{dbsources} = join " ", map { "[${_}]" } sort User->dbsources($form);
758
759   $form->{CHARTS} = [];
760
761   opendir SQLDIR, "sql/." or $form->error($ERRNO);
762   foreach my $item (sort grep /-chart\.sql\z/, readdir SQLDIR) {
763     next if ($item eq 'Default-chart.sql');
764     $item =~ s/-chart\.sql//;
765     push @{ $form->{CHARTS} }, { "name"     => $item,
766                                  "selected" => $item eq "Germany-DATEV-SKR03EU" };
767   }
768   closedir SQLDIR;
769
770   my $default_charset = $main::dbcharset;
771   $default_charset ||= Common::DEFAULT_CHARSET;
772
773   my $cluster_encoding = User->dbclusterencoding($form);
774   if ($cluster_encoding && ($cluster_encoding =~ m/^(?:UTF-?8|UNICODE)$/i)) {
775     if ($main::dbcharset !~ m/^UTF-?8$/i) {
776       $form->show_generic_error($locale->text('The selected  PostgreSQL installation uses UTF-8 as its encoding. ' .
777                                               'Therefore you have to configure Lx-Office to use UTF-8 as well.'),
778                                 'back_button' => 1);
779     }
780
781     $form->{FORCE_DBENCODING} = 'UNICODE';
782
783   } else {
784     $form->{DBENCODINGS} = [];
785
786     foreach my $encoding (@Common::db_encodings) {
787       push @{ $form->{DBENCODINGS} }, { "dbencoding" => $encoding->{dbencoding},
788                                         "label"      => $encoding->{label},
789                                         "selected"   => $encoding->{charset} eq $default_charset };
790     }
791   }
792
793   $form->{title} =
794       "Lx-Office ERP "
795     . $locale->text('Database Administration') . " / "
796     . $locale->text('Create Dataset');
797
798   $form->header();
799   print $form->parse_html_template("admin/create_dataset");
800 }
801
802 sub dbcreate {
803   my $form     = $main::form;
804   my $locale   = $main::locale;
805
806   $form->isblank("db", $locale->text('Dataset missing!'));
807
808   User->dbcreate(\%$form);
809
810   $form->{title} =
811       "Lx-Office ERP "
812     . $locale->text('Database Administration') . " / "
813     . $locale->text('Create Dataset');
814
815   $form->header();
816   print $form->parse_html_template("admin/dbcreate");
817 }
818
819 sub delete_dataset {
820   my $form     = $main::form;
821   my $locale   = $main::locale;
822
823   my @dbsources = User->dbsources_unused($form);
824   $form->error($locale->text('Nothing to delete!')) unless @dbsources;
825
826   $form->{title} =
827       "Lx-Office ERP "
828     . $locale->text('Database Administration') . " / "
829     . $locale->text('Delete Dataset');
830   $form->{DBSOURCES} = [ map { { "name", $_ } } sort @dbsources ];
831
832   $form->header();
833   print $form->parse_html_template("admin/delete_dataset");
834 }
835
836 sub dbdelete {
837   my $form     = $main::form;
838   my $locale   = $main::locale;
839
840   if (!$form->{db}) {
841     $form->error($locale->text('No Dataset selected!'));
842   }
843
844   User->dbdelete(\%$form);
845
846   $form->{title} =
847       "Lx-Office ERP "
848     . $locale->text('Database Administration') . " / "
849     . $locale->text('Delete Dataset');
850   $form->header();
851   print $form->parse_html_template("admin/dbdelete");
852 }
853
854 sub backup_dataset {
855   my $form     = $main::form;
856   my $locale   = $main::locale;
857
858   $form->{title} =
859       "Lx-Office ERP "
860     . $locale->text('Database Administration') . " / "
861     . $locale->text('Backup Dataset');
862
863   if ("$main::pg_dump_exe" eq "DISABLED") {
864     $form->error($locale->text('Database backups and restorations are disabled in lx-erp.conf.'));
865   }
866
867   my @dbsources         = sort User->dbsources($form);
868   $form->{DATABASES}    = [ map { { "dbname" => $_ } } @dbsources ];
869   $form->{NO_DATABASES} = !scalar @dbsources;
870
871   my $username  = getpwuid $UID || "unknown-user";
872   my $hostname  = hostname() || "unknown-host";
873   $form->{from} = "Lx-Office Admin <${username}\@${hostname}>";
874
875   $form->header();
876   print $form->parse_html_template("admin/backup_dataset");
877 }
878
879 sub backup_dataset_start {
880   my $form     = $main::form;
881   my $locale   = $main::locale;
882
883   $form->{title} =
884       "Lx-Office ERP "
885     . $locale->text('Database Administration') . " / "
886     . $locale->text('Backup Dataset');
887
888   $main::pg_dump_exe ||= "pg_dump";
889
890   if ("$main::pg_dump_exe" eq "DISABLED") {
891     $form->error($locale->text('Database backups and restorations are disabled in lx-erp.conf.'));
892   }
893
894   $form->isblank("dbname", $locale->text('The dataset name is missing.'));
895   $form->isblank("to", $locale->text('The email address is missing.')) if $form->{destination} eq "email";
896
897   my $tmpdir = "/tmp/lx_office_backup_" . Common->unique_id();
898   mkdir $tmpdir, 0700 || $form->error($locale->text('A temporary directory could not be created:') . " $ERRNO");
899
900   my $pgpass = IO::File->new("${tmpdir}/.pgpass", O_WRONLY | O_CREAT, 0600);
901
902   if (!$pgpass) {
903     unlink $tmpdir;
904     $form->error($locale->text('A temporary file could not be created:') . " $ERRNO");
905   }
906
907   print $pgpass "$form->{dbhost}:$form->{dbport}:$form->{dbname}:$form->{dbuser}:$form->{dbpasswd}\n";
908   $pgpass->close();
909
910   $ENV{HOME} = $tmpdir;
911
912   my @args = ("-Ft", "-c", "-o", "-h", $form->{dbhost}, "-U", $form->{dbuser});
913   push @args, ("-p", $form->{dbport}) if ($form->{dbport});
914   push @args, $form->{dbname};
915
916   my $cmd  = "$main::pg_dump_exe " . join(" ", map { s/\\/\\\\/g; s/\"/\\\"/g; $_ } @args);
917   my $name = "dataset_backup_$form->{dbname}_" . strftime("%Y%m%d", localtime()) . ".tar";
918
919   if ($form->{destination} ne "email") {
920     my $in = IO::File->new("$cmd |");
921
922     if (!$in) {
923       unlink "${tmpdir}/.pgpass";
924       rmdir $tmpdir;
925
926       $form->error($locale->text('The pg_dump process could not be started.'));
927     }
928
929     print "content-type: application/x-tar\n";
930     print "content-disposition: attachment; filename=\"${name}\"\n\n";
931
932     while (my $line = <$in>) {
933       print $line;
934     }
935
936     $in->close();
937
938     unlink "${tmpdir}/.pgpass";
939     rmdir $tmpdir;
940
941   } else {
942     my $tmp = $tmpdir . "/dump_" . Common::unique_id();
943
944     if (system("$cmd > $tmp") != 0) {
945       unlink "${tmpdir}/.pgpass", $tmp;
946       rmdir $tmpdir;
947
948       $form->error($locale->text('The pg_dump process could not be started.'));
949     }
950
951     my $mail = new Mailer;
952
953     map { $mail->{$_} = $form->{$_} } qw(from to cc subject message);
954
955     $mail->{charset}     = $main::dbcharset ? $main::dbcharset : Common::DEFAULT_CHARSET;
956     $mail->{attachments} = [ { "filename" => $tmp, "name" => $name } ];
957     $mail->send();
958
959     unlink "${tmpdir}/.pgpass", $tmp;
960     rmdir $tmpdir;
961
962     $form->{title} =
963         "Lx-Office ERP "
964       . $locale->text('Database Administration') . " / "
965       . $locale->text('Backup Dataset');
966
967     $form->header();
968     print $form->parse_html_template("admin/backup_dataset_email_done");
969   }
970 }
971
972 sub restore_dataset {
973   my $form     = $main::form;
974   my $locale   = $main::locale;
975
976   $form->{title} =
977       "Lx-Office ERP "
978     . $locale->text('Database Administration') . " / "
979     . $locale->text('Restore Dataset');
980
981   if ("$main::pg_restore_exe" eq "DISABLED") {
982     $form->error($locale->text('Database backups and restorations are disabled in lx-erp.conf.'));
983   }
984
985   my $default_charset   = $main::dbcharset;
986   $default_charset    ||= Common::DEFAULT_CHARSET;
987
988   $form->{DBENCODINGS}  = [];
989
990   foreach my $encoding (@Common::db_encodings) {
991     push @{ $form->{DBENCODINGS} }, { "dbencoding" => $encoding->{dbencoding},
992                                       "label"      => $encoding->{label},
993                                       "selected"   => $encoding->{charset} eq $default_charset };
994   }
995
996   $form->header();
997   print $form->parse_html_template("admin/restore_dataset");
998 }
999
1000 sub restore_dataset_start {
1001   my $form     = $main::form;
1002   my $locale   = $main::locale;
1003
1004   $form->{title} =
1005       "Lx-Office ERP "
1006     . $locale->text('Database Administration') . " / "
1007     . $locale->text('Restore Dataset');
1008
1009   $main::pg_restore_exe ||= "pg_restore";
1010
1011   if ("$main::pg_restore_exe" eq "DISABLED") {
1012     $form->error($locale->text('Database backups and restorations are disabled in lx-erp.conf.'));
1013   }
1014
1015   $form->isblank("new_dbname", $locale->text('The dataset name is missing.'));
1016   $form->isblank("content", $locale->text('No backup file has been uploaded.'));
1017
1018   # Create temporary directories. Write the backup file contents to a temporary
1019   # file. Create a .pgpass file with the username and password for the pg_restore
1020   # utility.
1021
1022   my $tmpdir = "/tmp/lx_office_backup_" . Common->unique_id();
1023   mkdir $tmpdir, 0700 || $form->error($locale->text('A temporary directory could not be created:') . " $ERRNO");
1024
1025   my $pgpass = IO::File->new("${tmpdir}/.pgpass", O_WRONLY | O_CREAT, 0600);
1026
1027   if (!$pgpass) {
1028     unlink $tmpdir;
1029     $form->error($locale->text('A temporary file could not be created:') . " $ERRNO");
1030   }
1031
1032   print $pgpass "$form->{dbhost}:$form->{dbport}:$form->{new_dbname}:$form->{dbuser}:$form->{dbpasswd}\n";
1033   $pgpass->close();
1034
1035   $ENV{HOME} = $tmpdir;
1036
1037   my $tmp = $tmpdir . "/dump_" . Common::unique_id();
1038   my $tmpfile;
1039
1040   if (substr($form->{content}, 0, 2) eq "\037\213") {
1041     $tmpfile = IO::File->new("| gzip -d > $tmp");
1042     $tmpfile->binary();
1043
1044   } else {
1045     $tmpfile = IO::File->new($tmp, O_WRONLY | O_CREAT | O_BINARY, 0600);
1046   }
1047
1048   if (!$tmpfile) {
1049     unlink "${tmpdir}/.pgpass";
1050     rmdir $tmpdir;
1051
1052     $form->error($locale->text('A temporary file could not be created:') . " $ERRNO");
1053   }
1054
1055   print $tmpfile $form->{content};
1056   $tmpfile->close();
1057
1058   delete $form->{content};
1059
1060   # Try to connect to the database. Find out if a database with the same name exists.
1061   # If yes, then drop the existing database. Create a new one with the name and encoding
1062   # given by the user.
1063
1064   User::dbconnect_vars($form, "template1");
1065
1066   my %myconfig = map { $_ => $form->{$_} } grep /^db/, keys %{ $form };
1067   my $dbh      = $form->dbconnect(\%myconfig) || $form->dberror();
1068
1069   my ($query, $sth);
1070
1071   $form->{new_dbname} =~ s|[^a-zA-Z0-9_\-]||g;
1072
1073   $query = qq|SELECT COUNT(*) FROM pg_database WHERE datname = ?|;
1074   my ($count) = selectrow_query($form, $dbh, $query, $form->{new_dbname});
1075   if ($count) {
1076     do_query($form, $dbh, qq|DROP DATABASE $form->{new_dbname}|);
1077   }
1078
1079   my $found = 0;
1080   foreach my $item (@Common::db_encodings) {
1081     if ($item->{dbencoding} eq $form->{dbencoding}) {
1082       $found = 1;
1083       last;
1084     }
1085   }
1086   $form->{dbencoding} = "LATIN9" unless $form->{dbencoding};
1087
1088   do_query($form, $dbh, qq|CREATE DATABASE $form->{new_dbname} ENCODING ? TEMPLATE template0|, $form->{dbencoding});
1089
1090   $dbh->disconnect();
1091
1092   # Spawn pg_restore on the temporary file.
1093
1094   my @args = ("-h", $form->{dbhost}, "-U", $form->{dbuser}, "-d", $form->{new_dbname});
1095   push @args, ("-p", $form->{dbport}) if ($form->{dbport});
1096   push @args, $tmp;
1097
1098   my $cmd = "$main::pg_restore_exe " . join(" ", map { s/\\/\\\\/g; s/\"/\\\"/g; $_ } @args);
1099
1100   my $in = IO::File->new("$cmd 2>&1 |");
1101
1102   if (!$in) {
1103     unlink "${tmpdir}/.pgpass", $tmp;
1104     rmdir $tmpdir;
1105
1106     $form->error($locale->text('The pg_restore process could not be started.'));
1107   }
1108
1109   $English::AUTOFLUSH = 1;
1110
1111   $form->header();
1112   print $form->parse_html_template("admin/restore_dataset_start_header");
1113
1114   while (my $line = <$in>) {
1115     print $line;
1116   }
1117   $in->close();
1118
1119   $form->{retval} = $CHILD_ERROR >> 8;
1120   print $form->parse_html_template("admin/restore_dataset_start_footer");
1121
1122   unlink "${tmpdir}/.pgpass", $tmp;
1123   rmdir $tmpdir;
1124 }
1125
1126 sub unlock_system {
1127   my $form     = $main::form;
1128   my $locale   = $main::locale;
1129
1130   unlink "$main::userspath/nologin";
1131
1132   $form->{callback} = "admin.pl?action=list_users";
1133
1134   $form->redirect($locale->text('Lockfile removed!'));
1135
1136 }
1137
1138 sub lock_system {
1139   my $form     = $main::form;
1140   my $locale   = $main::locale;
1141
1142   open(FH, ">$main::userspath/nologin")
1143     or $form->error($locale->text('Cannot create Lock!'));
1144   close(FH);
1145
1146   $form->{callback} = "admin.pl?action=list_users";
1147
1148   $form->redirect($locale->text('Lockfile created!'));
1149
1150 }
1151
1152 sub yes {
1153   call_sub($main::form->{yes_nextsub});
1154 }
1155
1156 sub no {
1157   call_sub($main::form->{no_nextsub});
1158 }
1159
1160 sub add {
1161   call_sub($main::form->{add_nextsub});
1162 }
1163
1164 sub edit {
1165   my $form     = $main::form;
1166
1167   $form->{edit_nextsub} ||= 'edit_user';
1168
1169   call_sub($form->{edit_nextsub});
1170 }
1171
1172 sub delete {
1173   my $form     = $main::form;
1174
1175   $form->{delete_nextsub} ||= 'delete_user';
1176
1177   call_sub($form->{delete_nextsub});
1178 }
1179
1180 sub save {
1181   my $form     = $main::form;
1182
1183   $form->{save_nextsub} ||= 'save_user';
1184
1185   call_sub($form->{save_nextsub});
1186 }
1187
1188 sub back {
1189   call_sub($main::form->{back_nextsub});
1190 }
1191
1192 sub dispatcher {
1193   my $form     = $main::form;
1194   my $locale   = $main::locale;
1195
1196   foreach my $action (qw(create_standard_group dont_create_standard_group
1197                          save_user delete_user save_user_as_new)) {
1198     if ($form->{"action_${action}"}) {
1199       call_sub($action);
1200       return;
1201     }
1202   }
1203
1204   call_sub($form->{default_action}) if ($form->{default_action});
1205
1206   $form->error($locale->text('No action defined.'));
1207 }
1208
1209 1;