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