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