46f16d79083fdb5ab3fb89f94a69c437f3400068
[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   my ($login, $password, $newfile);
540   if ($main::webdav) {
541     my @webdavdirs =
542       qw(angebote bestellungen rechnungen anfragen lieferantenbestellungen einkaufsrechnungen);
543     foreach my $directory (@webdavdirs) {
544       my $file = "webdav/" . $directory . "/webdav-user";
545       if ($form->{$directory}) {
546         if (open(HTACCESS, "$file")) {
547           while (<HTACCESS>) {
548             ($login, $password) = split(/:/, $_);
549             if ($login ne $form->{login}) {
550               $newfile .= $_;
551             }
552           }
553           close(HTACCESS);
554         }
555         open(HTACCESS, "> $file") or die "cannot open $file $ERRNO\n";
556         $newfile .= $myconfig->{login} . ":" . $myconfig->{password} . "\n";
557         print(HTACCESS $newfile);
558         close(HTACCESS);
559       } else {
560         $form->{$directory} = 0;
561         if (open(HTACCESS, "$file")) {
562           while (<HTACCESS>) {
563             ($login, $password) = split(/:/, $_);
564             if ($login ne $form->{login}) {
565               $newfile .= $_;
566             }
567           }
568           close(HTACCESS);
569         }
570         open(HTACCESS, "> $file") or die "cannot open $file $ERRNO\n";
571         print(HTACCESS $newfile);
572         close(HTACCESS);
573       }
574     }
575   }
576
577   $form->{templates}       =~ s|.*/||;
578   $form->{templates}       =  "$main::templates/$form->{templates}";
579   $form->{mastertemplates} =~ s|.*/||;
580
581   # create user template directory and copy master files
582   if (!-d "$form->{templates}") {
583     umask(002);
584
585     if (mkdir "$form->{templates}", oct("771")) {
586
587       umask(007);
588
589       # copy templates to the directory
590       opendir TEMPLATEDIR, "$main::templates/." or $form->error("$main::templates : $ERRNO");
591       my @templates = grep /$form->{mastertemplates}.*?\.(html|tex|sty|odt|xml|txb)$/,
592         readdir TEMPLATEDIR;
593       closedir TEMPLATEDIR;
594
595       foreach my $file (@templates) {
596         open(TEMP, "$main::templates/$file")
597           or $form->error("$main::templates/$file : $ERRNO");
598
599         $file =~ s/\Q$form->{mastertemplates}\E-//;
600         open(NEW, ">$form->{templates}/$file")
601           or $form->error("$form->{templates}/$file : $ERRNO");
602
603         while (my $line = <TEMP>) {
604           print NEW $line;
605         }
606         close(TEMP);
607         close(NEW);
608       }
609     } else {
610       $form->error("$ERRNO: $form->{templates}");
611     }
612   }
613
614   # Add new user to his groups.
615   if (ref $form->{new_user_group_ids} eq 'ARRAY') {
616     my $all_groups = $main::auth->read_groups();
617     my %user       = $main::auth->read_user($form->{login});
618
619     foreach my $group_id (@{ $form->{new_user_group_ids} }) {
620       my $group = $all_groups->{$group_id};
621
622       next if !$group;
623
624       push @{ $group->{members} }, $user{id};
625       $main::auth->save_group($group);
626     }
627   }
628
629   $form->redirect($locale->text('User saved!'));
630
631 }
632
633 sub save_user_as_new {
634   my $form     = $main::form;
635
636   $form->{login} = $form->{new_user_login};
637   delete @{$form}{qw(edit new_user_login)};
638
639   save_user();
640 }
641
642 sub delete_user {
643   my $form     = $main::form;
644   my $locale   = $main::locale;
645
646   my %members   = $main::auth->read_all_users();
647   my $templates = $members{$form->{login}}->{templates};
648
649   $main::auth->delete_user($form->{login});
650
651   if ($templates) {
652     my $templates_in_use = 0;
653
654     foreach my $login (keys %members) {
655       next if $form->{login} eq $login;
656       next if $members{$login}->{templates} ne $templates;
657       $templates_in_use = 1;
658       last;
659     }
660
661     if (!$templates_in_use && -d $templates) {
662       unlink <$templates/*>;
663       rmdir $templates;
664     }
665   }
666
667   $form->redirect($locale->text('User deleted!'));
668
669 }
670
671 sub login_name {
672   my $login = shift;
673
674   $login =~ s/\[\]//g;
675   return ($login) ? $login : undef;
676
677 }
678
679 sub get_value {
680   my $line = shift;
681
682   my $form     = $main::form;
683
684   my ($null, $value) = split(/=/, $line, 2);
685
686   # remove comments
687   $value =~ s/\s#.*//g;
688
689   # remove any trailing whitespace
690   $value =~ s/^\s*(.*?)\s*$/$1/;
691
692   $value;
693 }
694
695 sub pg_database_administration {
696   my $form     = $main::form;
697
698   $form->{dbdriver} = 'Pg';
699   dbselect_source();
700
701 }
702
703 sub dbselect_source {
704   my $form     = $main::form;
705   my $locale   = $main::locale;
706
707   $form->{dbport}    = '5432';
708   $form->{dbuser}    = 'postgres';
709   $form->{dbdefault} = 'template1';
710   $form->{dbhost}    = 'localhost';
711
712   $form->{title}     = "Lx-Office ERP / " . $locale->text('Database Administration');
713
714   # Intentionnaly disabled unless fixed to work with the authentication DB.
715   $form->{ALLOW_DBBACKUP} = 0; # "$pg_dump_exe" ne "DISABLED";
716
717   $form->header();
718   print $form->parse_html_template("admin/dbadmin");
719 }
720
721 sub test_db_connection {
722   my $form     = $main::form;
723   my $locale   = $main::locale;
724
725   $form->{dbdriver} = 'Pg';
726   User::dbconnect_vars($form, $form->{dbname});
727
728   my $dbh = DBI->connect($form->{dbconnect}, $form->{dbuser}, $form->{dbpasswd});
729
730   $form->{connection_ok} = $dbh ? 1 : 0;
731   $form->{errstr}        = $DBI::errstr;
732
733   $dbh->disconnect() if ($dbh);
734
735   $form->{title} = $locale->text('Database Connection Test');
736   $form->header();
737   print $form->parse_html_template("admin/test_db_connection");
738 }
739
740 sub continue {
741   call_sub($main::form->{"nextsub"});
742 }
743
744 sub update_dataset {
745   my $form     = $main::form;
746   my $locale   = $main::locale;
747
748   $form->{title} =
749       "Lx-Office ERP "
750     . $locale->text('Database Administration') . " / "
751     . $locale->text('Update Dataset');
752
753   my @need_updates      = User->dbneedsupdate($form);
754   $form->{NEED_UPDATES} = \@need_updates;
755   $form->{ALL_UPDATED}  = !scalar @need_updates;
756
757   $form->header();
758   print $form->parse_html_template("admin/update_dataset");
759 }
760
761 sub dbupdate {
762   my $form     = $main::form;
763   my $locale   = $main::locale;
764
765   $form->{stylesheet} = "lx-office-erp.css";
766   $form->{title}      = $locale->text("Dataset upgrade");
767   $form->header();
768
769   my $rowcount           = $form->{rowcount} * 1;
770   my @update_rows        = grep { $form->{"update_$_"} } (1 .. $rowcount);
771   $form->{NOTHING_TO_DO} = !scalar @update_rows;
772   my $saved_form         = save_form();
773
774   $| = 1;
775
776   print $form->parse_html_template("admin/dbupgrade_all_header");
777
778   foreach my $i (@update_rows) {
779     restore_form($saved_form);
780
781     map { $form->{$_} = $form->{"${_}_${i}"} } qw(dbname dbdriver dbhost dbport dbuser dbpasswd);
782
783     my $controls = parse_dbupdate_controls($form, $form->{dbdriver});
784
785     print $form->parse_html_template("admin/dbupgrade_header");
786
787     $form->{dbupdate}        = $form->{dbname};
788     $form->{$form->{dbname}} = 1;
789
790     User->dbupdate($form);
791     User->dbupdate2($form, $controls);
792
793     print $form->parse_html_template("admin/dbupgrade_footer");
794   }
795
796   print $form->parse_html_template("admin/dbupgrade_all_done");
797 }
798
799 sub create_dataset {
800   my $form     = $main::form;
801   my $locale   = $main::locale;
802
803   $form->{dbsources} = join " ", map { "[${_}]" } sort User->dbsources($form);
804
805   $form->{CHARTS} = [];
806
807   opendir SQLDIR, "sql/." or $form->error($ERRNO);
808   foreach my $item (sort grep /-chart\.sql\z/, readdir SQLDIR) {
809     next if ($item eq 'Default-chart.sql');
810     $item =~ s/-chart\.sql//;
811     push @{ $form->{CHARTS} }, { "name"     => $item,
812                                  "selected" => $item eq "Germany-DATEV-SKR03EU" };
813   }
814   closedir SQLDIR;
815
816   my $default_charset = $main::dbcharset;
817   $default_charset ||= Common::DEFAULT_CHARSET;
818
819   my $cluster_encoding = User->dbclusterencoding($form);
820   if ($cluster_encoding && ($cluster_encoding =~ m/^(?:UTF-?8|UNICODE)$/i)) {
821     if ($main::dbcharset !~ m/^UTF-?8$/i) {
822       $form->show_generic_error($locale->text('The selected  PostgreSQL installation uses UTF-8 as its encoding. ' .
823                                               'Therefore you have to configure Lx-Office to use UTF-8 as well.'),
824                                 'back_button' => 1);
825     }
826
827     $form->{FORCE_DBENCODING} = 'UNICODE';
828
829   } else {
830     $form->{DBENCODINGS} = [];
831
832     foreach my $encoding (@Common::db_encodings) {
833       push @{ $form->{DBENCODINGS} }, { "dbencoding" => $encoding->{dbencoding},
834                                         "label"      => $encoding->{label},
835                                         "selected"   => $encoding->{charset} eq $default_charset };
836     }
837   }
838
839   $form->{title} =
840       "Lx-Office ERP "
841     . $locale->text('Database Administration') . " / "
842     . $locale->text('Create Dataset');
843
844   $form->header();
845   print $form->parse_html_template("admin/create_dataset");
846 }
847
848 sub dbcreate {
849   my $form     = $main::form;
850   my $locale   = $main::locale;
851
852   $form->isblank("db", $locale->text('Dataset missing!'));
853
854   User->dbcreate(\%$form);
855
856   $form->{title} =
857       "Lx-Office ERP "
858     . $locale->text('Database Administration') . " / "
859     . $locale->text('Create Dataset');
860
861   $form->header();
862   print $form->parse_html_template("admin/dbcreate");
863 }
864
865 sub delete_dataset {
866   my $form     = $main::form;
867   my $locale   = $main::locale;
868
869   my @dbsources = User->dbsources_unused($form);
870   $form->error($locale->text('Nothing to delete!')) unless @dbsources;
871
872   $form->{title} =
873       "Lx-Office ERP "
874     . $locale->text('Database Administration') . " / "
875     . $locale->text('Delete Dataset');
876   $form->{DBSOURCES} = [ map { { "name", $_ } } sort @dbsources ];
877
878   $form->header();
879   print $form->parse_html_template("admin/delete_dataset");
880 }
881
882 sub dbdelete {
883   my $form     = $main::form;
884   my $locale   = $main::locale;
885
886   if (!$form->{db}) {
887     $form->error($locale->text('No Dataset selected!'));
888   }
889
890   User->dbdelete(\%$form);
891
892   $form->{title} =
893       "Lx-Office ERP "
894     . $locale->text('Database Administration') . " / "
895     . $locale->text('Delete Dataset');
896   $form->header();
897   print $form->parse_html_template("admin/dbdelete");
898 }
899
900 sub backup_dataset {
901   my $form     = $main::form;
902   my $locale   = $main::locale;
903
904   $form->{title} =
905       "Lx-Office ERP "
906     . $locale->text('Database Administration') . " / "
907     . $locale->text('Backup Dataset');
908
909   if ("$main::pg_dump_exe" eq "DISABLED") {
910     $form->error($locale->text('Database backups and restorations are disabled in lx-erp.conf.'));
911   }
912
913   my @dbsources         = sort User->dbsources($form);
914   $form->{DATABASES}    = [ map { { "dbname" => $_ } } @dbsources ];
915   $form->{NO_DATABASES} = !scalar @dbsources;
916
917   my $username  = getpwuid $UID || "unknown-user";
918   my $hostname  = hostname() || "unknown-host";
919   $form->{from} = "Lx-Office Admin <${username}\@${hostname}>";
920
921   $form->header();
922   print $form->parse_html_template("admin/backup_dataset");
923 }
924
925 sub backup_dataset_start {
926   my $form     = $main::form;
927   my $locale   = $main::locale;
928
929   $form->{title} =
930       "Lx-Office ERP "
931     . $locale->text('Database Administration') . " / "
932     . $locale->text('Backup Dataset');
933
934   $main::pg_dump_exe ||= "pg_dump";
935
936   if ("$main::pg_dump_exe" eq "DISABLED") {
937     $form->error($locale->text('Database backups and restorations are disabled in lx-erp.conf.'));
938   }
939
940   $form->isblank("dbname", $locale->text('The dataset name is missing.'));
941   $form->isblank("to", $locale->text('The email address is missing.')) if $form->{destination} eq "email";
942
943   my $tmpdir = "/tmp/lx_office_backup_" . Common->unique_id();
944   mkdir $tmpdir, 0700 || $form->error($locale->text('A temporary directory could not be created:') . " $ERRNO");
945
946   my $pgpass = IO::File->new("${tmpdir}/.pgpass", O_WRONLY | O_CREAT, 0600);
947
948   if (!$pgpass) {
949     unlink $tmpdir;
950     $form->error($locale->text('A temporary file could not be created:') . " $ERRNO");
951   }
952
953   print $pgpass "$form->{dbhost}:$form->{dbport}:$form->{dbname}:$form->{dbuser}:$form->{dbpasswd}\n";
954   $pgpass->close();
955
956   $ENV{HOME} = $tmpdir;
957
958   my @args = ("-Ft", "-c", "-o", "-h", $form->{dbhost}, "-U", $form->{dbuser});
959   push @args, ("-p", $form->{dbport}) if ($form->{dbport});
960   push @args, $form->{dbname};
961
962   my $cmd  = "$main::pg_dump_exe " . join(" ", map { s/\\/\\\\/g; s/\"/\\\"/g; $_ } @args);
963   my $name = "dataset_backup_$form->{dbname}_" . strftime("%Y%m%d", localtime()) . ".tar";
964
965   if ($form->{destination} ne "email") {
966     my $in = IO::File->new("$cmd |");
967
968     if (!$in) {
969       unlink "${tmpdir}/.pgpass";
970       rmdir $tmpdir;
971
972       $form->error($locale->text('The pg_dump process could not be started.'));
973     }
974
975     print "content-type: application/x-tar\n";
976     print "content-disposition: attachment; filename=\"${name}\"\n\n";
977
978     while (my $line = <$in>) {
979       print $line;
980     }
981
982     $in->close();
983
984     unlink "${tmpdir}/.pgpass";
985     rmdir $tmpdir;
986
987   } else {
988     my $tmp = $tmpdir . "/dump_" . Common::unique_id();
989
990     if (system("$cmd > $tmp") != 0) {
991       unlink "${tmpdir}/.pgpass", $tmp;
992       rmdir $tmpdir;
993
994       $form->error($locale->text('The pg_dump process could not be started.'));
995     }
996
997     my $mail = new Mailer;
998
999     map { $mail->{$_} = $form->{$_} } qw(from to cc subject message);
1000
1001     $mail->{charset}     = $main::dbcharset ? $main::dbcharset : Common::DEFAULT_CHARSET;
1002     $mail->{attachments} = [ { "filename" => $tmp, "name" => $name } ];
1003     $mail->send();
1004
1005     unlink "${tmpdir}/.pgpass", $tmp;
1006     rmdir $tmpdir;
1007
1008     $form->{title} =
1009         "Lx-Office ERP "
1010       . $locale->text('Database Administration') . " / "
1011       . $locale->text('Backup Dataset');
1012
1013     $form->header();
1014     print $form->parse_html_template("admin/backup_dataset_email_done");
1015   }
1016 }
1017
1018 sub restore_dataset {
1019   my $form     = $main::form;
1020   my $locale   = $main::locale;
1021
1022   $form->{title} =
1023       "Lx-Office ERP "
1024     . $locale->text('Database Administration') . " / "
1025     . $locale->text('Restore Dataset');
1026
1027   if ("$main::pg_restore_exe" eq "DISABLED") {
1028     $form->error($locale->text('Database backups and restorations are disabled in lx-erp.conf.'));
1029   }
1030
1031   my $default_charset   = $main::dbcharset;
1032   $default_charset    ||= Common::DEFAULT_CHARSET;
1033
1034   $form->{DBENCODINGS}  = [];
1035
1036   foreach my $encoding (@Common::db_encodings) {
1037     push @{ $form->{DBENCODINGS} }, { "dbencoding" => $encoding->{dbencoding},
1038                                       "label"      => $encoding->{label},
1039                                       "selected"   => $encoding->{charset} eq $default_charset };
1040   }
1041
1042   $form->header();
1043   print $form->parse_html_template("admin/restore_dataset");
1044 }
1045
1046 sub restore_dataset_start {
1047   my $form     = $main::form;
1048   my $locale   = $main::locale;
1049
1050   $form->{title} =
1051       "Lx-Office ERP "
1052     . $locale->text('Database Administration') . " / "
1053     . $locale->text('Restore Dataset');
1054
1055   $main::pg_restore_exe ||= "pg_restore";
1056
1057   if ("$main::pg_restore_exe" eq "DISABLED") {
1058     $form->error($locale->text('Database backups and restorations are disabled in lx-erp.conf.'));
1059   }
1060
1061   $form->isblank("new_dbname", $locale->text('The dataset name is missing.'));
1062   $form->isblank("content", $locale->text('No backup file has been uploaded.'));
1063
1064   # Create temporary directories. Write the backup file contents to a temporary
1065   # file. Create a .pgpass file with the username and password for the pg_restore
1066   # utility.
1067
1068   my $tmpdir = "/tmp/lx_office_backup_" . Common->unique_id();
1069   mkdir $tmpdir, 0700 || $form->error($locale->text('A temporary directory could not be created:') . " $ERRNO");
1070
1071   my $pgpass = IO::File->new("${tmpdir}/.pgpass", O_WRONLY | O_CREAT, 0600);
1072
1073   if (!$pgpass) {
1074     unlink $tmpdir;
1075     $form->error($locale->text('A temporary file could not be created:') . " $ERRNO");
1076   }
1077
1078   print $pgpass "$form->{dbhost}:$form->{dbport}:$form->{new_dbname}:$form->{dbuser}:$form->{dbpasswd}\n";
1079   $pgpass->close();
1080
1081   $ENV{HOME} = $tmpdir;
1082
1083   my $tmp = $tmpdir . "/dump_" . Common::unique_id();
1084   my $tmpfile;
1085
1086   if (substr($form->{content}, 0, 2) eq "\037\213") {
1087     $tmpfile = IO::File->new("| gzip -d > $tmp");
1088     $tmpfile->binary();
1089
1090   } else {
1091     $tmpfile = IO::File->new($tmp, O_WRONLY | O_CREAT | O_BINARY, 0600);
1092   }
1093
1094   if (!$tmpfile) {
1095     unlink "${tmpdir}/.pgpass";
1096     rmdir $tmpdir;
1097
1098     $form->error($locale->text('A temporary file could not be created:') . " $ERRNO");
1099   }
1100
1101   print $tmpfile $form->{content};
1102   $tmpfile->close();
1103
1104   delete $form->{content};
1105
1106   # Try to connect to the database. Find out if a database with the same name exists.
1107   # If yes, then drop the existing database. Create a new one with the name and encoding
1108   # given by the user.
1109
1110   User::dbconnect_vars($form, "template1");
1111
1112   my %myconfig = map { $_ => $form->{$_} } grep /^db/, keys %{ $form };
1113   my $dbh      = $form->dbconnect(\%myconfig) || $form->dberror();
1114
1115   my ($query, $sth);
1116
1117   $form->{new_dbname} =~ s|[^a-zA-Z0-9_\-]||g;
1118
1119   $query = qq|SELECT COUNT(*) FROM pg_database WHERE datname = ?|;
1120   my ($count) = selectrow_query($form, $dbh, $query, $form->{new_dbname});
1121   if ($count) {
1122     do_query($form, $dbh, qq|DROP DATABASE $form->{new_dbname}|);
1123   }
1124
1125   my $found = 0;
1126   foreach my $item (@Common::db_encodings) {
1127     if ($item->{dbencoding} eq $form->{dbencoding}) {
1128       $found = 1;
1129       last;
1130     }
1131   }
1132   $form->{dbencoding} = "LATIN9" unless $form->{dbencoding};
1133
1134   do_query($form, $dbh, qq|CREATE DATABASE $form->{new_dbname} ENCODING ? TEMPLATE template0|, $form->{dbencoding});
1135
1136   $dbh->disconnect();
1137
1138   # Spawn pg_restore on the temporary file.
1139
1140   my @args = ("-h", $form->{dbhost}, "-U", $form->{dbuser}, "-d", $form->{new_dbname});
1141   push @args, ("-p", $form->{dbport}) if ($form->{dbport});
1142   push @args, $tmp;
1143
1144   my $cmd = "$main::pg_restore_exe " . join(" ", map { s/\\/\\\\/g; s/\"/\\\"/g; $_ } @args);
1145
1146   my $in = IO::File->new("$cmd 2>&1 |");
1147
1148   if (!$in) {
1149     unlink "${tmpdir}/.pgpass", $tmp;
1150     rmdir $tmpdir;
1151
1152     $form->error($locale->text('The pg_restore process could not be started.'));
1153   }
1154
1155   $English::AUTOFLUSH = 1;
1156
1157   $form->header();
1158   print $form->parse_html_template("admin/restore_dataset_start_header");
1159
1160   while (my $line = <$in>) {
1161     print $line;
1162   }
1163   $in->close();
1164
1165   $form->{retval} = $CHILD_ERROR >> 8;
1166   print $form->parse_html_template("admin/restore_dataset_start_footer");
1167
1168   unlink "${tmpdir}/.pgpass", $tmp;
1169   rmdir $tmpdir;
1170 }
1171
1172 sub unlock_system {
1173   my $form     = $main::form;
1174   my $locale   = $main::locale;
1175
1176   unlink "$main::userspath/nologin";
1177
1178   $form->{callback} = "admin.pl?action=list_users";
1179
1180   $form->redirect($locale->text('Lockfile removed!'));
1181
1182 }
1183
1184 sub lock_system {
1185   my $form     = $main::form;
1186   my $locale   = $main::locale;
1187
1188   open(FH, ">$main::userspath/nologin")
1189     or $form->error($locale->text('Cannot create Lock!'));
1190   close(FH);
1191
1192   $form->{callback} = "admin.pl?action=list_users";
1193
1194   $form->redirect($locale->text('Lockfile created!'));
1195
1196 }
1197
1198 sub yes {
1199   call_sub($main::form->{yes_nextsub});
1200 }
1201
1202 sub no {
1203   call_sub($main::form->{no_nextsub});
1204 }
1205
1206 sub add {
1207   call_sub($main::form->{add_nextsub});
1208 }
1209
1210 sub edit {
1211   my $form     = $main::form;
1212
1213   $form->{edit_nextsub} ||= 'edit_user';
1214
1215   call_sub($form->{edit_nextsub});
1216 }
1217
1218 sub delete {
1219   my $form     = $main::form;
1220
1221   $form->{delete_nextsub} ||= 'delete_user';
1222
1223   call_sub($form->{delete_nextsub});
1224 }
1225
1226 sub save {
1227   my $form     = $main::form;
1228
1229   $form->{save_nextsub} ||= 'save_user';
1230
1231   call_sub($form->{save_nextsub});
1232 }
1233
1234 sub back {
1235   call_sub($main::form->{back_nextsub});
1236 }
1237
1238 sub dispatcher {
1239   my $form     = $main::form;
1240   my $locale   = $main::locale;
1241
1242   foreach my $action (qw(create_standard_group dont_create_standard_group
1243                          save_user delete_user save_user_as_new)) {
1244     if ($form->{"action_${action}"}) {
1245       call_sub($action);
1246       return;
1247     }
1248   }
1249
1250   call_sub($form->{default_action}) if ($form->{default_action});
1251
1252   $form->error($locale->text('No action defined.'));
1253 }
1254
1255 1;