Administration: Einen Button zum Testen der Datenbankeinstellung in der Maske zur...
[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 test_db_connection {
639   $form->{dbdriver} = 'Pg';
640   User::dbconnect_vars($form, $form->{dbname});
641
642   my $dbh = DBI->connect($form->{dbconnect}, $form->{dbuser}, $form->{dbpasswd});
643
644   $form->{connection_ok} = $dbh ? 1 : 0;
645   $form->{errstr}        = $DBI::errstr;
646
647   $dbh->disconnect() if ($dbh);
648
649   $form->{title} = $locale->text('Database Connection Test');
650   $form->header();
651   print $form->parse_html_template("admin/test_db_connection");
652 }
653
654 sub continue {
655   call_sub($form->{"nextsub"});
656 }
657
658 sub back {
659   call_sub($form->{"back_nextsub"});
660 }
661
662 sub update_dataset {
663   $form->{title} =
664       "Lx-Office ERP "
665     . $locale->text('Database Administration') . " / "
666     . $locale->text('Update Dataset');
667
668   my @need_updates      = User->dbneedsupdate($form);
669   $form->{NEED_UPDATES} = \@need_updates;
670   $form->{ALL_UPDATED}  = !scalar @need_updates;
671
672   $form->header();
673   print $form->parse_html_template("admin/update_dataset");
674 }
675
676 sub dbupdate {
677   $form->{stylesheet} = "lx-office-erp.css";
678   $form->{title}      = $locale->text("Dataset upgrade");
679   $form->header();
680
681   my $rowcount           = $form->{rowcount} * 1;
682   my @update_rows        = grep { $form->{"update_$_"} } (1 .. $rowcount);
683   $form->{NOTHING_TO_DO} = !scalar @update_rows;
684   my $saved_form         = save_form();
685
686   $| = 1;
687
688   print $form->parse_html_template("admin/dbupgrade_all_header");
689
690   foreach my $i (@update_rows) {
691     restore_form($saved_form);
692
693     map { $form->{$_} = $form->{"${_}_${i}"} } qw(dbname dbdriver dbhost dbport dbuser dbpasswd);
694
695     my $controls = parse_dbupdate_controls($form, $form->{dbdriver});
696
697     print $form->parse_html_template("admin/dbupgrade_header");
698
699     $form->{dbupdate}        = $form->{dbname};
700     $form->{$form->{dbname}} = 1;
701
702     User->dbupdate($form);
703     User->dbupdate2($form, $controls);
704
705     print $form->parse_html_template("admin/dbupgrade_footer");
706   }
707
708   print $form->parse_html_template("admin/dbupgrade_all_done");
709 }
710
711 sub create_dataset {
712   $form->{dbsources} = join " ", map { "[${_}]" } sort User->dbsources(\%$form);
713
714   $form->{CHARTS} = [];
715
716   opendir SQLDIR, "sql/." or $form - error($ERRNO);
717   foreach $item (sort grep /-chart\.sql\z/, readdir SQLDIR) {
718     next if ($item eq 'Default-chart.sql');
719     $item =~ s/-chart\.sql//;
720     push @{ $form->{CHARTS} }, { "name"     => $item,
721                                  "selected" => $item eq "Germany-DATEV-SKR03EU" };
722   }
723   closedir SQLDIR;
724
725   my $default_charset = $dbcharset;
726   $default_charset ||= Common::DEFAULT_CHARSET;
727
728   $form->{DBENCODINGS} = [];
729
730   foreach my $encoding (@Common::db_encodings) {
731     push @{ $form->{DBENCODINGS} }, { "dbencoding" => $encoding->{dbencoding},
732                                       "label"      => $encoding->{label},
733                                       "selected"   => $encoding->{charset} eq $default_charset };
734   }
735
736   $form->{title} =
737       "Lx-Office ERP "
738     . $locale->text('Database Administration') . " / "
739     . $locale->text('Create Dataset');
740
741   $form->header();
742   print $form->parse_html_template("admin/create_dataset");
743 }
744
745 sub dbcreate {
746   $form->isblank("db", $locale->text('Dataset missing!'));
747
748   User->dbcreate(\%$form);
749
750   $form->{title} =
751       "Lx-Office ERP "
752     . $locale->text('Database Administration') . " / "
753     . $locale->text('Create Dataset');
754
755   $form->header();
756   print $form->parse_html_template("admin/dbcreate");
757 }
758
759 sub delete_dataset {
760   @dbsources = User->dbsources_unused($form);
761   $form->error($locale->text('Nothing to delete!')) unless @dbsources;
762
763   $form->{title} =
764       "Lx-Office ERP "
765     . $locale->text('Database Administration') . " / "
766     . $locale->text('Delete Dataset');
767   $form->{DBSOURCES} = [ map { { "name", $_ } } sort @dbsources ];
768
769   $form->header();
770   print $form->parse_html_template("admin/delete_dataset");
771 }
772
773 sub dbdelete {
774
775   if (!$form->{db}) {
776     $form->error($locale->text('No Dataset selected!'));
777   }
778
779   User->dbdelete(\%$form);
780
781   $form->{title} =
782       "Lx-Office ERP "
783     . $locale->text('Database Administration') . " / "
784     . $locale->text('Delete Dataset');
785   $form->header();
786   print $form->parse_html_template("admin/dbdelete");
787 }
788
789 sub backup_dataset {
790   $form->{title} =
791       "Lx-Office ERP "
792     . $locale->text('Database Administration') . " / "
793     . $locale->text('Backup Dataset');
794
795   if ("$pg_dump_exe" eq "DISABLED") {
796     $form->error($locale->text('Database backups and restorations are disabled in lx-erp.conf.'));
797   }
798
799   my @dbsources         = sort User->dbsources($form);
800   $form->{DATABASES}    = [ map { { "dbname" => $_ } } @dbsources ];
801   $form->{NO_DATABASES} = !scalar @dbsources;
802
803   my $username  = getpwuid $UID || "unknown-user";
804   my $hostname  = hostname() || "unknown-host";
805   $form->{from} = "Lx-Office Admin <${username}\@${hostname}>";
806
807   $form->header();
808   print $form->parse_html_template("admin/backup_dataset");
809 }
810
811 sub backup_dataset_start {
812   $form->{title} =
813       "Lx-Office ERP "
814     . $locale->text('Database Administration') . " / "
815     . $locale->text('Backup Dataset');
816
817   $pg_dump_exe ||= "pg_dump";
818
819   if ("$pg_dump_exe" eq "DISABLED") {
820     $form->error($locale->text('Database backups and restorations are disabled in lx-erp.conf.'));
821   }
822
823   $form->isblank("dbname", $locale->text('The dataset name is missing.'));
824   $form->isblank("to", $locale->text('The email address is missing.')) if $form->{destination} eq "email";
825
826   my $tmpdir = "/tmp/lx_office_backup_" . Common->unique_id();
827   mkdir $tmpdir, 0700 || $form->error($locale->text('A temporary directory could not be created:') . " $ERRNO");
828
829   my $pgpass = IO::File->new("${tmpdir}/.pgpass", O_WRONLY | O_CREAT, 0600);
830
831   if (!$pgpass) {
832     unlink $tmpdir;
833     $form->error($locale->text('A temporary file could not be created:') . " $ERRNO");
834   }
835
836   print $pgpass "$form->{dbhost}:$form->{dbport}:$form->{dbname}:$form->{dbuser}:$form->{dbpasswd}\n";
837   $pgpass->close();
838
839   $ENV{HOME} = $tmpdir;
840
841   my @args = ("-Ft", "-c", "-o", "-h", $form->{dbhost}, "-U", $form->{dbuser});
842   push @args, ("-p", $form->{dbport}) if ($form->{dbport});
843   push @args, $form->{dbname};
844
845   my $cmd  = "${pg_dump_exe} " . join(" ", map { s/\\/\\\\/g; s/\"/\\\"/g; $_ } @args);
846   my $name = "dataset_backup_$form->{dbname}_" . strftime("%Y%m%d", localtime()) . ".tar";
847
848   if ($form->{destination} ne "email") {
849     my $in = IO::File->new("$cmd |");
850
851     if (!$in) {
852       unlink "${tmpdir}/.pgpass";
853       rmdir $tmpdir;
854
855       $form->error($locale->text('The pg_dump process could not be started.'));
856     }
857
858     print "content-type: application/x-tar\n";
859     print "content-disposition: attachment; filename=\"${name}\"\n\n";
860
861     while (my $line = <$in>) {
862       print $line;
863     }
864
865     $in->close();
866
867     unlink "${tmpdir}/.pgpass";
868     rmdir $tmpdir;
869
870   } else {
871     my $tmp = $tmpdir . "/dump_" . Common::unique_id();
872
873     if (system("$cmd > $tmp") != 0) {
874       unlink "${tmpdir}/.pgpass", $tmp;
875       rmdir $tmpdir;
876
877       $form->error($locale->text('The pg_dump process could not be started.'));
878     }
879
880     my $mail = new Mailer;
881
882     map { $mail->{$_} = $form->{$_} } qw(from to cc subject message);
883
884     $mail->{charset}     = $dbcharset ? $dbcharset : Common::DEFAULT_CHARSET;
885     $mail->{attachments} = [ { "filename" => $tmp, "name" => $name } ];
886     $mail->send();
887
888     unlink "${tmpdir}/.pgpass", $tmp;
889     rmdir $tmpdir;
890
891     $form->{title} =
892         "Lx-Office ERP "
893       . $locale->text('Database Administration') . " / "
894       . $locale->text('Backup Dataset');
895
896     $form->header();
897     print $form->parse_html_template("admin/backup_dataset_email_done");
898   }
899 }
900
901 sub restore_dataset {
902   $form->{title} =
903       "Lx-Office ERP "
904     . $locale->text('Database Administration') . " / "
905     . $locale->text('Restore Dataset');
906
907   if ("$pg_restore_exe" eq "DISABLED") {
908     $form->error($locale->text('Database backups and restorations are disabled in lx-erp.conf.'));
909   }
910
911   my $default_charset   = $dbcharset;
912   $default_charset    ||= Common::DEFAULT_CHARSET;
913
914   $form->{DBENCODINGS}  = [];
915
916   foreach my $encoding (@Common::db_encodings) {
917     push @{ $form->{DBENCODINGS} }, { "dbencoding" => $encoding->{dbencoding},
918                                       "label"      => $encoding->{label},
919                                       "selected"   => $encoding->{charset} eq $default_charset };
920   }
921
922   $form->header();
923   print $form->parse_html_template("admin/restore_dataset");
924 }
925
926 sub restore_dataset_start {
927   $form->{title} =
928       "Lx-Office ERP "
929     . $locale->text('Database Administration') . " / "
930     . $locale->text('Restore Dataset');
931
932   $pg_restore_exe ||= "pg_restore";
933
934   if ("$pg_restore_exe" eq "DISABLED") {
935     $form->error($locale->text('Database backups and restorations are disabled in lx-erp.conf.'));
936   }
937
938   $form->isblank("new_dbname", $locale->text('The dataset name is missing.'));
939   $form->isblank("content", $locale->text('No backup file has been uploaded.'));
940
941   # Create temporary directories. Write the backup file contents to a temporary
942   # file. Create a .pgpass file with the username and password for the pg_restore
943   # utility.
944
945   my $tmpdir = "/tmp/lx_office_backup_" . Common->unique_id();
946   mkdir $tmpdir, 0700 || $form->error($locale->text('A temporary directory could not be created:') . " $ERRNO");
947
948   my $pgpass = IO::File->new("${tmpdir}/.pgpass", O_WRONLY | O_CREAT, 0600);
949
950   if (!$pgpass) {
951     unlink $tmpdir;
952     $form->error($locale->text('A temporary file could not be created:') . " $ERRNO");
953   }
954
955   print $pgpass "$form->{dbhost}:$form->{dbport}:$form->{new_dbname}:$form->{dbuser}:$form->{dbpasswd}\n";
956   $pgpass->close();
957
958   $ENV{HOME} = $tmpdir;
959
960   my $tmp = $tmpdir . "/dump_" . Common::unique_id();
961   my $tmpfile;
962
963   if (substr($form->{content}, 0, 2) eq "\037\213") {
964     $tmpfile = IO::File->new("| gzip -d > $tmp");
965     $tmpfile->binary();
966
967   } else {
968     $tmpfile = IO::File->new($tmp, O_WRONLY | O_CREAT | O_BINARY, 0600);
969   }
970
971   if (!$tmpfile) {
972     unlink "${tmpdir}/.pgpass";
973     rmdir $tmpdir;
974
975     $form->error($locale->text('A temporary file could not be created:') . " $ERRNO");
976   }
977
978   print $tmpfile $form->{content};
979   $tmpfile->close();
980
981   delete $form->{content};
982
983   # Try to connect to the database. Find out if a database with the same name exists.
984   # If yes, then drop the existing database. Create a new one with the name and encoding
985   # given by the user.
986
987   User::dbconnect_vars($form, "template1");
988
989   my %myconfig = map { $_ => $form->{$_} } grep /^db/, keys %{ $form };
990   my $dbh      = $form->dbconnect(\%myconfig) || $form->dberror();
991
992   my ($query, $sth);
993
994   $form->{new_dbname} =~ s|[^a-zA-Z0-9_\-]||g;
995
996   $query = qq|SELECT COUNT(*) FROM pg_database WHERE datname = ?|;
997   my ($count) = selectrow_query($form, $dbh, $query, $form->{new_dbname});
998   if ($count) {
999     do_query($form, $dbh, qq|DROP DATABASE $form->{new_dbname}|);
1000   }
1001
1002   my $found = 0;
1003   foreach my $item (@Common::db_encodings) {
1004     if ($item->{dbencoding} eq $form->{dbencoding}) {
1005       $found = 1;
1006       last;
1007     }
1008   }
1009   $form->{dbencoding} = "LATIN9" unless $form->{dbencoding};
1010
1011   do_query($form, $dbh, qq|CREATE DATABASE $form->{new_dbname} ENCODING ? TEMPLATE template0|, $form->{dbencoding});
1012
1013   $dbh->disconnect();
1014
1015   # Spawn pg_restore on the temporary file.
1016
1017   my @args = ("-h", $form->{dbhost}, "-U", $form->{dbuser}, "-d", $form->{new_dbname});
1018   push @args, ("-p", $form->{dbport}) if ($form->{dbport});
1019   push @args, $tmp;
1020
1021   my $cmd = "${pg_restore_exe} " . join(" ", map { s/\\/\\\\/g; s/\"/\\\"/g; $_ } @args);
1022
1023   my $in = IO::File->new("$cmd 2>&1 |");
1024
1025   if (!$in) {
1026     unlink "${tmpdir}/.pgpass", $tmp;
1027     rmdir $tmpdir;
1028
1029     $form->error($locale->text('The pg_restore process could not be started.'));
1030   }
1031
1032   $AUTOFLUSH = 1;
1033
1034   $form->header();
1035   print $form->parse_html_template("admin/restore_dataset_start_header");
1036
1037   while (my $line = <$in>) {
1038     print $line;
1039   }
1040   $in->close();
1041
1042   $form->{retval} = $CHILD_ERROR >> 8;
1043   print $form->parse_html_template("admin/restore_dataset_start_footer");
1044
1045   unlink "${tmpdir}/.pgpass", $tmp;
1046   rmdir $tmpdir;
1047 }
1048
1049 sub unlock_system {
1050
1051   unlink "$userspath/nologin";
1052
1053   $form->{callback} = "admin.pl?action=list_users";
1054
1055   $form->redirect($locale->text('Lockfile removed!'));
1056
1057 }
1058
1059 sub lock_system {
1060
1061   open(FH, ">$userspath/nologin")
1062     or $form->error($locale->text('Cannot create Lock!'));
1063   close(FH);
1064
1065   $form->{callback} = "admin.pl?action=list_users";
1066
1067   $form->redirect($locale->text('Lockfile created!'));
1068
1069 }
1070
1071 sub yes {
1072   call_sub($form->{yes_nextsub});
1073 }
1074
1075 sub no {
1076   call_sub($form->{no_nextsub});
1077 }
1078
1079 sub add {
1080   call_sub($form->{add_nextsub});
1081 }
1082
1083 sub edit {
1084   $form->{edit_nextsub} ||= 'edit_user';
1085
1086   call_sub($form->{edit_nextsub});
1087 }
1088
1089 sub delete {
1090   $form->{delete_nextsub} ||= 'delete_user';
1091
1092   call_sub($form->{delete_nextsub});
1093 }
1094
1095 sub save {
1096   $form->{save_nextsub} ||= 'save_user';
1097
1098   call_sub($form->{save_nextsub});
1099 }
1100
1101 sub back {
1102   call_sub($form->{back_nextsub});
1103 }
1104
1105 sub dispatcher {
1106   foreach my $action (qw(create_standard_group dont_create_standard_group)) {
1107     if ($form->{"action_${action}"}) {
1108       call_sub($action);
1109       return;
1110     }
1111   }
1112
1113   call_sub($form->{default_action}) if ($form->{default_action});
1114
1115   $form->error($locale->text('No action defined.'));
1116 }
1117
1118 1;