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