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