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