Diese Variable wurde umbenannt.
[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   my %dbcreate = (
359     'Pg'     => qq|CREATE DATABASE "$form->{db}"|,
360     'Oracle' =>
361       qq|CREATE USER "$form->{db}" DEFAULT TABLESPACE USERS TEMPORARY TABLESPACE TEMP IDENTIFIED BY "$form->{db}"|
362   );
363
364   $dbcreate{Pg} .= " WITH ENCODING = '$form->{encoding}'" if $form->{encoding};
365
366   $form->{sid} = $form->{dbdefault};
367   &dbconnect_vars($form, $form->{dbdefault});
368   my $dbh =
369     DBI->connect($form->{dbconnect}, $form->{dbuser}, $form->{dbpasswd})
370     or $form->dberror;
371   my $query = qq|$dbcreate{$form->{dbdriver}}|;
372   $dbh->do($query) || $form->dberror($query);
373
374   if ($form->{dbdriver} eq 'Oracle') {
375     $query = qq|GRANT CONNECT,RESOURCE TO "$form->{db}"|;
376     $dbh->do($query) || $form->dberror($query);
377   }
378   $dbh->disconnect;
379
380   # setup variables for the new database
381   if ($form->{dbdriver} eq 'Oracle') {
382     $form->{dbuser}   = $form->{db};
383     $form->{dbpasswd} = $form->{db};
384   }
385
386   &dbconnect_vars($form, $form->{db});
387
388   $dbh = DBI->connect($form->{dbconnect}, $form->{dbuser}, $form->{dbpasswd})
389     or $form->dberror;
390
391   # create the tables
392   my $filename = qq|sql/lx-office.sql|;
393   $self->process_query($form, $dbh, $filename);
394
395   # load gifi
396   ($filename) = split /_/, $form->{chart};
397   $filename =~ s/_//;
398   $self->process_query($form, $dbh, "sql/${filename}-gifi.sql");
399
400   # load chart of accounts
401   $filename = qq|sql/$form->{chart}-chart.sql|;
402   $self->process_query($form, $dbh, $filename);
403
404   $query = "UPDATE defaults SET coa = " . $dbh->quote($form->{"chart"});
405   $dbh->do($query) || $form->dberror($query);
406
407   $dbh->disconnect;
408
409   $main::lxdebug->leave_sub();
410 }
411
412 # Process a Perl script which updates the database.
413 # If the script returns 1 then the update was successful.
414 # Return code "2" means "needs more interaction; remove
415 # users/nologin and exit".
416 # All other return codes are fatal errors.
417 sub process_perl_script {
418   $main::lxdebug->enter_sub();
419
420   my ($self, $form, $dbh, $filename, $version) = @_;
421
422   open(FH, "$filename") or $form->error("$filename : $!\n");
423   my $contents = join("", <FH>);
424   close(FH);
425
426   $dbh->begin_work();
427
428   my %dbup_myconfig = ();
429   map({ $dbup_myconfig{$_} = $form->{$_}; }
430       qw(dbname dbuser dbpasswd dbhost dbport dbconnect));
431
432   my $nls_file = $filename;
433   $nls_file =~ s|.*/||;
434   $nls_file =~ s|.pl$||;
435   my $dbup_locale = Locale->new($main::language, $nls_file);
436
437   my $result = eval($contents);
438
439   if (1 != $result) {
440     $dbh->rollback();
441     $dbh->disconnect();
442   }
443
444   if (!defined($result)) {
445     print($form->parse_html_template("dbupgrade/error",
446                                      { "file" => $filename,
447                                        "error" => $@ }));
448     exit(0);
449   } elsif (1 != $result) {
450     unlink("users/nologin") if (2 == $result);
451     exit(0);
452   }
453
454   if ($version) {
455     $dbh->do("UPDATE defaults SET version = " . $dbh->quote($version));
456   }
457   $dbh->commit();
458
459   $main::lxdebug->leave_sub();
460 }
461
462 sub process_query {
463   $main::lxdebug->enter_sub();
464
465   my ($self, $form, $dbh, $filename, $version_or_control) = @_;
466
467   #  return unless (-f $filename);
468
469   open(FH, "$filename") or $form->error("$filename : $!\n");
470   my $query = "";
471   my $sth;
472   my @quote_chars;
473
474   $dbh->begin_work();
475
476   while (<FH>) {
477
478     # Remove DOS and Unix style line endings.
479     chomp;
480
481     # remove comments
482     s/--.*$//;
483
484     for (my $i = 0; $i < length($_); $i++) {
485       my $char = substr($_, $i, 1);
486
487       # Are we inside a string?
488       if (@quote_chars) {
489         if ($char eq $quote_chars[-1]) {
490           pop(@quote_chars);
491         }
492         $query .= $char;
493
494       } else {
495         if (($char eq "'") || ($char eq "\"")) {
496           push(@quote_chars, $char);
497
498         } elsif ($char eq ";") {
499
500           # Query is complete. Send it.
501
502           $sth = $dbh->prepare($query);
503           if (!$sth->execute()) {
504             my $errstr = $dbh->errstr;
505             $sth->finish();
506             $dbh->rollback();
507             $form->dberror("The database update/creation did not succeed. The file ${filename} containing the following query failed:<br>${query}<br>" .
508                            "The error message was: ${errstr}<br>" .
509                            "All changes in that file have been reverted.");
510           }
511           $sth->finish();
512
513           $char  = "";
514           $query = "";
515         }
516
517         $query .= $char;
518       }
519     }
520   }
521
522   if (ref($version_or_control) eq "HASH") {
523     $dbh->do("INSERT INTO schema_info (tag, login) VALUES (" .
524              $dbh->quote($version_or_control->{"tag"}) . ", " .
525              $dbh->quote($form->{"login"}) . ")");
526   } elsif ($version_or_control) {
527     $dbh->do("UPDATE defaults SET version = " .
528              $dbh->quote($version_or_control));
529   }
530   $dbh->commit();
531
532   close FH;
533
534   $main::lxdebug->leave_sub();
535 }
536
537 sub dbdelete {
538   $main::lxdebug->enter_sub();
539
540   my ($self, $form) = @_;
541
542   my %dbdelete = ('Pg'     => qq|DROP DATABASE "$form->{db}"|,
543                   'Oracle' => qq|DROP USER $form->{db} CASCADE|);
544
545   $form->{sid} = $form->{dbdefault};
546   &dbconnect_vars($form, $form->{dbdefault});
547   my $dbh =
548     DBI->connect($form->{dbconnect}, $form->{dbuser}, $form->{dbpasswd})
549     or $form->dberror;
550   my $query = qq|$dbdelete{$form->{dbdriver}}|;
551   $dbh->do($query) || $form->dberror($query);
552
553   $dbh->disconnect;
554
555   $main::lxdebug->leave_sub();
556 }
557
558 sub dbsources_unused {
559   $main::lxdebug->enter_sub();
560
561   my ($self, $form, $memfile) = @_;
562
563   my @dbexcl    = ();
564   my @dbsources = ();
565
566   $form->error('File locked!') if (-f "${memfile}.LCK");
567
568   # open members file
569   open(FH, "$memfile") or $form->error("$memfile : $!");
570
571   while (<FH>) {
572     if (/^dbname=/) {
573       my ($null, $item) = split(/=/);
574       push @dbexcl, $item;
575     }
576   }
577
578   close FH;
579
580   $form->{only_acc_db} = 1;
581   my @db = &dbsources("", $form);
582
583   push @dbexcl, $form->{dbdefault};
584
585   foreach $item (@db) {
586     unless (grep /$item$/, @dbexcl) {
587       push @dbsources, $item;
588     }
589   }
590
591   $main::lxdebug->leave_sub();
592
593   return @dbsources;
594 }
595
596 sub dbneedsupdate {
597   $main::lxdebug->enter_sub();
598
599   my ($self, $form) = @_;
600
601   my %dbsources = ();
602   my $query;
603
604   $form->{sid} = $form->{dbdefault};
605   &dbconnect_vars($form, $form->{dbdefault});
606
607   my $dbh =
608     DBI->connect($form->{dbconnect}, $form->{dbuser}, $form->{dbpasswd})
609     or $form->dberror;
610
611   if ($form->{dbdriver} eq 'Pg') {
612
613     $query = qq|SELECT d.datname FROM pg_database d, pg_user u
614                 WHERE d.datdba = u.usesysid
615                 AND u.usename = '$form->{dbuser}'|;
616     my $sth = $dbh->prepare($query);
617     $sth->execute || $form->dberror($query);
618
619     while (my ($db) = $sth->fetchrow_array) {
620
621       next if ($db =~ /^template/);
622
623       &dbconnect_vars($form, $db);
624
625       my $dbh =
626         DBI->connect($form->{dbconnect}, $form->{dbuser}, $form->{dbpasswd})
627         or $form->dberror;
628
629       $query = qq|SELECT t.tablename FROM pg_tables t
630                   WHERE t.tablename = 'defaults'|;
631       my $sth = $dbh->prepare($query);
632       $sth->execute || $form->dberror($query);
633
634       if ($sth->fetchrow_array) {
635         $query = qq|SELECT version FROM defaults|;
636         my $sth = $dbh->prepare($query);
637         $sth->execute;
638
639         if (my ($version) = $sth->fetchrow_array) {
640           $dbsources{$db} = $version;
641         }
642         $sth->finish;
643       }
644       $sth->finish;
645       $dbh->disconnect;
646     }
647     $sth->finish;
648   }
649
650   if ($form->{dbdriver} eq 'Oracle') {
651     $query = qq|SELECT o.owner FROM dba_objects o
652                 WHERE o.object_name = 'DEFAULTS'
653                 AND o.object_type = 'TABLE'|;
654
655     $sth = $dbh->prepare($query);
656     $sth->execute || $form->dberror($query);
657
658     while (my ($db) = $sth->fetchrow_array) {
659
660       $form->{dbuser} = $db;
661       &dbconnect_vars($form, $db);
662
663       my $dbh =
664         DBI->connect($form->{dbconnect}, $form->{dbuser}, $form->{dbpasswd})
665         or $form->dberror;
666
667       $query = qq|SELECT version FROM defaults|;
668       my $sth = $dbh->prepare($query);
669       $sth->execute;
670
671       if (my ($version) = $sth->fetchrow_array) {
672         $dbsources{$db} = $version;
673       }
674       $sth->finish;
675       $dbh->disconnect;
676     }
677     $sth->finish;
678   }
679
680   $dbh->disconnect;
681
682   $main::lxdebug->leave_sub();
683
684   return %dbsources;
685 }
686
687 ## LINET
688 sub calc_version {
689   $main::lxdebug->enter_sub(2);
690
691   my (@v, $version, $i);
692
693   @v = split(/\./, $_[0]);
694   while (scalar(@v) < 4) {
695     push(@v, 0);
696   }
697   $version = 0;
698   for ($i = 0; $i < 4; $i++) {
699     $version *= 1000;
700     $version += $v[$i];
701   }
702
703   $main::lxdebug->leave_sub(2);
704   return $version;
705 }
706
707 sub cmp_script_version {
708   my ($a_from, $a_to, $b_from, $b_to);
709   my ($i, $res_a, $res_b);
710   my ($my_a, $my_b) = ($a, $b);
711
712   $my_a =~ s/.*-upgrade-//;
713   $my_a =~ s/.sql$//;
714   $my_b =~ s/.*-upgrade-//;
715   $my_b =~ s/.sql$//;
716   ($my_a_from, $my_a_to) = split(/-/, $my_a);
717   ($my_b_from, $my_b_to) = split(/-/, $my_b);
718
719   $res_a = calc_version($my_a_from);
720   $res_b = calc_version($my_b_from);
721
722   if ($res_a == $res_b) {
723     $res_a = calc_version($my_a_to);
724     $res_b = calc_version($my_b_to);
725   }
726
727   return $res_a <=> $res_b;
728 }
729 ## /LINET
730
731 sub update_available {
732   my ($dbdriver, $cur_version) = @_;
733
734   opendir SQLDIR, "sql/${dbdriver}-upgrade" or &error("", "sql/${dbdriver}-upgrade: $!");
735   my @upgradescripts =
736     grep(/$form->{dbdriver}-upgrade-\Q$cur_version\E.*\.(sql|pl)$/, readdir(SQLDIR));
737   closedir SQLDIR;
738
739   return ($#upgradescripts > -1);
740 }
741
742 sub create_schema_info_table {
743   $main::lxdebug->enter_sub();
744
745   my ($self, $form, $dbh) = @_;
746
747   my $query = "SELECT tag FROM schema_info LIMIT 1";
748   if (!$dbh->do($query)) {
749     $query =
750       "CREATE TABLE schema_info (" .
751       "  tag text, " .
752       "  login text, " .
753       "  itime timestamp DEFAULT now(), " .
754       "  PRIMARY KEY (tag))";
755     $dbh->do($query) || $form->dberror($query);
756   }
757
758   $main::lxdebug->leave_sub();
759 }
760
761 sub dbupdate {
762   $main::lxdebug->enter_sub();
763
764   my ($self, $form) = @_;
765
766   $form->{sid} = $form->{dbdefault};
767
768   my @upgradescripts = ();
769   my $query;
770   my $rc = -2;
771
772   if ($form->{dbupdate}) {
773
774     # read update scripts into memory
775     opendir SQLDIR, "sql/" . $form->{dbdriver} . "-upgrade" or &error("", "sql/" . $form->{dbdriver} . "-upgrade : $!");
776     ## LINET
777     @upgradescripts =
778       sort(cmp_script_version
779            grep(/$form->{dbdriver}-upgrade-.*?\.(sql|pl)$/, readdir(SQLDIR)));
780     ## /LINET
781     closedir SQLDIR;
782   }
783
784   foreach my $db (split / /, $form->{dbupdate}) {
785
786     next unless $form->{$db};
787
788     # strip db from dataset
789     $db =~ s/^db//;
790     &dbconnect_vars($form, $db);
791
792     my $dbh =
793       DBI->connect($form->{dbconnect}, $form->{dbuser}, $form->{dbpasswd})
794       or $form->dberror;
795
796     # check version
797     $query = qq|SELECT version FROM defaults|;
798     my $sth = $dbh->prepare($query);
799
800     # no error check, let it fall through
801     $sth->execute;
802
803     my $version = $sth->fetchrow_array;
804     $sth->finish;
805
806     next unless $version;
807
808     ## LINET
809     $version = calc_version($version);
810     ## /LINET
811
812     foreach my $upgradescript (@upgradescripts) {
813       my $a = $upgradescript;
814       $a =~ s/^$form->{dbdriver}-upgrade-|\.(sql|pl)$//g;
815       my $file_type = $1;
816
817       my ($mindb, $maxdb) = split /-/, $a;
818       my $str_maxdb = $maxdb;
819       ## LINET
820       $mindb = calc_version($mindb);
821       $maxdb = calc_version($maxdb);
822       ## /LINET
823
824       next if ($version >= $maxdb);
825
826       # if there is no upgrade script exit
827       last if ($version < $mindb);
828
829       # apply upgrade
830       $main::lxdebug->message(DEBUG2, "Applying Update $upgradescript");
831       if ($file_type eq "sql") {
832         $self->process_query($form, $dbh, "sql/" . $form->{"dbdriver"} . "-upgrade/$upgradescript", $str_maxdb);
833       } else {
834         $self->process_perl_script($form, $dbh, "sql/" . $form->{"dbdriver"} . "-upgrade/$upgradescript", $str_maxdb);
835       }
836
837       $version = $maxdb;
838
839     }
840
841     $rc = 0;
842     $dbh->disconnect;
843
844   }
845
846   $main::lxdebug->leave_sub();
847
848   return $rc;
849 }
850
851 sub dbupdate2 {
852   $main::lxdebug->enter_sub();
853
854   my ($self, $form, $controls) = @_;
855
856   $form->{sid} = $form->{dbdefault};
857
858   my @upgradescripts = ();
859   my ($query, $sth, $tag);
860   my $rc = -2;
861
862   @upgradescripts = sort_dbupdate_controls($controls);
863
864   foreach my $db (split / /, $form->{dbupdate}) {
865
866     next unless $form->{$db};
867
868     # strip db from dataset
869     $db =~ s/^db//;
870     &dbconnect_vars($form, $db);
871
872     my $dbh =
873       DBI->connect($form->{dbconnect}, $form->{dbuser}, $form->{dbpasswd})
874       or $form->dberror;
875
876     map({ $_->{"applied"} = 0; } @upgradescripts);
877
878     $query = "SELECT tag FROM schema_info";
879     $sth = $dbh->prepare($query);
880     $sth->execute() || $form->dberror($query);
881     while (($tag) = $sth->fetchrow_array()) {
882       $controls->{$tag}->{"applied"} = 1 if (defined($controls->{$tag}));
883     }
884     $sth->finish();
885
886     my $all_applied = 1;
887     foreach (@upgradescripts) {
888       if (!$_->{"applied"}) {
889         $all_applied = 0;
890         last;
891       }
892     }
893
894     next if ($all_applied);
895
896     foreach my $control (@upgradescripts) {
897       next if ($control->{"applied"});
898
899       $control->{"file"} =~ /\.(sql|pl)$/;
900       my $file_type = $1;
901
902       # apply upgrade
903       $main::lxdebug->message(DEBUG2, "Applying Update $control->{file}");
904       print($form->parse_html_template("dbupgrade/upgrade_message2",
905                                        $control));
906
907       if ($file_type eq "sql") {
908         $self->process_query($form, $dbh, "sql/" . $form->{"dbdriver"} .
909                              "-upgrade2/$control->{file}", $control);
910       } else {
911         $self->process_perl_script($form, $dbh, "sql/" . $form->{"dbdriver"} .
912                                    "-upgrade2/$control->{file}", $control);
913       }
914     }
915
916     $rc = 0;
917     $dbh->disconnect;
918
919   }
920
921   $main::lxdebug->leave_sub();
922
923   return $rc;
924 }
925
926 sub update2_available {
927   $main::lxdebug->enter_sub();
928
929   my ($form, $controls) = @_;
930
931   map({ $_->{"applied"} = 0; } values(%{$controls}));
932
933   dbconnect_vars($form, $form->{"dbname"});
934
935   my $dbh =
936     DBI->connect($form->{dbconnect}, $form->{dbuser}, $form->{dbpasswd}) ||
937     $form->dberror;
938
939   my ($query, $tag, $sth);
940
941   $query = "SELECT tag FROM schema_info";
942   $sth = $dbh->prepare($query);
943   $sth->execute() || $form->dberror($query);
944   while (($tag) = $sth->fetchrow_array()) {
945     $controls->{$tag}->{"applied"} = 1 if (defined($controls->{$tag}));
946   }
947   $sth->finish();
948   $dbh->disconnect();
949
950   map({ $main::lxdebug->leave_sub() and return 1 if (!$_->{"applied"}) }
951       values(%{$controls}));
952
953   $main::lxdebug->leave_sub();
954   return 0;
955 }
956
957 sub create_config {
958   $main::lxdebug->enter_sub();
959
960   my ($self, $filename) = @_;
961
962   @config = &config_vars;
963
964   open(CONF, ">$filename") or $self->error("$filename : $!");
965
966   # create the config file
967   print CONF qq|# configuration file for $self->{login}
968
969 \%myconfig = (
970 |;
971
972   foreach $key (sort @config) {
973     $self->{$key} =~ s/\'/\\\'/g;
974     print CONF qq|  $key => '$self->{$key}',\n|;
975   }
976
977   print CONF qq|);\n\n|;
978
979   close CONF;
980
981   $main::lxdebug->leave_sub();
982 }
983
984 sub save_member {
985   $main::lxdebug->enter_sub();
986
987   my ($self, $memberfile, $userspath) = @_;
988
989   my $newmember = 1;
990
991   # format dbconnect and dboptions string
992   &dbconnect_vars($self, $self->{dbname});
993
994   $self->error('File locked!') if (-f "${memberfile}.LCK");
995   open(FH, ">${memberfile}.LCK") or $self->error("${memberfile}.LCK : $!");
996   close(FH);
997
998   open(CONF, "+<$memberfile") or $self->error("$memberfile : $!");
999
1000   @config = <CONF>;
1001
1002   seek(CONF, 0, 0);
1003   truncate(CONF, 0);
1004
1005   while ($line = shift @config) {
1006     if ($line =~ /^\[$self->{login}\]/) {
1007       $newmember = 0;
1008       last;
1009     }
1010     print CONF $line;
1011   }
1012
1013   # remove everything up to next login or EOF
1014   while ($line = shift @config) {
1015     last if ($line =~ /^\[/);
1016   }
1017
1018   # this one is either the next login or EOF
1019   print CONF $line;
1020
1021   while ($line = shift @config) {
1022     print CONF $line;
1023   }
1024
1025   print CONF qq|[$self->{login}]\n|;
1026
1027   if ((($self->{dbpasswd} ne $self->{old_dbpasswd}) || $newmember)
1028       && $self->{root}) {
1029     $self->{dbpasswd} = pack 'u', $self->{dbpasswd};
1030     chop $self->{dbpasswd};
1031   }
1032   if (defined($self->{new_password})) {
1033     if ($self->{new_password} ne $self->{old_password}) {
1034       $self->{password} = crypt $self->{new_password},
1035         substr($self->{login}, 0, 2)
1036         if $self->{new_password};
1037     }
1038   } else {
1039     if ($self->{password} ne $self->{old_password}) {
1040       $self->{password} = crypt $self->{password}, substr($self->{login}, 0, 2)
1041         if $self->{password};
1042     }
1043   }
1044
1045   if ($self->{'root login'}) {
1046     @config = ("password");
1047   } else {
1048     @config = &config_vars;
1049   }
1050
1051   # replace \r\n with \n
1052   map { $self->{$_} =~ s/\r\n/\\n/g } qw(address signature);
1053   foreach $key (sort @config) {
1054     print CONF qq|$key=$self->{$key}\n|;
1055   }
1056
1057   print CONF "\n";
1058   close CONF;
1059   unlink "${memberfile}.LCK";
1060
1061   # create conf file
1062   $self->create_config("$userspath/$self->{login}.conf")
1063     unless $self->{'root login'};
1064
1065   $main::lxdebug->leave_sub();
1066 }
1067
1068 sub config_vars {
1069   $main::lxdebug->enter_sub();
1070
1071   my @conf = qw(acs address admin businessnumber charset company countrycode
1072     currency dateformat dbconnect dbdriver dbhost dbport dboptions
1073     dbname dbuser dbpasswd email fax name numberformat in_numberformat password
1074     printer role sid signature stylesheet tel templates vclimit angebote bestellungen rechnungen
1075     anfragen lieferantenbestellungen einkaufsrechnungen taxnumber co_ustid duns menustyle
1076     template_format copies);
1077
1078   $main::lxdebug->leave_sub();
1079
1080   return @conf;
1081 }
1082
1083 sub error {
1084   $main::lxdebug->enter_sub();
1085
1086   my ($self, $msg) = @_;
1087
1088   if ($ENV{HTTP_USER_AGENT}) {
1089     print qq|Content-Type: text/html
1090
1091 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN">
1092
1093 <body bgcolor=ffffff>
1094
1095 <h2><font color=red>Error!</font></h2>
1096 <p><b>$msg</b>|;
1097
1098   }
1099
1100   die "Error: $msg\n";
1101
1102   $main::lxdebug->leave_sub();
1103 }
1104
1105 1;
1106