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