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