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