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