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