Für neue Benutzer kivitendo-Stylesheet vorauswählen
[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 Win2000.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 => 'v4',  title => $::locale->text('Top (CSS) new') },
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_message} = $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 # Note: Menu Style 'v3' is not compatible to all browsers!
384 # "menustyle"    => "old" sets the HTML Menu to default.
385 # User does not have a well behaved new constructor, so we#Ll just have to build one ourself
386   my $user     = bless {
387     "vclimit"      => 200,
388     "countrycode"  => "de",
389     "numberformat" => "1.000,00",
390     "dateformat"   => "dd.mm.yy",
391     "stylesheet"   => "kivitendo.css",
392     "menustyle"    => "old",
393     dbport         => $::auth->{DB_config}->{port} || 5432,
394     dbuser         => $::auth->{DB_config}->{user} || 'lxoffice',
395     dbhost         => $::auth->{DB_config}->{host} || 'localhost',
396   }, 'User';
397
398   edit_user_form($user);
399 }
400
401 sub edit_user {
402   $::form->{title} = "kivitendo " . $::locale->text('Administration') . " / " . $::locale->text('Edit User');
403   $::form->{edit}  = 1;
404
405   # get user
406   my $user = User->new(id => $::form->{user}{id});
407
408   # strip basedir from templates directory
409   $user->{templates} =~ s|.*/||;
410
411   edit_user_form($user);
412 }
413
414 sub edit_user_form {
415   my ($user) = @_;
416
417   my %cc = $user->country_codes;
418   my @all_countrycodes = map { id => $_, title => $cc{$_} }, sort { $cc{$a} cmp $cc{$b} } keys %cc;
419   my ($all_dir, $all_master) = _search_templates();
420   my $groups = [];
421
422   if ($::form->{edit}) {
423     my $user_id    = $::auth->get_user_id($user->{login});
424     my $all_groups = $::auth->read_groups();
425
426     for my $group (values %{ $all_groups }) {
427       push @{ $groups }, $group if (grep { $user_id == $_ } @{ $group->{members} });
428     }
429
430     $groups = [ sort { lc $a->{name} cmp lc $b->{name} } @{ $groups } ];
431   }
432
433   $::form->header;
434   print $::form->parse_html_template("admin/edit_user", {
435     GROUPS               => $groups,
436     CAN_CHANGE_PASSWORD  => $::auth->can_change_password,
437     user                 => $user->data,
438     all_stylesheets      => \@all_stylesheets,
439     all_numberformats    => \@valid_numberformats,
440     all_dateformats      => \@valid_dateformats,
441     all_countrycodes     => \@all_countrycodes,
442     all_menustyles       => \@all_menustyles,
443     all_templates        => $all_dir,
444     all_master_templates => $all_master,
445   });
446 }
447
448 sub save_user {
449   my $form          = $main::form;
450   my $locale        = $main::locale;
451
452   my $user = $form->{user};
453
454   $user->{dbdriver} = 'Pg';
455
456   if (!$::form->{edit}) {
457     # no spaces allowed in login name
458     $user->{login} =~ s/\s//g;
459     $::form->show_generic_error($::locale->text('Login name missing!')) unless $user->{login};
460
461     # check for duplicates
462     my %members = $::auth->read_all_users;
463     if ($members{$user->{login}}) {
464       $::form->show_generic_error($locale->text('Another user with the login #1 does already exist.', $user->{login}), 'back_button' => 1);
465     }
466   }
467
468   # no spaces allowed in directories
469   ($::form->{newtemplates}) = split / /, $::form->{newtemplates};
470   $user->{templates} = $::form->{newtemplates} || $::form->{usetemplates} || $user->{login};
471
472   # is there a basedir
473   if (!-d $::lx_office_conf{paths}->{templates}) {
474     $::form->error(sprintf($::locale->text("The directory %s does not exist."), $::lx_office_conf{paths}->{templates}));
475   }
476
477   # add base directory to $form->{templates}
478   $user->{templates} =~ s|.*/||;
479   $user->{templates} =  $::lx_office_conf{paths}->{templates} . "/$user->{templates}";
480
481   my $myconfig = new User(id => $user->{id});
482
483   $::form->show_generic_error($::locale->text('Dataset missing!'))       unless $user->{dbname};
484   $::form->show_generic_error($::locale->text('Database User missing!')) unless $user->{dbuser};
485
486   foreach my $item (keys %{$user}) {
487     $myconfig->{$item} = $user->{$item};
488   }
489
490   $myconfig->save_member;
491
492   $user->{templates}       =~ s|.*/||;
493   $user->{templates}       =  $::lx_office_conf{paths}->{templates} . "/$user->{templates}";
494   $::form->{mastertemplates} =~ s|.*/||;
495
496   # create user template directory and copy master files
497   if (!-d "$user->{templates}") {
498     umask(002);
499
500     if (mkdir "$user->{templates}", oct("771")) {
501
502       umask(007);
503
504       # copy templates to the directory
505
506       my $oldcurrdir = getcwd();
507       if (!chdir("$::lx_office_conf{paths}->{templates}/print/$::form->{mastertemplates}")) {
508         $form->error("$ERRNO: chdir $::lx_office_conf{paths}->{templates}/print/$::form->{mastertemplates}");
509       }
510
511       my $newdir = File::Spec->catdir($oldcurrdir, $user->{templates});
512
513       find(
514         sub
515         {
516           next if ($_ eq ".");
517
518           if (-d $_) {
519             if (!mkdir (File::Spec->catdir($newdir, $File::Find::name))) {
520               chdir($oldcurrdir);
521               $form->error("$ERRNO: mkdir $File::Find::name");
522             }
523           } elsif (-l $_) {
524             if (!symlink (readlink($_),
525                           File::Spec->catfile($newdir, $File::Find::name))) {
526               chdir($oldcurrdir);
527               $form->error("$ERRNO: symlink $File::Find::name");
528             }
529           } elsif (-f $_) {
530             if (!copy($_, File::Spec->catfile($newdir, $File::Find::name))) {
531               chdir($oldcurrdir);
532               $form->error("$ERRNO: cp $File::Find::name");
533             }
534           }
535         }, "./");
536
537       chdir($oldcurrdir);
538
539     } else {
540       $form->error("$ERRNO: $user->{templates}");
541     }
542   }
543
544   # Add new user to his groups.
545   if (ref $form->{new_user_group_ids} eq 'ARRAY') {
546     my $all_groups = $main::auth->read_groups();
547     my %user       = $main::auth->read_user(login => $myconfig->{login});
548
549     foreach my $group_id (@{ $form->{new_user_group_ids} }) {
550       my $group = $all_groups->{$group_id};
551
552       next if !$group;
553
554       push @{ $group->{members} }, $user{id};
555       $main::auth->save_group($group);
556     }
557   }
558
559   if ($main::auth->can_change_password()
560       && defined $::form->{new_password}
561       && ($::form->{new_password} ne '********')) {
562     my $verifier = SL::Auth::PasswordPolicy->new;
563     my $result   = $verifier->verify($::form->{new_password}, 1);
564
565     if ($result != SL::Auth::PasswordPolicy->OK()) {
566       $form->error($::locale->text('The settings were saved, but the password was not changed.') . ' ' . join(' ', $verifier->errors($result)));
567     }
568
569     $main::auth->change_password($myconfig->{login}, $::form->{new_password});
570   }
571
572   $::form->redirect($::locale->text('User saved!'));
573 }
574
575 sub save_user_as_new {
576   my $form       = $main::form;
577
578   $form->{user}{login} = $::form->{new_user_login};
579   delete $form->{user}{id};
580   delete @{$form}{qw(id edit new_user_login)};
581
582   save_user();
583 }
584
585 sub delete_user {
586   my $form      = $main::form;
587   my $locale    = $main::locale;
588
589   my $user = $::form->{user} || {};
590
591   $::form->show_generic_error($::locale->text('Missing user id!')) unless $user->{id};
592
593   my $loaded_user = User->new(id => $user->{id});
594
595   my %members   = $main::auth->read_all_users();
596   my $templates = $members{$loaded_user->{login}}->{templates};
597
598   $main::auth->delete_user($loaded_user->{login});
599
600   if ($templates) {
601     my $templates_in_use = 0;
602
603     foreach my $login (keys %members) {
604       next if $loaded_user->{login} eq $login;
605       next if $members{$login}->{templates} ne $templates;
606       $templates_in_use = 1;
607       last;
608     }
609
610     if (!$templates_in_use && -d $templates) {
611       unlink <$templates/*>;
612       rmdir $templates;
613     }
614   }
615
616   $form->redirect($locale->text('User deleted!'));
617
618 }
619
620 sub login_name {
621   my $login = shift;
622
623   $login =~ s/\[\]//g;
624   return ($login) ? $login : undef;
625
626 }
627
628 sub get_value {
629   my $line           = shift;
630   my ($null, $value) = split(/=/, $line, 2);
631
632   # remove comments
633   $value =~ s/\s#.*//g;
634
635   # remove any trailing whitespace
636   $value =~ s/^\s*(.*?)\s*$/$1/;
637
638   $value;
639 }
640
641 sub pg_database_administration {
642   my $form = $main::form;
643
644   $form->{dbdriver} = 'Pg';
645   dbselect_source();
646
647 }
648
649 sub dbselect_source {
650   my $form           = $main::form;
651   my $locale         = $main::locale;
652
653   $form->{dbport}    = $::auth->{DB_config}->{port} || 5432;
654   $form->{dbuser}    = $::auth->{DB_config}->{user} || 'lxoffice';
655   $form->{dbdefault} = 'template1';
656   $form->{dbhost}    = $::auth->{DB_config}->{host} || 'localhost';
657
658   $form->{title}     = "kivitendo / " . $locale->text('Database Administration');
659
660   # Intentionnaly disabled unless fixed to work with the authentication DB.
661   $form->{ALLOW_DBBACKUP} = 0; # "$pg_dump_exe" ne "DISABLED";
662
663   $form->header();
664   print $form->parse_html_template("admin/dbadmin");
665 }
666
667 sub test_db_connection {
668   my $form   = $main::form;
669   my $locale = $main::locale;
670
671   $form->{dbdriver} = 'Pg';
672   User::dbconnect_vars($form, $form->{dbname});
673
674   my $dbh = DBI->connect($form->{dbconnect}, $form->{dbuser}, $form->{dbpasswd});
675
676   $form->{connection_ok} = $dbh ? 1 : 0;
677   $form->{errstr}        = $DBI::errstr;
678
679   $dbh->disconnect() if ($dbh);
680
681   $form->{title} = $locale->text('Database Connection Test');
682   $form->header();
683   print $form->parse_html_template("admin/test_db_connection");
684 }
685
686 sub continue {
687   call_sub($main::form->{"nextsub"});
688 }
689
690 sub update_dataset {
691   my $form              = $main::form;
692   my $locale            = $main::locale;
693
694   $form->{title}        = "kivitendo " . $locale->text('Database Administration') . " / " . $locale->text('Update Dataset');
695
696   my @need_updates      = User->dbneedsupdate($form);
697   $form->{NEED_UPDATES} = \@need_updates;
698   $form->{ALL_UPDATED}  = !scalar @need_updates;
699
700   $form->header();
701   print $form->parse_html_template("admin/update_dataset");
702 }
703
704 sub dbupdate {
705   my $form            = $main::form;
706   my $locale          = $main::locale;
707
708   $::request->{layout}->use_stylesheet("lx-office-erp.css");
709   $form->{title}      = $locale->text("Dataset upgrade");
710   $form->header();
711
712   my $rowcount           = $form->{rowcount} * 1;
713   my @update_rows        = grep { $form->{"update_$_"} } (1 .. $rowcount);
714   $form->{NOTHING_TO_DO} = !scalar @update_rows;
715   my $saved_form         = save_form();
716
717   $| = 1;
718
719   print $form->parse_html_template("admin/dbupgrade_all_header");
720
721   foreach my $i (@update_rows) {
722     restore_form($saved_form);
723
724     %::myconfig = ();
725     map { $form->{$_} = $::myconfig{$_} = $form->{"${_}_${i}"} } qw(dbname dbdriver dbhost dbport dbuser dbpasswd);
726
727     print $form->parse_html_template("admin/dbupgrade_header");
728
729     $form->{dbupdate}        = $form->{dbname};
730     $form->{$form->{dbname}} = 1;
731
732     User->dbupdate($form);
733     User->dbupdate2($form, SL::DBUpgrade2->new(form => $form, dbdriver => $form->{dbdriver})->parse_dbupdate_controls);
734
735     print $form->parse_html_template("admin/dbupgrade_footer");
736   }
737
738   print $form->parse_html_template("admin/dbupgrade_all_done");
739 }
740
741 sub create_dataset {
742   my $form           = $main::form;
743   my $locale         = $main::locale;
744
745   $form->{dbsources} = join " ", map { "[${_}]" } sort User->dbsources($form);
746
747   $form->{CHARTS}    = [];
748
749   tie my %dir_h, 'IO::Dir', 'sql/';
750   foreach my $item (map { s/-chart\.sql$//; $_ } sort grep { /-chart\.sql\z/ && !/Default-chart.sql\z/ } keys %dir_h) {
751     push @{ $form->{CHARTS} }, { name     => $item,
752                                  selected => $item eq "Germany-DATEV-SKR03EU" };
753   }
754
755   $form->{ACCOUNTING_METHODS}    = [ map { { name => $_, selected => $_ eq 'cash'     } } qw(accrual cash)       ];
756   $form->{INVENTORY_SYSTEMS}     = [ map { { name => $_, selected => $_ eq 'periodic' } } qw(perpetual periodic) ];
757   $form->{PROFIT_DETERMINATIONS} = [ map { { name => $_, selected => $_ eq 'income'   } } qw(balance income)     ];
758
759   my $default_charset = $::lx_office_conf{system}->{dbcharset} || Common::DEFAULT_CHARSET;
760
761   my $cluster_encoding = User->dbclusterencoding($form);
762   if ($cluster_encoding && ($cluster_encoding =~ m/^(?:UTF-?8|UNICODE)$/i)) {
763     if ($::lx_office_conf{system}->{dbcharset} !~ m/^UTF-?8$/i) {
764       $form->show_generic_error($locale->text('The selected  PostgreSQL installation uses UTF-8 as its encoding. ' .
765                                               'Therefore you have to configure Lx-Office to use UTF-8 as well.'),
766                                 'back_button' => 1);
767     }
768
769     $form->{FORCE_DBENCODING} = 'UNICODE';
770
771   } else {
772     $form->{DBENCODINGS} = [ map { { %{$_}, selected => $_->{charset} eq $default_charset } } @Common::db_encodings ];
773   }
774
775   $form->{title} = "kivitendo " . $locale->text('Database Administration') . " / " . $locale->text('Create Dataset');
776
777   $form->header();
778   print $form->parse_html_template("admin/create_dataset");
779 }
780
781 sub dbcreate {
782   my $form   = $main::form;
783   my $locale = $main::locale;
784
785   $form->isblank("db", $locale->text('Dataset missing!'));
786
787   User->dbcreate(\%$form);
788
789   $form->{title} = "kivitendo " . $locale->text('Database Administration') . " / " . $locale->text('Create Dataset');
790
791   $form->header();
792   print $form->parse_html_template("admin/dbcreate");
793 }
794
795 sub delete_dataset {
796   my $form      = $main::form;
797   my $locale    = $main::locale;
798
799   my @dbsources = User->dbsources_unused($form);
800   $form->error($locale->text('Nothing to delete!')) unless @dbsources;
801
802   $form->{title}     = "kivitendo " . $locale->text('Database Administration') . " / " . $locale->text('Delete Dataset');
803   $form->{DBSOURCES} = [ map { { "name", $_ } } sort @dbsources ];
804
805   $form->header();
806   print $form->parse_html_template("admin/delete_dataset");
807 }
808
809 sub dbdelete {
810   my $form   = $main::form;
811   my $locale = $main::locale;
812
813   if (!$form->{db}) {
814     $form->error($locale->text('No Dataset selected!'));
815   }
816
817   User->dbdelete(\%$form);
818
819   $form->{title} = "kivitendo " . $locale->text('Database Administration') . " / " . $locale->text('Delete Dataset');
820   $form->header();
821   print $form->parse_html_template("admin/dbdelete");
822 }
823
824 sub backup_dataset {
825   my $form       = $main::form;
826   my $locale     = $main::locale;
827
828   $form->{title} = "kivitendo " . $locale->text('Database Administration') . " / " . $locale->text('Backup Dataset');
829
830   if ($::lx_office_conf{applications}->{pg_dump} eq "DISABLED") {
831     $form->error($locale->text('Database backups and restorations are disabled in the configuration.'));
832   }
833
834   my @dbsources         = sort User->dbsources($form);
835   $form->{DATABASES}    = [ map { { "dbname" => $_ } } @dbsources ];
836   $form->{NO_DATABASES} = !scalar @dbsources;
837
838   my $username  = getpwuid $UID || "unknown-user";
839   my $hostname  = hostname() || "unknown-host";
840   $form->{from} = "kivitendo Admin <${username}\@${hostname}>";
841
842   $form->header();
843   print $form->parse_html_template("admin/backup_dataset");
844 }
845
846 sub backup_dataset_start {
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   my $pg_dump_exe = $::lx_office_conf{applications}->{pg_dump} || "pg_dump";
853
854   if ("$pg_dump_exe" eq "DISABLED") {
855     $form->error($locale->text('Database backups and restorations are disabled in the configuration.'));
856   }
857
858   $form->isblank("dbname", $locale->text('The dataset name is missing.'));
859   $form->isblank("to", $locale->text('The email address is missing.')) if $form->{destination} eq "email";
860
861   my $tmpdir = "/tmp/lx_office_backup_" . Common->unique_id();
862   mkdir $tmpdir, 0700 || $form->error($locale->text('A temporary directory could not be created:') . " $ERRNO");
863
864   my $pgpass = IO::File->new("${tmpdir}/.pgpass", O_WRONLY | O_CREAT, 0600);
865
866   if (!$pgpass) {
867     unlink $tmpdir;
868     $form->error($locale->text('A temporary file could not be created:') . " $ERRNO");
869   }
870
871   print $pgpass "$form->{dbhost}:$form->{dbport}:$form->{dbname}:$form->{dbuser}:$form->{dbpasswd}\n";
872   $pgpass->close();
873
874   $ENV{HOME} = $tmpdir;
875
876   my @args = ("-Ft", "-c", "-o", "-h", $form->{dbhost}, "-U", $form->{dbuser});
877   push @args, ("-p", $form->{dbport}) if ($form->{dbport});
878   push @args, $form->{dbname};
879
880   my $cmd  = "$pg_dump_exe " . join(" ", map { s/\\/\\\\/g; s/\"/\\\"/g; $_ } @args);
881   my $name = "dataset_backup_$form->{dbname}_" . strftime("%Y%m%d", localtime()) . ".tar";
882
883   if ($form->{destination} ne "email") {
884     my $in = IO::File->new("$cmd |");
885
886     if (!$in) {
887       unlink "${tmpdir}/.pgpass";
888       rmdir $tmpdir;
889
890       $form->error($locale->text('The pg_dump process could not be started.'));
891     }
892
893     print "content-type: application/x-tar\n";
894     print "content-disposition: attachment; filename=\"${name}\"\n\n";
895
896     while (my $line = <$in>) {
897       print $line;
898     }
899
900     $in->close();
901
902     unlink "${tmpdir}/.pgpass";
903     rmdir $tmpdir;
904
905   } else {
906     my $tmp = $tmpdir . "/dump_" . Common::unique_id();
907
908     if (system("$cmd > $tmp") != 0) {
909       unlink "${tmpdir}/.pgpass", $tmp;
910       rmdir $tmpdir;
911
912       $form->error($locale->text('The pg_dump process could not be started.'));
913     }
914
915     my $mail = new Mailer;
916
917     map { $mail->{$_} = $form->{$_} } qw(from to cc subject message);
918
919     $mail->{charset}     = $::lx_office_conf{system}->{dbcharset} || Common::DEFAULT_CHARSET;
920     $mail->{attachments} = [ { "filename" => $tmp, "name" => $name } ];
921     $mail->send();
922
923     unlink "${tmpdir}/.pgpass", $tmp;
924     rmdir $tmpdir;
925
926     $form->{title} = "kivitendo " . $locale->text('Database Administration') . " / " . $locale->text('Backup Dataset');
927
928     $form->header();
929     print $form->parse_html_template("admin/backup_dataset_email_done");
930   }
931 }
932
933 sub restore_dataset {
934   my $form       = $main::form;
935   my $locale     = $main::locale;
936
937   $form->{title} = "kivitendo " . $locale->text('Database Administration') . " / " . $locale->text('Restore Dataset');
938
939   if ($::lx_office_conf{applications}->{pg_restore} eq "DISABLED") {
940     $form->error($locale->text('Database backups and restorations are disabled in the configuration.'));
941   }
942
943   my $default_charset   = $::lx_office_conf{system}->{dbcharset};
944   $default_charset    ||= Common::DEFAULT_CHARSET;
945
946   $form->{DBENCODINGS}  = [];
947
948   foreach my $encoding (@Common::db_encodings) {
949     push @{ $form->{DBENCODINGS} }, { "dbencoding" => $encoding->{dbencoding},
950                                       "label"      => $encoding->{label},
951                                       "selected"   => $encoding->{charset} eq $default_charset };
952   }
953
954   $form->header();
955   print $form->parse_html_template("admin/restore_dataset");
956 }
957
958 sub restore_dataset_start {
959   my $form       = $main::form;
960   my $locale     = $main::locale;
961
962   $form->{title} = "kivitendo " . $locale->text('Database Administration') . " / " . $locale->text('Restore Dataset');
963
964   my $pg_restore_exe = $::lx_office_conf{applications}->{pg_restore} || "pg_restore";
965
966   if ("$pg_restore_exe" eq "DISABLED") {
967     $form->error($locale->text('Database backups and restorations are disabled in the configuration.'));
968   }
969
970   $form->isblank("new_dbname", $locale->text('The dataset name is missing.'));
971   $form->isblank("content", $locale->text('No backup file has been uploaded.'));
972
973   # Create temporary directories. Write the backup file contents to a temporary
974   # file. Create a .pgpass file with the username and password for the pg_restore
975   # utility.
976
977   my $tmpdir = "/tmp/lx_office_backup_" . Common->unique_id();
978   mkdir $tmpdir, 0700 || $form->error($locale->text('A temporary directory could not be created:') . " $ERRNO");
979
980   my $pgpass = IO::File->new("${tmpdir}/.pgpass", O_WRONLY | O_CREAT, 0600);
981
982   if (!$pgpass) {
983     unlink $tmpdir;
984     $form->error($locale->text('A temporary file could not be created:') . " $ERRNO");
985   }
986
987   print $pgpass "$form->{dbhost}:$form->{dbport}:$form->{new_dbname}:$form->{dbuser}:$form->{dbpasswd}\n";
988   $pgpass->close();
989
990   $ENV{HOME} = $tmpdir;
991
992   my $tmp = $tmpdir . "/dump_" . Common::unique_id();
993   my $tmpfile;
994
995   if (substr($form->{content}, 0, 2) eq "\037\213") {
996     $tmpfile = IO::File->new("| gzip -d > $tmp");
997     $tmpfile->binary();
998
999   } else {
1000     $tmpfile = IO::File->new($tmp, O_WRONLY | O_CREAT | O_BINARY, 0600);
1001   }
1002
1003   if (!$tmpfile) {
1004     unlink "${tmpdir}/.pgpass";
1005     rmdir $tmpdir;
1006
1007     $form->error($locale->text('A temporary file could not be created:') . " $ERRNO");
1008   }
1009
1010   print $tmpfile $form->{content};
1011   $tmpfile->close();
1012
1013   delete $form->{content};
1014
1015   # Try to connect to the database. Find out if a database with the same name exists.
1016   # If yes, then drop the existing database. Create a new one with the name and encoding
1017   # given by the user.
1018
1019   User::dbconnect_vars($form, "template1");
1020
1021   my %myconfig = map { $_ => $form->{$_} } grep /^db/, keys %{ $form };
1022   my $dbh      = $form->dbconnect(\%myconfig) || $form->dberror();
1023
1024   my ($query, $sth);
1025
1026   $form->{new_dbname} =~ s|[^a-zA-Z0-9_\-]||g;
1027
1028   $query = qq|SELECT COUNT(*) FROM pg_database WHERE datname = ?|;
1029   my ($count) = selectrow_query($form, $dbh, $query, $form->{new_dbname});
1030   if ($count) {
1031     do_query($form, $dbh, qq|DROP DATABASE $form->{new_dbname}|);
1032   }
1033
1034   my $found = 0;
1035   foreach my $item (@Common::db_encodings) {
1036     if ($item->{dbencoding} eq $form->{dbencoding}) {
1037       $found = 1;
1038       last;
1039     }
1040   }
1041   $form->{dbencoding} = "LATIN9" unless $form->{dbencoding};
1042
1043   do_query($form, $dbh, qq|CREATE DATABASE $form->{new_dbname} ENCODING ? TEMPLATE template0|, $form->{dbencoding});
1044
1045   $dbh->disconnect();
1046
1047   # Spawn pg_restore on the temporary file.
1048
1049   my @args = ("-h", $form->{dbhost}, "-U", $form->{dbuser}, "-d", $form->{new_dbname});
1050   push @args, ("-p", $form->{dbport}) if ($form->{dbport});
1051   push @args, $tmp;
1052
1053   my $cmd = "$pg_restore_exe " . join(" ", map { s/\\/\\\\/g; s/\"/\\\"/g; $_ } @args);
1054
1055   my $in = IO::File->new("$cmd 2>&1 |");
1056
1057   if (!$in) {
1058     unlink "${tmpdir}/.pgpass", $tmp;
1059     rmdir $tmpdir;
1060
1061     $form->error($locale->text('The pg_restore process could not be started.'));
1062   }
1063
1064   $English::AUTOFLUSH = 1;
1065
1066   $form->header();
1067   print $form->parse_html_template("admin/restore_dataset_start_header");
1068
1069   while (my $line = <$in>) {
1070     print $line;
1071   }
1072   $in->close();
1073
1074   $form->{retval} = $CHILD_ERROR >> 8;
1075   print $form->parse_html_template("admin/restore_dataset_start_footer");
1076
1077   unlink "${tmpdir}/.pgpass", $tmp;
1078   rmdir $tmpdir;
1079 }
1080
1081 sub unlock_system {
1082   my $form   = $main::form;
1083   my $locale = $main::locale;
1084
1085   unlink _nologin_file_name();;
1086
1087   $form->{callback} = "admin.pl?action=list_users";
1088
1089   $form->redirect($locale->text('Lockfile removed!'));
1090
1091 }
1092
1093 sub lock_system {
1094   my $form   = $main::form;
1095   my $locale = $main::locale;
1096
1097   open(FH, ">", _nologin_file_name())
1098     or $form->error($locale->text('Cannot create Lock!'));
1099   close(FH);
1100
1101   $form->{callback} = "admin.pl?action=list_users";
1102
1103   $form->redirect($locale->text('Lockfile created!'));
1104
1105 }
1106
1107 sub yes {
1108   call_sub($main::form->{yes_nextsub});
1109 }
1110
1111 sub no {
1112   call_sub($main::form->{no_nextsub});
1113 }
1114
1115 sub add {
1116   call_sub($main::form->{add_nextsub});
1117 }
1118
1119 sub edit {
1120   my $form = $main::form;
1121
1122   $form->{edit_nextsub} ||= 'edit_user';
1123
1124   call_sub($form->{edit_nextsub});
1125 }
1126
1127 sub delete {
1128   my $form     = $main::form;
1129
1130   $form->{delete_nextsub} ||= 'delete_user';
1131
1132   call_sub($form->{delete_nextsub});
1133 }
1134
1135 sub save {
1136   my $form = $main::form;
1137
1138   $form->{save_nextsub} ||= 'save_user';
1139
1140   call_sub($form->{save_nextsub});
1141 }
1142
1143 sub back {
1144   call_sub($main::form->{back_nextsub});
1145 }
1146
1147 sub dispatcher {
1148   my $form   = $main::form;
1149   my $locale = $main::locale;
1150
1151   foreach my $action (qw(create_standard_group dont_create_standard_group
1152                          save_user delete_user save_user_as_new)) {
1153     if ($form->{"action_${action}"}) {
1154       call_sub($action);
1155       return;
1156     }
1157   }
1158
1159   call_sub($form->{default_action}) if ($form->{default_action});
1160
1161   $form->error($locale->text('No action defined.'));
1162 }
1163
1164 sub _apply_dbupgrade_scripts {
1165   ::end_of_request() if SL::DBUpgrade2->new(form => $::form, dbdriver => 'Pg', auth => 1)->apply_admin_dbupgrade_scripts(1);
1166 }
1167
1168 sub _nologin_file_name {
1169   return $::lx_office_conf{paths}->{userspath} . '/nologin';
1170 }
1171
1172 sub _search_templates {
1173   # is there a templates basedir
1174   if (!-d $::lx_office_conf{paths}->{templates}) {
1175     $::form->error(sprintf($::locale->text("The directory %s does not exist."), $::lx_office_conf{paths}->{templates}));
1176   }
1177
1178   tie my %dir_h, 'IO::Dir', $::lx_office_conf{paths}->{templates};
1179
1180   my @alldir  = sort grep {
1181        -d ($::lx_office_conf{paths}->{templates} . "/$_")
1182     && !/^\.\.?$/
1183     && !m/\.(?:html|tex|sty|odt|xml|txb)$/
1184     && !m/^(?:webpages$|print$|\.)/
1185   } keys %dir_h;
1186
1187   tie %dir_h, 'IO::Dir', "$::lx_office_conf{paths}->{templates}/print";
1188   my @allmaster = ('Standard', sort grep { -d ("$::lx_office_conf{paths}->{templates}/print" . "/$_") && !/^\.\.?$/ && !/^Standard$/ } keys %dir_h);
1189
1190   return \@alldir, \@allmaster;
1191 }
1192
1193 1;