Das Verhalten der Checkbox "Formulardetails anzeigen/verstecken" kann in den Benutzer...
[kivitendo-erp.git] / SL / User.pm
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) 2001
10 #
11 #  Author: Dieter Simader
12 #   Email: dsimader@sql-ledger.org
13 #     Web: http://www.sql-ledger.org
14 #
15 #  Contributors:
16 #
17 # This program is free software; you can redistribute it and/or modify
18 # it under the terms of the GNU General Public License as published by
19 # the Free Software Foundation; either version 2 of the License, or
20 # (at your option) any later version.
21 #
22 # This program is distributed in the hope that it will be useful,
23 # but WITHOUT ANY WARRANTY; without even the implied warranty of
24 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
25 # GNU General Public License for more details.
26 # You should have received a copy of the GNU General Public License
27 # along with this program; if not, write to the Free Software
28 # Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
29 #=====================================================================
30 #
31 # user related functions
32 #
33 #=====================================================================
34
35 package User;
36
37 use SL::DBUpgrade2;
38
39 sub new {
40   $main::lxdebug->enter_sub();
41
42   my ($type, $memfile, $login) = @_;
43   my $self = {};
44
45   if ($login ne "") {
46     &error("", "$memfile locked!") if (-f "${memfile}.LCK");
47
48     open(MEMBER, "$memfile") or &error("", "$memfile : $!");
49
50     while (<MEMBER>) {
51       if (/^\[$login\]/) {
52         while (<MEMBER>) {
53           last if /^\[/;
54           next if /^(#|\s)/;
55
56           # remove comments
57           s/\s#.*//g;
58
59           # remove any trailing whitespace
60           s/^\s*(.*?)\s*$/$1/;
61
62           ($key, $value) = split(/=/, $_, 2);
63
64           if (($key eq "stylesheet") && ($value eq "sql-ledger.css")) {
65             $value = "lx-office-erp.css";
66           }
67
68           $self->{$key} = $value;
69         }
70
71         $self->{login} = $login;
72
73         last;
74       }
75     }
76     close MEMBER;
77   }
78
79   $main::lxdebug->leave_sub();
80   bless $self, $type;
81 }
82
83 sub country_codes {
84   $main::lxdebug->enter_sub();
85
86   my %cc       = ();
87   my @language = ();
88
89   # scan the locale directory and read in the LANGUAGE files
90   opendir DIR, "locale";
91
92   my @dir = grep !/(^\.\.?$|\..*)/, readdir DIR;
93
94   foreach my $dir (@dir) {
95     next unless open(FH, "locale/$dir/LANGUAGE");
96     @language = <FH>;
97     close FH;
98
99     $cc{$dir} = "@language";
100   }
101
102   closedir(DIR);
103
104   $main::lxdebug->leave_sub();
105
106   return %cc;
107 }
108
109 sub login {
110   $main::lxdebug->enter_sub();
111
112   my ($self, $form, $userspath) = @_;
113
114   my $rc = -3;
115
116   if ($self->{login}) {
117
118     if ($self->{password}) {
119       if ($form->{hashed_password}) {
120         $form->{password} = $form->{hashed_password};
121       } else {
122         $form->{password} = crypt($form->{password},
123                                   substr($self->{login}, 0, 2));
124       }
125       if ($self->{password} ne $form->{password}) {
126         $main::lxdebug->leave_sub();
127         return -1;
128       }
129     }
130
131     unless (-e "$userspath/$self->{login}.conf") {
132       $self->create_config("$userspath/$self->{login}.conf");
133     }
134
135     do "$userspath/$self->{login}.conf";
136     $myconfig{dbpasswd} = unpack 'u', $myconfig{dbpasswd};
137
138     # check if database is down
139     my $dbh =
140       DBI->connect($myconfig{dbconnect}, $myconfig{dbuser},
141                    $myconfig{dbpasswd})
142       or $self->error(DBI::errstr);
143
144     # we got a connection, check the version
145     my $query = qq|SELECT version FROM defaults|;
146     my $sth   = $dbh->prepare($query);
147     $sth->execute || $form->dberror($query);
148
149     my ($dbversion) = $sth->fetchrow_array;
150     $sth->finish;
151
152     # add login to employee table if it does not exist
153     # no error check for employee table, ignore if it does not exist
154     $query = qq|SELECT e.id FROM employee e WHERE e.login = '$self->{login}'|;
155     $sth   = $dbh->prepare($query);
156     $sth->execute;
157
158     my ($login) = $sth->fetchrow_array;
159     $sth->finish;
160
161     if (!$login) {
162       $query = qq|INSERT INTO employee (login, name, workphone, role)
163                   VALUES ('$self->{login}', '$myconfig{name}',
164                   '$myconfig{tel}', 'user')|;
165       $dbh->do($query);
166     }
167
168     $self->create_schema_info_table($form, $dbh);
169
170     $dbh->disconnect;
171
172     $rc = 0;
173
174     my $controls =
175       parse_dbupdate_controls($form, $myconfig{"dbdriver"});
176
177     map({ $form->{$_} = $myconfig{$_} }
178         qw(dbname dbhost dbport dbdriver dbuser dbpasswd dbconnect));
179
180     if (update_available($myconfig{"dbdriver"}, $dbversion) ||
181         update2_available($form, $controls)) {
182
183       $form->{"stylesheet"} = "lx-office-erp.css";
184       $form->{"title"} = $main::locale->text("Dataset upgrade");
185       $form->header();
186       print($form->parse_html_template("dbupgrade/header"));
187
188       $form->{dbupdate} = "db$myconfig{dbname}";
189       $form->{ $form->{dbupdate} } = 1;
190
191       if ($form->{"show_dbupdate_warning"}) {
192         print($form->parse_html_template("dbupgrade/warning"));
193         exit(0);
194       }
195
196       # update the tables
197       open(FH, ">$userspath/nologin") or die("$!");
198
199       # required for Oracle
200       $form->{dbdefault} = $sid;
201
202       # ignore HUP, QUIT in case the webserver times out
203       $SIG{HUP}  = 'IGNORE';
204       $SIG{QUIT} = 'IGNORE';
205
206       $self->dbupdate($form);
207       $self->dbupdate2($form, $controls);
208
209       # remove lock file
210       unlink("$userspath/nologin");
211
212       print($form->parse_html_template("dbupgrade/footer"));
213
214       $rc = -2;
215
216     }
217   }
218
219   $main::lxdebug->leave_sub();
220
221   return $rc;
222 }
223
224 sub dbconnect_vars {
225   $main::lxdebug->enter_sub();
226
227   my ($form, $db) = @_;
228
229   my %dboptions = (
230         'Pg' => { 'yy-mm-dd'   => 'set DateStyle to \'ISO\'',
231                   'yyyy-mm-dd' => 'set DateStyle to \'ISO\'',
232                   'mm/dd/yy'   => 'set DateStyle to \'SQL, US\'',
233                   'mm-dd-yy'   => 'set DateStyle to \'POSTGRES, US\'',
234                   'dd/mm/yy'   => 'set DateStyle to \'SQL, EUROPEAN\'',
235                   'dd-mm-yy'   => 'set DateStyle to \'POSTGRES, EUROPEAN\'',
236                   'dd.mm.yy'   => 'set DateStyle to \'GERMAN\''
237         },
238         'Oracle' => {
239           'yy-mm-dd'   => 'ALTER SESSION SET NLS_DATE_FORMAT = \'YY-MM-DD\'',
240           'yyyy-mm-dd' => 'ALTER SESSION SET NLS_DATE_FORMAT = \'YYYY-MM-DD\'',
241           'mm/dd/yy'   => 'ALTER SESSION SET NLS_DATE_FORMAT = \'MM/DD/YY\'',
242           'mm-dd-yy'   => 'ALTER SESSION SET NLS_DATE_FORMAT = \'MM-DD-YY\'',
243           'dd/mm/yy'   => 'ALTER SESSION SET NLS_DATE_FORMAT = \'DD/MM/YY\'',
244           'dd-mm-yy'   => 'ALTER SESSION SET NLS_DATE_FORMAT = \'DD-MM-YY\'',
245           'dd.mm.yy'   => 'ALTER SESSION SET NLS_DATE_FORMAT = \'DD.MM.YY\'',
246         });
247
248   $form->{dboptions} = $dboptions{ $form->{dbdriver} }{ $form->{dateformat} };
249
250   if ($form->{dbdriver} eq 'Pg') {
251     $form->{dbconnect} = "dbi:Pg:dbname=$db";
252   }
253
254   if ($form->{dbdriver} eq 'Oracle') {
255     $form->{dbconnect} = "dbi:Oracle:sid=$form->{sid}";
256   }
257
258   if ($form->{dbhost}) {
259     $form->{dbconnect} .= ";host=$form->{dbhost}";
260   }
261   if ($form->{dbport}) {
262     $form->{dbconnect} .= ";port=$form->{dbport}";
263   }
264
265   $main::lxdebug->leave_sub();
266 }
267
268 sub dbdrivers {
269   $main::lxdebug->enter_sub();
270
271   my @drivers = DBI->available_drivers();
272
273   $main::lxdebug->leave_sub();
274
275   return (grep { /(Pg|Oracle)/ } @drivers);
276 }
277
278 sub dbsources {
279   $main::lxdebug->enter_sub();
280
281   my ($self, $form) = @_;
282
283   my @dbsources = ();
284   my ($sth, $query);
285
286   $form->{dbdefault} = $form->{dbuser} unless $form->{dbdefault};
287   $form->{sid} = $form->{dbdefault};
288   &dbconnect_vars($form, $form->{dbdefault});
289
290   my $dbh =
291     DBI->connect($form->{dbconnect}, $form->{dbuser}, $form->{dbpasswd})
292     or $form->dberror;
293
294   if ($form->{dbdriver} eq 'Pg') {
295
296     $query = qq|SELECT datname FROM pg_database WHERE NOT ((datname = 'template0') OR (datname = 'template1'))|;
297     $sth   = $dbh->prepare($query);
298     $sth->execute || $form->dberror($query);
299
300     while (my ($db) = $sth->fetchrow_array) {
301
302       if ($form->{only_acc_db}) {
303
304         next if ($db =~ /^template/);
305
306         &dbconnect_vars($form, $db);
307         my $dbh =
308           DBI->connect($form->{dbconnect}, $form->{dbuser}, $form->{dbpasswd})
309           or $form->dberror;
310
311         $query = qq|SELECT p.tablename FROM pg_tables p
312                     WHERE p.tablename = 'defaults'
313                     AND p.tableowner = '$form->{dbuser}'|;
314         my $sth = $dbh->prepare($query);
315         $sth->execute || $form->dberror($query);
316
317         if ($sth->fetchrow_array) {
318           push @dbsources, $db;
319         }
320         $sth->finish;
321         $dbh->disconnect;
322         next;
323       }
324       push @dbsources, $db;
325     }
326   }
327
328   if ($form->{dbdriver} eq 'Oracle') {
329     if ($form->{only_acc_db}) {
330       $query = qq|SELECT o.owner FROM dba_objects o
331                   WHERE o.object_name = 'DEFAULTS'
332                   AND o.object_type = 'TABLE'|;
333     } else {
334       $query = qq|SELECT username FROM dba_users|;
335     }
336
337     $sth = $dbh->prepare($query);
338     $sth->execute || $form->dberror($query);
339
340     while (my ($db) = $sth->fetchrow_array) {
341       push @dbsources, $db;
342     }
343   }
344
345   $sth->finish;
346   $dbh->disconnect;
347
348   $main::lxdebug->leave_sub();
349
350   return @dbsources;
351 }
352
353 sub dbcreate {
354   $main::lxdebug->enter_sub();
355
356   my ($self, $form) = @_;
357
358   $form->{sid} = $form->{dbdefault};
359   &dbconnect_vars($form, $form->{dbdefault});
360   my $dbh =
361     DBI->connect($form->{dbconnect}, $form->{dbuser}, $form->{dbpasswd})
362     or $form->dberror;
363
364   my %dbcreate = (
365     'Pg'     => qq|CREATE DATABASE "$form->{db}"|,
366     'Oracle' =>
367       qq|CREATE USER "$form->{db}" DEFAULT TABLESPACE USERS TEMPORARY TABLESPACE TEMP IDENTIFIED BY "$form->{db}"|
368   );
369
370   my %dboptions = (
371     'Pg' => [],
372   );
373
374   push(@{$dboptions{"Pg"}}, "ENCODING = " . $dbh->quote($form->{"encoding"}))
375     if ($form->{"encoding"});
376   if ($form->{"dbdefault"}) {
377     my $dbdefault = $form->{"dbdefault"};
378     $dbdefault =~ s/[^a-zA-Z0-9_\-]//g;
379     push(@{$dboptions{"Pg"}}, "TEMPLATE = $dbdefault");
380   }
381
382   my $query = qq|$dbcreate{$form->{dbdriver}}|;
383   $query .= " WITH " . join(" ", @{$dboptions{"Pg"}}) if (@{$dboptions{"Pg"}});
384
385   $dbh->do($query) || $form->dberror($query);
386
387   if ($form->{dbdriver} eq 'Oracle') {
388     $query = qq|GRANT CONNECT,RESOURCE TO "$form->{db}"|;
389     $dbh->do($query) || $form->dberror($query);
390   }
391   $dbh->disconnect;
392
393   # setup variables for the new database
394   if ($form->{dbdriver} eq 'Oracle') {
395     $form->{dbuser}   = $form->{db};
396     $form->{dbpasswd} = $form->{db};
397   }
398
399   &dbconnect_vars($form, $form->{db});
400
401   $dbh = DBI->connect($form->{dbconnect}, $form->{dbuser}, $form->{dbpasswd})
402     or $form->dberror;
403
404   # create the tables
405   my $filename = qq|sql/lx-office.sql|;
406   $self->process_query($form, $dbh, $filename);
407
408   # load gifi
409   ($filename) = split /_/, $form->{chart};
410   $filename =~ s/_//;
411   $self->process_query($form, $dbh, "sql/${filename}-gifi.sql");
412
413   # load chart of accounts
414   $filename = qq|sql/$form->{chart}-chart.sql|;
415   $self->process_query($form, $dbh, $filename);
416
417   $query = "UPDATE defaults SET coa = " . $dbh->quote($form->{"chart"});
418   $dbh->do($query) || $form->dberror($query);
419
420   $dbh->disconnect;
421
422   $main::lxdebug->leave_sub();
423 }
424
425 # Process a Perl script which updates the database.
426 # If the script returns 1 then the update was successful.
427 # Return code "2" means "needs more interaction; remove
428 # users/nologin and exit".
429 # All other return codes are fatal errors.
430 sub process_perl_script {
431   $main::lxdebug->enter_sub();
432
433   my ($self, $form, $dbh, $filename, $version) = @_;
434
435   open(FH, "$filename") or $form->error("$filename : $!\n");
436   my $contents = join("", <FH>);
437   close(FH);
438
439   $dbh->begin_work();
440
441   my %dbup_myconfig = ();
442   map({ $dbup_myconfig{$_} = $form->{$_}; }
443       qw(dbname dbuser dbpasswd dbhost dbport dbconnect));
444
445   my $nls_file = $filename;
446   $nls_file =~ s|.*/||;
447   $nls_file =~ s|.pl$||;
448   my $dbup_locale = Locale->new($main::language, $nls_file);
449
450   my $result = eval($contents);
451
452   if (1 != $result) {
453     $dbh->rollback();
454     $dbh->disconnect();
455   }
456
457   if (!defined($result)) {
458     print($form->parse_html_template("dbupgrade/error",
459                                      { "file" => $filename,
460                                        "error" => $@ }));
461     exit(0);
462   } elsif (1 != $result) {
463     unlink("users/nologin") if (2 == $result);
464     exit(0);
465   }
466
467   if ($version) {
468     $dbh->do("UPDATE defaults SET version = " . $dbh->quote($version));
469   }
470   $dbh->commit();
471
472   $main::lxdebug->leave_sub();
473 }
474
475 sub process_query {
476   $main::lxdebug->enter_sub();
477
478   my ($self, $form, $dbh, $filename, $version_or_control) = @_;
479
480   #  return unless (-f $filename);
481
482   open(FH, "$filename") or $form->error("$filename : $!\n");
483   my $query = "";
484   my $sth;
485   my @quote_chars;
486
487   $dbh->begin_work();
488
489   while (<FH>) {
490
491     # Remove DOS and Unix style line endings.
492     chomp;
493
494     # remove comments
495     s/--.*$//;
496
497     for (my $i = 0; $i < length($_); $i++) {
498       my $char = substr($_, $i, 1);
499
500       # Are we inside a string?
501       if (@quote_chars) {
502         if ($char eq $quote_chars[-1]) {
503           pop(@quote_chars);
504         }
505         $query .= $char;
506
507       } else {
508         if (($char eq "'") || ($char eq "\"")) {
509           push(@quote_chars, $char);
510
511         } elsif ($char eq ";") {
512
513           # Query is complete. Send it.
514
515           $sth = $dbh->prepare($query);
516           if (!$sth->execute()) {
517             my $errstr = $dbh->errstr;
518             $sth->finish();
519             $dbh->rollback();
520             $form->dberror("The database update/creation did not succeed. The file ${filename} containing the following query failed:<br>${query}<br>" .
521                            "The error message was: ${errstr}<br>" .
522                            "All changes in that file have been reverted.");
523           }
524           $sth->finish();
525
526           $char  = "";
527           $query = "";
528         }
529
530         $query .= $char;
531       }
532     }
533   }
534
535   if (ref($version_or_control) eq "HASH") {
536     $dbh->do("INSERT INTO schema_info (tag, login) VALUES (" .
537              $dbh->quote($version_or_control->{"tag"}) . ", " .
538              $dbh->quote($form->{"login"}) . ")");
539   } elsif ($version_or_control) {
540     $dbh->do("UPDATE defaults SET version = " .
541              $dbh->quote($version_or_control));
542   }
543   $dbh->commit();
544
545   close FH;
546
547   $main::lxdebug->leave_sub();
548 }
549
550 sub dbdelete {
551   $main::lxdebug->enter_sub();
552
553   my ($self, $form) = @_;
554
555   my %dbdelete = ('Pg'     => qq|DROP DATABASE "$form->{db}"|,
556                   'Oracle' => qq|DROP USER $form->{db} CASCADE|);
557
558   $form->{sid} = $form->{dbdefault};
559   &dbconnect_vars($form, $form->{dbdefault});
560   my $dbh =
561     DBI->connect($form->{dbconnect}, $form->{dbuser}, $form->{dbpasswd})
562     or $form->dberror;
563   my $query = qq|$dbdelete{$form->{dbdriver}}|;
564   $dbh->do($query) || $form->dberror($query);
565
566   $dbh->disconnect;
567
568   $main::lxdebug->leave_sub();
569 }
570
571 sub dbsources_unused {
572   $main::lxdebug->enter_sub();
573
574   my ($self, $form, $memfile) = @_;
575
576   my @dbexcl    = ();
577   my @dbsources = ();
578
579   $form->error('File locked!') if (-f "${memfile}.LCK");
580
581   # open members file
582   open(FH, "$memfile") or $form->error("$memfile : $!");
583
584   while (<FH>) {
585     if (/^dbname=/) {
586       my ($null, $item) = split(/=/);
587       push @dbexcl, $item;
588     }
589   }
590
591   close FH;
592
593   $form->{only_acc_db} = 1;
594   my @db = &dbsources("", $form);
595
596   push @dbexcl, $form->{dbdefault};
597
598   foreach $item (@db) {
599     unless (grep /$item$/, @dbexcl) {
600       push @dbsources, $item;
601     }
602   }
603
604   $main::lxdebug->leave_sub();
605
606   return @dbsources;
607 }
608
609 sub dbneedsupdate {
610   $main::lxdebug->enter_sub();
611
612   my ($self, $form) = @_;
613
614   my %dbsources = ();
615   my $query;
616
617   $form->{sid} = $form->{dbdefault};
618   &dbconnect_vars($form, $form->{dbdefault});
619
620   my $dbh =
621     DBI->connect($form->{dbconnect}, $form->{dbuser}, $form->{dbpasswd})
622     or $form->dberror;
623
624   if ($form->{dbdriver} eq 'Pg') {
625
626     $query = qq|SELECT d.datname FROM pg_database d, pg_user u
627                 WHERE d.datdba = u.usesysid
628                 AND u.usename = '$form->{dbuser}'|;
629     my $sth = $dbh->prepare($query);
630     $sth->execute || $form->dberror($query);
631
632     while (my ($db) = $sth->fetchrow_array) {
633
634       next if ($db =~ /^template/);
635
636       &dbconnect_vars($form, $db);
637
638       my $dbh =
639         DBI->connect($form->{dbconnect}, $form->{dbuser}, $form->{dbpasswd})
640         or $form->dberror;
641
642       $query = qq|SELECT t.tablename FROM pg_tables t
643                   WHERE t.tablename = 'defaults'|;
644       my $sth = $dbh->prepare($query);
645       $sth->execute || $form->dberror($query);
646
647       if ($sth->fetchrow_array) {
648         $query = qq|SELECT version FROM defaults|;
649         my $sth = $dbh->prepare($query);
650         $sth->execute;
651
652         if (my ($version) = $sth->fetchrow_array) {
653           $dbsources{$db} = $version;
654         }
655         $sth->finish;
656       }
657       $sth->finish;
658       $dbh->disconnect;
659     }
660     $sth->finish;
661   }
662
663   if ($form->{dbdriver} eq 'Oracle') {
664     $query = qq|SELECT o.owner FROM dba_objects o
665                 WHERE o.object_name = 'DEFAULTS'
666                 AND o.object_type = 'TABLE'|;
667
668     $sth = $dbh->prepare($query);
669     $sth->execute || $form->dberror($query);
670
671     while (my ($db) = $sth->fetchrow_array) {
672
673       $form->{dbuser} = $db;
674       &dbconnect_vars($form, $db);
675
676       my $dbh =
677         DBI->connect($form->{dbconnect}, $form->{dbuser}, $form->{dbpasswd})
678         or $form->dberror;
679
680       $query = qq|SELECT version FROM defaults|;
681       my $sth = $dbh->prepare($query);
682       $sth->execute;
683
684       if (my ($version) = $sth->fetchrow_array) {
685         $dbsources{$db} = $version;
686       }
687       $sth->finish;
688       $dbh->disconnect;
689     }
690     $sth->finish;
691   }
692
693   $dbh->disconnect;
694
695   $main::lxdebug->leave_sub();
696
697   return %dbsources;
698 }
699
700 ## LINET
701 sub calc_version {
702   $main::lxdebug->enter_sub(2);
703
704   my (@v, $version, $i);
705
706   @v = split(/\./, $_[0]);
707   while (scalar(@v) < 4) {
708     push(@v, 0);
709   }
710   $version = 0;
711   for ($i = 0; $i < 4; $i++) {
712     $version *= 1000;
713     $version += $v[$i];
714   }
715
716   $main::lxdebug->leave_sub(2);
717   return $version;
718 }
719
720 sub cmp_script_version {
721   my ($a_from, $a_to, $b_from, $b_to);
722   my ($i, $res_a, $res_b);
723   my ($my_a, $my_b) = ($a, $b);
724
725   $my_a =~ s/.*-upgrade-//;
726   $my_a =~ s/.sql$//;
727   $my_b =~ s/.*-upgrade-//;
728   $my_b =~ s/.sql$//;
729   ($my_a_from, $my_a_to) = split(/-/, $my_a);
730   ($my_b_from, $my_b_to) = split(/-/, $my_b);
731
732   $res_a = calc_version($my_a_from);
733   $res_b = calc_version($my_b_from);
734
735   if ($res_a == $res_b) {
736     $res_a = calc_version($my_a_to);
737     $res_b = calc_version($my_b_to);
738   }
739
740   return $res_a <=> $res_b;
741 }
742 ## /LINET
743
744 sub update_available {
745   my ($dbdriver, $cur_version) = @_;
746
747   opendir SQLDIR, "sql/${dbdriver}-upgrade" or &error("", "sql/${dbdriver}-upgrade: $!");
748   my @upgradescripts =
749     grep(/$form->{dbdriver}-upgrade-\Q$cur_version\E.*\.(sql|pl)$/, readdir(SQLDIR));
750   closedir SQLDIR;
751
752   return ($#upgradescripts > -1);
753 }
754
755 sub create_schema_info_table {
756   $main::lxdebug->enter_sub();
757
758   my ($self, $form, $dbh) = @_;
759
760   my $query = "SELECT tag FROM schema_info LIMIT 1";
761   if (!$dbh->do($query)) {
762     $query =
763       "CREATE TABLE schema_info (" .
764       "  tag text, " .
765       "  login text, " .
766       "  itime timestamp DEFAULT now(), " .
767       "  PRIMARY KEY (tag))";
768     $dbh->do($query) || $form->dberror($query);
769   }
770
771   $main::lxdebug->leave_sub();
772 }
773
774 sub dbupdate {
775   $main::lxdebug->enter_sub();
776
777   my ($self, $form) = @_;
778
779   $form->{sid} = $form->{dbdefault};
780
781   my @upgradescripts = ();
782   my $query;
783   my $rc = -2;
784
785   if ($form->{dbupdate}) {
786
787     # read update scripts into memory
788     opendir SQLDIR, "sql/" . $form->{dbdriver} . "-upgrade" or &error("", "sql/" . $form->{dbdriver} . "-upgrade : $!");
789     ## LINET
790     @upgradescripts =
791       sort(cmp_script_version
792            grep(/$form->{dbdriver}-upgrade-.*?\.(sql|pl)$/, readdir(SQLDIR)));
793     ## /LINET
794     closedir SQLDIR;
795   }
796
797   foreach my $db (split / /, $form->{dbupdate}) {
798
799     next unless $form->{$db};
800
801     # strip db from dataset
802     $db =~ s/^db//;
803     &dbconnect_vars($form, $db);
804
805     my $dbh =
806       DBI->connect($form->{dbconnect}, $form->{dbuser}, $form->{dbpasswd})
807       or $form->dberror;
808
809     # check version
810     $query = qq|SELECT version FROM defaults|;
811     my $sth = $dbh->prepare($query);
812
813     # no error check, let it fall through
814     $sth->execute;
815
816     my $version = $sth->fetchrow_array;
817     $sth->finish;
818
819     next unless $version;
820
821     ## LINET
822     $version = calc_version($version);
823     ## /LINET
824
825     foreach my $upgradescript (@upgradescripts) {
826       my $a = $upgradescript;
827       $a =~ s/^$form->{dbdriver}-upgrade-|\.(sql|pl)$//g;
828       my $file_type = $1;
829
830       my ($mindb, $maxdb) = split /-/, $a;
831       my $str_maxdb = $maxdb;
832       ## LINET
833       $mindb = calc_version($mindb);
834       $maxdb = calc_version($maxdb);
835       ## /LINET
836
837       next if ($version >= $maxdb);
838
839       # if there is no upgrade script exit
840       last if ($version < $mindb);
841
842       # apply upgrade
843       $main::lxdebug->message(DEBUG2, "Applying Update $upgradescript");
844       if ($file_type eq "sql") {
845         $self->process_query($form, $dbh, "sql/" . $form->{"dbdriver"} . "-upgrade/$upgradescript", $str_maxdb);
846       } else {
847         $self->process_perl_script($form, $dbh, "sql/" . $form->{"dbdriver"} . "-upgrade/$upgradescript", $str_maxdb);
848       }
849
850       $version = $maxdb;
851
852     }
853
854     $rc = 0;
855     $dbh->disconnect;
856
857   }
858
859   $main::lxdebug->leave_sub();
860
861   return $rc;
862 }
863
864 sub dbupdate2 {
865   $main::lxdebug->enter_sub();
866
867   my ($self, $form, $controls) = @_;
868
869   $form->{sid} = $form->{dbdefault};
870
871   my @upgradescripts = ();
872   my ($query, $sth, $tag);
873   my $rc = -2;
874
875   @upgradescripts = sort_dbupdate_controls($controls);
876
877   foreach my $db (split / /, $form->{dbupdate}) {
878
879     next unless $form->{$db};
880
881     # strip db from dataset
882     $db =~ s/^db//;
883     &dbconnect_vars($form, $db);
884
885     my $dbh =
886       DBI->connect($form->{dbconnect}, $form->{dbuser}, $form->{dbpasswd})
887       or $form->dberror;
888
889     map({ $_->{"applied"} = 0; } @upgradescripts);
890
891     $query = "SELECT tag FROM schema_info";
892     $sth = $dbh->prepare($query);
893     $sth->execute() || $form->dberror($query);
894     while (($tag) = $sth->fetchrow_array()) {
895       $controls->{$tag}->{"applied"} = 1 if (defined($controls->{$tag}));
896     }
897     $sth->finish();
898
899     my $all_applied = 1;
900     foreach (@upgradescripts) {
901       if (!$_->{"applied"}) {
902         $all_applied = 0;
903         last;
904       }
905     }
906
907     next if ($all_applied);
908
909     foreach my $control (@upgradescripts) {
910       next if ($control->{"applied"});
911
912       $control->{"file"} =~ /\.(sql|pl)$/;
913       my $file_type = $1;
914
915       # apply upgrade
916       $main::lxdebug->message(DEBUG2, "Applying Update $control->{file}");
917       print($form->parse_html_template("dbupgrade/upgrade_message2",
918                                        $control));
919
920       if ($file_type eq "sql") {
921         $self->process_query($form, $dbh, "sql/" . $form->{"dbdriver"} .
922                              "-upgrade2/$control->{file}", $control);
923       } else {
924         $self->process_perl_script($form, $dbh, "sql/" . $form->{"dbdriver"} .
925                                    "-upgrade2/$control->{file}", $control);
926       }
927     }
928
929     $rc = 0;
930     $dbh->disconnect;
931
932   }
933
934   $main::lxdebug->leave_sub();
935
936   return $rc;
937 }
938
939 sub update2_available {
940   $main::lxdebug->enter_sub();
941
942   my ($form, $controls) = @_;
943
944   map({ $_->{"applied"} = 0; } values(%{$controls}));
945
946   dbconnect_vars($form, $form->{"dbname"});
947
948   my $dbh =
949     DBI->connect($form->{dbconnect}, $form->{dbuser}, $form->{dbpasswd}) ||
950     $form->dberror;
951
952   my ($query, $tag, $sth);
953
954   $query = "SELECT tag FROM schema_info";
955   $sth = $dbh->prepare($query);
956   $sth->execute() || $form->dberror($query);
957   while (($tag) = $sth->fetchrow_array()) {
958     $controls->{$tag}->{"applied"} = 1 if (defined($controls->{$tag}));
959   }
960   $sth->finish();
961   $dbh->disconnect();
962
963   map({ $main::lxdebug->leave_sub() and return 1 if (!$_->{"applied"}) }
964       values(%{$controls}));
965
966   $main::lxdebug->leave_sub();
967   return 0;
968 }
969
970 sub create_config {
971   $main::lxdebug->enter_sub();
972
973   my ($self, $filename) = @_;
974
975   @config = &config_vars;
976
977   open(CONF, ">$filename") or $self->error("$filename : $!");
978
979   # create the config file
980   print CONF qq|# configuration file for $self->{login}
981
982 \%myconfig = (
983 |;
984
985   foreach $key (sort @config) {
986     $self->{$key} =~ s/\'/\\\'/g;
987     print CONF qq|  $key => '$self->{$key}',\n|;
988   }
989
990   print CONF qq|);\n\n|;
991
992   close CONF;
993
994   $main::lxdebug->leave_sub();
995 }
996
997 sub save_member {
998   $main::lxdebug->enter_sub();
999
1000   my ($self, $memberfile, $userspath) = @_;
1001
1002   my $newmember = 1;
1003
1004   # format dbconnect and dboptions string
1005   &dbconnect_vars($self, $self->{dbname});
1006
1007   $self->error('File locked!') if (-f "${memberfile}.LCK");
1008   open(FH, ">${memberfile}.LCK") or $self->error("${memberfile}.LCK : $!");
1009   close(FH);
1010
1011   open(CONF, "+<$memberfile") or $self->error("$memberfile : $!");
1012
1013   @config = <CONF>;
1014
1015   seek(CONF, 0, 0);
1016   truncate(CONF, 0);
1017
1018   while ($line = shift @config) {
1019     if ($line =~ /^\[$self->{login}\]/) {
1020       $newmember = 0;
1021       last;
1022     }
1023     print CONF $line;
1024   }
1025
1026   # remove everything up to next login or EOF
1027   while ($line = shift @config) {
1028     last if ($line =~ /^\[/);
1029   }
1030
1031   # this one is either the next login or EOF
1032   print CONF $line;
1033
1034   while ($line = shift @config) {
1035     print CONF $line;
1036   }
1037
1038   print CONF qq|[$self->{login}]\n|;
1039
1040   if ((($self->{dbpasswd} ne $self->{old_dbpasswd}) || $newmember)
1041       && $self->{root}) {
1042     $self->{dbpasswd} = pack 'u', $self->{dbpasswd};
1043     chop $self->{dbpasswd};
1044   }
1045   if (defined($self->{new_password})) {
1046     if ($self->{new_password} ne $self->{old_password}) {
1047       $self->{password} = crypt $self->{new_password},
1048         substr($self->{login}, 0, 2)
1049         if $self->{new_password};
1050     }
1051   } else {
1052     if ($self->{password} ne $self->{old_password}) {
1053       $self->{password} = crypt $self->{password}, substr($self->{login}, 0, 2)
1054         if $self->{password};
1055     }
1056   }
1057
1058   if ($self->{'root login'}) {
1059     @config = ("password");
1060   } else {
1061     @config = &config_vars;
1062   }
1063
1064   # replace \r\n with \n
1065   map { $self->{$_} =~ s/\r\n/\\n/g } qw(address signature);
1066   foreach $key (sort @config) {
1067     print CONF qq|$key=$self->{$key}\n|;
1068   }
1069
1070   print CONF "\n";
1071   close CONF;
1072   unlink "${memberfile}.LCK";
1073
1074   # create conf file
1075   $self->create_config("$userspath/$self->{login}.conf")
1076     unless $self->{'root login'};
1077
1078   $main::lxdebug->leave_sub();
1079 }
1080
1081 sub config_vars {
1082   $main::lxdebug->enter_sub();
1083
1084   my @conf = qw(acs address admin businessnumber charset company countrycode
1085     currency dateformat dbconnect dbdriver dbhost dbport dboptions
1086     dbname dbuser dbpasswd email fax name numberformat in_numberformat password
1087     printer role sid signature stylesheet tel templates vclimit angebote bestellungen rechnungen
1088     anfragen lieferantenbestellungen einkaufsrechnungen taxnumber co_ustid duns menustyle
1089     template_format copies show_form_details);
1090
1091   $main::lxdebug->leave_sub();
1092
1093   return @conf;
1094 }
1095
1096 sub error {
1097   $main::lxdebug->enter_sub();
1098
1099   my ($self, $msg) = @_;
1100
1101   if ($ENV{HTTP_USER_AGENT}) {
1102     print qq|Content-Type: text/html
1103
1104 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN">
1105
1106 <body bgcolor=ffffff>
1107
1108 <h2><font color=red>Error!</font></h2>
1109 <p><b>$msg</b>|;
1110
1111   }
1112
1113   die "Error: $msg\n";
1114
1115   $main::lxdebug->leave_sub();
1116 }
1117
1118 1;
1119