ef646845c89dc9cb0f900b372b219f89caa09a4a
[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 $menufile = "menu.ini";
36
37 use DBI;
38 use CGI;
39 use POSIX qw(strftime);
40 use IO::File;
41 use Fcntl;
42 use English qw(-no_match_vars);
43 use Sys::Hostname;
44
45 use SL::Form;
46 use SL::Mailer;
47 use SL::User;
48 use SL::Common;
49 use SL::Inifile;
50 use SL::DBUpgrade2;
51 use SL::DBUtils;
52
53 require "bin/mozilla/common.pl";
54
55 our $cgi = new CGI('');
56
57 $form = new Form;
58 $form->{"root"} = "root login";
59
60 $locale = new Locale $language, "admin";
61
62 # customization
63 if (-f "bin/mozilla/custom_$form->{script}") {
64   eval { require "bin/mozilla/custom_$form->{script}"; };
65   $form->error($@) if ($@);
66 }
67
68 $form->{stylesheet} = "lx-office-erp.css";
69 $form->{favicon}    = "favicon.ico";
70
71 if ($form->{action}) {
72
73
74   $subroutine = $locale->findsub($form->{action});
75
76   if ($subroutine eq 'login') {
77     if ($form->{rpw}) {
78       $form->{rpw} = crypt $form->{rpw}, "ro";
79     }
80   }
81
82   check_password();
83
84   call_sub($subroutine);
85
86 } else {
87
88   # if there are no drivers bail out
89   $form->error($locale->text('No Database Drivers available!'))
90     unless (User->dbdrivers);
91
92   # create memberfile
93   if (!-f $memberfile) {
94     open(FH, ">$memberfile") or $form->error("$memberfile : $ERRNO");
95     print FH qq|# SQL-Ledger Accounting members
96
97 [root login]
98 password=
99
100 |;
101     close FH;
102   }
103
104   adminlogin();
105
106 }
107
108 1;
109
110 # end
111
112 sub adminlogin {
113
114   $form->{title} =
115     qq|Lx-Office ERP $form->{version} | . $locale->text('Administration');
116
117   $form->header();
118   print $form->parse_html_template('admin/adminlogin');
119 }
120
121 sub login {
122   list_users();
123 }
124
125 sub list_users {
126
127   $form->error($locale->text('File locked!')) if (-f "${memberfile}.LCK");
128
129   open(FH, "$memberfile") or $form->error("$memberfile : $ERRNO");
130
131   my %members;
132
133   while (<FH>) {
134     chomp;
135
136     if (/^\[.*\]/) {
137       $login = $_;
138       $login =~ s/(\[|\])//g;
139
140       $members{$login} = { "login" => $login };
141     }
142
143     if (/^([a-z]+)=(.*)/) {
144       $members{$login}->{$1} = $2;
145     }
146   }
147
148   close(FH);
149
150   delete $members{"root login"};
151   map { $_->{templates} =~ s|.*/||; } values %members;
152
153   $form->{title}  = "Lx-Office ERP " . $locale->text('Administration');
154   $form->{LOCKED} = -e "$userspath/nologin";
155   $form->{MEMBERS} = [ @members{sort { lc $a cmp lc $b } keys %members} ];
156
157   $form->header();
158   print $form->parse_html_template("admin/list_users");
159 }
160
161 sub add_user {
162
163   $form->{title} =
164       "Lx-Office ERP "
165     . $locale->text('Administration') . " / "
166     . $locale->text('Add User');
167
168   my $myconfig = {
169     "vclimit"      => 200,
170     "countrycode"  => "de",
171     "numberformat" => "1.000,00",
172     "dateformat"   => "dd.mm.yy",
173     "stylesheet"   => "lx-office-erp.css",
174     "menustyle"    => "v3",
175   };
176
177   edit_user_form($myconfig);
178 }
179
180 sub edit {
181
182   $form->{title} =
183       "Lx-Office ERP "
184     . $locale->text('Administration') . " / "
185     . $locale->text('Edit User');
186   $form->{edit} = 1;
187
188   $form->isblank("login", $locale->text("The login is missing."));
189
190   # get user
191   my $myconfig = new User "$memberfile", "$form->{login}";
192
193   $myconfig->{signature} =~ s/\\n/\r\n/g;
194   $myconfig->{address}   =~ s/\\n/\r\n/g;
195
196   # strip basedir from templates directory
197   $myconfig->{templates} =~ s|.*/||;
198
199   edit_user_form($myconfig);
200 }
201
202 sub edit_user_form {
203   my ($myconfig) = @_;
204
205   my @valid_dateformats = qw(mm-dd-yy mm/dd/yy dd-mm-yy dd/mm/yy dd.mm.yy yyyy-mm-dd);
206   $form->{ALL_DATEFORMATS} = [ map { { "format" => $_, "selected" => $_ eq $myconfig->{dateformat} } } @valid_dateformats ];
207
208   my @valid_numberformats = qw(1,000.00 1000.00 1.000,00 1000,00);
209   $form->{ALL_NUMBERFORMATS} = [ map { { "format" => $_, "selected" => $_ eq $myconfig->{numberformat} } } @valid_numberformats ];
210
211   %countrycodes = User->country_codes;
212   $form->{ALL_COUNTRYCODES} = [];
213   foreach $countrycode (sort { $countrycodes{$a} cmp $countrycodes{$b} } keys %countrycodes) {
214     push @{ $form->{ALL_COUNTRYCODES} }, { "value"    => $countrycode,
215                                            "name"     => $countrycodes{$countrycode},
216                                            "selected" => $countrycode eq $myconfig->{countrycode} };
217   }
218
219   # is there a templates basedir
220   if (!-d "$templates") {
221     $form->error(sprintf($locale->text("The directory %s does not exist."), $templates));
222   }
223
224   opendir TEMPLATEDIR, "$templates/." or $form->error("$templates : $ERRNO");
225   my @all     = readdir(TEMPLATEDIR);
226   my @alldir  = sort grep { -d "$templates/$_" && !/^\.\.?$/ } @all;
227   my @allhtml = sort grep { -f "$templates/$_" && /\.html$/ } @all;
228   closedir TEMPLATEDIR;
229
230   @alldir = grep !/\.(html|tex|sty|odt|xml|txb)$/, @alldir;
231   @alldir = grep !/^(webpages|\.svn)$/, @alldir;
232
233   @allhtml = reverse grep !/Default/, @allhtml;
234   push @allhtml, 'Default';
235   @allhtml = reverse @allhtml;
236
237   $form->{ALL_TEMPLATES} = [ map { { "name", => $_, "selected" => $_ eq $myconfig->{templates} } } @alldir ];
238
239   $lastitem = $allhtml[0];
240   $lastitem =~ s/-.*//g;
241   $form->{ALL_MASTER_TEMPLATES} = [ { "name" => $lastitem, "selected" => $lastitem eq "German" } ];
242   foreach $item (@allhtml) {
243     $item =~ s/-.*//g;
244     next if ($item eq $lastitem);
245
246     push @{ $form->{ALL_MASTER_TEMPLATES} }, { "name" => $item, "selected" => $item eq "German" };
247     $lastitem = $item;
248   }
249
250   # css dir has styles that are not intended as general layouts.
251   # reverting to hardcoded list
252   $form->{ALL_STYLESHEETS} = [ map { { "name" => $_, "selected" => $_ eq $myconfig->{stylesheet} } } qw(lx-office-erp.css Win2000.css) ];
253
254   $form->{"menustyle_" . $myconfig->{menustyle} } = 1;
255
256   map { $form->{"myc_${_}"} = $myconfig->{$_} } keys %{ $myconfig };
257
258   # access control
259   my @acsorder = ();
260   my %acs      = ();
261   my %excl     = ();
262   open(FH, $menufile) or $form->error("$menufile : $ERRNO");
263
264   while ($item = <FH>) {
265     next unless $item =~ /\[/;
266     next if $item =~ /\#/;
267
268     $item =~ s/(\[|\])//g;
269     chomp $item;
270
271     my ($level, $menuitem);
272
273     if ($item =~ /--/) {
274       ($level, $menuitem) = split /--/, $item, 2;
275     } else {
276       $level    = $item;
277       $menuitem = $item;
278       push @acsorder, $item;
279     }
280
281     $acs{$level} ||= [];
282     push @{ $acs{$level} }, $menuitem;
283
284   }
285
286   foreach $item (split(/;/, $myconfig->{acs})) {
287     ($key, $value) = split /--/, $item, 2;
288     $excl{$key}{$value} = 1;
289   }
290
291   $form->{ACLS}    = [];
292   $form->{all_acs} = "";
293
294   foreach $key (@acsorder) {
295     my $acl = { "checked" => $form->{login} ? !$excl{$key}->{$key} : 1,
296                 "name"    => "${key}--${key}",
297                 "title"   => $key,
298                 "SUBACLS" => [], };
299     $form->{all_acs} .= "${key}--${key};";
300
301     foreach $item (@{ $acs{$key} }) {
302       next if ($key eq $item);
303
304       my $subacl = { "checked" => $form->{login} ? !$excl{$key}->{$item} : 1,
305                      "name"    => "${key}--${item}",
306                      "title"   => $item };
307       push @{ $acl->{SUBACLS} }, $subacl;
308       $form->{all_acs} .= "${key}--${item};";
309     }
310     push @{ $form->{ACLS} }, $acl;
311   }
312
313   chop $form->{all_acs};
314
315   $form->header();
316   print $form->parse_html_template("admin/edit_user");
317 }
318
319 sub save {
320
321   $form->{dbdriver} = 'Pg';
322
323   # no spaces allowed in login name
324   ($form->{login}) = split / /, $form->{login};
325
326   $form->isblank("login", $locale->text('Login name missing!'));
327
328   # check for duplicates
329   if (!$form->{edit}) {
330     $temp = new User "$memberfile", "$form->{login}";
331
332     if ($temp->{login}) {
333       $form->error("$form->{login} " . $locale->text('is already a member!'));
334     }
335   }
336
337   # no spaces allowed in directories
338   ($form->{newtemplates}) = split / /, $form->{newtemplates};
339
340   if ($form->{newtemplates}) {
341     $form->{templates} = $form->{newtemplates};
342   } else {
343     $form->{templates} =
344       ($form->{usetemplates}) ? $form->{usetemplates} : $form->{login};
345   }
346
347   # is there a basedir
348   if (!-d "$templates") {
349     $form->error(sprintf($locale->text("The directory %s does not exist."), $templates));
350   }
351
352   # add base directory to $form->{templates}
353   $form->{templates} =~ s|.*/||;
354   $form->{templates} =  "$templates/$form->{templates}";
355
356   $myconfig = new User "$memberfile", "$form->{login}";
357
358   # redo acs variable and delete all the acs codes
359   my @acs;
360   foreach $item (split m|;|, $form->{all_acs}) {
361     my $name =  "ACS_${item}";
362     $name    =~ s| |+|g;
363     push @acs, $item if !$form->{$name};
364     delete $form->{$name};
365   }
366   $form->{acs} = join ";", @acs;
367
368   $form->isblank("dbname", $locale->text('Dataset missing!'));
369   $form->isblank("dbuser", $locale->text('Database User missing!'));
370
371   foreach $item (keys %{$form}) {
372     $myconfig->{$item} = $form->{$item};
373   }
374
375   delete $myconfig->{stylesheet};
376   if ($form->{userstylesheet}) {
377     $myconfig->{stylesheet} = $form->{userstylesheet};
378   }
379
380   $myconfig->save_member($memberfile, $userspath);
381
382   if ($webdav) {
383     @webdavdirs =
384       qw(angebote bestellungen rechnungen anfragen lieferantenbestellungen einkaufsrechnungen);
385     foreach $directory (@webdavdirs) {
386       $file = "webdav/" . $directory . "/webdav-user";
387       if ($form->{$directory}) {
388         if (open(HTACCESS, "$file")) {
389           while (<HTACCESS>) {
390             ($login, $password) = split(/:/, $_);
391             if ($login ne $form->{login}) {
392               $newfile .= $_;
393             }
394           }
395           close(HTACCESS);
396         }
397         open(HTACCESS, "> $file") or die "cannot open $file $ERRNO\n";
398         $newfile .= $myconfig->{login} . ":" . $myconfig->{password} . "\n";
399         print(HTACCESS $newfile);
400         close(HTACCESS);
401       } else {
402         $form->{$directory} = 0;
403         if (open(HTACCESS, "$file")) {
404           while (<HTACCESS>) {
405             ($login, $password) = split(/:/, $_);
406             if ($login ne $form->{login}) {
407               $newfile .= $_;
408             }
409           }
410           close(HTACCESS);
411         }
412         open(HTACCESS, "> $file") or die "cannot open $file $ERRNO\n";
413         print(HTACCESS $newfile);
414         close(HTACCESS);
415       }
416     }
417   }
418
419   $form->{templates}       =~ s|.*/||;
420   $form->{templates}       =  "${templates}/$form->{templates}";
421   $form->{mastertemplates} =~ s|.*/||;
422
423   # create user template directory and copy master files
424   if (!-d "$form->{templates}") {
425     umask(002);
426
427     if (mkdir "$form->{templates}", oct("771")) {
428
429       umask(007);
430
431       # copy templates to the directory
432       opendir TEMPLATEDIR, "$templates/." or $form - error("$templates : $ERRNO");
433       @templates = grep /$form->{mastertemplates}.*?\.(html|tex|sty|xml|txb)$/,
434         readdir TEMPLATEDIR;
435       closedir TEMPLATEDIR;
436
437       foreach $file (@templates) {
438         open(TEMP, "$templates/$file")
439           or $form->error("$templates/$file : $ERRNO");
440
441         $file =~ s/\Q$form->{mastertemplates}\E-//;
442         open(NEW, ">$form->{templates}/$file")
443           or $form->error("$form->{templates}/$file : $ERRNO");
444
445         while ($line = <TEMP>) {
446           print NEW $line;
447         }
448         close(TEMP);
449         close(NEW);
450       }
451     } else {
452       $form->error("$ERRNO: $form->{templates}");
453     }
454   }
455
456   $form->redirect($locale->text('User saved!'));
457
458 }
459
460 sub delete {
461   $form->error($locale->text('File locked!')) if (-f ${memberfile} . LCK);
462   open(FH, ">${memberfile}.LCK") or $form->error("${memberfile}.LCK : $ERRNO");
463   close(FH);
464
465   my $members = Inifile->new($memberfile);
466   my $templates = $members->{$form->{login}}->{templates};
467   delete $members->{$form->{login}};
468   $members->write();
469   unlink "${memberfile}.LCK";
470
471   if ($templates) {
472     my $templates_in_use = 0;
473     foreach $login (keys %{ $members }) {
474       next if $login =~ m/^[A-Z]+$/;
475       next if $members->{$login}->{templates} ne $templates;
476       $templates_in_use = 1;
477       last;
478     }
479
480     if (!$templates_in_use && -d $templates) {
481       unlink <$templates/*>;
482       rmdir $templates;
483     }
484   }
485
486   # delete config file for user
487   unlink "$userspath/$form->{login}.conf";
488
489   $form->redirect($locale->text('User deleted!'));
490
491 }
492
493 sub login_name {
494   my $login = shift;
495
496   $login =~ s/\[\]//g;
497   return ($login) ? $login : undef;
498
499 }
500
501 sub get_value {
502   my $line = shift;
503
504   my ($null, $value) = split(/=/, $line, 2);
505
506   # remove comments
507   $value =~ s/\s#.*//g;
508
509   # remove any trailing whitespace
510   $value =~ s/^\s*(.*?)\s*$/$1/;
511
512   $value;
513 }
514
515 sub change_admin_password {
516
517   $form->{title} =
518       qq|Lx-Office ERP |
519     . $locale->text('Administration') . " / "
520     . $locale->text('Change Admin Password');
521
522   $form->header();
523   print $form->parse_html_template("admin/change_admin_password");
524 }
525
526 sub change_password {
527   if ($form->{"password"} ne $form->{"password_again"}) {
528     $form->{title} =
529       qq|Lx-Office ERP |
530       . $locale->text('Administration') . " / "
531       . $locale->text('Change Admin Password');
532
533     $form->header();
534     $form->error($locale->text("The passwords do not match."));
535   }
536
537   $root->{password} = $form->{password};
538
539   $root->{'root login'} = 1;
540   $root->save_member($memberfile);
541
542   $form->{callback} =
543     "$form->{script}?action=list_users&rpw=$root->{password}";
544
545   $form->redirect($locale->text('Password changed!'));
546 }
547
548 sub check_password {
549   $root = new User "$memberfile", $form->{root};
550
551   if (!defined($root->{password}) || ($root->{password} ne $form->{rpw})) {
552     $form->error($locale->text('Incorrect Password!'));
553   }
554
555 }
556
557 sub pg_database_administration {
558
559   $form->{dbdriver} = 'Pg';
560   dbselect_source();
561
562 }
563
564 sub dbselect_source {
565   $form->{dbport}    = '5432';
566   $form->{dbuser}    = 'postgres';
567   $form->{dbdefault} = 'template1';
568   $form->{dbhost}    = 'localhost';
569
570   $form->{title}     = "Lx-Office ERP / " . $locale->text('Database Administration');
571
572   $form->{ALLOW_DBBACKUP} = "$pg_dump_exe" ne "DISABLED";
573
574   $form->header();
575   print $form->parse_html_template("admin/dbadmin");
576 }
577
578 sub continue {
579   call_sub($form->{"nextsub"});
580 }
581
582 sub back {
583   call_sub($form->{"back_nextsub"});
584 }
585
586 sub update_dataset {
587   $form->{title} =
588       "Lx-Office ERP "
589     . $locale->text('Database Administration') . " / "
590     . $locale->text('Update Dataset');
591
592   my @need_updates      = User->dbneedsupdate($form);
593   $form->{NEED_UPDATES} = \@need_updates;
594   $form->{ALL_UPDATED}  = !scalar @need_updates;
595
596   $form->header();
597   print $form->parse_html_template("admin/update_dataset");
598 }
599
600 sub dbupdate {
601   $form->{stylesheet} = "lx-office-erp.css";
602   $form->{title}      = $locale->text("Dataset upgrade");
603   $form->header();
604
605   my $rowcount           = $form->{rowcount} * 1;
606   my @update_rows        = grep { $form->{"update_$_"} } (1 .. $rowcount);
607   $form->{NOTHING_TO_DO} = !scalar @update_rows;
608   my $saved_form         = save_form();
609
610   $| = 1;
611
612   print $form->parse_html_template("admin/dbupgrade_all_header");
613
614   foreach my $i (@update_rows) {
615     restore_form($saved_form);
616
617     map { $form->{$_} = $form->{"${_}_${i}"} } qw(dbname dbdriver dbhost dbport dbuser dbpasswd);
618
619     my $controls = parse_dbupdate_controls($form, $form->{dbdriver});
620
621     print $form->parse_html_template("admin/dbupgrade_header");
622
623     $form->{dbupdate}        = $form->{dbname};
624     $form->{$form->{dbname}} = 1;
625
626     User->dbupdate($form);
627     User->dbupdate2($form, $controls);
628
629     print $form->parse_html_template("admin/dbupgrade_footer");
630   }
631
632   print $form->parse_html_template("admin/dbupgrade_all_done");
633 }
634
635 sub create_dataset {
636   $form->{dbsources} = join " ", map { "[${_}]" } sort User->dbsources(\%$form);
637
638   $form->{CHARTS} = [];
639
640   opendir SQLDIR, "sql/." or $form - error($ERRNO);
641   foreach $item (sort grep /-chart\.sql\z/, readdir SQLDIR) {
642     next if ($item eq 'Default-chart.sql');
643     $item =~ s/-chart\.sql//;
644     push @{ $form->{CHARTS} }, { "name"     => $item,
645                                  "selected" => $item eq "Germany-DATEV-SKR03EU" };
646   }
647   closedir SQLDIR;
648
649   my $default_charset = $dbcharset;
650   $default_charset ||= Common::DEFAULT_CHARSET;
651
652   $form->{DBENCODINGS} = [];
653
654   foreach my $encoding (@Common::db_encodings) {
655     push @{ $form->{DBENCODINGS} }, { "dbencoding" => $encoding->{dbencoding},
656                                       "label"      => $encoding->{label},
657                                       "selected"   => $encoding->{charset} eq $default_charset };
658   }
659
660   $form->{title} =
661       "Lx-Office ERP "
662     . $locale->text('Database Administration') . " / "
663     . $locale->text('Create Dataset');
664
665   $form->header();
666   print $form->parse_html_template("admin/create_dataset");
667 }
668
669 sub dbcreate {
670   $form->isblank("db", $locale->text('Dataset missing!'));
671
672   User->dbcreate(\%$form);
673
674   $form->{title} =
675       "Lx-Office ERP "
676     . $locale->text('Database Administration') . " / "
677     . $locale->text('Create Dataset');
678
679   $form->header();
680   print $form->parse_html_template("admin/dbcreate");
681 }
682
683 sub delete_dataset {
684   @dbsources = User->dbsources_unused(\%$form, $memberfile);
685   $form->error($locale->text('Nothing to delete!')) unless @dbsources;
686
687   $form->{title} =
688       "Lx-Office ERP "
689     . $locale->text('Database Administration') . " / "
690     . $locale->text('Delete Dataset');
691   $form->{DBSOURCES} = [ map { { "name", $_ } } sort @dbsources ];
692
693   $form->header();
694   print $form->parse_html_template("admin/delete_dataset");
695 }
696
697 sub dbdelete {
698
699   if (!$form->{db}) {
700     $form->error($locale->text('No Dataset selected!'));
701   }
702
703   User->dbdelete(\%$form);
704
705   $form->{title} =
706       "Lx-Office ERP "
707     . $locale->text('Database Administration') . " / "
708     . $locale->text('Delete Dataset');
709   $form->header();
710   print $form->parse_html_template("admin/dbdelete");
711 }
712
713 sub backup_dataset {
714   $form->{title} =
715       "Lx-Office ERP "
716     . $locale->text('Database Administration') . " / "
717     . $locale->text('Backup Dataset');
718
719   if ("$pg_dump_exe" eq "DISABLED") {
720     $form->error($locale->text('Database backups and restorations are disabled in lx-erp.conf.'));
721   }
722
723   my @dbsources         = sort User->dbsources($form);
724   $form->{DATABASES}    = [ map { { "dbname" => $_ } } @dbsources ];
725   $form->{NO_DATABASES} = !scalar @dbsources;
726
727   my $username  = getpwuid $UID || "unknown-user";
728   my $hostname  = hostname() || "unknown-host";
729   $form->{from} = "Lx-Office Admin <${username}\@${hostname}>";
730
731   $form->header();
732   print $form->parse_html_template("admin/backup_dataset");
733 }
734
735 sub backup_dataset_start {
736   $form->{title} =
737       "Lx-Office ERP "
738     . $locale->text('Database Administration') . " / "
739     . $locale->text('Backup Dataset');
740
741   $pg_dump_exe ||= "pg_dump";
742
743   if ("$pg_dump_exe" eq "DISABLED") {
744     $form->error($locale->text('Database backups and restorations are disabled in lx-erp.conf.'));
745   }
746
747   $form->isblank("dbname", $locale->text('The dataset name is missing.'));
748   $form->isblank("to", $locale->text('The email address is missing.')) if $form->{destination} eq "email";
749
750   my $tmpdir = "/tmp/lx_office_backup_" . Common->unique_id();
751   mkdir $tmpdir, 0700 || $form->error($locale->text('A temporary directory could not be created:') . " $ERRNO");
752
753   my $pgpass = IO::File->new("${tmpdir}/.pgpass", O_WRONLY | O_CREAT, 0600);
754
755   if (!$pgpass) {
756     unlink $tmpdir;
757     $form->error($locale->text('A temporary file could not be created:') . " $ERRNO");
758   }
759
760   print $pgpass "$form->{dbhost}:$form->{dbport}:$form->{dbname}:$form->{dbuser}:$form->{dbpasswd}\n";
761   $pgpass->close();
762
763   $ENV{HOME} = $tmpdir;
764
765   my @args = ("-Ft", "-c", "-o", "-h", $form->{dbhost}, "-U", $form->{dbuser});
766   push @args, ("-p", $form->{dbport}) if ($form->{dbport});
767   push @args, $form->{dbname};
768
769   my $cmd  = "${pg_dump_exe} " . join(" ", map { s/\\/\\\\/g; s/\"/\\\"/g; $_ } @args);
770   my $name = "dataset_backup_$form->{dbname}_" . strftime("%Y%m%d", localtime()) . ".tar";
771
772   if ($form->{destination} ne "email") {
773     my $in = IO::File->new("$cmd |");
774
775     if (!$in) {
776       unlink "${tmpdir}/.pgpass";
777       rmdir $tmpdir;
778
779       $form->error($locale->text('The pg_dump process could not be started.'));
780     }
781
782     print "content-type: application/x-tar\n";
783     print "content-disposition: attachment; filename=\"${name}\"\n\n";
784
785     while (my $line = <$in>) {
786       print $line;
787     }
788
789     $in->close();
790
791     unlink "${tmpdir}/.pgpass";
792     rmdir $tmpdir;
793
794   } else {
795     my $tmp = $tmpdir . "/dump_" . Common::unique_id();
796
797     if (system("$cmd > $tmp") != 0) {
798       unlink "${tmpdir}/.pgpass", $tmp;
799       rmdir $tmpdir;
800
801       $form->error($locale->text('The pg_dump process could not be started.'));
802     }
803
804     my $mail = new Mailer;
805
806     map { $mail->{$_} = $form->{$_} } qw(from to cc subject message);
807
808     $mail->{charset}     = $dbcharset ? $dbcharset : Common::DEFAULT_CHARSET;
809     $mail->{attachments} = [ { "filename" => $tmp, "name" => $name } ];
810     $mail->send();
811
812     unlink "${tmpdir}/.pgpass", $tmp;
813     rmdir $tmpdir;
814
815     $form->{title} =
816         "Lx-Office ERP "
817       . $locale->text('Database Administration') . " / "
818       . $locale->text('Backup Dataset');
819
820     $form->header();
821     print $form->parse_html_template("admin/backup_dataset_email_done");
822   }
823 }
824
825 sub restore_dataset {
826   $form->{title} =
827       "Lx-Office ERP "
828     . $locale->text('Database Administration') . " / "
829     . $locale->text('Restore Dataset');
830
831   if ("$pg_restore_exe" eq "DISABLED") {
832     $form->error($locale->text('Database backups and restorations are disabled in lx-erp.conf.'));
833   }
834
835   my $default_charset   = $dbcharset;
836   $default_charset    ||= Common::DEFAULT_CHARSET;
837
838   $form->{DBENCODINGS}  = [];
839
840   foreach my $encoding (@Common::db_encodings) {
841     push @{ $form->{DBENCODINGS} }, { "dbencoding" => $encoding->{dbencoding},
842                                       "label"      => $encoding->{label},
843                                       "selected"   => $encoding->{charset} eq $default_charset };
844   }
845
846   $form->header();
847   print $form->parse_html_template("admin/restore_dataset");
848 }
849
850 sub restore_dataset_start {
851   $form->{title} =
852       "Lx-Office ERP "
853     . $locale->text('Database Administration') . " / "
854     . $locale->text('Restore Dataset');
855
856   $pg_restore_exe ||= "pg_restore";
857
858   if ("$pg_restore_exe" eq "DISABLED") {
859     $form->error($locale->text('Database backups and restorations are disabled in lx-erp.conf.'));
860   }
861
862   $form->isblank("new_dbname", $locale->text('The dataset name is missing.'));
863   $form->isblank("content", $locale->text('No backup file has been uploaded.'));
864
865   # Create temporary directories. Write the backup file contents to a temporary
866   # file. Create a .pgpass file with the username and password for the pg_restore
867   # utility.
868
869   my $tmpdir = "/tmp/lx_office_backup_" . Common->unique_id();
870   mkdir $tmpdir, 0700 || $form->error($locale->text('A temporary directory could not be created:') . " $ERRNO");
871
872   my $pgpass = IO::File->new("${tmpdir}/.pgpass", O_WRONLY | O_CREAT, 0600);
873
874   if (!$pgpass) {
875     unlink $tmpdir;
876     $form->error($locale->text('A temporary file could not be created:') . " $ERRNO");
877   }
878
879   print $pgpass "$form->{dbhost}:$form->{dbport}:$form->{new_dbname}:$form->{dbuser}:$form->{dbpasswd}\n";
880   $pgpass->close();
881
882   $ENV{HOME} = $tmpdir;
883
884   my $tmp = $tmpdir . "/dump_" . Common::unique_id();
885   my $tmpfile;
886
887   if (substr($form->{content}, 0, 2) eq "\037\213") {
888     $tmpfile = IO::File->new("| gzip -d > $tmp");
889     $tmpfile->binary();
890
891   } else {
892     $tmpfile = IO::File->new($tmp, O_WRONLY | O_CREAT | O_BINARY, 0600);
893   }
894
895   if (!$tmpfile) {
896     unlink "${tmpdir}/.pgpass";
897     rmdir $tmpdir;
898
899     $form->error($locale->text('A temporary file could not be created:') . " $ERRNO");
900   }
901
902   print $tmpfile $form->{content};
903   $tmpfile->close();
904
905   delete $form->{content};
906
907   # Try to connect to the database. Find out if a database with the same name exists.
908   # If yes, then drop the existing database. Create a new one with the name and encoding
909   # given by the user.
910
911   User::dbconnect_vars($form, "template1");
912
913   my %myconfig = map { $_ => $form->{$_} } grep /^db/, keys %{ $form };
914   my $dbh      = $form->dbconnect(\%myconfig) || $form->dberror();
915
916   my ($query, $sth);
917
918   $form->{new_dbname} =~ s|[^a-zA-Z0-9_\-]||g;
919
920   $query = qq|SELECT COUNT(*) FROM pg_database WHERE datname = ?|;
921   my ($count) = selectrow_query($form, $dbh, $query, $form->{new_dbname});
922   if ($count) {
923     do_query($form, $dbh, qq|DROP DATABASE $form->{new_dbname}|);
924   }
925
926   my $found = 0;
927   foreach my $item (@Common::db_encodings) {
928     if ($item->{dbencoding} eq $form->{dbencoding}) {
929       $found = 1;
930       last;
931     }
932   }
933   $form->{dbencoding} = "LATIN9" unless $form->{dbencoding};
934
935   do_query($form, $dbh, qq|CREATE DATABASE $form->{new_dbname} ENCODING ? TEMPLATE template0|, $form->{dbencoding});
936
937   $dbh->disconnect();
938
939   # Spawn pg_restore on the temporary file.
940
941   my @args = ("-h", $form->{dbhost}, "-U", $form->{dbuser}, "-d", $form->{new_dbname});
942   push @args, ("-p", $form->{dbport}) if ($form->{dbport});
943   push @args, $tmp;
944
945   my $cmd = "${pg_restore_exe} " . join(" ", map { s/\\/\\\\/g; s/\"/\\\"/g; $_ } @args);
946
947   my $in = IO::File->new("$cmd 2>&1 |");
948
949   if (!$in) {
950     unlink "${tmpdir}/.pgpass", $tmp;
951     rmdir $tmpdir;
952
953     $form->error($locale->text('The pg_restore process could not be started.'));
954   }
955
956   $AUTOFLUSH = 1;
957
958   $form->header();
959   print $form->parse_html_template("admin/restore_dataset_start_header");
960
961   while (my $line = <$in>) {
962     print $line;
963   }
964   $in->close();
965
966   $form->{retval} = $CHILD_ERROR >> 8;
967   print $form->parse_html_template("admin/restore_dataset_start_footer");
968
969   unlink "${tmpdir}/.pgpass", $tmp;
970   rmdir $tmpdir;
971 }
972
973 sub unlock_system {
974
975   unlink "$userspath/nologin";
976
977   $form->{callback} =
978     "$form->{script}?action=list_users&rpw=$root->{password}";
979
980   $form->redirect($locale->text('Lockfile removed!'));
981
982 }
983
984 sub lock_system {
985
986   open(FH, ">$userspath/nologin")
987     or $form->error($locale->text('Cannot create Lock!'));
988   close(FH);
989
990   $form->{callback} =
991     "$form->{script}?action=list_users&rpw=$root->{password}";
992
993   $form->redirect($locale->text('Lockfile created!'));
994
995 }