Kosmetik.
[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" => "1000,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/$form->{mastertemplates}-//;
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 update_dataset {
583   $form->{title} =
584       "Lx-Office ERP "
585     . $locale->text('Database Administration') . " / "
586     . $locale->text('Update Dataset');
587
588   my @need_updates      = User->dbneedsupdate($form);
589   $form->{NEED_UPDATES} = \@need_updates;
590   $form->{ALL_UPDATED}  = !scalar @need_updates;
591
592   $form->header();
593   print $form->parse_html_template("admin/update_dataset");
594 }
595
596 sub dbupdate {
597   $form->{stylesheet} = "lx-office-erp.css";
598   $form->{title}      = $locale->text("Dataset upgrade");
599   $form->header();
600
601   my $rowcount           = $form->{rowcount} * 1;
602   my @update_rows        = grep { $form->{"update_$_"} } (1 .. $rowcount);
603   $form->{NOTHING_TO_DO} = !scalar @update_rows;
604   my $saved_form         = save_form();
605
606   $| = 1;
607
608   print $form->parse_html_template("admin/dbupgrade_all_header");
609
610   foreach my $i (@update_rows) {
611     restore_form($saved_form);
612
613     map { $form->{$_} = $form->{"${_}_${i}"} } qw(dbname dbdriver dbhost dbport dbuser dbpasswd);
614
615     my $controls = parse_dbupdate_controls($form, $form->{dbdriver});
616
617     print $form->parse_html_template("admin/dbupgrade_header");
618
619     $form->{dbupdate}        = $form->{dbname};
620     $form->{$form->{dbname}} = 1;
621
622     User->dbupdate($form);
623     User->dbupdate2($form, $controls);
624
625     print $form->parse_html_template("admin/dbupgrade_footer");
626   }
627
628   print $form->parse_html_template("admin/dbupgrade_all_done");
629 }
630
631 sub create_dataset {
632   $form->{dbsources} = join " ", map { "[${_}]" } sort User->dbsources(\%$form);
633
634   $form->{CHARTS} = [];
635
636   opendir SQLDIR, "sql/." or $form - error($ERRNO);
637   foreach $item (sort grep /-chart\.sql\z/, readdir SQLDIR) {
638     next if ($item eq 'Default-chart.sql');
639     $item =~ s/-chart\.sql//;
640     push @{ $form->{CHARTS} }, { "name"     => $item,
641                                  "selected" => $item eq "Germany-DATEV-SKR03EU" };
642   }
643   closedir SQLDIR;
644
645   my $default_charset = $dbcharset;
646   $default_charset ||= Common::DEFAULT_CHARSET;
647
648   $form->{DBENCODINGS} = [];
649
650   foreach my $encoding (@Common::db_encodings) {
651     push @{ $form->{DBENCODINGS} }, { "dbencoding" => $encoding->{dbencoding},
652                                       "label"      => $encoding->{label},
653                                       "selected"   => $encoding->{charset} eq $default_charset };
654   }
655
656   $form->{title} =
657       "Lx-Office ERP "
658     . $locale->text('Database Administration') . " / "
659     . $locale->text('Create Dataset');
660
661   $form->header();
662   print $form->parse_html_template("admin/create_dataset");
663 }
664
665 sub dbcreate {
666   $form->isblank("db", $locale->text('Dataset missing!'));
667
668   User->dbcreate(\%$form);
669
670   $form->{title} =
671       "Lx-Office ERP "
672     . $locale->text('Database Administration') . " / "
673     . $locale->text('Create Dataset');
674
675   $form->header();
676   print $form->parse_html_template("admin/dbcreate");
677 }
678
679 sub delete_dataset {
680   @dbsources = User->dbsources_unused(\%$form, $memberfile);
681   $form->error($locale->text('Nothing to delete!')) unless @dbsources;
682
683   $form->{title} =
684       "Lx-Office ERP "
685     . $locale->text('Database Administration') . " / "
686     . $locale->text('Delete Dataset');
687   $form->{DBSOURCES} = [ map { { "name", $_ } } sort @dbsources ];
688
689   $form->header();
690   print $form->parse_html_template("admin/delete_dataset");
691 }
692
693 sub dbdelete {
694
695   if (!$form->{db}) {
696     $form->error($locale->text('No Dataset selected!'));
697   }
698
699   User->dbdelete(\%$form);
700
701   $form->{title} =
702       "Lx-Office ERP "
703     . $locale->text('Database Administration') . " / "
704     . $locale->text('Delete Dataset');
705   $form->header();
706   print $form->parse_html_template("admin/dbdelete");
707 }
708
709 sub backup_dataset {
710   $form->{title} =
711       "Lx-Office ERP "
712     . $locale->text('Database Administration') . " / "
713     . $locale->text('Backup Dataset');
714
715   if ("$pg_dump_exe" eq "DISABLED") {
716     $form->error($locale->text('Database backups and restorations are disabled in lx-erp.conf.'));
717   }
718
719   my @dbsources         = sort User->dbsources($form);
720   $form->{DATABASES}    = [ map { { "dbname" => $_ } } @dbsources ];
721   $form->{NO_DATABASES} = !scalar @dbsources;
722
723   my $username  = getpwuid $UID || "unknown-user";
724   my $hostname  = hostname() || "unknown-host";
725   $form->{from} = "Lx-Office Admin <${username}\@${hostname}>";
726
727   $form->header();
728   print $form->parse_html_template("admin/backup_dataset");
729 }
730
731 sub backup_dataset_start {
732   $form->{title} =
733       "Lx-Office ERP "
734     . $locale->text('Database Administration') . " / "
735     . $locale->text('Backup Dataset');
736
737   $pg_dump_exe ||= "pg_dump";
738
739   if ("$pg_dump_exe" eq "DISABLED") {
740     $form->error($locale->text('Database backups and restorations are disabled in lx-erp.conf.'));
741   }
742
743   $form->isblank("dbname", $locale->text('The dataset name is missing.'));
744   $form->isblank("to", $locale->text('The email address is missing.')) if $form->{destination} eq "email";
745
746   my $tmpdir = "/tmp/lx_office_backup_" . Common->unique_id();
747   mkdir $tmpdir, 0700 || $form->error($locale->text('A temporary directory could not be created:') . " $ERRNO");
748
749   my $pgpass = IO::File->new("${tmpdir}/.pgpass", O_WRONLY | O_CREAT, 0600);
750
751   if (!$pgpass) {
752     unlink $tmpdir;
753     $form->error($locale->text('A temporary file could not be created:') . " $ERRNO");
754   }
755
756   print $pgpass "$form->{dbhost}:$form->{dbport}:$form->{dbname}:$form->{dbuser}:$form->{dbpasswd}\n";
757   $pgpass->close();
758
759   $ENV{HOME} = $tmpdir;
760
761   my @args = ("-Ft", "-c", "-o", "-h", $form->{dbhost}, "-U", $form->{dbuser});
762   push @args, ("-p", $form->{dbport}) if ($form->{dbport});
763   push @args, $form->{dbname};
764
765   my $cmd  = "${pg_dump_exe} " . join(" ", map { s/\\/\\\\/g; s/\"/\\\"/g; $_ } @args);
766   my $name = "dataset_backup_$form->{dbname}_" . strftime("%Y%m%d", localtime()) . ".tar";
767
768   if ($form->{destination} ne "email") {
769     my $in = IO::File->new("$cmd |");
770
771     if (!$in) {
772       unlink "${tmpdir}/.pgpass";
773       rmdir $tmpdir;
774
775       $form->error($locale->text('The pg_dump process could not be started.'));
776     }
777
778     print "content-type: application/x-tar\n";
779     print "content-disposition: attachment; filename=\"${name}\"\n\n";
780
781     while (my $line = <$in>) {
782       print $line;
783     }
784
785     $in->close();
786
787     unlink "${tmpdir}/.pgpass";
788     rmdir $tmpdir;
789
790   } else {
791     my $tmp = $tmpdir . "/dump_" . Common::unique_id();
792
793     if (system("$cmd > $tmp") != 0) {
794       unlink "${tmpdir}/.pgpass", $tmp;
795       rmdir $tmpdir;
796
797       $form->error($locale->text('The pg_dump process could not be started.'));
798     }
799
800     my $mail = new Mailer;
801
802     map { $mail->{$_} = $form->{$_} } qw(from to cc subject message);
803
804     $mail->{charset}     = $dbcharset ? $dbcharset : Common::DEFAULT_CHARSET;
805     $mail->{attachments} = [ { "filename" => $tmp, "name" => $name } ];
806     $mail->send();
807
808     unlink "${tmpdir}/.pgpass", $tmp;
809     rmdir $tmpdir;
810
811     $form->{title} =
812         "Lx-Office ERP "
813       . $locale->text('Database Administration') . " / "
814       . $locale->text('Backup Dataset');
815
816     $form->header();
817     print $form->parse_html_template("admin/backup_dataset_email_done");
818   }
819 }
820
821 sub restore_dataset {
822   $form->{title} =
823       "Lx-Office ERP "
824     . $locale->text('Database Administration') . " / "
825     . $locale->text('Restore Dataset');
826
827   if ("$pg_restore_exe" eq "DISABLED") {
828     $form->error($locale->text('Database backups and restorations are disabled in lx-erp.conf.'));
829   }
830
831   my $default_charset   = $dbcharset;
832   $default_charset    ||= Common::DEFAULT_CHARSET;
833
834   $form->{DBENCODINGS}  = [];
835
836   foreach my $encoding (@Common::db_encodings) {
837     push @{ $form->{DBENCODINGS} }, { "dbencoding" => $encoding->{dbencoding},
838                                       "label"      => $encoding->{label},
839                                       "selected"   => $encoding->{charset} eq $default_charset };
840   }
841
842   $form->header();
843   print $form->parse_html_template("admin/restore_dataset");
844 }
845
846 sub restore_dataset_start {
847   $form->{title} =
848       "Lx-Office ERP "
849     . $locale->text('Database Administration') . " / "
850     . $locale->text('Restore Dataset');
851
852   $pg_restore_exe ||= "pg_restore";
853
854   if ("$pg_restore_exe" eq "DISABLED") {
855     $form->error($locale->text('Database backups and restorations are disabled in lx-erp.conf.'));
856   }
857
858   $form->isblank("new_dbname", $locale->text('The dataset name is missing.'));
859   $form->isblank("content", $locale->text('No backup file has been uploaded.'));
860
861   # Create temporary directories. Write the backup file contents to a temporary
862   # file. Create a .pgpass file with the username and password for the pg_restore
863   # utility.
864
865   my $tmpdir = "/tmp/lx_office_backup_" . Common->unique_id();
866   mkdir $tmpdir, 0700 || $form->error($locale->text('A temporary directory could not be created:') . " $ERRNO");
867
868   my $pgpass = IO::File->new("${tmpdir}/.pgpass", O_WRONLY | O_CREAT, 0600);
869
870   if (!$pgpass) {
871     unlink $tmpdir;
872     $form->error($locale->text('A temporary file could not be created:') . " $ERRNO");
873   }
874
875   print $pgpass "$form->{dbhost}:$form->{dbport}:$form->{new_dbname}:$form->{dbuser}:$form->{dbpasswd}\n";
876   $pgpass->close();
877
878   $ENV{HOME} = $tmpdir;
879
880   my $tmp = $tmpdir . "/dump_" . Common::unique_id();
881   my $tmpfile;
882
883   if (substr($form->{content}, 0, 2) eq "\037\213") {
884     $tmpfile = IO::File->new("| gzip -d > $tmp");
885     $tmpfile->binary();
886
887   } else {
888     $tmpfile = IO::File->new($tmp, O_WRONLY | O_CREAT | O_BINARY, 0600);
889   }
890
891   if (!$tmpfile) {
892     unlink "${tmpdir}/.pgpass";
893     rmdir $tmpdir;
894
895     $form->error($locale->text('A temporary file could not be created:') . " $ERRNO");
896   }
897
898   print $tmpfile $form->{content};
899   $tmpfile->close();
900
901   delete $form->{content};
902
903   # Try to connect to the database. Find out if a database with the same name exists.
904   # If yes, then drop the existing database. Create a new one with the name and encoding
905   # given by the user.
906
907   User::dbconnect_vars($form, "template1");
908
909   my %myconfig = map { $_ => $form->{$_} } grep /^db/, keys %{ $form };
910   my $dbh      = $form->dbconnect(\%myconfig) || $form->dberror();
911
912   my ($query, $sth);
913
914   $form->{new_dbname} =~ s|[^a-zA-Z0-9_\-]||g;
915
916   $query = qq|SELECT COUNT(*) FROM pg_database WHERE datname = ?|;
917   my ($count) = selectrow_query($form, $dbh, $query, $form->{new_dbname});
918   if ($count) {
919     do_query($form, $dbh, qq|DROP DATABASE $form->{new_dbname}|);
920   }
921
922   my $found = 0;
923   foreach my $item (@Common::db_encodings) {
924     if ($item->{dbencoding} eq $form->{dbencoding}) {
925       $found = 1;
926       last;
927     }
928   }
929   $form->{dbencoding} = "LATIN9" unless $form->{dbencoding};
930
931   do_query($form, $dbh, qq|CREATE DATABASE $form->{new_dbname} ENCODING ? TEMPLATE template0|, $form->{dbencoding});
932
933   $dbh->disconnect();
934
935   # Spawn pg_restore on the temporary file.
936
937   my @args = ("-h", $form->{dbhost}, "-U", $form->{dbuser}, "-d", $form->{new_dbname});
938   push @args, ("-p", $form->{dbport}) if ($form->{dbport});
939   push @args, $tmp;
940
941   my $cmd = "${pg_restore_exe} " . join(" ", map { s/\\/\\\\/g; s/\"/\\\"/g; $_ } @args);
942
943   my $in = IO::File->new("$cmd 2>&1 |");
944
945   if (!$in) {
946     unlink "${tmpdir}/.pgpass", $tmp;
947     rmdir $tmpdir;
948
949     $form->error($locale->text('The pg_restore process could not be started.'));
950   }
951
952   $AUTOFLUSH = 1;
953
954   $form->header();
955   print $form->parse_html_template("admin/restore_dataset_start_header");
956
957   while (my $line = <$in>) {
958     print $line;
959   }
960   $in->close();
961
962   $form->{retval} = $CHILD_ERROR >> 8;
963   print $form->parse_html_template("admin/restore_dataset_start_footer");
964
965   unlink "${tmpdir}/.pgpass", $tmp;
966   rmdir $tmpdir;
967 }
968
969 sub unlock_system {
970
971   unlink "$userspath/nologin";
972
973   $form->{callback} =
974     "$form->{script}?action=list_users&rpw=$root->{password}";
975
976   $form->redirect($locale->text('Lockfile removed!'));
977
978 }
979
980 sub lock_system {
981
982   open(FH, ">$userspath/nologin")
983     or $form->error($locale->text('Cannot create Lock!'));
984   close(FH);
985
986   $form->{callback} =
987     "$form->{script}?action=list_users&rpw=$root->{password}";
988
989   $form->redirect($locale->text('Lockfile created!'));
990
991 }