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