7581e9b34ad2fc9cf9eabb6c8594fbe489da3762
[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 # parserhappy(R):
65
66 #  $locale->text('periodic')
67 #  $locale->text('income')
68 #  $locale->text('perpetual')
69 #  $locale->text('balance')
70
71 our $cgi;
72 our $form;
73 our $locale;
74 our $auth;
75
76 my @valid_dateformats = qw(mm-dd-yy mm/dd/yy dd-mm-yy dd/mm/yy dd.mm.yy yyyy-mm-dd);
77 my @valid_numberformats = ('1,000.00', '1000.00', '1.000,00', '1000,00');
78 my @all_stylesheets = qw(lx-office-erp.css Win2000.css Mobile.css kivitendo.css);
79 my @all_menustyles = (
80   { id => 'old', title => $::locale->text('Old (on the side)') },
81   { id => 'v3',  title => $::locale->text('Top (CSS)') },
82   { id => 'v4',  title => $::locale->text('Top (CSS) new') },
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   $form->{stylesheet} = "lx-office-erp.css";
95   $form->{favicon}    = "favicon.ico";
96
97   if ($form->{action}) {
98     if ($auth->authenticate_root($form->{'{AUTH}admin_password'}) != $auth->OK()) {
99       $auth->punish_wrong_login;
100       $form->{error_message} = $locale->text('Incorrect Password!');
101       $auth->delete_session_value('admin_password');
102       adminlogin();
103     } else {
104       if ($auth->session_tables_present()) {
105         delete $::form->{'{AUTH}admin_password'};
106         _apply_dbupgrade_scripts();
107       }
108
109       call_sub($locale->findsub($form->{action}));
110     }
111   } else {
112     # if there are no drivers bail out
113     $form->error($locale->text('No Database Drivers available!'))
114       unless (User->dbdrivers);
115
116     adminlogin();
117   }
118   $::lxdebug->leave_sub;
119 }
120
121 sub adminlogin {
122   my $form   = $main::form;
123   my $locale = $main::locale;
124
125   $form->{title} = qq|kivitendo $form->{version} | . $locale->text('Administration');
126
127   $form->header();
128   print $form->parse_html_template('admin/adminlogin');
129 }
130
131 sub login {
132   check_auth_db_and_tables();
133   list_users();
134 }
135
136 sub logout {
137   $main::auth->destroy_session();
138   adminlogin();
139 }
140
141 sub check_auth_db_and_tables {
142   my $form   = $main::form;
143   my $locale = $main::locale;
144
145   my %params;
146
147   map { $params{"db_${_}"} = $main::auth->{DB_config}->{$_} } keys %{ $auth->{DB_config} };
148
149   $params{admin_password} = $::lx_office_conf{authentication}->{admin_password};
150
151   if (!$main::auth->check_database()) {
152     $form->{title} = $locale->text('Authentification database creation');
153     $form->header();
154     print $form->parse_html_template('admin/check_auth_database', \%params);
155
156     ::end_of_request();
157   }
158
159   if (!$main::auth->check_tables()) {
160     $form->{title} = $locale->text('Authentification tables creation');
161     $form->header();
162     print $form->parse_html_template('admin/check_auth_tables', \%params);
163
164     ::end_of_request();
165   }
166
167   my $memberfile = $::lx_office_conf{paths}->{memberfile};
168   if (-f $memberfile) {
169     my $memberdir = "";
170
171     if ($memberfile =~ m|^.*/|) {
172       $memberdir = $&;
173     }
174
175     my $backupdir = "${memberdir}member-file-migration";
176
177     $form->{title} = $locale->text('User data migration');
178     $form->header();
179     print $form->parse_html_template('admin/user_migration', { 'memberfile' => $memberfile,
180                                                                'backupdir'  => $backupdir });
181
182     ::end_of_request();
183   }
184 }
185
186 sub create_auth_db {
187   my $form = $main::form;
188
189   $main::auth->create_database('superuser'          => $form->{db_superuser},
190                                'superuser_password' => $form->{db_superuser_password},
191                                'template'           => $form->{db_template});
192   login();
193 }
194
195 sub create_auth_tables {
196   my $form   = $main::form;
197   my $locale = $main::locale;
198
199   $main::auth->create_tables();
200   $main::auth->set_session_value('admin_password', $form->{'{AUTH}admin_password'});
201   $main::auth->create_or_refresh_session();
202
203   my $memberfile = $::lx_office_conf{paths}->{memberfile};
204   if (!-f $memberfile) {
205     # New installation -- create a standard group with full access
206     my %members;
207     my $group = {
208       'name'        => $locale->text('Full Access'),
209       'description' => $locale->text('Full access to all functions'),
210       'rights'      => { map { $_ => 1 } SL::Auth::all_rights() },
211       'members'     => [ map { $_->{id} } values %members ],
212     };
213
214     $main::auth->save_group($group);
215   }
216
217   _apply_dbupgrade_scripts();
218   login();
219 }
220
221 sub migrate_users {
222   $main::lxdebug->enter_sub();
223
224   my $form      = $main::form;
225   my $locale    = $main::locale;
226
227   my $memberdir = "";
228
229   my $memberfile = $::lx_office_conf{paths}->{memberfile};
230   if ($memberfile =~ m|^.*/|) {
231     $memberdir = $&;
232   }
233
234   my $backupdir = "${memberdir}member-file-migration";
235
236   if (! -d $backupdir && !mkdir $backupdir, 0700) {
237     $form->error(sprintf($locale->text('The directory "%s" could not be created:\n%s'), $backupdir, $!));
238   }
239
240   copy $memberfile, "users/member-file-migration/members";
241
242   my $in = IO::File->new($memberfile, "r");
243
244   $form->error($locale->text('Could not open the old memberfile.')) if (!$in);
245
246   my (%members, $login);
247
248   while (<$in>) {
249     chomp;
250
251     next if (m/^\s*\#/);
252
253     if (m/^\[.*\]/) {
254       $login = $_;
255       $login =~ s/(\[|\])//g;
256       $login =~ s/^\s*//;
257       $login =~ s/\s*$//;
258
259       $members{$login} = { "login" => $login };
260       next;
261     }
262
263     if ($login && m/=/) {
264       my ($key, $value) = split m/\s*=\s*/, $_, 2;
265       $key   =~ s|^\s*||;
266       $value =~ s|\s*$||;
267
268       $value =~ s|\\r||g;
269       $value =~ s|\\n|\n|g;
270
271       $members{$login}->{$key} = $value;
272     }
273   }
274
275   $in->close();
276
277   delete $members{"root login"};
278
279   map { $_->{dbpasswd} = unpack 'u', $_->{dbpasswd} } values %members;
280
281   while (my ($login, $params) = each %members) {
282     $main::auth->save_user($login, %{ $params });
283     $main::auth->change_password($login, $params->{password}, 1);
284
285     my $conf_file = "${memberdir}${login}.conf";
286
287     if (-f $conf_file) {
288       copy   $conf_file, "${backupdir}/${login}.conf";
289       unlink $conf_file;
290     }
291   }
292
293   unlink $memberfile;
294
295   my @member_list = sort { lc $a->{login} cmp lc $b->{login} } values %members;
296
297   $form->{title} = $locale->text('User data migration');
298   $form->header();
299   print $form->parse_html_template('admin/user_migration_done', { 'MEMBERS' => \@member_list });
300
301   $main::lxdebug->leave_sub();
302 }
303
304 sub create_standard_group_ask {
305   my $form   = $main::form;
306   my $locale = $main::locale;
307
308   $form->{title} = $locale->text('Create a standard group');
309
310   $form->header();
311   print $form->parse_html_template("admin/create_standard_group_ask");
312 }
313
314 sub create_standard_group {
315   my $form    = $main::form;
316   my $locale  = $main::locale;
317
318   my %members = $main::auth->read_all_users();
319
320   my $groups  = $main::auth->read_groups();
321
322   foreach my $group (values %{$groups}) {
323     if (($form->{group_id} != $group->{id})
324         && ($form->{name} eq $group->{name})) {
325       $form->show_generic_error($locale->text("A group with that name does already exist."));
326     }
327   }
328
329   my $group = {
330     'name'        => $locale->text('Full Access'),
331     'description' => $locale->text('Full access to all functions'),
332     'rights'      => { map { $_ => 1 } SL::Auth::all_rights() },
333     'members'     => [ map { $_->{id} } values %members ],
334   };
335
336   $main::auth->save_group($group);
337
338   user_migration_complete(1);
339 }
340
341 sub dont_create_standard_group {
342   user_migration_complete(0);
343 }
344
345 sub user_migration_complete {
346   my $standard_group_created = shift;
347
348   my $form                   = $main::form;
349   my $locale                 = $main::locale;
350
351   $form->{title} = $locale->text('User migration complete');
352   $form->header();
353
354   print $form->parse_html_template('admin/user_migration_complete', { 'standard_group_created' => $standard_group_created });
355 }
356
357 sub list_users {
358   my $form    = $main::form;
359   my $locale  = $main::locale;
360
361   my %members = $main::auth->read_all_users();
362
363   delete $members{"root login"};
364
365   for (values %members) {
366     $_->{templates} =~ s|.*/||;
367     $_->{login_url} =  $::locale->is_utf8 ? Encode::encode('utf-8-strict', $_->{login}) : $_->{login_url};
368   }
369
370   $form->{title}   = "kivitendo " . $locale->text('Administration');
371   $form->{LOCKED}  = -e _nologin_file_name();
372   $form->{MEMBERS} = [ @members{sort { lc $a cmp lc $b } keys %members} ];
373
374   $form->header();
375   print $form->parse_html_template("admin/list_users");
376 }
377
378 sub add_user {
379   $::form->{title}   = "kivitendo " . $::locale->text('Administration') . " / " . $::locale->text('Add User');
380
381 # Note: Menu Style 'v3' is not compatible to all browsers!
382 # "menustyle"    => "old" sets the HTML Menu to default.
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"   => "lx-office-erp.css",
390     "menustyle"    => "old",
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   $form->{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   opendir SQLDIR, "sql/." or $form->error($ERRNO);
748   foreach my $item (sort grep /-chart\.sql\z/, readdir SQLDIR) {
749     next if ($item eq 'Default-chart.sql');
750     $item =~ s/-chart\.sql//;
751     push @{ $form->{CHARTS} }, { "name"     => $item,
752                                  "selected" => $item eq "Germany-DATEV-SKR03EU" };
753   }
754   closedir SQLDIR;
755
756   $form->{ACCOUNTING_METHODS} = [];
757   foreach my $item ( qw(accrual cash) ) {
758     push @{ $form->{ACCOUNTING_METHODS} }, { "name"     => $item,
759                                  "selected" => $item eq "cash" };
760   };
761
762   $form->{INVENTORY_SYSTEMS} = [];
763   foreach my $item ( qw(perpetual periodic) ) {
764     push @{ $form->{INVENTORY_SYSTEMS} }, { "name"     => $item,
765                                  "selected" => $item eq "periodic" };
766   };
767
768   $form->{PROFIT_DETERMINATIONS} = [];
769   foreach my $item ( qw(balance income) ) {
770     push @{ $form->{PROFIT_DETERMINATIONS} }, { "name"     => $item,
771                                  "selected" => $item eq "income" };
772   };
773
774   my $default_charset = $::lx_office_conf{system}->{dbcharset};
775   $default_charset ||= Common::DEFAULT_CHARSET;
776
777   my $cluster_encoding = User->dbclusterencoding($form);
778   if ($cluster_encoding && ($cluster_encoding =~ m/^(?:UTF-?8|UNICODE)$/i)) {
779     if ($::lx_office_conf{system}->{dbcharset} !~ m/^UTF-?8$/i) {
780       $form->show_generic_error($locale->text('The selected  PostgreSQL installation uses UTF-8 as its encoding. ' .
781                                               'Therefore you have to configure Lx-Office to use UTF-8 as well.'),
782                                 'back_button' => 1);
783     }
784
785     $form->{FORCE_DBENCODING} = 'UNICODE';
786
787   } else {
788     $form->{DBENCODINGS} = [];
789
790     foreach my $encoding (@Common::db_encodings) {
791       push @{ $form->{DBENCODINGS} }, { "dbencoding" => $encoding->{dbencoding},
792                                         "label"      => $encoding->{label},
793                                         "selected"   => $encoding->{charset} eq $default_charset };
794     }
795   }
796
797   $form->{title} = "kivitendo " . $locale->text('Database Administration') . " / " . $locale->text('Create Dataset');
798
799   $form->header();
800   print $form->parse_html_template("admin/create_dataset");
801 }
802
803 sub dbcreate {
804   my $form   = $main::form;
805   my $locale = $main::locale;
806
807   $form->isblank("db", $locale->text('Dataset missing!'));
808
809   User->dbcreate(\%$form);
810
811   $form->{title} = "kivitendo " . $locale->text('Database Administration') . " / " . $locale->text('Create Dataset');
812
813   $form->header();
814   print $form->parse_html_template("admin/dbcreate");
815 }
816
817 sub delete_dataset {
818   my $form      = $main::form;
819   my $locale    = $main::locale;
820
821   my @dbsources = User->dbsources_unused($form);
822   $form->error($locale->text('Nothing to delete!')) unless @dbsources;
823
824   $form->{title}     = "kivitendo " . $locale->text('Database Administration') . " / " . $locale->text('Delete Dataset');
825   $form->{DBSOURCES} = [ map { { "name", $_ } } sort @dbsources ];
826
827   $form->header();
828   print $form->parse_html_template("admin/delete_dataset");
829 }
830
831 sub dbdelete {
832   my $form   = $main::form;
833   my $locale = $main::locale;
834
835   if (!$form->{db}) {
836     $form->error($locale->text('No Dataset selected!'));
837   }
838
839   User->dbdelete(\%$form);
840
841   $form->{title} = "kivitendo " . $locale->text('Database Administration') . " / " . $locale->text('Delete Dataset');
842   $form->header();
843   print $form->parse_html_template("admin/dbdelete");
844 }
845
846 sub backup_dataset {
847   my $form       = $main::form;
848   my $locale     = $main::locale;
849
850   $form->{title} = "kivitendo " . $locale->text('Database Administration') . " / " . $locale->text('Backup Dataset');
851
852   if ($::lx_office_conf{applications}->{pg_dump} eq "DISABLED") {
853     $form->error($locale->text('Database backups and restorations are disabled in the configuration.'));
854   }
855
856   my @dbsources         = sort User->dbsources($form);
857   $form->{DATABASES}    = [ map { { "dbname" => $_ } } @dbsources ];
858   $form->{NO_DATABASES} = !scalar @dbsources;
859
860   my $username  = getpwuid $UID || "unknown-user";
861   my $hostname  = hostname() || "unknown-host";
862   $form->{from} = "kivitendo Admin <${username}\@${hostname}>";
863
864   $form->header();
865   print $form->parse_html_template("admin/backup_dataset");
866 }
867
868 sub backup_dataset_start {
869   my $form       = $main::form;
870   my $locale     = $main::locale;
871
872   $form->{title} = "kivitendo " . $locale->text('Database Administration') . " / " . $locale->text('Backup Dataset');
873
874   my $pg_dump_exe = $::lx_office_conf{applications}->{pg_dump} || "pg_dump";
875
876   if ("$pg_dump_exe" eq "DISABLED") {
877     $form->error($locale->text('Database backups and restorations are disabled in the configuration.'));
878   }
879
880   $form->isblank("dbname", $locale->text('The dataset name is missing.'));
881   $form->isblank("to", $locale->text('The email address is missing.')) if $form->{destination} eq "email";
882
883   my $tmpdir = "/tmp/lx_office_backup_" . Common->unique_id();
884   mkdir $tmpdir, 0700 || $form->error($locale->text('A temporary directory could not be created:') . " $ERRNO");
885
886   my $pgpass = IO::File->new("${tmpdir}/.pgpass", O_WRONLY | O_CREAT, 0600);
887
888   if (!$pgpass) {
889     unlink $tmpdir;
890     $form->error($locale->text('A temporary file could not be created:') . " $ERRNO");
891   }
892
893   print $pgpass "$form->{dbhost}:$form->{dbport}:$form->{dbname}:$form->{dbuser}:$form->{dbpasswd}\n";
894   $pgpass->close();
895
896   $ENV{HOME} = $tmpdir;
897
898   my @args = ("-Ft", "-c", "-o", "-h", $form->{dbhost}, "-U", $form->{dbuser});
899   push @args, ("-p", $form->{dbport}) if ($form->{dbport});
900   push @args, $form->{dbname};
901
902   my $cmd  = "$pg_dump_exe " . join(" ", map { s/\\/\\\\/g; s/\"/\\\"/g; $_ } @args);
903   my $name = "dataset_backup_$form->{dbname}_" . strftime("%Y%m%d", localtime()) . ".tar";
904
905   if ($form->{destination} ne "email") {
906     my $in = IO::File->new("$cmd |");
907
908     if (!$in) {
909       unlink "${tmpdir}/.pgpass";
910       rmdir $tmpdir;
911
912       $form->error($locale->text('The pg_dump process could not be started.'));
913     }
914
915     print "content-type: application/x-tar\n";
916     print "content-disposition: attachment; filename=\"${name}\"\n\n";
917
918     while (my $line = <$in>) {
919       print $line;
920     }
921
922     $in->close();
923
924     unlink "${tmpdir}/.pgpass";
925     rmdir $tmpdir;
926
927   } else {
928     my $tmp = $tmpdir . "/dump_" . Common::unique_id();
929
930     if (system("$cmd > $tmp") != 0) {
931       unlink "${tmpdir}/.pgpass", $tmp;
932       rmdir $tmpdir;
933
934       $form->error($locale->text('The pg_dump process could not be started.'));
935     }
936
937     my $mail = new Mailer;
938
939     map { $mail->{$_} = $form->{$_} } qw(from to cc subject message);
940
941     $mail->{charset}     = $::lx_office_conf{system}->{dbcharset} || Common::DEFAULT_CHARSET;
942     $mail->{attachments} = [ { "filename" => $tmp, "name" => $name } ];
943     $mail->send();
944
945     unlink "${tmpdir}/.pgpass", $tmp;
946     rmdir $tmpdir;
947
948     $form->{title} = "kivitendo " . $locale->text('Database Administration') . " / " . $locale->text('Backup Dataset');
949
950     $form->header();
951     print $form->parse_html_template("admin/backup_dataset_email_done");
952   }
953 }
954
955 sub restore_dataset {
956   my $form       = $main::form;
957   my $locale     = $main::locale;
958
959   $form->{title} = "kivitendo " . $locale->text('Database Administration') . " / " . $locale->text('Restore Dataset');
960
961   if ($::lx_office_conf{applications}->{pg_restore} eq "DISABLED") {
962     $form->error($locale->text('Database backups and restorations are disabled in the configuration.'));
963   }
964
965   my $default_charset   = $::lx_office_conf{system}->{dbcharset};
966   $default_charset    ||= Common::DEFAULT_CHARSET;
967
968   $form->{DBENCODINGS}  = [];
969
970   foreach my $encoding (@Common::db_encodings) {
971     push @{ $form->{DBENCODINGS} }, { "dbencoding" => $encoding->{dbencoding},
972                                       "label"      => $encoding->{label},
973                                       "selected"   => $encoding->{charset} eq $default_charset };
974   }
975
976   $form->header();
977   print $form->parse_html_template("admin/restore_dataset");
978 }
979
980 sub restore_dataset_start {
981   my $form       = $main::form;
982   my $locale     = $main::locale;
983
984   $form->{title} = "kivitendo " . $locale->text('Database Administration') . " / " . $locale->text('Restore Dataset');
985
986   my $pg_restore_exe = $::lx_office_conf{applications}->{pg_restore} || "pg_restore";
987
988   if ("$pg_restore_exe" eq "DISABLED") {
989     $form->error($locale->text('Database backups and restorations are disabled in the configuration.'));
990   }
991
992   $form->isblank("new_dbname", $locale->text('The dataset name is missing.'));
993   $form->isblank("content", $locale->text('No backup file has been uploaded.'));
994
995   # Create temporary directories. Write the backup file contents to a temporary
996   # file. Create a .pgpass file with the username and password for the pg_restore
997   # utility.
998
999   my $tmpdir = "/tmp/lx_office_backup_" . Common->unique_id();
1000   mkdir $tmpdir, 0700 || $form->error($locale->text('A temporary directory could not be created:') . " $ERRNO");
1001
1002   my $pgpass = IO::File->new("${tmpdir}/.pgpass", O_WRONLY | O_CREAT, 0600);
1003
1004   if (!$pgpass) {
1005     unlink $tmpdir;
1006     $form->error($locale->text('A temporary file could not be created:') . " $ERRNO");
1007   }
1008
1009   print $pgpass "$form->{dbhost}:$form->{dbport}:$form->{new_dbname}:$form->{dbuser}:$form->{dbpasswd}\n";
1010   $pgpass->close();
1011
1012   $ENV{HOME} = $tmpdir;
1013
1014   my $tmp = $tmpdir . "/dump_" . Common::unique_id();
1015   my $tmpfile;
1016
1017   if (substr($form->{content}, 0, 2) eq "\037\213") {
1018     $tmpfile = IO::File->new("| gzip -d > $tmp");
1019     $tmpfile->binary();
1020
1021   } else {
1022     $tmpfile = IO::File->new($tmp, O_WRONLY | O_CREAT | O_BINARY, 0600);
1023   }
1024
1025   if (!$tmpfile) {
1026     unlink "${tmpdir}/.pgpass";
1027     rmdir $tmpdir;
1028
1029     $form->error($locale->text('A temporary file could not be created:') . " $ERRNO");
1030   }
1031
1032   print $tmpfile $form->{content};
1033   $tmpfile->close();
1034
1035   delete $form->{content};
1036
1037   # Try to connect to the database. Find out if a database with the same name exists.
1038   # If yes, then drop the existing database. Create a new one with the name and encoding
1039   # given by the user.
1040
1041   User::dbconnect_vars($form, "template1");
1042
1043   my %myconfig = map { $_ => $form->{$_} } grep /^db/, keys %{ $form };
1044   my $dbh      = $form->dbconnect(\%myconfig) || $form->dberror();
1045
1046   my ($query, $sth);
1047
1048   $form->{new_dbname} =~ s|[^a-zA-Z0-9_\-]||g;
1049
1050   $query = qq|SELECT COUNT(*) FROM pg_database WHERE datname = ?|;
1051   my ($count) = selectrow_query($form, $dbh, $query, $form->{new_dbname});
1052   if ($count) {
1053     do_query($form, $dbh, qq|DROP DATABASE $form->{new_dbname}|);
1054   }
1055
1056   my $found = 0;
1057   foreach my $item (@Common::db_encodings) {
1058     if ($item->{dbencoding} eq $form->{dbencoding}) {
1059       $found = 1;
1060       last;
1061     }
1062   }
1063   $form->{dbencoding} = "LATIN9" unless $form->{dbencoding};
1064
1065   do_query($form, $dbh, qq|CREATE DATABASE $form->{new_dbname} ENCODING ? TEMPLATE template0|, $form->{dbencoding});
1066
1067   $dbh->disconnect();
1068
1069   # Spawn pg_restore on the temporary file.
1070
1071   my @args = ("-h", $form->{dbhost}, "-U", $form->{dbuser}, "-d", $form->{new_dbname});
1072   push @args, ("-p", $form->{dbport}) if ($form->{dbport});
1073   push @args, $tmp;
1074
1075   my $cmd = "$pg_restore_exe " . join(" ", map { s/\\/\\\\/g; s/\"/\\\"/g; $_ } @args);
1076
1077   my $in = IO::File->new("$cmd 2>&1 |");
1078
1079   if (!$in) {
1080     unlink "${tmpdir}/.pgpass", $tmp;
1081     rmdir $tmpdir;
1082
1083     $form->error($locale->text('The pg_restore process could not be started.'));
1084   }
1085
1086   $English::AUTOFLUSH = 1;
1087
1088   $form->header();
1089   print $form->parse_html_template("admin/restore_dataset_start_header");
1090
1091   while (my $line = <$in>) {
1092     print $line;
1093   }
1094   $in->close();
1095
1096   $form->{retval} = $CHILD_ERROR >> 8;
1097   print $form->parse_html_template("admin/restore_dataset_start_footer");
1098
1099   unlink "${tmpdir}/.pgpass", $tmp;
1100   rmdir $tmpdir;
1101 }
1102
1103 sub unlock_system {
1104   my $form   = $main::form;
1105   my $locale = $main::locale;
1106
1107   unlink _nologin_file_name();;
1108
1109   $form->{callback} = "admin.pl?action=list_users";
1110
1111   $form->redirect($locale->text('Lockfile removed!'));
1112
1113 }
1114
1115 sub lock_system {
1116   my $form   = $main::form;
1117   my $locale = $main::locale;
1118
1119   open(FH, ">", _nologin_file_name())
1120     or $form->error($locale->text('Cannot create Lock!'));
1121   close(FH);
1122
1123   $form->{callback} = "admin.pl?action=list_users";
1124
1125   $form->redirect($locale->text('Lockfile created!'));
1126
1127 }
1128
1129 sub yes {
1130   call_sub($main::form->{yes_nextsub});
1131 }
1132
1133 sub no {
1134   call_sub($main::form->{no_nextsub});
1135 }
1136
1137 sub add {
1138   call_sub($main::form->{add_nextsub});
1139 }
1140
1141 sub edit {
1142   my $form = $main::form;
1143
1144   $form->{edit_nextsub} ||= 'edit_user';
1145
1146   call_sub($form->{edit_nextsub});
1147 }
1148
1149 sub delete {
1150   my $form     = $main::form;
1151
1152   $form->{delete_nextsub} ||= 'delete_user';
1153
1154   call_sub($form->{delete_nextsub});
1155 }
1156
1157 sub save {
1158   my $form = $main::form;
1159
1160   $form->{save_nextsub} ||= 'save_user';
1161
1162   call_sub($form->{save_nextsub});
1163 }
1164
1165 sub back {
1166   call_sub($main::form->{back_nextsub});
1167 }
1168
1169 sub dispatcher {
1170   my $form   = $main::form;
1171   my $locale = $main::locale;
1172
1173   foreach my $action (qw(create_standard_group dont_create_standard_group
1174                          save_user delete_user save_user_as_new)) {
1175     if ($form->{"action_${action}"}) {
1176       call_sub($action);
1177       return;
1178     }
1179   }
1180
1181   call_sub($form->{default_action}) if ($form->{default_action});
1182
1183   $form->error($locale->text('No action defined.'));
1184 }
1185
1186 sub _apply_dbupgrade_scripts {
1187   ::end_of_request() if SL::DBUpgrade2->new(form => $::form, dbdriver => 'Pg', auth => 1)->apply_admin_dbupgrade_scripts(1);
1188 }
1189
1190 sub _nologin_file_name {
1191   return $::lx_office_conf{paths}->{userspath} . '/nologin';
1192 }
1193
1194 sub _search_templates {
1195   # is there a templates basedir
1196   if (!-d $::lx_office_conf{paths}->{templates}) {
1197     $::form->error(sprintf($::locale->text("The directory %s does not exist."), $::lx_office_conf{paths}->{templates}));
1198   }
1199
1200   opendir TEMPLATEDIR, $::lx_office_conf{paths}->{templates} or $::form->error($::lx_office_conf{paths}->{templates} . " : $ERRNO");
1201   my @all     = readdir(TEMPLATEDIR);
1202   my @alldir  = sort grep { -d ($::lx_office_conf{paths}->{templates} . "/$_") && !/^\.\.?$/ } @all;
1203   closedir TEMPLATEDIR;
1204
1205   @alldir = grep !/\.(html|tex|sty|odt|xml|txb)$/, @alldir;
1206   @alldir = grep !/^(webpages|print|\.svn)$/, @alldir;
1207
1208   # mastertemplates
1209   opendir TEMPLATEDIR, "$::lx_office_conf{paths}->{templates}/print" or $::form->error("$::lx_office_conf{paths}->{templates}/print" . " : $ERRNO");
1210   my @allmaster = readdir(TEMPLATEDIR);
1211   closedir TEMPLATEDIR;
1212
1213   @allmaster  = sort grep { -d ("$::lx_office_conf{paths}->{templates}/print" . "/$_") && !/^\.\.?$/ } @allmaster;
1214   @allmaster = reverse grep !/Default/, @allmaster;
1215   push @allmaster, 'Default';
1216   @allmaster = reverse @allmaster;
1217
1218   return \@alldir, \@allmaster;
1219 }
1220
1221 1;