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