Valid Flag für Custom Variables in Artikeln.
[kivitendo-erp.git] / SL / Auth.pm
1 package SL::Auth;
2
3 use constant OK              =>   0;
4 use constant ERR_PASSWORD    =>   1;
5 use constant ERR_BACKEND     => 100;
6
7 use constant SESSION_OK      =>   0;
8 use constant SESSION_NONE    =>   1;
9 use constant SESSION_EXPIRED =>   2;
10
11 use Digest::MD5 qw(md5_hex);
12 use IO::File;
13 use Time::HiRes qw(gettimeofday);
14 use List::MoreUtils qw(uniq);
15
16 use SL::Auth::DB;
17 use SL::Auth::LDAP;
18
19 use SL::User;
20 use SL::DBUtils;
21
22 sub new {
23   $main::lxdebug->enter_sub();
24
25   my $type = shift;
26   my $self = {};
27
28   bless $self, $type;
29
30   $self->{SESSION} = { };
31
32   $self->_read_auth_config();
33
34   $main::lxdebug->leave_sub();
35
36   return $self;
37 }
38
39 sub DESTROY {
40   my $self = shift;
41
42   $self->{dbh}->disconnect() if ($self->{dbh});
43 }
44
45 sub _read_auth_config {
46   $main::lxdebug->enter_sub();
47
48   my $self   = shift;
49
50   my $form   = $main::form;
51   my $locale = $main::locale;
52
53   my $code;
54   my $in = IO::File->new('config/authentication.pl', 'r');
55
56   if (!$in) {
57     $form->error($locale->text('The config file "config/authentication.pl" was not found.'));
58   }
59
60   while (<$in>) {
61     $code .= $_;
62   }
63   $in->close();
64
65   eval $code;
66
67   if ($@) {
68     $form->error($locale->text('The config file "config/authentication.pl" contained invalid Perl code:') . "\n" . $@);
69   }
70
71   if ($self->{module} eq 'DB') {
72     $self->{authenticator} = SL::Auth::DB->new($self);
73
74   } elsif ($self->{module} eq 'LDAP') {
75     $self->{authenticator} = SL::Auth::LDAP->new($self);
76   }
77
78   if (!$self->{authenticator}) {
79     $form->error($locale->text('No or an unknown authenticantion module specified in "config/authentication.pl".'));
80   }
81
82   my $cfg = $self->{DB_config};
83
84   if (!$cfg) {
85     $form->error($locale->text('config/authentication.pl: Key "DB_config" is missing.'));
86   }
87
88   if (!$cfg->{host} || !$cfg->{db} || !$cfg->{user}) {
89     $form->error($locale->text('config/authentication.pl: Missing parameters in "DB_config". Required parameters are "host", "db" and "user".'));
90   }
91
92   $self->{authenticator}->verify_config();
93
94   $self->{session_timeout} *= 1;
95   $self->{session_timeout}  = 8 * 60 if (!$self->{session_timeout});
96
97   $main::lxdebug->leave_sub();
98 }
99
100 sub authenticate_root {
101   $main::lxdebug->enter_sub();
102
103   my $self           = shift;
104   my $password       = shift;
105   my $is_crypted     = shift;
106
107   $password          = crypt $password, 'ro' if (!$password || !$is_crypted);
108   my $admin_password = crypt "$self->{admin_password}", 'ro';
109
110   $main::lxdebug->leave_sub();
111
112   return $password eq $admin_password ? OK : ERR_PASSWORD;
113 }
114
115 sub authenticate {
116   $main::lxdebug->enter_sub();
117
118   my $self = shift;
119
120   $main::lxdebug->leave_sub();
121
122   return $self->{authenticator}->authenticate(@_);
123 }
124
125 sub dbconnect {
126   $main::lxdebug->enter_sub(2);
127
128   my $self     = shift;
129   my $may_fail = shift;
130
131   if ($self->{dbh}) {
132     $main::lxdebug->leave_sub(2);
133     return $self->{dbh};
134   }
135
136   my $cfg = $self->{DB_config};
137   my $dsn = 'dbi:Pg:dbname=' . $cfg->{db} . ';host=' . $cfg->{host};
138
139   if ($cfg->{port}) {
140     $dsn .= ';port=' . $cfg->{port};
141   }
142
143   $main::lxdebug->message(LXDebug::DEBUG1, "Auth::dbconnect DSN: $dsn");
144
145   $self->{dbh} = DBI->connect($dsn, $cfg->{user}, $cfg->{password}, { 'AutoCommit' => 0 });
146
147   if (!$may_fail && !$self->{dbh}) {
148     $main::form->error($main::locale->text('The connection to the authentication database failed:') . "\n" . $DBI::errstr);
149   }
150
151   $main::lxdebug->leave_sub();
152
153   return $self->{dbh};
154 }
155
156 sub dbdisconnect {
157   $main::lxdebug->enter_sub();
158
159   my $self = shift;
160
161   if ($self->{dbh}) {
162     $self->{dbh}->disconnect();
163     delete $self->{dbh};
164   }
165
166   $main::lxdebug->leave_sub();
167 }
168
169 sub check_tables {
170   $main::lxdebug->enter_sub();
171
172   my $self    = shift;
173
174   my $dbh     = $self->dbconnect();
175   my $query   = qq|SELECT COUNT(*) FROM pg_tables WHERE (schemaname = 'auth') AND (tablename = 'user')|;
176
177   my ($count) = $dbh->selectrow_array($query);
178
179   $main::lxdebug->leave_sub();
180
181   return $count > 0;
182 }
183
184 sub check_database {
185   $main::lxdebug->enter_sub();
186
187   my $self = shift;
188
189   my $dbh  = $self->dbconnect(1);
190
191   $main::lxdebug->leave_sub();
192
193   return $dbh ? 1 : 0;
194 }
195
196 sub create_database {
197   $main::lxdebug->enter_sub();
198
199   my $self   = shift;
200   my %params = @_;
201
202   my $cfg    = $self->{DB_config};
203
204   if (!$params{superuser}) {
205     $params{superuser}          = $cfg->{user};
206     $params{superuser_password} = $cfg->{password};
207   }
208
209   $params{template} ||= 'template0';
210   $params{template}   =~ s|[^a-zA-Z0-9_\-]||g;
211
212   my $dsn = 'dbi:Pg:dbname=template1;host=' . $cfg->{host};
213
214   if ($cfg->{port}) {
215     $dsn .= ';port=' . $cfg->{port};
216   }
217
218   $main::lxdebug->message(LXDebug::DEBUG1, "Auth::create_database DSN: $dsn");
219
220   my $dbh = DBI->connect($dsn, $params{superuser}, $params{superuser_password});
221
222   if (!$dbh) {
223     $main::form->error($main::locale->text('The connection to the template database failed:') . "\n" . $DBI::errstr);
224   }
225
226   my $charset    = $main::dbcharset;
227   $charset     ||= Common::DEFAULT_CHARSET;
228   my $encoding   = $Common::charset_to_db_encoding{$charset};
229   $encoding    ||= 'UNICODE';
230
231   my $query = qq|CREATE DATABASE "$cfg->{db}" OWNER "$cfg->{user}" TEMPLATE "$params{template}" ENCODING '$encoding'|;
232
233   $main::lxdebug->message(LXDebug::DEBUG1, "Auth::create_database query: $query");
234
235   $dbh->do($query);
236
237   if ($dbh->err) {
238     my $error = $dbh->errstr();
239
240     $query                 = qq|SELECT pg_encoding_to_char(encoding) FROM pg_database WHERE datname = 'template0'|;
241     my ($cluster_encoding) = $dbh->selectrow_array($query);
242
243     if ($cluster_encoding && ($cluster_encoding =~ m/^(?:UTF-?8|UNICODE)$/i) && ($encoding !~ m/^(?:UTF-?8|UNICODE)$/i)) {
244       $error = $main::locale->text('Your PostgreSQL installationen uses UTF-8 as its encoding. Therefore you have to configure Lx-Office to use UTF-8 as well.');
245     }
246
247     $dbh->disconnect();
248
249     $main::form->error($main::locale->text('The creation of the authentication database failed:') . "\n" . $error);
250   }
251
252   $dbh->disconnect();
253
254   $main::lxdebug->leave_sub();
255 }
256
257 sub create_tables {
258   $main::lxdebug->enter_sub();
259
260   my $self = shift;
261   my $dbh  = $self->dbconnect();
262
263   my $charset    = $main::dbcharset;
264   $charset     ||= Common::DEFAULT_CHARSET;
265
266   $dbh->rollback();
267   User->process_query($main::form, $dbh, 'sql/auth_db.sql', undef, $charset);
268
269   $main::lxdebug->leave_sub();
270 }
271
272 sub save_user {
273   $main::lxdebug->enter_sub();
274
275   my $self   = shift;
276   my $login  = shift;
277   my %params = @_;
278
279   my $form   = $main::form;
280
281   my $dbh    = $self->dbconnect();
282
283   my ($sth, $query, $user_id);
284
285   $query     = qq|SELECT id FROM auth."user" WHERE login = ?|;
286   ($user_id) = selectrow_query($form, $dbh, $query, $login);
287
288   if (!$user_id) {
289     $query     = qq|SELECT nextval('auth.user_id_seq')|;
290     ($user_id) = selectrow_query($form, $dbh, $query);
291
292     $query     = qq|INSERT INTO auth."user" (id, login) VALUES (?, ?)|;
293     do_query($form, $dbh, $query, $user_id, $login);
294   }
295
296   $query = qq|DELETE FROM auth.user_config WHERE (user_id = ?)|;
297   do_query($form, $dbh, $query, $user_id);
298
299   $query = qq|INSERT INTO auth.user_config (user_id, cfg_key, cfg_value) VALUES (?, ?, ?)|;
300   $sth   = prepare_query($form, $dbh, $query);
301
302   while (my ($cfg_key, $cfg_value) = each %params) {
303     next if ($cfg_key eq 'password');
304
305     do_statement($form, $sth, $query, $user_id, $cfg_key, $cfg_value);
306   }
307
308   $dbh->commit();
309
310   $main::lxdebug->leave_sub();
311 }
312
313 sub can_change_password {
314   my $self = shift;
315
316   return $self->{authenticator}->can_change_password();
317 }
318
319 sub change_password {
320   $main::lxdebug->enter_sub();
321
322   my $self   = shift;
323   my $result = $self->{authenticator}->change_password(@_);
324
325   $main::lxdebug->leave_sub();
326
327   return $result;
328 }
329
330 sub read_all_users {
331   $main::lxdebug->enter_sub();
332
333   my $self  = shift;
334
335   my $dbh   = $self->dbconnect();
336   my $query = qq|SELECT u.id, u.login, cfg.cfg_key, cfg.cfg_value
337                  FROM auth.user_config cfg
338                  LEFT JOIN auth."user" u ON (cfg.user_id = u.id)|;
339   my $sth   = prepare_execute_query($main::form, $dbh, $query);
340
341   my %users;
342
343   while (my $ref = $sth->fetchrow_hashref()) {
344     $users{$ref->{login}}                    ||= { 'login' => $ref->{login}, 'id' => $ref->{id} };
345     $users{$ref->{login}}->{$ref->{cfg_key}}   = $ref->{cfg_value} if (($ref->{cfg_key} ne 'login') && ($ref->{cfg_key} ne 'id'));
346   }
347
348   $sth->finish();
349
350   $main::lxdebug->leave_sub();
351
352   return %users;
353 }
354
355 sub read_user {
356   $main::lxdebug->enter_sub();
357
358   my $self  = shift;
359   my $login = shift;
360
361   my $dbh   = $self->dbconnect();
362   my $query = qq|SELECT u.id, u.login, cfg.cfg_key, cfg.cfg_value
363                  FROM auth.user_config cfg
364                  LEFT JOIN auth."user" u ON (cfg.user_id = u.id)
365                  WHERE (u.login = ?)|;
366   my $sth   = prepare_execute_query($main::form, $dbh, $query, $login);
367
368   my %user_data;
369
370   while (my $ref = $sth->fetchrow_hashref()) {
371     $user_data{$ref->{cfg_key}} = $ref->{cfg_value};
372     @user_data{qw(id login)}    = @{$ref}{qw(id login)};
373   }
374
375   $sth->finish();
376
377   $main::lxdebug->leave_sub();
378
379   return %user_data;
380 }
381
382 sub get_user_id {
383   $main::lxdebug->enter_sub();
384
385   my $self  = shift;
386   my $login = shift;
387
388   my $dbh   = $self->dbconnect();
389   my ($id)  = selectrow_query($main::form, $dbh, qq|SELECT id FROM auth."user" WHERE login = ?|, $login);
390
391   $main::lxdebug->leave_sub();
392
393   return $id;
394 }
395
396 sub delete_user {
397   $main::lxdebug->enter_sub();
398
399   my $self  = shift;
400   my $login = shift;
401
402   my $form  = $main::form;
403
404   my $dbh   = $self->dbconnect();
405   my $query = qq|SELECT id FROM auth."user" WHERE login = ?|;
406
407   my ($id)  = selectrow_query($form, $dbh, $query, $login);
408
409   return $main::lxdebug->leave_sub() if (!$id);
410
411   do_query($form, $dbh, qq|DELETE FROM auth.user_group WHERE user_id = ?|, $id);
412   do_query($form, $dbh, qq|DELETE FROM auth.user_config WHERE user_id = ?|, $id);
413
414   $dbh->commit();
415
416   $main::lxdebug->leave_sub();
417 }
418
419 # --------------------------------------
420
421 my $session_id;
422
423 sub restore_session {
424   $main::lxdebug->enter_sub();
425
426   my $self = shift;
427
428   my $cgi            =  $main::cgi;
429   $cgi             ||=  CGI->new('');
430
431   $session_id        =  $cgi->cookie($self->get_session_cookie_name());
432   $session_id        =~ s|[^0-9a-f]||g;
433
434   $self->{SESSION}   = { };
435
436   if (!$session_id) {
437     $main::lxdebug->leave_sub();
438     return SESSION_NONE;
439   }
440
441   my ($dbh, $query, $sth, $cookie, $ref, $form);
442
443   $form   = $main::form;
444
445   $dbh    = $self->dbconnect();
446   $query  = qq|SELECT *, (mtime < (now() - '$self->{session_timeout}m'::interval)) AS is_expired FROM auth.session WHERE id = ?|;
447
448   $cookie = selectfirst_hashref_query($form, $dbh, $query, $session_id);
449
450   if (!$cookie || $cookie->{is_expired} || ($cookie->{ip_address} ne $ENV{REMOTE_ADDR})) {
451     $self->destroy_session();
452     $main::lxdebug->leave_sub();
453     return SESSION_EXPIRED;
454   }
455
456   $query = qq|SELECT sess_key, sess_value FROM auth.session_content WHERE session_id = ?|;
457   $sth   = prepare_execute_query($form, $dbh, $query, $session_id);
458
459   while (my $ref = $sth->fetchrow_hashref()) {
460     $self->{SESSION}->{$ref->{sess_key}} = $ref->{sess_value};
461     $form->{$ref->{sess_key}}            = $ref->{sess_value} if (!defined $form->{$ref->{sess_key}});
462   }
463
464   $sth->finish();
465
466   $main::lxdebug->leave_sub();
467
468   return SESSION_OK;
469 }
470
471 sub destroy_session {
472   $main::lxdebug->enter_sub();
473
474   my $self = shift;
475
476   if ($session_id) {
477     my $dbh = $self->dbconnect();
478
479     do_query($main::form, $dbh, qq|DELETE FROM auth.session_content WHERE session_id = ?|, $session_id);
480     do_query($main::form, $dbh, qq|DELETE FROM auth.session WHERE id = ?|, $session_id);
481
482     $dbh->commit();
483
484     $session_id      = undef;
485     $self->{SESSION} = { };
486   }
487
488   $main::lxdebug->leave_sub();
489 }
490
491 sub expire_sessions {
492   $main::lxdebug->enter_sub();
493
494   my $self  = shift;
495
496   my $dbh   = $self->dbconnect();
497   my $query =
498     qq|DELETE FROM auth.session_content
499        WHERE session_id IN
500          (SELECT id
501           FROM auth.session
502           WHERE (mtime < (now() - '$self->{session_timeout}m'::interval)))|;
503
504   do_query($main::form, $dbh, $query);
505
506   $query =
507     qq|DELETE FROM auth.session
508        WHERE (mtime < (now() - '$self->{session_timeout}m'::interval))|;
509
510   do_query($main::form, $dbh, $query);
511
512   $dbh->commit();
513
514   $main::lxdebug->leave_sub();
515 }
516
517 sub _create_session_id {
518   $main::lxdebug->enter_sub();
519
520   my @data;
521   map { push @data, int(rand() * 255); } (1..32);
522
523   my $id = md5_hex(pack 'C*', @data);
524
525   $main::lxdebug->leave_sub();
526
527   return $id;
528 }
529
530 sub create_or_refresh_session {
531   $main::lxdebug->enter_sub();
532
533   my $self = shift;
534
535   $session_id ||= $self->_create_session_id();
536
537   my ($form, $dbh, $query, $sth, $id);
538
539   $form  = $main::form;
540   $dbh   = $self->dbconnect();
541
542   $query = qq|SELECT id FROM auth.session WHERE id = ?|;
543
544   ($id)  = selectrow_query($form, $dbh, $query, $session_id);
545
546   if ($id) {
547     do_query($form, $dbh, qq|UPDATE auth.session SET mtime = now() WHERE id = ?|, $session_id);
548     do_query($form, $dbh, qq|DELETE FROM auth.session_content WHERE session_id = ?|, $session_id);
549
550   } else {
551     do_query($form, $dbh, qq|INSERT INTO auth.session (id, ip_address, mtime) VALUES (?, ?, now())|, $session_id, $ENV{REMOTE_ADDR});
552
553   }
554
555   $query = qq|INSERT INTO auth.session_content (session_id, sess_key, sess_value) VALUES (?, ?, ?)|;
556   $sth   = prepare_query($form, $dbh, $query);
557
558   foreach my $key (sort keys %{ $self->{SESSION} }) {
559     do_statement($form, $sth, $query, $session_id, $key, $self->{SESSION}->{$key});
560   }
561
562   $sth->finish();
563   $dbh->commit();
564
565   $main::lxdebug->leave_sub();
566 }
567
568 sub set_session_value {
569   $main::lxdebug->enter_sub();
570
571   my $self  = shift;
572
573   $self->{SESSION} ||= { };
574
575   while (2 <= scalar @_) {
576     my $key   = shift;
577     my $value = shift;
578
579     $self->{SESSION}->{$key} = $value;
580   }
581
582   $main::lxdebug->leave_sub();
583 }
584
585 sub set_cookie_environment_variable {
586   my $self = shift;
587   $ENV{HTTP_COOKIE} = $self->get_session_cookie_name() . "=${session_id}";
588 }
589
590 sub get_session_cookie_name {
591   my $self = shift;
592
593   return $self->{cookie_name} || 'lx_office_erp_session_id';
594 }
595
596 sub get_session_id {
597   return $session_id;
598 }
599
600 sub session_tables_present {
601   $main::lxdebug->enter_sub();
602
603   my $self = shift;
604   my $dbh  = $self->dbconnect(1);
605
606   if (!$dbh) {
607     $main::lxdebug->leave_sub();
608     return 0;
609   }
610
611   my $query =
612     qq|SELECT COUNT(*)
613        FROM pg_tables
614        WHERE (schemaname = 'auth')
615          AND (tablename IN ('session', 'session_content'))|;
616
617   my ($count) = selectrow_query($main::form, $dbh, $query);
618
619   $main::lxdebug->leave_sub();
620
621   return 2 == $count;
622 }
623
624 # --------------------------------------
625
626 sub all_rights_full {
627   my $locale = $main::locale;
628
629   my @all_rights = (
630     ["--crm",                          $locale->text("CRM optional software")],
631     ["crm_search",                     $locale->text("CRM search")],
632     ["crm_new",                        $locale->text("CRM create customers, vendors and contacts")],
633     ["crm_service",                    $locale->text("CRM services")],
634     ["crm_admin",                      $locale->text("CRM admin")],
635     ["crm_adminuser",                  $locale->text("CRM user")],
636     ["crm_adminstatus",                $locale->text("CRM status")],
637     ["crm_email",                      $locale->text("CRM send email")],
638     ["crm_termin",                     $locale->text("CRM termin")],
639     ["crm_opportunity",                $locale->text("CRM opportunity")],
640     ["crm_knowhow",                    $locale->text("CRM know how")],
641     ["crm_follow",                     $locale->text("CRM follow up")],
642     ["crm_notices",                    $locale->text("CRM notices")],
643     ["crm_other",                      $locale->text("CRM other")],
644     ["--master_data",                  $locale->text("Master Data")],
645     ["customer_vendor_edit",           $locale->text("Create and edit customers and vendors")],
646     ["part_service_assembly_edit",     $locale->text("Create and edit parts, services, assemblies")],
647     ["project_edit",                   $locale->text("Create and edit projects")],
648     ["license_edit",                   $locale->text("Manage license keys")],
649     ["--ar",                           $locale->text("AR")],
650     ["sales_quotation_edit",           $locale->text("Create and edit sales quotations")],
651     ["sales_order_edit",               $locale->text("Create and edit sales orders")],
652     ["sales_delivery_order_edit",      $locale->text("Create and edit sales delivery orders")],
653     ["invoice_edit",                   $locale->text("Create and edit invoices and credit notes")],
654     ["dunning_edit",                   $locale->text("Create and edit dunnings")],
655     ["--ap",                           $locale->text("AP")],
656     ["request_quotation_edit",         $locale->text("Create and edit RFQs")],
657     ["purchase_order_edit",            $locale->text("Create and edit purchase orders")],
658     ["purchase_delivery_order_edit",   $locale->text("Create and edit purchase delivery orders")],
659     ["vendor_invoice_edit",            $locale->text("Create and edit vendor invoices")],
660     ["--warehouse_management",         $locale->text("Warehouse management")],
661     ["warehouse_contents",             $locale->text("View warehouse content")],
662     ["warehouse_management",           $locale->text("Warehouse management")],
663     ["--general_ledger_cash",          $locale->text("General ledger and cash")],
664     ["general_ledger",                 $locale->text("Transactions, AR transactions, AP transactions")],
665     ["datev_export",                   $locale->text("DATEV Export")],
666     ["cash",                           $locale->text("Receipt, payment, reconciliation")],
667     ["--reports",                      $locale->text('Reports')],
668     ["report",                         $locale->text('All reports')],
669     ["advance_turnover_tax_return",    $locale->text('Advance turnover tax return')],
670     ["--others",                       $locale->text("Others")],
671     ["email_bcc",                      $locale->text("May set the BCC field when sending emails")],
672     ["config",                         $locale->text("Change Lx-Office installation settings (all menu entries beneath 'System')")],
673     );
674
675   return @all_rights;
676 }
677
678 sub all_rights {
679   return grep !/^--/, map { $_->[0] } all_rights_full();
680 }
681
682 sub read_groups {
683   $main::lxdebug->enter_sub();
684
685   my $self = shift;
686
687   my $form   = $main::form;
688   my $groups = {};
689   my $dbh    = $self->dbconnect();
690
691   my $query  = 'SELECT * FROM auth."group"';
692   my $sth    = prepare_execute_query($form, $dbh, $query);
693
694   my ($row, $group);
695
696   while ($row = $sth->fetchrow_hashref()) {
697     $groups->{$row->{id}} = $row;
698   }
699   $sth->finish();
700
701   $query = 'SELECT * FROM auth.user_group WHERE group_id = ?';
702   $sth   = prepare_query($form, $dbh, $query);
703
704   foreach $group (values %{$groups}) {
705     my @members;
706
707     do_statement($form, $sth, $query, $group->{id});
708
709     while ($row = $sth->fetchrow_hashref()) {
710       push @members, $row->{user_id};
711     }
712     $group->{members} = [ uniq @members ];
713   }
714   $sth->finish();
715
716   $query = 'SELECT * FROM auth.group_rights WHERE group_id = ?';
717   $sth   = prepare_query($form, $dbh, $query);
718
719   foreach $group (values %{$groups}) {
720     $group->{rights} = {};
721
722     do_statement($form, $sth, $query, $group->{id});
723
724     while ($row = $sth->fetchrow_hashref()) {
725       $group->{rights}->{$row->{right}} |= $row->{granted};
726     }
727
728     map { $group->{rights}->{$_} = 0 if (!defined $group->{rights}->{$_}); } all_rights();
729   }
730   $sth->finish();
731
732   $main::lxdebug->leave_sub();
733
734   return $groups;
735 }
736
737 sub save_group {
738   $main::lxdebug->enter_sub();
739
740   my $self  = shift;
741   my $group = shift;
742
743   my $form  = $main::form;
744   my $dbh   = $self->dbconnect();
745
746   my ($query, $sth, $row, $rights);
747
748   if (!$group->{id}) {
749     ($group->{id}) = selectrow_query($form, $dbh, qq|SELECT nextval('auth.group_id_seq')|);
750
751     $query = qq|INSERT INTO auth."group" (id, name, description) VALUES (?, '', '')|;
752     do_query($form, $dbh, $query, $group->{id});
753   }
754
755   do_query($form, $dbh, qq|UPDATE auth."group" SET name = ?, description = ? WHERE id = ?|, map { $group->{$_} } qw(name description id));
756
757   do_query($form, $dbh, qq|DELETE FROM auth.user_group WHERE group_id = ?|, $group->{id});
758
759   $query  = qq|INSERT INTO auth.user_group (user_id, group_id) VALUES (?, ?)|;
760   $sth    = prepare_query($form, $dbh, $query);
761
762   foreach my $user_id (uniq @{ $group->{members} }) {
763     do_statement($form, $sth, $query, $user_id, $group->{id});
764   }
765   $sth->finish();
766
767   do_query($form, $dbh, qq|DELETE FROM auth.group_rights WHERE group_id = ?|, $group->{id});
768
769   $query = qq|INSERT INTO auth.group_rights (group_id, "right", granted) VALUES (?, ?, ?)|;
770   $sth   = prepare_query($form, $dbh, $query);
771
772   foreach my $right (keys %{ $group->{rights} }) {
773     do_statement($form, $sth, $query, $group->{id}, $right, $group->{rights}->{$right} ? 't' : 'f');
774   }
775   $sth->finish();
776
777   $dbh->commit();
778
779   $main::lxdebug->leave_sub();
780 }
781
782 sub delete_group {
783   $main::lxdebug->enter_sub();
784
785   my $self = shift;
786   my $id   = shift;
787
788   my $form = $main::from;
789
790   my $dbh  = $self->dbconnect();
791
792   do_query($form, $dbh, qq|DELETE FROM auth.user_group WHERE group_id = ?|, $id);
793   do_query($form, $dbh, qq|DELETE FROM auth.group_rights WHERE group_id = ?|, $id);
794   do_query($form, $dbh, qq|DELETE FROM auth."group" WHERE id = ?|, $id);
795
796   $dbh->commit();
797
798   $main::lxdebug->leave_sub();
799 }
800
801 sub evaluate_rights_ary {
802   $main::lxdebug->enter_sub(2);
803
804   my $ary    = shift;
805
806   my $value  = 0;
807   my $action = '|';
808
809   foreach my $el (@{$ary}) {
810     if (ref $el eq "ARRAY") {
811       if ($action eq '|') {
812         $value |= evaluate_rights_ary($el);
813       } else {
814         $value &= evaluate_rights_ary($el);
815       }
816
817     } elsif (($el eq '&') || ($el eq '|')) {
818       $action = $el;
819
820     } elsif ($action eq '|') {
821       $value |= $el;
822
823     } else {
824       $value &= $el;
825
826     }
827   }
828
829   $main::lxdebug->enter_sub(2);
830
831   return $value;
832 }
833
834 sub _parse_rights_string {
835   $main::lxdebug->enter_sub(2);
836
837   my $self   = shift;
838
839   my $login  = shift;
840   my $access = shift;
841
842   my @stack;
843   my $cur_ary = [];
844
845   push @stack, $cur_ary;
846
847   while ($access =~ m/^([a-z_0-9]+|\||\&|\(|\)|\s+)/) {
848     my $token = $1;
849     substr($access, 0, length $1) = "";
850
851     next if ($token =~ /\s/);
852
853     if ($token eq "(") {
854       my $new_cur_ary = [];
855       push @stack, $new_cur_ary;
856       push @{$cur_ary}, $new_cur_ary;
857       $cur_ary = $new_cur_ary;
858
859     } elsif ($token eq ")") {
860       pop @stack;
861
862       if (!@stack) {
863         $main::lxdebug->enter_sub(2);
864         return 0;
865       }
866
867       $cur_ary = $stack[-1];
868
869     } elsif (($token eq "|") || ($token eq "&")) {
870       push @{$cur_ary}, $token;
871
872     } else {
873       push @{$cur_ary}, $self->{RIGHTS}->{$login}->{$token} * 1;
874     }
875   }
876
877   my $result = ($access || (1 < scalar @stack)) ? 0 : evaluate_rights_ary($stack[0]);
878
879   $main::lxdebug->enter_sub(2);
880
881   return $result;
882 }
883
884 sub check_right {
885   $main::lxdebug->enter_sub(2);
886
887   my $self    = shift;
888   my $login   = shift;
889   my $right   = shift;
890   my $default = shift;
891
892   $self->{FULL_RIGHTS}           ||= { };
893   $self->{FULL_RIGHTS}->{$login} ||= { };
894
895   if (!defined $self->{FULL_RIGHTS}->{$login}->{$right}) {
896     $self->{RIGHTS}           ||= { };
897     $self->{RIGHTS}->{$login} ||= $self->load_rights_for_user($login);
898
899     $self->{FULL_RIGHTS}->{$login}->{$right} = $self->_parse_rights_string($login, $right);
900   }
901
902   my $granted = $self->{FULL_RIGHTS}->{$login}->{$right};
903   $granted    = $default if (!defined $granted);
904
905   $main::lxdebug->leave_sub(2);
906
907   return $granted;
908 }
909
910 sub assert {
911   $main::lxdebug->enter_sub(2);
912
913   my $self       = shift;
914   my $right      = shift;
915   my $dont_abort = shift;
916
917   my $form       = $main::form;
918
919   if ($self->check_right($form->{login}, $right)) {
920     $main::lxdebug->leave_sub(2);
921     return 1;
922   }
923
924   if (!$dont_abort) {
925     delete $form->{title};
926     $form->show_generic_error($main::locale->text("You do not have the permissions to access this function."));
927   }
928
929   $main::lxdebug->leave_sub(2);
930
931   return 0;
932 }
933
934 sub load_rights_for_user {
935   $main::lxdebug->enter_sub();
936
937   my $self  = shift;
938   my $login = shift;
939
940   my $form  = $main::form;
941   my $dbh   = $self->dbconnect();
942
943   my ($query, $sth, $row, $rights);
944
945   $rights = {};
946
947   $query =
948     qq|SELECT gr."right", gr.granted
949        FROM auth.group_rights gr
950        WHERE group_id IN
951          (SELECT ug.group_id
952           FROM auth.user_group ug
953           LEFT JOIN auth."user" u ON (ug.user_id = u.id)
954           WHERE u.login = ?)|;
955
956   $sth = prepare_execute_query($form, $dbh, $query, $login);
957
958   while ($row = $sth->fetchrow_hashref()) {
959     $rights->{$row->{right}} |= $row->{granted};
960   }
961   $sth->finish();
962
963   map({ $rights->{$_} = 0 unless (defined $rights->{$_}); } SL::Auth::all_rights());
964
965   $main::lxdebug->leave_sub();
966
967   return $rights;
968 }
969
970 1;