Changelog ueberarbeitet, Versionsnummern hochgesetzt, Pg-upgrade-Skript umbenannt
[kivitendo-erp.git] / SL / Form.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) 1998-2002
10 #
11 #  Author: Dieter Simader
12 #   Email: dsimader@sql-ledger.org
13 #     Web: http://www.sql-ledger.org
14 #
15 # Contributors: Thomas Bayen <bayen@gmx.de>
16 #               Antti Kaihola <akaihola@siba.fi>
17 #               Moritz Bunkus (tex code)
18 #
19 # This program is free software; you can redistribute it and/or modify
20 # it under the terms of the GNU General Public License as published by
21 # the Free Software Foundation; either version 2 of the License, or
22 # (at your option) any later version.
23 #
24 # This program is distributed in the hope that it will be useful,
25 # but WITHOUT ANY WARRANTY; without even the implied warranty of
26 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
27 # GNU General Public License for more details.
28 # You should have received a copy of the GNU General Public License
29 # along with this program; if not, write to the Free Software
30 # Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
31 #======================================================================
32 # Utilities for parsing forms
33 # and supporting routines for linking account numbers
34 # used in AR, AP and IS, IR modules
35 #
36 #======================================================================
37
38 package Form;
39
40 sub _input_to_hash {
41   $main::lxdebug->enter_sub();
42
43   my $input = $_[0];
44   my %in    = ();
45   my @pairs = split(/&/, $input);
46
47   foreach (@pairs) {
48     my ($name, $value) = split(/=/, $_, 2);
49     $in{$name} = unescape(undef, $value);
50   }
51
52   $main::lxdebug->leave_sub();
53
54   return %in;
55 }
56
57 sub _request_to_hash {
58   $main::lxdebug->enter_sub();
59
60   my ($input) = @_;
61   my ($i,        $loc,  $key,    $val);
62   my (%ATTACH,   $f,    $header, $header_body, $len, $buf);
63   my ($boundary, @list, $size,   $body, $x, $blah, $name);
64
65   if ($ENV{'CONTENT_TYPE'}
66       && ($ENV{'CONTENT_TYPE'} =~ /multipart\/form-data; boundary=(.+)$/)) {
67     $boundary = quotemeta('--' . $1);
68     @list     = split(/$boundary/, $input);
69
70     # For some reason there are always 2 extra, that are empty
71     $size = @list - 2;
72
73     for ($x = 1; $x <= $size; $x++) {
74       $header_body = $list[$x];
75       $header_body =~ /\r\n\r\n|\n\n/;
76
77       # Here we split the header and body
78       $header = $`;
79       $body   = $';    #'
80       $body =~ s/\r\n$//;
81
82       # Now we try to get the file name
83       $name = $header;
84       $name =~ /name=\"(.+)\"/;
85       ($name, $blah) = split(/\"/, $1);
86
87       # If the form name is not attach, then we need to parse this like
88       # regular form data
89       if ($name ne "attach") {
90         $body =~ s/%([0-9a-fA-Z]{2})/pack("c",hex($1))/eg;
91         $ATTACH{$name} = $body;
92
93         # Otherwise it is an attachment and we need to finish it up
94       } elsif ($name eq "attach") {
95         $header =~ /filename=\"(.+)\"/;
96         $ATTACH{'FILE_NAME'} = $1;
97         $ATTACH{'FILE_NAME'} =~ s/\"//g;
98         $ATTACH{'FILE_NAME'} =~ s/\s//g;
99         $ATTACH{'FILE_CONTENT'} = $body;
100
101         for ($i = $x; $list[$i]; $i++) {
102           $list[$i] =~ s/^.+name=$//;
103           $list[$i] =~ /\"(\w+)\"/;
104           $ATTACH{$1} = $';    #'
105         }
106       }
107     }
108
109     $main::lxdebug->leave_sub();
110     return %ATTACH;
111
112       } else {
113     $main::lxdebug->leave_sub();
114     return _input_to_hash($input);
115   }
116 }
117
118 sub new {
119   $main::lxdebug->enter_sub();
120
121   my $type = shift;
122
123   my $self = {};
124
125   read(STDIN, $_, $ENV{CONTENT_LENGTH});
126
127   if ($ENV{QUERY_STRING}) {
128     $_ = $ENV{QUERY_STRING};
129   }
130
131   if ($ARGV[0]) {
132     $_ = $ARGV[0];
133   }
134
135   my %parameters = _request_to_hash($_);
136   map({ $self->{$_} = $parameters{$_}; } keys(%parameters));
137
138   $self->{menubar} = 1 if $self->{path} =~ /lynx/i;
139
140   $self->{action} = lc $self->{action};
141   $self->{action} =~ s/( |-|,|#)/_/g;
142
143   $self->{version}   = "2.2.0";
144   $self->{dbversion} = "2.2.0";
145
146   $main::lxdebug->leave_sub();
147
148   bless $self, $type;
149 }
150
151 sub debug {
152   $main::lxdebug->enter_sub();
153
154   my ($self) = @_;
155
156   print "\n";
157
158   map { print "$_ = $self->{$_}\n" } (sort keys %{$self});
159
160   $main::lxdebug->leave_sub();
161 }
162
163 sub escape {
164   $main::lxdebug->enter_sub();
165
166   my ($self, $str, $beenthere) = @_;
167
168   # for Apache 2 we escape strings twice
169   #if (($ENV{SERVER_SOFTWARE} =~ /Apache\/2/) && !$beenthere) {
170   #  $str = $self->escape($str, 1);
171   #}
172
173   $str =~ s/([^a-zA-Z0-9_.-])/sprintf("%%%02x", ord($1))/ge;
174
175   $main::lxdebug->leave_sub();
176
177   return $str;
178 }
179
180 sub unescape {
181   $main::lxdebug->enter_sub();
182
183   my ($self, $str) = @_;
184
185   $str =~ tr/+/ /;
186   $str =~ s/\\$//;
187
188   $str =~ s/%([0-9a-fA-Z]{2})/pack("c",hex($1))/eg;
189
190   $main::lxdebug->leave_sub();
191
192   return $str;
193 }
194
195 sub quote {
196   my ($self, $str) = @_;
197
198   if ($str && ! ref($str)) {
199     $str =~ s/"/&quot;/g;
200   }
201
202   $str;
203
204 }
205
206
207 sub unquote {
208   my ($self, $str) = @_;
209
210   if ($str && ! ref($str)) {
211     $str =~ s/&quot;/"/g;
212   }
213
214   $str;
215
216 }
217
218  
219 sub hide_form {
220   my $self = shift;
221
222   if (@_) {
223     for (@_) { print qq|<input type=hidden name="$_" value="|.$self->quote($self->{$_}).qq|">\n| }
224   } else {
225     delete $self->{header};
226     for (sort keys %$self) { print qq|<input type=hidden name="$_" value="|.$self->quote($self->{$_}).qq|">\n| }
227   }
228   
229 }
230
231 sub error {
232   $main::lxdebug->enter_sub();
233
234   my ($self, $msg) = @_;
235
236   if ($ENV{HTTP_USER_AGENT}) {
237     $msg =~ s/\n/<br>/g;
238
239     $self->header;
240
241     print qq|
242     <body>
243
244     <h2 class=error>Error!</h2>
245
246     <p><b>$msg</b>
247
248     </body>
249     </html>
250     |;
251
252     die "Error: $msg\n";
253
254   } else {
255
256     if ($self->{error_function}) {
257       &{ $self->{error_function} }($msg);
258     } else {
259       die "Error: $msg\n";
260     }
261   }
262
263   $main::lxdebug->leave_sub();
264 }
265
266 sub info {
267   $main::lxdebug->enter_sub();
268
269   my ($self, $msg) = @_;
270
271   if ($ENV{HTTP_USER_AGENT}) {
272     $msg =~ s/\n/<br>/g;
273
274     if (!$self->{header}) {
275       $self->header;
276       print qq|
277       <body>|;
278     }
279
280     print qq|
281
282     <p><b>$msg</b>
283     |;
284
285   } else {
286
287     if ($self->{info_function}) {
288       &{ $self->{info_function} }($msg);
289     } else {
290       print "$msg\n";
291     }
292   }
293
294   $main::lxdebug->leave_sub();
295 }
296
297 sub numtextrows {
298   $main::lxdebug->enter_sub();
299
300   my ($self, $str, $cols, $maxrows) = @_;
301
302   my $rows = 0;
303
304   map { $rows += int(((length) - 2) / $cols) + 1 } split /\r/, $str;
305
306   $maxrows = $rows unless defined $maxrows;
307
308   $main::lxdebug->leave_sub();
309
310   return ($rows > $maxrows) ? $maxrows : $rows;
311 }
312
313 sub dberror {
314   $main::lxdebug->enter_sub();
315
316   my ($self, $msg) = @_;
317
318   $self->error("$msg\n" . $DBI::errstr);
319
320   $main::lxdebug->leave_sub();
321 }
322
323 sub isblank {
324   $main::lxdebug->enter_sub();
325
326   my ($self, $name, $msg) = @_;
327
328   if ($self->{$name} =~ /^\s*$/) {
329     $self->error($msg);
330   }
331   $main::lxdebug->leave_sub();
332 }
333
334 sub header {
335   $main::lxdebug->enter_sub();
336
337   my ($self) = @_;
338
339   if ($self->{header}) {
340     $main::lxdebug->leave_sub();
341     return;
342   }
343
344   my ($stylesheet, $favicon, $charset);
345
346   if ($ENV{HTTP_USER_AGENT}) {
347
348     if ($self->{stylesheet} && (-f "css/$self->{stylesheet}")) {
349       $stylesheet =
350         qq|<LINK REL="stylesheet" HREF="css/$self->{stylesheet}" TYPE="text/css" TITLE="Lx-Office stylesheet">
351  |;
352     }
353
354     if ($self->{favicon} && (-f "$self->{favicon}")) {
355       $favicon =
356         qq|<LINK REL="shortcut icon" HREF="$self->{favicon}" TYPE="image/x-icon">
357   |;
358     }
359
360     if ($self->{charset}) {
361       $charset =
362         qq|<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=$self->{charset}">
363   |;
364     }
365     if ($self->{landscape}) {
366       $pagelayout = qq|<style type="text/css">
367                         \@page { size:landscape; }
368                         </style>|;
369     }
370     if ($self->{fokus}) {
371       $fokus = qq|<script type="text/javascript">
372 <!--
373 function fokus(){document.$self->{fokus}.focus();}
374 //-->
375 </script>|;
376     }
377
378     #Set Calendar
379     $jsscript = "";
380     if ($self->{jsscript} == 1) {
381
382       $jsscript = qq|
383         <style type="text/css">\@import url(js/jscalendar/calendar-win2k-1.css);</style>
384         <script type="text/javascript" src="js/jscalendar/calendar.js"></script>
385         <script type="text/javascript" src="js/jscalendar/lang/calendar-de.js"></script>
386         <script type="text/javascript" src="js/jscalendar/calendar-setup.js"></script>
387         $self->{javascript}
388        |;
389     }
390
391     $self->{titlebar} =
392       ($self->{title})
393       ? "$self->{title} - $self->{titlebar}"
394       : $self->{titlebar};
395
396     print qq|Content-Type: text/html
397
398 <head>
399   <title>$self->{titlebar}</title>
400   $stylesheet
401   $pagelayout
402   $favicon
403   $charset
404   $jsscript
405   $fokus
406 </head>
407
408 |;
409   }
410   $self->{header} = 1;
411
412   $main::lxdebug->leave_sub();
413 }
414
415 # write Trigger JavaScript-Code ($qty = quantity of Triggers)
416 # changed it to accept an arbitrary number of triggers - sschoeling
417 sub write_trigger {
418   $main::lxdebug->enter_sub();
419
420   my $self     = shift;
421   my $myconfig = shift;
422   my $qty      = shift;
423
424   # set dateform for jsscript
425   # default
426   $ifFormat = "%d.%m.%Y";
427   if ($myconfig->{dateformat} eq "dd.mm.yy") {
428     $ifFormat = "%d.%m.%Y";
429   } else {
430     if ($myconfig->{dateformat} eq "dd-mm-yy") {
431       $ifFormat = "%d-%m-%Y";
432     } else {
433       if ($myconfig->{dateformat} eq "dd/mm/yy") {
434         $ifFormat = "%d/%m/%Y";
435       } else {
436         if ($myconfig->{dateformat} eq "mm/dd/yy") {
437           $ifFormat = "%m/%d/%Y";
438         } else {
439           if ($myconfig->{dateformat} eq "mm-dd-yy") {
440             $ifFormat = "%m-%d-%Y";
441           } else {
442             if ($myconfig->{dateformat} eq "yyyy-mm-dd") {
443               $ifFormat = "%Y-%m-%d";
444             }
445           }
446         }
447       }
448     }
449   }
450
451   while ($#_ >= 2) {
452     push @triggers, qq|
453        Calendar.setup(
454       {
455       inputField : "|.(shift).qq|",
456       ifFormat :"$ifFormat",
457       align : "|.(shift).qq|", 
458       button : "|.(shift).qq|"
459       }
460       );
461        |;
462   }
463   $jsscript = qq|
464        <script type="text/javascript">
465        <!--|.join("", @triggers).qq|//-->
466         </script>
467         |;
468
469   $main::lxdebug->leave_sub();
470
471   return $jsscript;
472 }    #end sub write_trigger
473
474 sub redirect {
475   $main::lxdebug->enter_sub();
476
477   my ($self, $msg) = @_;
478
479   if ($self->{callback}) {
480
481     ($script, $argv) = split(/\?/, $self->{callback});
482     exec("perl", "$script", $argv);
483
484   } else {
485
486     $self->info($msg);
487     exit;
488   }
489
490   $main::lxdebug->leave_sub();
491 }
492
493 # sort of columns removed - empty sub
494 sub sort_columns {
495   $main::lxdebug->enter_sub();
496
497   my ($self, @columns) = @_;
498
499   $main::lxdebug->leave_sub();
500
501   return @columns;
502 }
503
504 sub format_amount {
505   $main::lxdebug->enter_sub();
506
507   my ($self, $myconfig, $amount, $places, $dash) = @_;
508   
509   #Workaround for $format_amount calls without $places
510   if (!defined $places){
511   (my $dec) = ($amount =~ /\.(\d+)/);
512   $places           = length $dec;
513   }                    
514
515   if ($places =~ /\d/) {
516     $amount = $self->round_amount($amount, $places);
517   }
518
519   # is the amount negative
520   my $negative = ($amount < 0);
521   my $fillup = "";
522
523   if ($amount != 0) {
524     if ($myconfig->{numberformat} && ($myconfig->{numberformat} ne '1000.00'))
525     {
526       my ($whole, $dec) = split /\./, "$amount";
527       $whole =~ s/-//;
528       $amount = join '', reverse split //, $whole;
529       $fillup = "0" x ($places - length($dec));
530
531       if ($myconfig->{numberformat} eq '1,000.00') {
532         $amount =~ s/\d{3,}?/$&,/g;
533         $amount =~ s/,$//;
534         $amount = join '', reverse split //, $amount;
535         $amount .= "\.$dec".$fillup if ($places ne '' && $places*1 != 0);
536       }
537
538       if ($myconfig->{numberformat} eq '1.000,00') {
539         $amount =~ s/\d{3,}?/$&./g;
540         $amount =~ s/\.$//;
541         $amount = join '', reverse split //, $amount;
542         $amount .= ",$dec".$fillup if ($places ne '' && $places*1 != 0);
543       }
544
545       if ($myconfig->{numberformat} eq '1000,00') {
546         $amount = "$whole";
547         $amount .= ",$dec" .$fillup if ($places ne '' && $places*1 != 0);
548       }
549
550       if ($dash =~ /-/) {
551         $amount = ($negative) ? "($amount)" : "$amount";
552       } elsif ($dash =~ /DRCR/) {
553         $amount = ($negative) ? "$amount DR" : "$amount CR";
554       } else {
555         $amount = ($negative) ? "-$amount" : "$amount";
556       }
557     }
558   } else {
559     if ($dash eq "0" && $places) {
560       if ($myconfig->{numberformat} eq '1.000,00') {
561         $amount = "0" . "," . "0" x $places;
562       } else {
563         $amount = "0" . "." . "0" x $places;
564       }
565     } else {
566       $amount = ($dash ne "") ? "$dash" : "0";
567     }
568   }
569
570   $main::lxdebug->leave_sub();
571
572   return $amount;
573 }
574
575 sub parse_amount {
576   $main::lxdebug->enter_sub();
577
578   my ($self, $myconfig, $amount) = @_;
579   $main::lxdebug->message(LXDebug::DEBUG2, "Start amount: $amount");  
580  
581   if ($myconfig->{in_numberformat} == 1){
582     # Extra input number format 1000.00 or 1000,00
583     $main::lxdebug->message(LXDebug::DEBUG2, "in_numberformat: " . $main::locale->text('1000,00 or 1000.00'));
584     $amount =~ s/,/\./g;
585     #$main::lxdebug->message(LXDebug::DEBUG2, "1.Parsed Number: $amount") if ($amount);
586     $amount = scalar reverse $amount;
587     #$main::lxdebug->message(LXDebug::DEBUG2, "2.Parsed Number: $amount") if ($amount);
588     $amount =~ s/\./DOT/;
589     #$main::lxdebug->message(LXDebug::DEBUG2, "3.Parsed Number: $amount") if ($amount);
590     $amount =~ s/\.//g;
591     #$main::lxdebug->message(LXDebug::DEBUG2, "4.Parsed Number: $amount") if ($amount);
592     $amount =~ s/DOT/\./;
593     #$main::lxdebug->message(LXDebug::DEBUG2, "5.Parsed Number:" . $amount) if ($amount);
594     $amount = scalar reverse $amount ;
595     $main::lxdebug->message(LXDebug::DEBUG2, "Parsed amount:" . $amount . "\n");
596
597     return ($amount * 1);
598
599   }
600   $main::lxdebug->message(LXDebug::DEBUG2, "in_numberformat: " . $main::locale->text('equal Outputformat'));
601   $main::lxdebug->message(LXDebug::DEBUG2, " = numberformat: $myconfig->{numberformat}");
602   if (   ($myconfig->{numberformat} eq '1.000,00')
603       || ($myconfig->{numberformat} eq '1000,00')) {
604     $amount =~ s/\.//g;
605     $amount =~ s/,/\./;
606   }
607
608   if ($myconfig->{numberformat} eq "1'000.00") {
609       $amount =~ s/'//g;
610   }
611
612   $amount =~ s/,//g;
613   
614   $main::lxdebug->message(LXDebug::DEBUG2, "Parsed amount:" . $amount. "\n") if ($amount);
615   $main::lxdebug->leave_sub();
616   
617   return ($amount * 1);
618 }
619
620 sub round_amount {
621   $main::lxdebug->enter_sub();
622
623   my ($self, $amount, $places) = @_;
624   my $round_amount;
625
626   # Rounding like "Kaufmannsrunden"
627   # Descr. http://de.wikipedia.org/wiki/Rundung
628   # Inspired by 
629   # http://www.perl.com/doc/FAQs/FAQ/oldfaq-html/Q4.13.html
630   # Solves Bug: 189
631   # Udo Spallek
632   $amount       = $amount * (10 ** ($places));
633   $round_amount = int($amount + .5 * ($amount <=> 0))/(10**($places));
634
635   $main::lxdebug->leave_sub();
636
637   return $round_amount;
638   
639 }
640
641
642
643 sub parse_template {
644   $main::lxdebug->enter_sub();
645
646   my ($self, $myconfig, $userspath) = @_;
647
648   # { Moritz Bunkus
649   # Some variables used for page breaks
650   my ($chars_per_line, $lines_on_first_page, $lines_on_second_page) =
651     (0, 0, 0);
652   my ($current_page, $current_line, $current_row) = (1, 1, 0);
653   my $pagebreak = "";
654   my $sum       = 0;
655
656   # } Moritz Bunkus
657
658   # Make sure that all *notes* (intnotes, partnotes_*, notes etc) are converted to markup correctly.
659   $self->format_string(grep(/notes/, keys(%{$self})));
660
661   # Copy the notes from the invoice/sales order etc. back to the variable "notes" because that is where most templates expect it to be.
662   $self->{"notes"} = $self->{ $self->{"formname"} . "notes" };
663
664   map({ $self->{"employee_${_}"} = $myconfig->{$_}; }
665       qw(email tel fax name signature));
666
667   open(IN, "$self->{templates}/$self->{IN}")
668     or $self->error("$self->{IN} : $!");
669
670   @_ = <IN>;
671   close(IN);
672
673   $self->{copies} = 1 if (($self->{copies} *= 1) <= 0);
674
675   # OUT is used for the media, screen, printer, email
676   # for postscript we store a copy in a temporary file
677   my $fileid = time;
678   $self->{tmpfile} = "$userspath/${fileid}.$self->{IN}";
679   if ($self->{format} =~ /(postscript|pdf)/ || $self->{media} eq 'email') {
680     $out = $self->{OUT};
681     $self->{OUT} = ">$self->{tmpfile}";
682   }
683
684   if ($self->{OUT}) {
685     open(OUT, "$self->{OUT}") or $self->error("$self->{OUT} : $!");
686   } else {
687     open(OUT, ">-") or $self->error("STDOUT : $!");
688     $self->header;
689   }
690
691   # Do we have to run LaTeX two times? This is needed if
692   # the template contains page references.
693   $two_passes = 0;
694
695   # first we generate a tmpfile
696   # read file and replace <%variable%>
697   while ($_ = shift) {
698
699     $par = "";
700     $var = $_;
701
702     $two_passes = 1 if (/\\pageref/);
703
704     # { Moritz Bunkus
705     # detect pagebreak block and its parameters
706     if (/\s*<%pagebreak ([0-9]+) ([0-9]+) ([0-9]+)%>/) {
707       $chars_per_line       = $1;
708       $lines_on_first_page  = $2;
709       $lines_on_second_page = $3;
710
711       while ($_ = shift) {
712         last if (/\s*<%end pagebreak%>/);
713         $pagebreak .= $_;
714       }
715     }
716
717     # } Moritz Bunkus
718
719     if (/\s*<%foreach /) {
720
721       # this one we need for the count
722       chomp $var;
723       $var =~ s/\s*<%foreach (.+?)%>/$1/;
724       while ($_ = shift) {
725         last if (/\s*<%end /);
726
727         # store line in $par
728         $par .= $_;
729       }
730
731       # display contents of $self->{number}[] array
732       for $i (0 .. $#{ $self->{$var} }) {
733
734         # { Moritz Bunkus
735         # Try to detect whether a manual page break is necessary
736         # but only if there was a <%pagebreak ...%> block before
737
738         if ($chars_per_line) {
739           my $lines =
740             int(length($self->{"description"}[$i]) / $chars_per_line + 0.95);
741           my $lpp;
742
743           my $_description = $self->{"description"}[$i];
744           while ($_description =~ /\\newline/) {
745             $lines++;
746             $_description =~ s/\\newline//;
747           }
748           $self->{"description"}[$i] =~ s/(\\newline\s?)*$//;
749
750           if ($current_page == 1) {
751             $lpp = $lines_on_first_page;
752           } else {
753             $lpp = $lines_on_second_page;
754           }
755
756           # Yes we need a manual page break -- or the user has forced one
757           if ((($current_line + $lines) > $lpp) ||
758               ($self->{"_forced_pagebreaks"} && grep(/^${current_row}$/, @{$self->{"_forced_pagebreaks"}}))) {
759             my $pb = $pagebreak;
760
761             # replace the special variables <%sumcarriedforward%>
762             # and <%lastpage%>
763
764             my $psum = $self->format_amount($myconfig, $sum, 2);
765             $pb =~ s/<%sumcarriedforward%>/$psum/g;
766             $pb =~ s/<%lastpage%>/$current_page/g;
767
768             # only "normal" variables are supported here
769             # (no <%if, no <%foreach, no <%include)
770
771             $pb =~ s/<%(.+?)%>/$self->{$1}/g;
772
773             # page break block is ready to rock
774             print(OUT $pb);
775             $current_page++;
776             $current_line = 1;
777           }
778           $current_line += $lines;
779           $current_row++;
780         }
781         $sum += $self->parse_amount($myconfig, $self->{"linetotal"}[$i]);
782
783         # } Moritz Bunkus
784
785         # don't parse par, we need it for each line
786         $_ = $par;
787         s/<%(.+?)%>/$self->{$1}[$i]/mg;
788         print OUT;
789       }
790       next;
791     }
792
793     # if not comes before if!
794     if (/\s*<%if not /) {
795
796       # check if it is not set and display
797       chop;
798       s/\s*<%if not (.+?)%>/$1/;
799
800       unless ($self->{$_}) {
801         while ($_ = shift) {
802           last if (/\s*<%end /);
803
804           # store line in $par
805           $par .= $_;
806         }
807
808         $_ = $par;
809
810       } else {
811         while ($_ = shift) {
812           last if (/\s*<%end /);
813         }
814         next;
815       }
816     }
817
818     if (/\s*<%if /) {
819
820       # check if it is set and display
821       chop;
822       s/\s*<%if (.+?)%>/$1/;
823
824       if ($self->{$_}) {
825         while ($_ = shift) {
826           last if (/\s*<%end /);
827
828           # store line in $par
829           $par .= $_;
830         }
831
832         $_ = $par;
833
834       } else {
835         while ($_ = shift) {
836           last if (/\s*<%end /);
837         }
838         next;
839       }
840     }
841
842     # check for <%include filename%>
843     if (/\s*<%include /) {
844
845       # get the filename
846       chomp $var;
847       $var =~ s/\s*<%include (.+?)%>/$1/;
848
849       # mangle filename
850       $var =~ s/(\/|\.\.)//g;
851
852       # prevent the infinite loop!
853       next if ($self->{"$var"});
854
855       open(INC, "$self->{templates}/$var")
856         or $self->error($self->cleanup . "$self->{templates}/$var : $!");
857       unshift(@_, <INC>);
858       close(INC);
859
860       $self->{"$var"} = 1;
861
862       next;
863     }
864
865     s/<%(.+?)%>/$self->{$1}/g;
866     s/<nobr><\/nobr>/&nbsp;/g;
867     print OUT;
868   }
869
870   close(OUT);
871
872   # { Moritz Bunkus
873   # Convert the tex file to postscript
874   if ($self->{format} =~ /(postscript|pdf)/) {
875
876     use Cwd;
877     $self->{cwd}    = cwd();
878     $self->{tmpdir} = "$self->{cwd}/$userspath";
879
880     chdir("$userspath") or $self->error($self->cleanup . "chdir : $!");
881
882     $self->{tmpfile} =~ s/$userspath\///g;
883
884     if ($self->{format} eq 'postscript') {
885       system(
886         "latex --interaction=nonstopmode $self->{tmpfile} > $self->{tmpfile}.err"
887       );
888       $self->error($self->cleanup) if ($?);
889       if ($two_passes) {
890         system(
891           "latex --interaction=nonstopmode $self->{tmpfile} > $self->{tmpfile}.err"
892         );
893         $self->error($self->cleanup) if ($?);
894       }
895
896       $self->{tmpfile} =~ s/tex$/dvi/;
897
898       system("dvips $self->{tmpfile} -o -q > /dev/null");
899       $self->error($self->cleanup . "dvips : $!") if ($?);
900       $self->{tmpfile} =~ s/dvi$/ps/;
901     }
902     if ($self->{format} eq 'pdf') {
903       system(
904         "pdflatex --interaction=nonstopmode $self->{tmpfile} > $self->{tmpfile}.err"
905       );
906       $self->error($self->cleanup) if ($?);
907       if ($two_passes) {
908         system(
909           "pdflatex --interaction=nonstopmode $self->{tmpfile} > $self->{tmpfile}.err"
910         );
911         $self->error($self->cleanup) if ($?);
912       }
913       $self->{tmpfile} =~ s/tex$/pdf/;
914     }
915
916   }
917
918   if ($self->{format} =~ /(postscript|pdf)/ || $self->{media} eq 'email') {
919
920     if ($self->{media} eq 'email') {
921
922       use SL::Mailer;
923
924       my $mail = new Mailer;
925
926       map { $mail->{$_} = $self->{$_} }
927         qw(cc bcc subject message version format charset);
928       $mail->{to}     = qq|$self->{email}|;
929       $mail->{from}   = qq|"$myconfig->{name}" <$myconfig->{email}>|;
930       $mail->{fileid} = "$fileid.";
931
932       # if we send html or plain text inline
933       if (($self->{format} eq 'html') && ($self->{sendmode} eq 'inline')) {
934         $mail->{contenttype} = "text/html";
935
936         $mail->{message}       =~ s/\r\n/<br>\n/g;
937         $myconfig->{signature} =~ s/\\n/<br>\n/g;
938         $mail->{message} .= "<br>\n--<br>\n$myconfig->{signature}\n<br>";
939
940         open(IN, $self->{tmpfile})
941           or $self->error($self->cleanup . "$self->{tmpfile} : $!");
942         while (<IN>) {
943           $mail->{message} .= $_;
944         }
945
946         close(IN);
947
948       } else {
949
950         @{ $mail->{attachments} } = ($self->{tmpfile});
951
952         $myconfig->{signature} =~ s/\\n/\r\n/g;
953         $mail->{message} .= "\r\n--\r\n$myconfig->{signature}";
954
955       }
956
957       my $err = $mail->send($out);
958       $self->error($self->cleanup . "$err") if ($err);
959
960     } else {
961
962       $self->{OUT} = $out;
963
964       my $numbytes = (-s $self->{tmpfile});
965       open(IN, $self->{tmpfile})
966         or $self->error($self->cleanup . "$self->{tmpfile} : $!");
967
968       $self->{copies} = 1 unless $self->{media} eq 'printer';
969
970       chdir("$self->{cwd}");
971
972       for my $i (1 .. $self->{copies}) {
973         if ($self->{OUT}) {
974           open(OUT, $self->{OUT})
975             or $self->error($self->cleanup . "$self->{OUT} : $!");
976         } else {
977
978           # launch application
979           print qq|Content-Type: application/$self->{format}
980 Content-Disposition: attachment; filename="$self->{tmpfile}"
981 Content-Length: $numbytes
982
983 |;
984
985           open(OUT, ">-") or $self->error($self->cleanup . "$!: STDOUT");
986
987         }
988
989         while (<IN>) {
990           print OUT $_;
991         }
992
993         close(OUT);
994
995         seek IN, 0, 0;
996       }
997
998       close(IN);
999     }
1000
1001     $self->cleanup;
1002
1003   }
1004
1005   chdir("$self->{cwd}");
1006   $main::lxdebug->leave_sub();
1007 }
1008
1009 sub cleanup {
1010   $main::lxdebug->enter_sub();
1011
1012   my $self = shift;
1013
1014   chdir("$self->{tmpdir}");
1015
1016   my @err = ();
1017   if (-f "$self->{tmpfile}.err") {
1018     open(FH, "$self->{tmpfile}.err");
1019     @err = <FH>;
1020     close(FH);
1021   }
1022
1023   if ($self->{tmpfile}) {
1024
1025     # strip extension
1026     $self->{tmpfile} =~ s/\.\w+$//g;
1027     my $tmpfile = $self->{tmpfile};
1028     unlink(<$tmpfile.*>);
1029   }
1030
1031   chdir("$self->{cwd}");
1032
1033   $main::lxdebug->leave_sub();
1034
1035   return "@err";
1036 }
1037
1038 sub format_string {
1039   $main::lxdebug->enter_sub();
1040
1041   my ($self, @fields) = @_;
1042   my %unique_fields;
1043
1044   %unique_fields = map({ $_ => 1 } @fields);
1045   @fields = keys(%unique_fields);
1046
1047   foreach my $field (@fields) {
1048     next unless ($self->{$field} =~ /\<pagebreak\>/);
1049     $self->{$field} =~ s/\<pagebreak\>//g;
1050     if ($field =~ /.*_(\d+)$/) {
1051       if (!$self->{"_forced_pagebreaks"}) {
1052         $self->{"_forced_pagebreaks"} = [];
1053       }
1054       push(@{ $self->{"_forced_pagebreaks"} }, "$1");
1055     }
1056   }
1057
1058   my $format = $self->{format};
1059   if ($self->{format} =~ /(postscript|pdf)/) {
1060     $format = 'tex';
1061   }
1062
1063   my %replace = (
1064     'order' => {
1065       'html' => [
1066         '<', '>', quotemeta('\n'), '
1067 '
1068       ],
1069       'tex' => [
1070         '&', quotemeta('\n'), '
1071 ',
1072         '"', '\$', '%', '_', '#', quotemeta('^'),
1073         '{', '}',  '<', '>', '£', "\r"
1074       ]
1075     },
1076     'html' => {
1077       '<'             => '&lt;',
1078       '>'             => '&gt;',
1079       quotemeta('\n') => '<br>',
1080       '
1081 ' => '<br>'
1082     },
1083     'tex' => {
1084       '"'             => "''",
1085       '&'             => '\&',
1086       '\$'            => '\$',
1087       '%'             => '\%',
1088       '_'             => '\_',
1089       '#'             => '\#',
1090       quotemeta('^')  => '\^\\',
1091       '{'             => '\{',
1092       '}'             => '\}',
1093       '<'             => '$<$',
1094       '>'             => '$>$',
1095       quotemeta('\n') => '\newline ',
1096       '
1097 '          => '\newline ',
1098       '£'  => '\pounds ',
1099       "\r" => ""
1100     });
1101
1102   foreach my $key (@{ $replace{order}{$format} }) {
1103     map { $self->{$_} =~ s/$key/$replace{$format}{$key}/g; } @fields;
1104   }
1105
1106   # Allow some HTML markup to be converted into the output format's
1107   # corresponding markup code, e.g. bold or italic.
1108   if ('html' eq $format) {
1109     my @markup_replace = ('b', 'i', 's', 'u');
1110
1111     foreach my $key (@markup_replace) {
1112       map({ $self->{$_} =~ s/\&lt;(\/?)${key}\&gt;/<$1${key}>/g } @fields);
1113     }
1114
1115   } elsif ('tex' eq $format) {
1116     my %markup_replace = ('b' => 'textbf',
1117                           'i' => 'textit',
1118                           'u' => 'underline');
1119
1120     foreach my $field (@fields) {
1121       foreach my $key (keys(%markup_replace)) {
1122         my $new = $markup_replace{$key};
1123         $self->{$field} =~
1124           s/\$\<\$${key}\$\>\$(.*?)\$<\$\/${key}\$>\$/\\${new}\{$1\}/gi;
1125       }
1126     }
1127   }
1128
1129   $main::lxdebug->leave_sub();
1130 }
1131
1132 sub datetonum {
1133   $main::lxdebug->enter_sub();
1134
1135   my ($self, $date, $myconfig) = @_;
1136
1137   if ($date && $date =~ /\D/) {
1138
1139     if ($myconfig->{dateformat} =~ /^yy/) {
1140       ($yy, $mm, $dd) = split /\D/, $date;
1141     }
1142     if ($myconfig->{dateformat} =~ /^mm/) {
1143       ($mm, $dd, $yy) = split /\D/, $date;
1144     }
1145     if ($myconfig->{dateformat} =~ /^dd/) {
1146       ($dd, $mm, $yy) = split /\D/, $date;
1147     }
1148
1149     $dd *= 1;
1150     $mm *= 1;
1151     $yy = ($yy < 70) ? $yy + 2000 : $yy;
1152     $yy = ($yy >= 70 && $yy <= 99) ? $yy + 1900 : $yy;
1153
1154     $dd = "0$dd" if ($dd < 10);
1155     $mm = "0$mm" if ($mm < 10);
1156
1157     $date = "$yy$mm$dd";
1158   }
1159
1160   $main::lxdebug->leave_sub();
1161
1162   return $date;
1163 }
1164
1165 # Database routines used throughout
1166
1167 sub dbconnect {
1168   $main::lxdebug->enter_sub();
1169
1170   my ($self, $myconfig) = @_;
1171
1172   # connect to database
1173   my $dbh =
1174     DBI->connect($myconfig->{dbconnect},
1175                  $myconfig->{dbuser}, $myconfig->{dbpasswd})
1176     or $self->dberror;
1177
1178   # set db options
1179   if ($myconfig->{dboptions}) {
1180     $dbh->do($myconfig->{dboptions}) || $self->dberror($myconfig->{dboptions});
1181   }
1182
1183   $main::lxdebug->leave_sub();
1184
1185   return $dbh;
1186 }
1187
1188 sub dbconnect_noauto {
1189   $main::lxdebug->enter_sub();
1190
1191   my ($self, $myconfig) = @_;
1192
1193   # connect to database
1194   $dbh =
1195     DBI->connect($myconfig->{dbconnect}, $myconfig->{dbuser},
1196                  $myconfig->{dbpasswd}, { AutoCommit => 0 })
1197     or $self->dberror;
1198
1199   # set db options
1200   if ($myconfig->{dboptions}) {
1201     $dbh->do($myconfig->{dboptions}) || $self->dberror($myconfig->{dboptions});
1202   }
1203
1204   $main::lxdebug->leave_sub();
1205
1206   return $dbh;
1207 }
1208
1209 sub update_balance {
1210   $main::lxdebug->enter_sub();
1211
1212   my ($self, $dbh, $table, $field, $where, $value) = @_;
1213
1214   # if we have a value, go do it
1215   if ($value != 0) {
1216
1217     # retrieve balance from table
1218     my $query = "SELECT $field FROM $table WHERE $where FOR UPDATE";
1219     my $sth   = $dbh->prepare($query);
1220
1221     $sth->execute || $self->dberror($query);
1222     my ($balance) = $sth->fetchrow_array;
1223     $sth->finish;
1224
1225     $balance += $value;
1226
1227     # update balance
1228     $query = "UPDATE $table SET $field = $balance WHERE $where";
1229     $dbh->do($query) || $self->dberror($query);
1230   }
1231   $main::lxdebug->leave_sub();
1232 }
1233
1234 sub update_exchangerate {
1235   $main::lxdebug->enter_sub();
1236
1237   my ($self, $dbh, $curr, $transdate, $buy, $sell) = @_;
1238
1239   # some sanity check for currency
1240   if ($curr eq '') {
1241     $main::lxdebug->leave_sub();
1242     return;
1243   }
1244
1245   my $query = qq|SELECT e.curr FROM exchangerate e
1246                  WHERE e.curr = '$curr'
1247                  AND e.transdate = '$transdate'
1248                  FOR UPDATE|;
1249   my $sth = $dbh->prepare($query);
1250   $sth->execute || $self->dberror($query);
1251
1252   my $set;
1253   if ($buy != 0 && $sell != 0) {
1254     $set = "buy = $buy, sell = $sell";
1255   } elsif ($buy != 0) {
1256     $set = "buy = $buy";
1257   } elsif ($sell != 0) {
1258     $set = "sell = $sell";
1259   }
1260
1261   if ($sth->fetchrow_array) {
1262     $query = qq|UPDATE exchangerate
1263                 SET $set
1264                 WHERE curr = '$curr'
1265                 AND transdate = '$transdate'|;
1266   } else {
1267     $query = qq|INSERT INTO exchangerate (curr, buy, sell, transdate)
1268                 VALUES ('$curr', $buy, $sell, '$transdate')|;
1269   }
1270   $sth->finish;
1271   $dbh->do($query) || $self->dberror($query);
1272
1273   $main::lxdebug->leave_sub();
1274 }
1275
1276 sub save_exchangerate {
1277   $main::lxdebug->enter_sub();
1278
1279   my ($self, $myconfig, $currency, $transdate, $rate, $fld) = @_;
1280
1281   my $dbh = $self->dbconnect($myconfig);
1282
1283   my ($buy, $sell) = (0, 0);
1284   $buy  = $rate if $fld eq 'buy';
1285   $sell = $rate if $fld eq 'sell';
1286
1287   $self->update_exchangerate($dbh, $currency, $transdate, $buy, $sell);
1288
1289   $dbh->disconnect;
1290
1291   $main::lxdebug->leave_sub();
1292 }
1293
1294 sub get_exchangerate {
1295   $main::lxdebug->enter_sub();
1296
1297   my ($self, $dbh, $curr, $transdate, $fld) = @_;
1298   
1299   unless ($transdate) {
1300     $main::lxdebug->leave_sub();
1301     return "";
1302   }
1303
1304   my $query = qq|SELECT e.$fld FROM exchangerate e
1305                  WHERE e.curr = '$curr'
1306                  AND e.transdate = '$transdate'|;
1307   my $sth = $dbh->prepare($query);
1308   $sth->execute || $self->dberror($query);
1309
1310   my ($exchangerate) = $sth->fetchrow_array;
1311   $sth->finish;
1312
1313   $main::lxdebug->leave_sub();
1314
1315   return $exchangerate;
1316 }
1317
1318 sub check_exchangerate {
1319   $main::lxdebug->enter_sub();
1320
1321   my ($self, $myconfig, $currency, $transdate, $fld) = @_;
1322
1323   unless ($transdate) {
1324     $main::lxdebug->leave_sub();
1325     return "";
1326   }
1327
1328   my $dbh = $self->dbconnect($myconfig);
1329
1330   my $query = qq|SELECT e.$fld FROM exchangerate e
1331                  WHERE e.curr = '$currency'
1332                  AND e.transdate = '$transdate'|;
1333   my $sth = $dbh->prepare($query);
1334   $sth->execute || $self->dberror($query);
1335
1336   my ($exchangerate) = $sth->fetchrow_array;
1337   $sth->finish;
1338   $dbh->disconnect;
1339
1340   $main::lxdebug->leave_sub();
1341
1342   return $exchangerate;
1343 }
1344
1345 sub add_shipto {
1346   $main::lxdebug->enter_sub();
1347
1348   my ($self, $dbh, $id) = @_;
1349 ##LINET
1350   my $shipto;
1351   foreach
1352     my $item (qw(name department_1 department_2 street zipcode city country contact phone fax email)) {
1353     if ($self->{"shipto$item"}) {
1354       $shipto = 1 if ($self->{$item} ne $self->{"shipto$item"});
1355     }
1356     $self->{"shipto$item"} =~ s/\'/\'\'/g;
1357   }
1358
1359   if ($shipto) {
1360     my $query = qq|INSERT INTO shipto (trans_id, shiptoname, shiptodepartment_1, shiptodepartment_2, shiptostreet,
1361                    shiptozipcode, shiptocity, shiptocountry, shiptocontact,
1362                    shiptophone, shiptofax, shiptoemail) VALUES ($id,
1363                    '$self->{shiptoname}', '$self->{shiptodepartment_1}', '$self->{shiptodepartment_2}', '$self->{shiptostreet}',
1364                    '$self->{shiptozipcode}', '$self->{shiptocity}',
1365                    '$self->{shiptocountry}', '$self->{shiptocontact}',
1366                    '$self->{shiptophone}', '$self->{shiptofax}',
1367                    '$self->{shiptoemail}')|;
1368     $dbh->do($query) || $self->dberror($query);
1369   }
1370 ##/LINET
1371   $main::lxdebug->leave_sub();
1372 }
1373
1374 sub get_employee {
1375   $main::lxdebug->enter_sub();
1376
1377   my ($self, $dbh) = @_;
1378
1379   my $query = qq|SELECT e.id, e.name FROM employee e
1380                  WHERE e.login = '$self->{login}'|;
1381   my $sth = $dbh->prepare($query);
1382   $sth->execute || $self->dberror($query);
1383
1384   ($self->{employee_id}, $self->{employee}) = $sth->fetchrow_array;
1385   $self->{employee_id} *= 1;
1386
1387   $sth->finish;
1388
1389   $main::lxdebug->leave_sub();
1390 }
1391
1392 # get other contact for transaction and form - html/tex
1393 sub get_contact {
1394   $main::lxdebug->enter_sub();
1395
1396   my ($self, $dbh, $id) = @_;
1397
1398   my $query = qq|SELECT c.*
1399               FROM contacts c
1400               WHERE cp_id=$id|;
1401   $sth = $dbh->prepare($query);
1402   $sth->execute || $self->dberror($query);
1403
1404   $ref = $sth->fetchrow_hashref(NAME_lc);
1405
1406   push @{ $self->{$_} }, $ref;
1407
1408   $sth->finish;
1409   $main::lxdebug->leave_sub();
1410 }
1411
1412 # get contacts for id, if no contact return {"","","","",""}
1413 sub get_contacts {
1414   $main::lxdebug->enter_sub();
1415
1416   my ($self, $dbh, $id) = @_;
1417
1418   my $query = qq|SELECT c.cp_id, c.cp_cv_id, c.cp_name, c.cp_givenname
1419               FROM contacts c
1420               WHERE cp_cv_id=$id|;
1421   my $sth = $dbh->prepare($query);
1422   $sth->execute || $self->dberror($query);
1423
1424   my $i = 0;
1425   while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
1426     push @{ $self->{all_contacts} }, $ref;
1427     $i++;
1428   }
1429
1430   if ($i == 0) {
1431     push @{ $self->{all_contacts} }, { { "", "", "", "", "" } };
1432   }
1433   $sth->finish;
1434   $main::lxdebug->leave_sub();
1435 }
1436
1437 # this sub gets the id and name from $table
1438 sub get_name {
1439   $main::lxdebug->enter_sub();
1440
1441   my ($self, $myconfig, $table) = @_;
1442
1443   # connect to database
1444   my $dbh = $self->dbconnect($myconfig);
1445
1446   my $name           = $self->like(lc $self->{$table});
1447   my $customernumber = $self->like(lc $self->{customernumber});
1448
1449   if ($self->{customernumber} ne "") {
1450     $query = qq~SELECT c.id, c.name,
1451                   c.street || ' ' || c.zipcode || ' ' || c.city || ' ' || c.country AS address
1452                   FROM $table c
1453                   WHERE (lower(c.customernumber) LIKE '$customernumber') AND (not c.obsolete)
1454                   ORDER BY c.name~;
1455   } else {
1456     $query = qq~SELECT c.id, c.name,
1457                  c.street || ' ' || c.zipcode || ' ' || c.city || ' ' || c.country AS address
1458                  FROM $table c
1459                  WHERE (lower(c.name) LIKE '$name') AND (not c.obsolete)
1460                  ORDER BY c.name~;
1461   }
1462
1463   if ($self->{openinvoices}) {
1464     $query = qq~SELECT DISTINCT c.id, c.name,
1465                 c.street || ' ' || c.zipcode || ' ' || c.city || ' ' || c.country AS address
1466                 FROM $self->{arap} a
1467                 JOIN $table c ON (a.${table}_id = c.id)
1468                 WHERE NOT a.amount = a.paid
1469                 AND lower(c.name) LIKE '$name'
1470                 ORDER BY c.name~;
1471   }
1472   my $sth = $dbh->prepare($query);
1473
1474   $sth->execute || $self->dberror($query);
1475
1476   my $i = 0;
1477   while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
1478     push(@{ $self->{name_list} }, $ref);
1479     $i++;
1480   }
1481   $sth->finish;
1482   $dbh->disconnect;
1483
1484   $main::lxdebug->leave_sub();
1485
1486   return $i;
1487 }
1488
1489 # the selection sub is used in the AR, AP, IS, IR and OE module
1490 #
1491 sub all_vc {
1492   $main::lxdebug->enter_sub();
1493
1494   my ($self, $myconfig, $table, $module) = @_;
1495
1496   my $ref;
1497   my $dbh = $self->dbconnect($myconfig);
1498
1499   my $query = qq|SELECT count(*) FROM $table|;
1500   my $sth   = $dbh->prepare($query);
1501   $sth->execute || $self->dberror($query);
1502   my ($count) = $sth->fetchrow_array;
1503   $sth->finish;
1504
1505   # build selection list
1506   if ($count < $myconfig->{vclimit}) {
1507     $query = qq|SELECT id, name
1508                 FROM $table WHERE not obsolete
1509                 ORDER BY name|;
1510     $sth = $dbh->prepare($query);
1511     $sth->execute || $self->dberror($query);
1512
1513     while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
1514       push @{ $self->{"all_$table"} }, $ref;
1515     }
1516
1517     $sth->finish;
1518
1519   }
1520
1521   # get self
1522   $self->get_employee($dbh);
1523
1524   # setup sales contacts
1525   $query = qq|SELECT e.id, e.name
1526               FROM employee e
1527               WHERE e.sales = '1'
1528               AND NOT e.id = $self->{employee_id}|;
1529   $sth = $dbh->prepare($query);
1530   $sth->execute || $self->dberror($query);
1531
1532   while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
1533     push @{ $self->{all_employees} }, $ref;
1534   }
1535   $sth->finish;
1536
1537   # this is for self
1538   push @{ $self->{all_employees} },
1539     { id   => $self->{employee_id},
1540       name => $self->{employee} };
1541
1542   # sort the whole thing
1543   @{ $self->{all_employees} } =
1544     sort { $a->{name} cmp $b->{name} } @{ $self->{all_employees} };
1545
1546   if ($module eq 'AR') {
1547
1548     # prepare query for departments
1549     $query = qq|SELECT d.id, d.description
1550                 FROM department d
1551                 WHERE d.role = 'P'
1552                 ORDER BY 2|;
1553
1554   } else {
1555     $query = qq|SELECT d.id, d.description
1556                 FROM department d
1557                 ORDER BY 2|;
1558   }
1559
1560   $sth = $dbh->prepare($query);
1561   $sth->execute || $self->dberror($query);
1562
1563   while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
1564     push @{ $self->{all_departments} }, $ref;
1565   }
1566   $sth->finish;
1567
1568   $dbh->disconnect;
1569   $main::lxdebug->leave_sub();
1570 }
1571
1572 # this is only used for reports
1573 sub all_departments {
1574   $main::lxdebug->enter_sub();
1575
1576   my ($self, $myconfig, $table) = @_;
1577
1578   my $dbh   = $self->dbconnect($myconfig);
1579   my $where = "1 = 1";
1580
1581   if (defined $table) {
1582     if ($table eq 'customer') {
1583       $where = " d.role = 'P'";
1584     }
1585   }
1586
1587   my $query = qq|SELECT d.id, d.description
1588                  FROM department d
1589                  WHERE $where
1590                  ORDER BY 2|;
1591   my $sth = $dbh->prepare($query);
1592   $sth->execute || $self->dberror($query);
1593
1594   while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
1595     push @{ $self->{all_departments} }, $ref;
1596   }
1597   $sth->finish;
1598
1599   $dbh->disconnect;
1600
1601   $main::lxdebug->leave_sub();
1602 }
1603
1604 sub create_links {
1605   $main::lxdebug->enter_sub();
1606
1607   my ($self, $module, $myconfig, $table) = @_;
1608
1609   $self->all_vc($myconfig, $table, $module);
1610
1611   # get last customers or vendors
1612   my ($query, $sth);
1613
1614   my $dbh = $self->dbconnect($myconfig);
1615
1616   my %xkeyref = ();
1617
1618   # now get the account numbers
1619   $query =
1620     qq|SELECT c.accno, c.description, c.link, c.taxkey_id
1621               FROM chart c
1622               WHERE c.link LIKE '%$module%'
1623               ORDER BY c.accno|;
1624
1625   $sth = $dbh->prepare($query);
1626   $sth->execute || $self->dberror($query);
1627
1628   $self->{accounts} = "";
1629   while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
1630
1631     foreach my $key (split /:/, $ref->{link}) {
1632       if ($key =~ /$module/) {
1633
1634         # cross reference for keys
1635         $xkeyref{ $ref->{accno} } = $key;
1636
1637         push @{ $self->{"${module}_links"}{$key} },
1638           { accno       => $ref->{accno},
1639             description => $ref->{description},
1640             taxkey      => $ref->{taxkey_id} };
1641
1642         $self->{accounts} .= "$ref->{accno} " unless $key =~ /tax/;
1643       }
1644     }
1645   }
1646   $sth->finish;
1647
1648   if (($module eq "AP") || ($module eq "AR")) {
1649
1650     # get tax rates and description
1651     $query = qq| SELECT * FROM tax t|;
1652     $sth   = $dbh->prepare($query);
1653     $sth->execute || $self->dberror($query);
1654     $form->{TAX} = ();
1655     while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
1656       push @{ $self->{TAX} }, $ref;
1657     }
1658     $sth->finish;
1659   }
1660
1661   if ($self->{id}) {
1662     my $arap = ($table eq 'customer') ? 'ar' : 'ap';
1663
1664     $query = qq|SELECT a.cp_id, a.invnumber, a.transdate,
1665                 a.${table}_id, a.datepaid, a.duedate, a.ordnumber,
1666                 a.taxincluded, a.curr AS currency, a.notes, a.intnotes,
1667                 c.name AS $table, a.department_id, d.description AS department,
1668                 a.amount AS oldinvtotal, a.paid AS oldtotalpaid,
1669                 a.employee_id, e.name AS employee, a.gldate
1670                 FROM $arap a
1671                 JOIN $table c ON (a.${table}_id = c.id)
1672                 LEFT JOIN employee e ON (e.id = a.employee_id)
1673                 LEFT JOIN department d ON (d.id = a.department_id)
1674                 WHERE a.id = $self->{id}|;
1675     $sth = $dbh->prepare($query);
1676     $sth->execute || $self->dberror($query);
1677
1678     $ref = $sth->fetchrow_hashref(NAME_lc);
1679     foreach $key (keys %$ref) {
1680       $self->{$key} = $ref->{$key};
1681     }
1682     $sth->finish;
1683
1684     # get amounts from individual entries
1685     $query = qq|SELECT c.accno, c.description, a.source, a.amount, a.memo,
1686                 a.transdate, a.cleared, a.project_id, p.projectnumber, a.taxkey, t.rate
1687                 FROM acc_trans a
1688                 JOIN chart c ON (c.id = a.chart_id)
1689                 LEFT JOIN project p ON (p.id = a.project_id)
1690                 LEFT Join tax t ON (a.taxkey = t.taxkey)
1691                 WHERE a.trans_id = $self->{id}
1692                 AND a.fx_transaction = '0'
1693                 ORDER BY a.oid,a.transdate|;
1694     $sth = $dbh->prepare($query);
1695     $sth->execute || $self->dberror($query);
1696
1697     my $fld = ($table eq 'customer') ? 'buy' : 'sell';
1698
1699     # get exchangerate for currency
1700     $self->{exchangerate} =
1701       $self->get_exchangerate($dbh, $self->{currency}, $self->{transdate},
1702                               $fld);
1703     my $index=0;
1704
1705     # store amounts in {acc_trans}{$key} for multiple accounts
1706     while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
1707       $ref->{exchangerate} =
1708         $self->get_exchangerate($dbh, $self->{currency}, $ref->{transdate},
1709                                 $fld);
1710       if ( !($xkeyref{ $ref->{accno} } =~ /tax/)) {
1711         $index++;
1712       }
1713       $ref->{index} = $index;
1714
1715       push @{ $self->{acc_trans}{ $xkeyref{ $ref->{accno} } } }, $ref;
1716     }
1717     $sth->finish;
1718
1719     $query = qq|SELECT d.curr AS currencies, d.closedto, d.revtrans,
1720                   (SELECT c.accno FROM chart c
1721                    WHERE d.fxgain_accno_id = c.id) AS fxgain_accno,
1722                   (SELECT c.accno FROM chart c
1723                    WHERE d.fxloss_accno_id = c.id) AS fxloss_accno
1724                 FROM defaults d|;
1725     $sth = $dbh->prepare($query);
1726     $sth->execute || $self->dberror($query);
1727
1728     $ref = $sth->fetchrow_hashref(NAME_lc);
1729     map { $self->{$_} = $ref->{$_} } keys %$ref;
1730     $sth->finish;
1731
1732   } else {
1733
1734     # get date
1735     $query = qq|SELECT current_date AS transdate,
1736                 d.curr AS currencies, d.closedto, d.revtrans,
1737                   (SELECT c.accno FROM chart c
1738                    WHERE d.fxgain_accno_id = c.id) AS fxgain_accno,
1739                   (SELECT c.accno FROM chart c
1740                    WHERE d.fxloss_accno_id = c.id) AS fxloss_accno
1741                 FROM defaults d|;
1742     $sth = $dbh->prepare($query);
1743     $sth->execute || $self->dberror($query);
1744
1745     $ref = $sth->fetchrow_hashref(NAME_lc);
1746     map { $self->{$_} = $ref->{$_} } keys %$ref;
1747     $sth->finish;
1748
1749     if ($self->{"$self->{vc}_id"}) {
1750
1751       # only setup currency
1752       ($self->{currency}) = split /:/, $self->{currencies};
1753
1754     } else {
1755
1756       $self->lastname_used($dbh, $myconfig, $table, $module);
1757
1758       my $fld = ($table eq 'customer') ? 'buy' : 'sell';
1759
1760       # get exchangerate for currency
1761       $self->{exchangerate} =
1762         $self->get_exchangerate($dbh, $self->{currency}, $self->{transdate},
1763                                 $fld);
1764
1765     }
1766
1767   }
1768
1769   $dbh->disconnect;
1770
1771   $main::lxdebug->leave_sub();
1772 }
1773
1774 sub lastname_used {
1775   $main::lxdebug->enter_sub();
1776
1777   my ($self, $dbh, $myconfig, $table, $module) = @_;
1778
1779   my $arap  = ($table eq 'customer') ? "ar" : "ap";
1780   my $where = "1 = 1";
1781
1782   if ($self->{type} =~ /_order/) {
1783     $arap  = 'oe';
1784     $where = "quotation = '0'";
1785   }
1786   if ($self->{type} =~ /_quotation/) {
1787     $arap  = 'oe';
1788     $where = "quotation = '1'";
1789   }
1790
1791   my $query = qq|SELECT MAX(id) FROM $arap
1792                               WHERE $where
1793                               AND ${table}_id > 0|;
1794   my $sth = $dbh->prepare($query);
1795   $sth->execute || $self->dberror($query);
1796
1797   my ($trans_id) = $sth->fetchrow_array;
1798   $sth->finish;
1799
1800   $trans_id *= 1;
1801   $query = qq|SELECT ct.name, a.curr, a.${table}_id,
1802               current_date + ct.terms AS duedate, a.department_id,
1803               d.description AS department
1804               FROM $arap a
1805               JOIN $table ct ON (a.${table}_id = ct.id)
1806               LEFT JOIN department d ON (a.department_id = d.id)
1807               WHERE a.id = $trans_id|;
1808   $sth = $dbh->prepare($query);
1809   $sth->execute || $self->dberror($query);
1810
1811   ($self->{$table},  $self->{currency},      $self->{"${table}_id"},
1812    $self->{duedate}, $self->{department_id}, $self->{department})
1813     = $sth->fetchrow_array;
1814   $sth->finish;
1815
1816   $main::lxdebug->leave_sub();
1817 }
1818
1819 sub current_date {
1820   $main::lxdebug->enter_sub();
1821
1822   my ($self, $myconfig, $thisdate, $days) = @_;
1823
1824   my $dbh = $self->dbconnect($myconfig);
1825   my ($sth, $query);
1826
1827   $days *= 1;
1828   if ($thisdate) {
1829     my $dateformat = $myconfig->{dateformat};
1830     $dateformat .= "yy" if $myconfig->{dateformat} !~ /^y/;
1831
1832     $query = qq|SELECT to_date('$thisdate', '$dateformat') + $days AS thisdate
1833                 FROM defaults|;
1834     $sth = $dbh->prepare($query);
1835     $sth->execute || $self->dberror($query);
1836   } else {
1837     $query = qq|SELECT current_date AS thisdate
1838                 FROM defaults|;
1839     $sth = $dbh->prepare($query);
1840     $sth->execute || $self->dberror($query);
1841   }
1842
1843   ($thisdate) = $sth->fetchrow_array;
1844   $sth->finish;
1845
1846   $dbh->disconnect;
1847
1848   $main::lxdebug->leave_sub();
1849
1850   return $thisdate;
1851 }
1852
1853 sub like {
1854   $main::lxdebug->enter_sub();
1855
1856   my ($self, $string) = @_;
1857
1858   if ($string !~ /%/) {
1859     $string = "%$string%";
1860   }
1861
1862   $string =~ s/\'/\'\'/g;
1863
1864   $main::lxdebug->leave_sub();
1865
1866   return $string;
1867 }
1868
1869 sub redo_rows {
1870   $main::lxdebug->enter_sub();
1871
1872   my ($self, $flds, $new, $count, $numrows) = @_;
1873
1874   my @ndx = ();
1875
1876   map { push @ndx, { num => $new->[$_ - 1]->{runningnumber}, ndx => $_ } }
1877     (1 .. $count);
1878
1879   my $i = 0;
1880
1881   # fill rows
1882   foreach my $item (sort { $a->{num} <=> $b->{num} } @ndx) {
1883     $i++;
1884     $j = $item->{ndx} - 1;
1885     map { $self->{"${_}_$i"} = $new->[$j]->{$_} } @{$flds};
1886   }
1887
1888   # delete empty rows
1889   for $i ($count + 1 .. $numrows) {
1890     map { delete $self->{"${_}_$i"} } @{$flds};
1891   }
1892
1893   $main::lxdebug->leave_sub();
1894 }
1895
1896 sub update_status {
1897   $main::lxdebug->enter_sub();
1898
1899   my ($self, $myconfig) = @_;
1900
1901   my ($i, $id);
1902
1903   my $dbh = $self->dbconnect_noauto($myconfig);
1904
1905   my $query = qq|DELETE FROM status
1906                  WHERE formname = '$self->{formname}'
1907                  AND trans_id = ?|;
1908   my $sth = $dbh->prepare($query) || $self->dberror($query);
1909
1910   if ($self->{formname} =~ /(check|receipt)/) {
1911     for $i (1 .. $self->{rowcount}) {
1912       $sth->execute($self->{"id_$i"} * 1) || $self->dberror($query);
1913       $sth->finish;
1914     }
1915   } else {
1916     $sth->execute($self->{id}) || $self->dberror($query);
1917     $sth->finish;
1918   }
1919
1920   my $printed = ($self->{printed} =~ /$self->{formname}/) ? "1" : "0";
1921   my $emailed = ($self->{emailed} =~ /$self->{formname}/) ? "1" : "0";
1922
1923   my %queued = split / /, $self->{queued};
1924
1925   if ($self->{formname} =~ /(check|receipt)/) {
1926
1927     # this is a check or receipt, add one entry for each lineitem
1928     my ($accno) = split /--/, $self->{account};
1929     $query = qq|INSERT INTO status (trans_id, printed, spoolfile, formname,
1930                 chart_id) VALUES (?, '$printed',
1931                 '$queued{$self->{formname}}', '$self->{prinform}',
1932                 (SELECT c.id FROM chart c WHERE c.accno = '$accno'))|;
1933     $sth = $dbh->prepare($query) || $self->dberror($query);
1934
1935     for $i (1 .. $self->{rowcount}) {
1936       if ($self->{"checked_$i"}) {
1937         $sth->execute($self->{"id_$i"}) || $self->dberror($query);
1938         $sth->finish;
1939       }
1940     }
1941   } else {
1942     $query = qq|INSERT INTO status (trans_id, printed, emailed,
1943                 spoolfile, formname)
1944                 VALUES ($self->{id}, '$printed', '$emailed',
1945                 '$queued{$self->{formname}}', '$self->{formname}')|;
1946     $dbh->do($query) || $self->dberror($query);
1947   }
1948
1949   $dbh->commit;
1950   $dbh->disconnect;
1951
1952   $main::lxdebug->leave_sub();
1953 }
1954
1955 sub save_status {
1956   $main::lxdebug->enter_sub();
1957
1958   my ($self, $dbh) = @_;
1959
1960   my ($query, $printed, $emailed);
1961
1962   my $formnames  = $self->{printed};
1963   my $emailforms = $self->{emailed};
1964
1965   my $query = qq|DELETE FROM status
1966                  WHERE formname = '$self->{formname}'
1967                  AND trans_id = $self->{id}|;
1968   $dbh->do($query) || $self->dberror($query);
1969
1970   # this only applies to the forms
1971   # checks and receipts are posted when printed or queued
1972
1973   if ($self->{queued}) {
1974     my %queued = split / /, $self->{queued};
1975
1976     foreach my $formname (keys %queued) {
1977       $printed = ($self->{printed} =~ /$self->{formname}/) ? "1" : "0";
1978       $emailed = ($self->{emailed} =~ /$self->{formname}/) ? "1" : "0";
1979
1980       $query = qq|INSERT INTO status (trans_id, printed, emailed,
1981                   spoolfile, formname)
1982                   VALUES ($self->{id}, '$printed', '$emailed',
1983                   '$queued{$formname}', '$formname')|;
1984       $dbh->do($query) || $self->dberror($query);
1985
1986       $formnames  =~ s/$self->{formname}//;
1987       $emailforms =~ s/$self->{formname}//;
1988
1989     }
1990   }
1991
1992   # save printed, emailed info
1993   $formnames  =~ s/^ +//g;
1994   $emailforms =~ s/^ +//g;
1995
1996   my %status = ();
1997   map { $status{$_}{printed} = 1 } split / +/, $formnames;
1998   map { $status{$_}{emailed} = 1 } split / +/, $emailforms;
1999
2000   foreach my $formname (keys %status) {
2001     $printed = ($formnames  =~ /$self->{formname}/) ? "1" : "0";
2002     $emailed = ($emailforms =~ /$self->{formname}/) ? "1" : "0";
2003
2004     $query = qq|INSERT INTO status (trans_id, printed, emailed, formname)
2005                 VALUES ($self->{id}, '$printed', '$emailed', '$formname')|;
2006     $dbh->do($query) || $self->dberror($query);
2007   }
2008
2009   $main::lxdebug->leave_sub();
2010 }
2011
2012 sub update_defaults {
2013   $main::lxdebug->enter_sub();
2014
2015   my ($self, $myconfig, $fld) = @_;
2016
2017   my $dbh   = $self->dbconnect_noauto($myconfig);
2018   my $query = qq|SELECT $fld FROM defaults FOR UPDATE|;
2019   my $sth   = $dbh->prepare($query);
2020
2021   $sth->execute || $self->dberror($query);
2022   my ($var) = $sth->fetchrow_array;
2023   $sth->finish;
2024
2025   $var++;
2026
2027   $query = qq|UPDATE defaults
2028               SET $fld = '$var'|;
2029   $dbh->do($query) || $form->dberror($query);
2030
2031   $dbh->commit;
2032   $dbh->disconnect;
2033
2034   $main::lxdebug->leave_sub();
2035
2036   return $var;
2037 }
2038
2039 sub update_business {
2040   $main::lxdebug->enter_sub();
2041
2042   my ($self, $myconfig, $business_id) = @_;
2043
2044   my $dbh   = $self->dbconnect_noauto($myconfig);
2045   my $query =
2046     qq|SELECT customernumberinit FROM business  WHERE id=$business_id FOR UPDATE|;
2047   my $sth = $dbh->prepare($query);
2048
2049   $sth->execute || $self->dberror($query);
2050   my ($var) = $sth->fetchrow_array;
2051   $sth->finish;
2052   if ($var ne "") {
2053     $var++;
2054   }
2055   $query = qq|UPDATE business
2056               SET customernumberinit = '$var' WHERE id=$business_id|;
2057   $dbh->do($query) || $form->dberror($query);
2058
2059   $dbh->commit;
2060   $dbh->disconnect;
2061
2062   $main::lxdebug->leave_sub();
2063
2064   return $var;
2065 }
2066
2067 sub get_salesman {
2068   $main::lxdebug->enter_sub();
2069
2070   my ($self, $myconfig, $salesman) = @_;
2071
2072   my $dbh   = $self->dbconnect($myconfig);
2073   my $query =
2074     qq|SELECT id, name FROM customer  WHERE (customernumber ilike '%$salesman%' OR name ilike '%$salesman%') AND business_id in (SELECT id from business WHERE salesman)|;
2075   my $sth = $dbh->prepare($query);
2076   $sth->execute || $self->dberror($query);
2077
2078   my $i = 0;
2079   while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
2080     push(@{ $self->{salesman_list} }, $ref);
2081     $i++;
2082   }
2083   $dbh->commit;
2084   $main::lxdebug->leave_sub();
2085
2086   return $i;
2087 }
2088
2089 sub get_partsgroup {
2090   $main::lxdebug->enter_sub();
2091
2092   my ($self, $myconfig, $p) = @_;
2093
2094   my $dbh = $self->dbconnect($myconfig);
2095
2096   my $query = qq|SELECT DISTINCT pg.id, pg.partsgroup
2097                  FROM partsgroup pg
2098                  JOIN parts p ON (p.partsgroup_id = pg.id)|;
2099
2100   if ($p->{searchitems} eq 'part') {
2101     $query .= qq|
2102                  WHERE p.inventory_accno_id > 0|;
2103   }
2104   if ($p->{searchitems} eq 'service') {
2105     $query .= qq|
2106                  WHERE p.inventory_accno_id IS NULL|;
2107   }
2108   if ($p->{searchitems} eq 'assembly') {
2109     $query .= qq|
2110                  WHERE p.assembly = '1'|;
2111   }
2112   if ($p->{searchitems} eq 'labor') {
2113     $query .= qq|
2114                  WHERE p.inventory_accno_id > 0 AND p.income_accno_id IS NULL|;
2115   }
2116
2117   $query .= qq|
2118                  ORDER BY partsgroup|;
2119
2120   if ($p->{all}) {
2121     $query = qq|SELECT id, partsgroup FROM partsgroup
2122                 ORDER BY partsgroup|;
2123   }
2124
2125   if ($p->{language_code}) {
2126     $query = qq|SELECT DISTINCT pg.id, pg.partsgroup,
2127                 t.description AS translation
2128                 FROM partsgroup pg
2129                 JOIN parts p ON (p.partsgroup_id = pg.id)
2130                 LEFT JOIN translation t ON (t.trans_id = pg.id AND t.language_code = '$p->{language_code}')
2131                 ORDER BY translation|;
2132   }
2133
2134   my $sth = $dbh->prepare($query);
2135   $sth->execute || $self->dberror($query);
2136
2137   $self->{all_partsgroup} = ();
2138   while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
2139     push @{ $self->{all_partsgroup} }, $ref;
2140   }
2141   $sth->finish;
2142   $dbh->disconnect;
2143   $main::lxdebug->leave_sub();
2144 }
2145
2146
2147 sub get_pricegroup {
2148   $main::lxdebug->enter_sub();
2149
2150   my ($self, $myconfig, $p) = @_;
2151
2152   my $dbh = $self->dbconnect($myconfig);
2153
2154   my $query = qq|SELECT p.id, p.pricegroup
2155                  FROM pricegroup p|;
2156
2157   $query .= qq|
2158                  ORDER BY pricegroup|;
2159
2160   if ($p->{all}) {
2161     $query = qq|SELECT id, pricegroup FROM pricegroup
2162                 ORDER BY pricegroup|;
2163   }
2164
2165   my $sth = $dbh->prepare($query);
2166   $sth->execute || $self->dberror($query);
2167
2168   $self->{all_pricegroup} = ();
2169   while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
2170     push @{ $self->{all_pricegroup} }, $ref;
2171   }
2172   $sth->finish;
2173   $dbh->disconnect;
2174
2175   $main::lxdebug->leave_sub();
2176 }
2177
2178
2179 sub audittrail {
2180   my ($self, $dbh, $myconfig, $audittrail) = @_;
2181   
2182 # table, $reference, $formname, $action, $id, $transdate) = @_;
2183
2184   my $query;
2185   my $rv;
2186   my $disconnect;
2187
2188   if (! $dbh) {
2189     $dbh = $self->dbconnect($myconfig);
2190     $disconnect = 1;
2191   }
2192     
2193   # if we have an id add audittrail, otherwise get a new timestamp
2194   
2195   if ($audittrail->{id}) {
2196     
2197     $query = qq|SELECT audittrail FROM defaults|;
2198     
2199     if ($dbh->selectrow_array($query)) {
2200       my ($null, $employee_id) = $self->get_employee($dbh);
2201
2202       if ($self->{audittrail} && !$myconfig) {
2203         chop $self->{audittrail};
2204         
2205         my @a = split /\|/, $self->{audittrail};
2206         my %newtrail = ();
2207         my $key;
2208         my $i;
2209         my @flds = qw(tablename reference formname action transdate);
2210
2211         # put into hash and remove dups
2212         while (@a) {
2213           $key = "$a[2]$a[3]";
2214           $i = 0;
2215           $newtrail{$key} = { map { $_ => $a[$i++] } @flds };
2216           splice @a, 0, 5;
2217         }
2218         
2219         $query = qq|INSERT INTO audittrail (trans_id, tablename, reference,
2220                     formname, action, employee_id, transdate)
2221                     VALUES ($audittrail->{id}, ?, ?,
2222                     ?, ?, $employee_id, ?)|;
2223         my $sth = $dbh->prepare($query) || $self->dberror($query);
2224
2225         foreach $key (sort { $newtrail{$a}{transdate} cmp $newtrail{$b}{transdate} } keys %newtrail) {
2226           $i = 1;
2227           for (@flds) { $sth->bind_param($i++, $newtrail{$key}{$_}) }
2228
2229           $sth->execute || $self->dberror;
2230           $sth->finish;
2231         }
2232       }
2233
2234      
2235       if ($audittrail->{transdate}) {
2236         $query = qq|INSERT INTO audittrail (trans_id, tablename, reference,
2237                     formname, action, employee_id, transdate) VALUES (
2238                     $audittrail->{id}, '$audittrail->{tablename}', |
2239                     .$dbh->quote($audittrail->{reference}).qq|,
2240                     '$audittrail->{formname}', '$audittrail->{action}',
2241                     $employee_id, '$audittrail->{transdate}')|;
2242       } else {
2243         $query = qq|INSERT INTO audittrail (trans_id, tablename, reference,
2244                     formname, action, employee_id) VALUES ($audittrail->{id},
2245                     '$audittrail->{tablename}', |
2246                     .$dbh->quote($audittrail->{reference}).qq|,
2247                     '$audittrail->{formname}', '$audittrail->{action}',
2248                     $employee_id)|;
2249       }
2250       $dbh->do($query);
2251     }
2252   } else {
2253     
2254     $query = qq|SELECT current_timestamp FROM defaults|;
2255     my ($timestamp) = $dbh->selectrow_array($query);
2256
2257     $rv = "$audittrail->{tablename}|$audittrail->{reference}|$audittrail->{formname}|$audittrail->{action}|$timestamp|";
2258   }
2259
2260   $dbh->disconnect if $disconnect;
2261   
2262   $rv;
2263   
2264 }
2265
2266 package Locale;
2267
2268 sub new {
2269   $main::lxdebug->enter_sub();
2270
2271   my ($type, $country, $NLS_file) = @_;
2272   my $self = {};
2273
2274   %self = ();
2275   if ($country && -d "locale/$country") {
2276     $self->{countrycode} = $country;
2277     eval { require "locale/$country/$NLS_file"; };
2278   }
2279
2280   $self->{NLS_file} = $NLS_file;
2281
2282   push @{ $self->{LONG_MONTH} },
2283     ("January",   "February", "March",    "April",
2284      "May ",      "June",     "July",     "August",
2285      "September", "October",  "November", "December");
2286   push @{ $self->{SHORT_MONTH} },
2287     (qw(Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec));
2288
2289   $main::lxdebug->leave_sub();
2290
2291   bless $self, $type;
2292 }
2293
2294 sub text {
2295   my ($self, $text) = @_;
2296
2297   return (exists $self{texts}{$text}) ? $self{texts}{$text} : $text;
2298 }
2299
2300 sub findsub {
2301   $main::lxdebug->enter_sub();
2302
2303   my ($self, $text) = @_;
2304
2305   if (exists $self{subs}{$text}) {
2306     $text = $self{subs}{$text};
2307   } else {
2308     if ($self->{countrycode} && $self->{NLS_file}) {
2309       Form->error(
2310          "$text not defined in locale/$self->{countrycode}/$self->{NLS_file}");
2311     }
2312   }
2313
2314   $main::lxdebug->leave_sub();
2315
2316   return $text;
2317 }
2318
2319 sub date {
2320   $main::lxdebug->enter_sub();
2321
2322   my ($self, $myconfig, $date, $longformat) = @_;
2323
2324   my $longdate  = "";
2325   my $longmonth = ($longformat) ? 'LONG_MONTH' : 'SHORT_MONTH';
2326
2327   if ($date) {
2328
2329     # get separator
2330     $spc = $myconfig->{dateformat};
2331     $spc =~ s/\w//g;
2332     $spc = substr($spc, 1, 1);
2333
2334     if ($date =~ /\D/) {
2335       if ($myconfig->{dateformat} =~ /^yy/) {
2336         ($yy, $mm, $dd) = split /\D/, $date;
2337       }
2338       if ($myconfig->{dateformat} =~ /^mm/) {
2339         ($mm, $dd, $yy) = split /\D/, $date;
2340       }
2341       if ($myconfig->{dateformat} =~ /^dd/) {
2342         ($dd, $mm, $yy) = split /\D/, $date;
2343       }
2344     } else {
2345       $date = substr($date, 2);
2346       ($yy, $mm, $dd) = ($date =~ /(..)(..)(..)/);
2347     }
2348
2349     $dd *= 1;
2350     $mm--;
2351     $yy = ($yy < 70) ? $yy + 2000 : $yy;
2352     $yy = ($yy >= 70 && $yy <= 99) ? $yy + 1900 : $yy;
2353
2354     if ($myconfig->{dateformat} =~ /^dd/) {
2355       if (defined $longformat && $longformat == 0) {
2356         $mm++;
2357         $dd = "0$dd" if ($dd < 10);
2358         $mm = "0$mm" if ($mm < 10);
2359         $longdate = "$dd$spc$mm$spc$yy";
2360       } else {
2361         $longdate = "$dd";
2362         $longdate .= ($spc eq '.') ? ". " : " ";
2363         $longdate .= &text($self, $self->{$longmonth}[$mm]) . " $yy";
2364       }
2365     } elsif ($myconfig->{dateformat} eq "yyyy-mm-dd") {
2366
2367       # Use German syntax with the ISO date style "yyyy-mm-dd" because
2368       # Lx-Office is mainly used in Germany or German speaking countries.
2369       if (defined $longformat && $longformat == 0) {
2370         $mm++;
2371         $dd = "0$dd" if ($dd < 10);
2372         $mm = "0$mm" if ($mm < 10);
2373         $longdate = "$yy-$mm-$dd";
2374       } else {
2375         $longdate = "$dd. ";
2376         $longdate .= &text($self, $self->{$longmonth}[$mm]) . " $yy";
2377       }
2378     } else {
2379       if (defined $longformat && $longformat == 0) {
2380         $mm++;
2381         $dd = "0$dd" if ($dd < 10);
2382         $mm = "0$mm" if ($mm < 10);
2383         $longdate = "$mm$spc$dd$spc$yy";
2384       } else {
2385         $longdate = &text($self, $self->{$longmonth}[$mm]) . " $dd, $yy";
2386       }
2387     }
2388
2389   }
2390
2391   $main::lxdebug->leave_sub();
2392
2393   return $longdate;
2394 }
2395
2396 sub parse_date {
2397   $main::lxdebug->enter_sub();
2398
2399   my ($self, $myconfig, $date, $longformat) = @_;
2400
2401   unless ($date) {
2402     $main::lxdebug->leave_sub();
2403     return ();
2404   }
2405
2406   # get separator
2407   $spc = $myconfig->{dateformat};
2408   $spc =~ s/\w//g;
2409   $spc = substr($spc, 1, 1);
2410
2411   if ($date =~ /\D/) {
2412     if ($myconfig->{dateformat} =~ /^yy/) {
2413       ($yy, $mm, $dd) = split /\D/, $date;
2414     } elsif ($myconfig->{dateformat} =~ /^mm/) {
2415       ($mm, $dd, $yy) = split /\D/, $date;
2416     } elsif ($myconfig->{dateformat} =~ /^dd/) {
2417       ($dd, $mm, $yy) = split /\D/, $date;
2418     }
2419   } else {
2420     $date = substr($date, 2);
2421     ($yy, $mm, $dd) = ($date =~ /(..)(..)(..)/);
2422   }
2423
2424   $dd *= 1;
2425   $mm *= 1;
2426   $yy = ($yy < 70) ? $yy + 2000 : $yy;
2427   $yy = ($yy >= 70 && $yy <= 99) ? $yy + 1900 : $yy;
2428
2429   $main::lxdebug->leave_sub();
2430   return ($yy, $mm, $dd);
2431 }
2432
2433 1;