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