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