Neuer Datenbankupgrademechanismus: Die Upgradedateien im neuen Verzeichnis sql/Pg...
[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 = " . $dbh->quote($version));
528   }
529   $dbh->commit();
530
531   close FH;
532
533   $main::lxdebug->leave_sub();
534 }
535
536 sub dbdelete {
537   $main::lxdebug->enter_sub();
538
539   my ($self, $form) = @_;
540
541   my %dbdelete = ('Pg'     => qq|DROP DATABASE "$form->{db}"|,
542                   'Oracle' => qq|DROP USER $form->{db} CASCADE|);
543
544   $form->{sid} = $form->{dbdefault};
545   &dbconnect_vars($form, $form->{dbdefault});
546   my $dbh =
547     DBI->connect($form->{dbconnect}, $form->{dbuser}, $form->{dbpasswd})
548     or $form->dberror;
549   my $query = qq|$dbdelete{$form->{dbdriver}}|;
550   $dbh->do($query) || $form->dberror($query);
551
552   $dbh->disconnect;
553
554   $main::lxdebug->leave_sub();
555 }
556
557 sub dbsources_unused {
558   $main::lxdebug->enter_sub();
559
560   my ($self, $form, $memfile) = @_;
561
562   my @dbexcl    = ();
563   my @dbsources = ();
564
565   $form->error('File locked!') if (-f "${memfile}.LCK");
566
567   # open members file
568   open(FH, "$memfile") or $form->error("$memfile : $!");
569
570   while (<FH>) {
571     if (/^dbname=/) {
572       my ($null, $item) = split(/=/);
573       push @dbexcl, $item;
574     }
575   }
576
577   close FH;
578
579   $form->{only_acc_db} = 1;
580   my @db = &dbsources("", $form);
581
582   push @dbexcl, $form->{dbdefault};
583
584   foreach $item (@db) {
585     unless (grep /$item$/, @dbexcl) {
586       push @dbsources, $item;
587     }
588   }
589
590   $main::lxdebug->leave_sub();
591
592   return @dbsources;
593 }
594
595 sub dbneedsupdate {
596   $main::lxdebug->enter_sub();
597
598   my ($self, $form) = @_;
599
600   my %dbsources = ();
601   my $query;
602
603   $form->{sid} = $form->{dbdefault};
604   &dbconnect_vars($form, $form->{dbdefault});
605
606   my $dbh =
607     DBI->connect($form->{dbconnect}, $form->{dbuser}, $form->{dbpasswd})
608     or $form->dberror;
609
610   if ($form->{dbdriver} eq 'Pg') {
611
612     $query = qq|SELECT d.datname FROM pg_database d, pg_user u
613                 WHERE d.datdba = u.usesysid
614                 AND u.usename = '$form->{dbuser}'|;
615     my $sth = $dbh->prepare($query);
616     $sth->execute || $form->dberror($query);
617
618     while (my ($db) = $sth->fetchrow_array) {
619
620       next if ($db =~ /^template/);
621
622       &dbconnect_vars($form, $db);
623
624       my $dbh =
625         DBI->connect($form->{dbconnect}, $form->{dbuser}, $form->{dbpasswd})
626         or $form->dberror;
627
628       $query = qq|SELECT t.tablename FROM pg_tables t
629                   WHERE t.tablename = 'defaults'|;
630       my $sth = $dbh->prepare($query);
631       $sth->execute || $form->dberror($query);
632
633       if ($sth->fetchrow_array) {
634         $query = qq|SELECT version FROM defaults|;
635         my $sth = $dbh->prepare($query);
636         $sth->execute;
637
638         if (my ($version) = $sth->fetchrow_array) {
639           $dbsources{$db} = $version;
640         }
641         $sth->finish;
642       }
643       $sth->finish;
644       $dbh->disconnect;
645     }
646     $sth->finish;
647   }
648
649   if ($form->{dbdriver} eq 'Oracle') {
650     $query = qq|SELECT o.owner FROM dba_objects o
651                 WHERE o.object_name = 'DEFAULTS'
652                 AND o.object_type = 'TABLE'|;
653
654     $sth = $dbh->prepare($query);
655     $sth->execute || $form->dberror($query);
656
657     while (my ($db) = $sth->fetchrow_array) {
658
659       $form->{dbuser} = $db;
660       &dbconnect_vars($form, $db);
661
662       my $dbh =
663         DBI->connect($form->{dbconnect}, $form->{dbuser}, $form->{dbpasswd})
664         or $form->dberror;
665
666       $query = qq|SELECT version FROM defaults|;
667       my $sth = $dbh->prepare($query);
668       $sth->execute;
669
670       if (my ($version) = $sth->fetchrow_array) {
671         $dbsources{$db} = $version;
672       }
673       $sth->finish;
674       $dbh->disconnect;
675     }
676     $sth->finish;
677   }
678
679   $dbh->disconnect;
680
681   $main::lxdebug->leave_sub();
682
683   return %dbsources;
684 }
685
686 ## LINET
687 sub calc_version {
688   $main::lxdebug->enter_sub(2);
689
690   my (@v, $version, $i);
691
692   @v = split(/\./, $_[0]);
693   while (scalar(@v) < 4) {
694     push(@v, 0);
695   }
696   $version = 0;
697   for ($i = 0; $i < 4; $i++) {
698     $version *= 1000;
699     $version += $v[$i];
700   }
701
702   $main::lxdebug->leave_sub(2);
703   return $version;
704 }
705
706 sub cmp_script_version {
707   my ($a_from, $a_to, $b_from, $b_to);
708   my ($i, $res_a, $res_b);
709   my ($my_a, $my_b) = ($a, $b);
710
711   $my_a =~ s/.*-upgrade-//;
712   $my_a =~ s/.sql$//;
713   $my_b =~ s/.*-upgrade-//;
714   $my_b =~ s/.sql$//;
715   ($my_a_from, $my_a_to) = split(/-/, $my_a);
716   ($my_b_from, $my_b_to) = split(/-/, $my_b);
717
718   $res_a = calc_version($my_a_from);
719   $res_b = calc_version($my_b_from);
720
721   if ($res_a == $res_b) {
722     $res_a = calc_version($my_a_to);
723     $res_b = calc_version($my_b_to);
724   }
725
726   return $res_a <=> $res_b;
727 }
728 ## /LINET
729
730 sub update_available {
731   my ($dbdriver, $cur_version) = @_;
732
733   opendir SQLDIR, "sql/${dbdriver}-upgrade" or &error("", "sql/${dbdriver}-upgrade: $!");
734   my @upgradescripts =
735     grep(/$form->{dbdriver}-upgrade-\Q$cur_version\E.*\.(sql|pl)/, readdir(SQLDIR));
736   closedir SQLDIR;
737
738   return ($#upgradescripts > -1);
739 }
740
741 sub create_schema_info_table {
742   $main::lxdebug->enter_sub();
743
744   my ($self, $form, $dbh) = @_;
745
746   my $query = "SELECT tag FROM schema_info LIMIT 1";
747   if (!$dbh->do($query)) {
748     $query =
749       "CREATE TABLE schema_info (" .
750       "  tag text, " .
751       "  login text, " .
752       "  itime timestamp DEFAULT now(), " .
753       "  PRIMARY KEY (tag))";
754     $dbh->do($query) || $form->dberror($query);
755   }
756
757   $main::lxdebug->leave_sub();
758 }
759
760 sub dbupdate {
761   $main::lxdebug->enter_sub();
762
763   my ($self, $form) = @_;
764
765   $form->{sid} = $form->{dbdefault};
766
767   my @upgradescripts = ();
768   my $query;
769   my $rc = -2;
770
771   if ($form->{dbupdate}) {
772
773     # read update scripts into memory
774     opendir SQLDIR, "sql/" . $form->{dbdriver} . "-upgrade" or &error("", "sql/" . $form->{dbdriver} . "-upgrade : $!");
775     ## LINET
776     @upgradescripts =
777       sort(cmp_script_version
778            grep(/$form->{dbdriver}-upgrade-.*?\.(sql|pl)$/, readdir(SQLDIR)));
779     ## /LINET
780     closedir SQLDIR;
781   }
782
783   foreach my $db (split / /, $form->{dbupdate}) {
784
785     next unless $form->{$db};
786
787     # strip db from dataset
788     $db =~ s/^db//;
789     &dbconnect_vars($form, $db);
790
791     my $dbh =
792       DBI->connect($form->{dbconnect}, $form->{dbuser}, $form->{dbpasswd})
793       or $form->dberror;
794
795     # check version
796     $query = qq|SELECT version FROM defaults|;
797     my $sth = $dbh->prepare($query);
798
799     # no error check, let it fall through
800     $sth->execute;
801
802     my $version = $sth->fetchrow_array;
803     $sth->finish;
804
805     next unless $version;
806
807     ## LINET
808     $version = calc_version($version);
809     ## /LINET
810
811     foreach my $upgradescript (@upgradescripts) {
812       my $a = $upgradescript;
813       $a =~ s/^$form->{dbdriver}-upgrade-|\.(sql|pl)$//g;
814       my $file_type = $1;
815
816       my ($mindb, $maxdb) = split /-/, $a;
817       my $str_maxdb = $maxdb;
818       ## LINET
819       $mindb = calc_version($mindb);
820       $maxdb = calc_version($maxdb);
821       ## /LINET
822
823       next if ($version >= $maxdb);
824
825       # if there is no upgrade script exit
826       last if ($version < $mindb);
827
828       # apply upgrade
829       $main::lxdebug->message(DEBUG2, "Applying Update $upgradescript");
830       if ($file_type eq "sql") {
831         $self->process_query($form, $dbh, "sql/" . $form->{"dbdriver"} . "-upgrade/$upgradescript", $str_maxdb);
832       } else {
833         $self->process_perl_script($form, $dbh, "sql/" . $form->{"dbdriver"} . "-upgrade/$upgradescript", $str_maxdb);
834       }
835
836       $version = $maxdb;
837
838     }
839
840     $rc = 0;
841     $dbh->disconnect;
842
843   }
844
845   $main::lxdebug->leave_sub();
846
847   return $rc;
848 }
849
850 sub dbupdate2 {
851   $main::lxdebug->enter_sub();
852
853   my ($self, $form, $controls) = @_;
854
855   $form->{sid} = $form->{dbdefault};
856
857   my @upgradescripts = ();
858   my ($query, $sth, $tag);
859   my $rc = -2;
860
861   @upgradescripts = sort_dbupdate_controls($controls);
862
863   foreach my $db (split / /, $form->{dbupdate}) {
864
865     next unless $form->{$db};
866
867     # strip db from dataset
868     $db =~ s/^db//;
869     &dbconnect_vars($form, $db);
870
871     my $dbh =
872       DBI->connect($form->{dbconnect}, $form->{dbuser}, $form->{dbpasswd})
873       or $form->dberror;
874
875     map({ $_->{"applied"} = 0; } @upgradescripts);
876
877     $query = "SELECT tag FROM schema_info";
878     $sth = $dbh->prepare($query);
879     $sth->execute() || $form->dberror($query);
880     while (($tag) = $sth->fetchrow_array()) {
881       $controls->{$tag}->{"applied"} = 1 if (defined($controls->{$tag}));
882     }
883     $sth->finish();
884
885     my $all_applied = 1;
886     foreach (@upgradescripts) {
887       if (!$_->{"applied"}) {
888         $all_applied = 0;
889         last;
890       }
891     }
892
893     next if ($all_applied);
894
895     foreach my $control (@upgradescripts) {
896       next if ($control->{"applied"});
897
898       $control->{"file"} =~ /\.(sql|pl)$/;
899       my $file_type = $1;
900
901       # apply upgrade
902       $main::lxdebug->message(DEBUG2, "Applying Update $control->{file}");
903       print($form->parse_html_template("dbupgrade/upgrade_message2",
904                                        $control));
905
906       if ($file_type eq "sql") {
907         $self->process_query($form, $dbh, "sql/" . $form->{"dbdriver"} .
908                              "-upgrade2/$control->{file}", $control);
909       } else {
910         $self->process_perl_script($form, $dbh, "sql/" . $form->{"dbdriver"} .
911                                    "-upgrade2/$control->{file}", $control);
912       }
913     }
914
915     $rc = 0;
916     $dbh->disconnect;
917
918   }
919
920   $main::lxdebug->leave_sub();
921
922   return $rc;
923 }
924
925 sub update2_available {
926   $main::lxdebug->enter_sub();
927
928   my ($form, $controls) = @_;
929
930   map({ $_->{"applied"} = 0; } values(%{$controls}));
931
932   dbconnect_vars($form, $form->{"dbname"});
933
934   my $dbh =
935     DBI->connect($form->{dbconnect}, $form->{dbuser}, $form->{dbpasswd}) ||
936     $form->dberror;
937
938   my ($query, $tag, $sth);
939
940   $query = "SELECT tag FROM schema_info";
941   $sth = $dbh->prepare($query);
942   $sth->execute() || $form->dberror($query);
943   while (($tag) = $sth->fetchrow_array()) {
944     $controls->{$tag}->{"applied"} = 1 if (defined($controls->{$tag}));
945   }
946   $sth->finish();
947   $dbh->disconnect();
948
949   map({ $main::lxdebug->leave_sub() and return 1 if (!$_->{"applied"}) }
950       values(%{$controls}));
951
952   $main::lxdebug->leave_sub();
953   return 0;
954 }
955
956 sub create_config {
957   $main::lxdebug->enter_sub();
958
959   my ($self, $filename) = @_;
960
961   @config = &config_vars;
962
963   open(CONF, ">$filename") or $self->error("$filename : $!");
964
965   # create the config file
966   print CONF qq|# configuration file for $self->{login}
967
968 \%myconfig = (
969 |;
970
971   foreach $key (sort @config) {
972     $self->{$key} =~ s/\'/\\\'/g;
973     print CONF qq|  $key => '$self->{$key}',\n|;
974   }
975
976   print CONF qq|);\n\n|;
977
978   close CONF;
979
980   $main::lxdebug->leave_sub();
981 }
982
983 sub save_member {
984   $main::lxdebug->enter_sub();
985
986   my ($self, $memberfile, $userspath) = @_;
987
988   my $newmember = 1;
989
990   # format dbconnect and dboptions string
991   &dbconnect_vars($self, $self->{dbname});
992
993   $self->error('File locked!') if (-f "${memberfile}.LCK");
994   open(FH, ">${memberfile}.LCK") or $self->error("${memberfile}.LCK : $!");
995   close(FH);
996
997   open(CONF, "+<$memberfile") or $self->error("$memberfile : $!");
998
999   @config = <CONF>;
1000
1001   seek(CONF, 0, 0);
1002   truncate(CONF, 0);
1003
1004   while ($line = shift @config) {
1005     if ($line =~ /^\[$self->{login}\]/) {
1006       $newmember = 0;
1007       last;
1008     }
1009     print CONF $line;
1010   }
1011
1012   # remove everything up to next login or EOF
1013   while ($line = shift @config) {
1014     last if ($line =~ /^\[/);
1015   }
1016
1017   # this one is either the next login or EOF
1018   print CONF $line;
1019
1020   while ($line = shift @config) {
1021     print CONF $line;
1022   }
1023
1024   print CONF qq|[$self->{login}]\n|;
1025
1026   if ((($self->{dbpasswd} ne $self->{old_dbpasswd}) || $newmember)
1027       && $self->{root}) {
1028     $self->{dbpasswd} = pack 'u', $self->{dbpasswd};
1029     chop $self->{dbpasswd};
1030   }
1031   if (defined($self->{new_password})) {
1032     if ($self->{new_password} ne $self->{old_password}) {
1033       $self->{password} = crypt $self->{new_password},
1034         substr($self->{login}, 0, 2)
1035         if $self->{new_password};
1036     }
1037   } else {
1038     if ($self->{password} ne $self->{old_password}) {
1039       $self->{password} = crypt $self->{password}, substr($self->{login}, 0, 2)
1040         if $self->{password};
1041     }
1042   }
1043
1044   if ($self->{'root login'}) {
1045     @config = ("password");
1046   } else {
1047     @config = &config_vars;
1048   }
1049
1050   # replace \r\n with \n
1051   map { $self->{$_} =~ s/\r\n/\\n/g } qw(address signature);
1052   foreach $key (sort @config) {
1053     print CONF qq|$key=$self->{$key}\n|;
1054   }
1055
1056   print CONF "\n";
1057   close CONF;
1058   unlink "${memberfile}.LCK";
1059
1060   # create conf file
1061   $self->create_config("$userspath/$self->{login}.conf")
1062     unless $self->{'root login'};
1063
1064   $main::lxdebug->leave_sub();
1065 }
1066
1067 sub config_vars {
1068   $main::lxdebug->enter_sub();
1069
1070   my @conf = qw(acs address admin businessnumber charset company countrycode
1071     currency dateformat dbconnect dbdriver dbhost dbport dboptions
1072     dbname dbuser dbpasswd email fax name numberformat in_numberformat password
1073     printer role sid signature stylesheet tel templates vclimit angebote bestellungen rechnungen
1074     anfragen lieferantenbestellungen einkaufsrechnungen steuernummer co_ustid duns menustyle);
1075
1076   $main::lxdebug->leave_sub();
1077
1078   return @conf;
1079 }
1080
1081 sub error {
1082   $main::lxdebug->enter_sub();
1083
1084   my ($self, $msg) = @_;
1085
1086   if ($ENV{HTTP_USER_AGENT}) {
1087     print qq|Content-Type: text/html
1088
1089 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN">
1090
1091 <body bgcolor=ffffff>
1092
1093 <h2><font color=red>Error!</font></h2>
1094 <p><b>$msg</b>|;
1095
1096   }
1097
1098   die "Error: $msg\n";
1099
1100   $main::lxdebug->leave_sub();
1101 }
1102
1103 1;
1104