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