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