Das Einspielen von Client-DB-Upgrades gefixt
[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 use DBI;
36 use Encode;
37 use English qw(-no_match_vars);
38 use Fcntl;
39 use File::Copy;
40 use File::Find;
41 use File::Spec;
42 use Cwd;
43 use IO::Dir;
44 use IO::File;
45 use POSIX qw(strftime);
46 use Sys::Hostname;
47
48 use SL::Auth;
49 use SL::Auth::PasswordPolicy;
50 use SL::DB::AuthClient;
51 use SL::DB::AuthUser;
52 use SL::Form;
53 use SL::Iconv;
54 use SL::Mailer;
55 use SL::User;
56 use SL::Common;
57 use SL::Inifile;
58 use SL::DBUpgrade2;
59 use SL::DBUtils;
60 use SL::Template;
61
62 require "bin/mozilla/common.pl";
63
64 use strict;
65
66 # parserhappy(R):
67
68 #  $locale->text('periodic')
69 #  $locale->text('income')
70 #  $locale->text('perpetual')
71 #  $locale->text('balance')
72
73 our $cgi;
74 our $form;
75 our $locale;
76 our $auth;
77
78 sub run {
79   $::lxdebug->enter_sub;
80   my $session_result = shift;
81
82   $form   = $::form;
83   $locale = $::locale;
84   $auth   = $::auth;
85
86   $::request->{layout} = SL::Layout::Dispatcher->new(style => 'admin');
87   $::request->{layout}->use_stylesheet("lx-office-erp.css");
88   $form->{favicon}    = "favicon.ico";
89
90   if ($form->{action}) {
91     if ($auth->authenticate_root($form->{'{AUTH}admin_password'}) != $auth->OK()) {
92       $auth->punish_wrong_login;
93       $form->{error} = $locale->text('Incorrect password!');
94       $auth->delete_session_value('admin_password');
95       adminlogin();
96     } else {
97       if ($auth->session_tables_present()) {
98         delete $::form->{'{AUTH}admin_password'};
99       }
100
101       call_sub($locale->findsub($form->{action}));
102     }
103   } else {
104     adminlogin();
105   }
106   $::lxdebug->leave_sub;
107 }
108
109 sub adminlogin {
110   my $form   = $main::form;
111   my $locale = $main::locale;
112
113   $form->{title} = qq|kivitendo $form->{version} | . $locale->text('Administration');
114
115   $form->header();
116   print $form->parse_html_template('admin/adminlogin');
117 }
118
119 sub login_name {
120   my $login = shift;
121
122   $login =~ s/\[\]//g;
123   return ($login) ? $login : undef;
124
125 }
126
127 sub get_value {
128   my $line           = shift;
129   my ($null, $value) = split(/=/, $line, 2);
130
131   # remove comments
132   $value =~ s/\s#.*//g;
133
134   # remove any trailing whitespace
135   $value =~ s/^\s*(.*?)\s*$/$1/;
136
137   $value;
138 }
139
140 sub pg_database_administration {
141   my $form = $main::form;
142   dbselect_source();
143 }
144
145 sub dbselect_source {
146   my $form           = $main::form;
147   my $locale         = $main::locale;
148
149   $form->{dbport}    = $::auth->{DB_config}->{port} || 5432;
150   $form->{dbuser}    = $::auth->{DB_config}->{user} || 'lxoffice';
151   $form->{dbdefault} = 'template1';
152   $form->{dbhost}    = $::auth->{DB_config}->{host} || 'localhost';
153
154   $form->{title}     = "kivitendo / " . $locale->text('Database Administration');
155
156   # Intentionnaly disabled unless fixed to work with the authentication DB.
157   $form->{ALLOW_DBBACKUP} = 0; # "$pg_dump_exe" ne "DISABLED";
158
159   $form->header();
160   print $form->parse_html_template("admin/dbadmin");
161 }
162
163 sub test_db_connection {
164   my $form   = $main::form;
165   my $locale = $main::locale;
166
167   User::dbconnect_vars($form, $form->{dbname});
168
169   my $dbh = DBI->connect($form->{dbconnect}, $form->{dbuser}, $form->{dbpasswd});
170
171   $form->{connection_ok} = $dbh ? 1 : 0;
172   $form->{errstr}        = $DBI::errstr;
173
174   $dbh->disconnect() if ($dbh);
175
176   $form->{title} = $locale->text('Database Connection Test');
177   $form->header();
178   print $form->parse_html_template("admin/test_db_connection");
179 }
180
181 sub continue {
182   call_sub($main::form->{"nextsub"});
183 }
184
185 sub update_dataset {
186   my $form              = $main::form;
187   my $locale            = $main::locale;
188
189   $form->{title}        = "kivitendo " . $locale->text('Database Administration') . " / " . $locale->text('Update Dataset');
190
191   my @need_updates      = User->dbneedsupdate($form);
192   $form->{NEED_UPDATES} = \@need_updates;
193   $form->{ALL_UPDATED}  = !scalar @need_updates;
194
195   $form->header();
196   print $form->parse_html_template("admin/update_dataset");
197 }
198
199 sub dbupdate {
200   my $form            = $main::form;
201   my $locale          = $main::locale;
202
203   $::request->{layout}->use_stylesheet("lx-office-erp.css");
204   $form->{title}      = $locale->text("Dataset upgrade");
205   $form->header();
206
207   my $rowcount           = $form->{rowcount} * 1;
208   my @update_rows        = grep { $form->{"update_$_"} } (1 .. $rowcount);
209   $form->{NOTHING_TO_DO} = !scalar @update_rows;
210   my $saved_form         = save_form();
211
212   $| = 1;
213
214   print $form->parse_html_template("admin/dbupgrade_all_header");
215
216   foreach my $i (@update_rows) {
217     restore_form($saved_form);
218
219     %::myconfig = ();
220     map { $form->{$_} = $::myconfig{$_} = $form->{"${_}_${i}"} } qw(dbname dbhost dbport dbuser dbpasswd);
221
222     print $form->parse_html_template("admin/dbupgrade_header");
223
224     User->dbupdate($form);
225     User->dbupdate2(form => $form, updater => SL::DBUpgrade2->new(form => $form)->parse_dbupdate_controls, database => $form->{dbname});
226
227     print $form->parse_html_template("admin/dbupgrade_footer");
228   }
229
230   print $form->parse_html_template("admin/dbupgrade_all_done");
231 }
232
233 sub create_dataset {
234   my $form           = $main::form;
235   my $locale         = $main::locale;
236
237   $form->{dbsources} = join " ", map { "[${_}]" } sort User->dbsources($form);
238
239   $form->{CHARTS}    = [];
240
241   tie my %dir_h, 'IO::Dir', 'sql/';
242   foreach my $item (map { s/-chart\.sql$//; $_ } sort grep { /-chart\.sql\z/ && !/Default-chart.sql\z/ } keys %dir_h) {
243     push @{ $form->{CHARTS} }, { name     => $item,
244                                  selected => $item eq "Germany-DATEV-SKR03EU" };
245   }
246
247   $form->{ACCOUNTING_METHODS}    = [ map { { name => $_, selected => $_ eq 'cash'     } } qw(accrual cash)       ];
248   $form->{INVENTORY_SYSTEMS}     = [ map { { name => $_, selected => $_ eq 'periodic' } } qw(perpetual periodic) ];
249   $form->{PROFIT_DETERMINATIONS} = [ map { { name => $_, selected => $_ eq 'income'   } } qw(balance income)     ];
250
251   my $default_charset = $::lx_office_conf{system}->{dbcharset} || Common::DEFAULT_CHARSET;
252
253   my $cluster_encoding = User->dbclusterencoding($form);
254   if ($cluster_encoding && ($cluster_encoding =~ m/^(?:UTF-?8|UNICODE)$/i)) {
255     if ($::lx_office_conf{system}->{dbcharset} !~ m/^UTF-?8$/i) {
256       $form->show_generic_error($locale->text('The selected  PostgreSQL installation uses UTF-8 as its encoding. ' .
257                                               'Therefore you have to configure kivitendo to use UTF-8 as well.'),
258                                 'back_button' => 1);
259     }
260
261     $form->{FORCE_DBENCODING} = 'UNICODE';
262
263   } else {
264     $form->{DBENCODINGS} = [ map { { %{$_}, selected => $_->{charset} eq $default_charset } } @Common::db_encodings ];
265   }
266
267   $form->{title} = "kivitendo " . $locale->text('Database Administration') . " / " . $locale->text('Create Dataset');
268
269   $form->header();
270   print $form->parse_html_template("admin/create_dataset");
271 }
272
273 sub dbcreate {
274   my $form   = $main::form;
275   my $locale = $main::locale;
276
277   $form->isblank("db", $locale->text('Dataset missing!'));
278   $form->isblank("defaultcurrency", $locale->text('Default currency missing!'));
279
280   User->dbcreate(\%$form);
281
282   $form->{title} = "kivitendo " . $locale->text('Database Administration') . " / " . $locale->text('Create Dataset');
283
284   $form->header();
285   print $form->parse_html_template("admin/dbcreate");
286 }
287
288 sub delete_dataset {
289   my $form      = $main::form;
290   my $locale    = $main::locale;
291
292   my @dbsources = User->dbsources_unused($form);
293   $form->error($locale->text('Nothing to delete!')) unless @dbsources;
294
295   $form->{title}     = "kivitendo " . $locale->text('Database Administration') . " / " . $locale->text('Delete Dataset');
296   $form->{DBSOURCES} = [ map { { "name", $_ } } sort @dbsources ];
297
298   $form->header();
299   print $form->parse_html_template("admin/delete_dataset");
300 }
301
302 sub dbdelete {
303   my $form   = $main::form;
304   my $locale = $main::locale;
305
306   if (!$form->{db}) {
307     $form->error($locale->text('No Dataset selected!'));
308   }
309
310   User->dbdelete(\%$form);
311
312   $form->{title} = "kivitendo " . $locale->text('Database Administration') . " / " . $locale->text('Delete Dataset');
313   $form->header();
314   print $form->parse_html_template("admin/dbdelete");
315 }
316
317 sub backup_dataset {
318   my $form       = $main::form;
319   my $locale     = $main::locale;
320
321   $form->{title} = "kivitendo " . $locale->text('Database Administration') . " / " . $locale->text('Backup Dataset');
322
323   if ($::lx_office_conf{applications}->{pg_dump} eq "DISABLED") {
324     $form->error($locale->text('Database backups and restorations are disabled in the configuration.'));
325   }
326
327   my @dbsources         = sort User->dbsources($form);
328   $form->{DATABASES}    = [ map { { "dbname" => $_ } } @dbsources ];
329   $form->{NO_DATABASES} = !scalar @dbsources;
330
331   my $username  = getpwuid $UID || "unknown-user";
332   my $hostname  = hostname() || "unknown-host";
333   $form->{from} = "kivitendo Admin <${username}\@${hostname}>";
334
335   $form->header();
336   print $form->parse_html_template("admin/backup_dataset");
337 }
338
339 sub backup_dataset_start {
340   my $form       = $main::form;
341   my $locale     = $main::locale;
342
343   $form->{title} = "kivitendo " . $locale->text('Database Administration') . " / " . $locale->text('Backup Dataset');
344
345   my $pg_dump_exe = $::lx_office_conf{applications}->{pg_dump} || "pg_dump";
346
347   if ("$pg_dump_exe" eq "DISABLED") {
348     $form->error($locale->text('Database backups and restorations are disabled in the configuration.'));
349   }
350
351   $form->isblank("dbname", $locale->text('The dataset name is missing.'));
352   $form->isblank("to", $locale->text('The email address is missing.')) if $form->{destination} eq "email";
353
354   my $tmpdir = "/tmp/lx_office_backup_" . Common->unique_id();
355   mkdir $tmpdir, 0700 || $form->error($locale->text('A temporary directory could not be created:') . " $ERRNO");
356
357   my $pgpass = IO::File->new("${tmpdir}/.pgpass", O_WRONLY | O_CREAT, 0600);
358
359   if (!$pgpass) {
360     unlink $tmpdir;
361     $form->error($locale->text('A temporary file could not be created:') . " $ERRNO");
362   }
363
364   print $pgpass "$form->{dbhost}:$form->{dbport}:$form->{dbname}:$form->{dbuser}:$form->{dbpasswd}\n";
365   $pgpass->close();
366
367   $ENV{HOME} = $tmpdir;
368
369   my @args = ("-Ft", "-c", "-o", "-h", $form->{dbhost}, "-U", $form->{dbuser});
370   push @args, ("-p", $form->{dbport}) if ($form->{dbport});
371   push @args, $form->{dbname};
372
373   my $cmd  = "$pg_dump_exe " . join(" ", map { s/\\/\\\\/g; s/\"/\\\"/g; $_ } @args);
374   my $name = "dataset_backup_$form->{dbname}_" . strftime("%Y%m%d", localtime()) . ".tar";
375
376   if ($form->{destination} ne "email") {
377     my $in = IO::File->new("$cmd |");
378
379     if (!$in) {
380       unlink "${tmpdir}/.pgpass";
381       rmdir $tmpdir;
382
383       $form->error($locale->text('The pg_dump process could not be started.'));
384     }
385
386     print "content-type: application/x-tar\n";
387     print "content-disposition: attachment; filename=\"${name}\"\n\n";
388
389     while (my $line = <$in>) {
390       print $line;
391     }
392
393     $in->close();
394
395     unlink "${tmpdir}/.pgpass";
396     rmdir $tmpdir;
397
398   } else {
399     my $tmp = $tmpdir . "/dump_" . Common::unique_id();
400
401     if (system("$cmd > $tmp") != 0) {
402       unlink "${tmpdir}/.pgpass", $tmp;
403       rmdir $tmpdir;
404
405       $form->error($locale->text('The pg_dump process could not be started.'));
406     }
407
408     my $mail = new Mailer;
409
410     map { $mail->{$_} = $form->{$_} } qw(from to cc subject message);
411
412     $mail->{charset}     = $::lx_office_conf{system}->{dbcharset} || Common::DEFAULT_CHARSET;
413     $mail->{attachments} = [ { "filename" => $tmp, "name" => $name } ];
414     $mail->send();
415
416     unlink "${tmpdir}/.pgpass", $tmp;
417     rmdir $tmpdir;
418
419     $form->{title} = "kivitendo " . $locale->text('Database Administration') . " / " . $locale->text('Backup Dataset');
420
421     $form->header();
422     print $form->parse_html_template("admin/backup_dataset_email_done");
423   }
424 }
425
426 sub restore_dataset {
427   my $form       = $main::form;
428   my $locale     = $main::locale;
429
430   $form->{title} = "kivitendo " . $locale->text('Database Administration') . " / " . $locale->text('Restore Dataset');
431
432   if ($::lx_office_conf{applications}->{pg_restore} eq "DISABLED") {
433     $form->error($locale->text('Database backups and restorations are disabled in the configuration.'));
434   }
435
436   my $default_charset   = $::lx_office_conf{system}->{dbcharset};
437   $default_charset    ||= Common::DEFAULT_CHARSET;
438
439   $form->{DBENCODINGS}  = [];
440
441   foreach my $encoding (@Common::db_encodings) {
442     push @{ $form->{DBENCODINGS} }, { "dbencoding" => $encoding->{dbencoding},
443                                       "label"      => $encoding->{label},
444                                       "selected"   => $encoding->{charset} eq $default_charset };
445   }
446
447   $form->header();
448   print $form->parse_html_template("admin/restore_dataset");
449 }
450
451 sub restore_dataset_start {
452   my $form       = $main::form;
453   my $locale     = $main::locale;
454
455   $form->{title} = "kivitendo " . $locale->text('Database Administration') . " / " . $locale->text('Restore Dataset');
456
457   my $pg_restore_exe = $::lx_office_conf{applications}->{pg_restore} || "pg_restore";
458
459   if ("$pg_restore_exe" eq "DISABLED") {
460     $form->error($locale->text('Database backups and restorations are disabled in the configuration.'));
461   }
462
463   $form->isblank("new_dbname", $locale->text('The dataset name is missing.'));
464   $form->isblank("content", $locale->text('No backup file has been uploaded.'));
465
466   # Create temporary directories. Write the backup file contents to a temporary
467   # file. Create a .pgpass file with the username and password for the pg_restore
468   # utility.
469
470   my $tmpdir = "/tmp/lx_office_backup_" . Common->unique_id();
471   mkdir $tmpdir, 0700 || $form->error($locale->text('A temporary directory could not be created:') . " $ERRNO");
472
473   my $pgpass = IO::File->new("${tmpdir}/.pgpass", O_WRONLY | O_CREAT, 0600);
474
475   if (!$pgpass) {
476     unlink $tmpdir;
477     $form->error($locale->text('A temporary file could not be created:') . " $ERRNO");
478   }
479
480   print $pgpass "$form->{dbhost}:$form->{dbport}:$form->{new_dbname}:$form->{dbuser}:$form->{dbpasswd}\n";
481   $pgpass->close();
482
483   $ENV{HOME} = $tmpdir;
484
485   my $tmp = $tmpdir . "/dump_" . Common::unique_id();
486   my $tmpfile;
487
488   if (substr($form->{content}, 0, 2) eq "\037\213") {
489     $tmpfile = IO::File->new("| gzip -d > $tmp");
490     $tmpfile->binary();
491
492   } else {
493     $tmpfile = IO::File->new($tmp, O_WRONLY | O_CREAT | O_BINARY, 0600);
494   }
495
496   if (!$tmpfile) {
497     unlink "${tmpdir}/.pgpass";
498     rmdir $tmpdir;
499
500     $form->error($locale->text('A temporary file could not be created:') . " $ERRNO");
501   }
502
503   print $tmpfile $form->{content};
504   $tmpfile->close();
505
506   delete $form->{content};
507
508   # Try to connect to the database. Find out if a database with the same name exists.
509   # If yes, then drop the existing database. Create a new one with the name and encoding
510   # given by the user.
511
512   User::dbconnect_vars($form, "template1");
513
514   my %myconfig = map { $_ => $form->{$_} } grep /^db/, keys %{ $form };
515   my $dbh      = $form->dbconnect(\%myconfig) || $form->dberror();
516
517   my ($query, $sth);
518
519   $form->{new_dbname} =~ s|[^a-zA-Z0-9_\-]||g;
520
521   $query = qq|SELECT COUNT(*) FROM pg_database WHERE datname = ?|;
522   my ($count) = selectrow_query($form, $dbh, $query, $form->{new_dbname});
523   if ($count) {
524     do_query($form, $dbh, qq|DROP DATABASE $form->{new_dbname}|);
525   }
526
527   my $found = 0;
528   foreach my $item (@Common::db_encodings) {
529     if ($item->{dbencoding} eq $form->{dbencoding}) {
530       $found = 1;
531       last;
532     }
533   }
534   $form->{dbencoding} = "LATIN9" unless $form->{dbencoding};
535
536   do_query($form, $dbh, qq|CREATE DATABASE $form->{new_dbname} ENCODING ? TEMPLATE template0|, $form->{dbencoding});
537
538   $dbh->disconnect();
539
540   # Spawn pg_restore on the temporary file.
541
542   my @args = ("-h", $form->{dbhost}, "-U", $form->{dbuser}, "-d", $form->{new_dbname});
543   push @args, ("-p", $form->{dbport}) if ($form->{dbport});
544   push @args, $tmp;
545
546   my $cmd = "$pg_restore_exe " . join(" ", map { s/\\/\\\\/g; s/\"/\\\"/g; $_ } @args);
547
548   my $in = IO::File->new("$cmd 2>&1 |");
549
550   if (!$in) {
551     unlink "${tmpdir}/.pgpass", $tmp;
552     rmdir $tmpdir;
553
554     $form->error($locale->text('The pg_restore process could not be started.'));
555   }
556
557   $English::AUTOFLUSH = 1;
558
559   $form->header();
560   print $form->parse_html_template("admin/restore_dataset_start_header");
561
562   while (my $line = <$in>) {
563     print $line;
564   }
565   $in->close();
566
567   $form->{retval} = $CHILD_ERROR >> 8;
568   print $form->parse_html_template("admin/restore_dataset_start_footer");
569
570   unlink "${tmpdir}/.pgpass", $tmp;
571   rmdir $tmpdir;
572 }
573
574 sub yes {
575   call_sub($main::form->{yes_nextsub});
576 }
577
578 sub no {
579   call_sub($main::form->{no_nextsub});
580 }
581
582 sub add {
583   call_sub($main::form->{add_nextsub});
584 }
585
586 sub edit {
587   my $form = $main::form;
588
589   $form->{edit_nextsub} ||= 'edit_user';
590
591   call_sub($form->{edit_nextsub});
592 }
593
594 sub delete {
595   my $form     = $main::form;
596
597   $form->{delete_nextsub} ||= 'delete_user';
598
599   call_sub($form->{delete_nextsub});
600 }
601
602 sub save {
603   my $form = $main::form;
604
605   $form->{save_nextsub} ||= 'save_user';
606
607   call_sub($form->{save_nextsub});
608 }
609
610 sub back {
611   call_sub($main::form->{back_nextsub});
612 }
613
614 sub dispatcher {
615   my $form   = $main::form;
616   my $locale = $main::locale;
617
618   foreach my $action (qw(create_standard_group dont_create_standard_group
619                          save_user delete_user save_user_as_new)) {
620     if ($form->{"action_${action}"}) {
621       call_sub($action);
622       return;
623     }
624   }
625
626   call_sub($form->{default_action}) if ($form->{default_action});
627
628   $form->error($locale->text('No action defined.'));
629 }
630
631 sub _search_templates {
632   my %templates = SL::Template->available_templates;
633
634   return ($templates{print_templates}, $templates{master_templates});
635 }
636
637 1;