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