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