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