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