format_amount an die neue round_amount angepasst, so dass wieder nachkommstellen...
[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   $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   $main::lxdebug->leave_sub();
1074 }
1075
1076 sub datetonum {
1077   $main::lxdebug->enter_sub();
1078
1079   my ($self, $date, $myconfig) = @_;
1080
1081   if ($date && $date =~ /\D/) {
1082
1083     if ($myconfig->{dateformat} =~ /^yy/) {
1084       ($yy, $mm, $dd) = split /\D/, $date;
1085     }
1086     if ($myconfig->{dateformat} =~ /^mm/) {
1087       ($mm, $dd, $yy) = split /\D/, $date;
1088     }
1089     if ($myconfig->{dateformat} =~ /^dd/) {
1090       ($dd, $mm, $yy) = split /\D/, $date;
1091     }
1092
1093     $dd *= 1;
1094     $mm *= 1;
1095     $yy = ($yy < 70) ? $yy + 2000 : $yy;
1096     $yy = ($yy >= 70 && $yy <= 99) ? $yy + 1900 : $yy;
1097
1098     $dd = "0$dd" if ($dd < 10);
1099     $mm = "0$mm" if ($mm < 10);
1100
1101     $date = "$yy$mm$dd";
1102   }
1103
1104   $main::lxdebug->leave_sub();
1105
1106   return $date;
1107 }
1108
1109 # Database routines used throughout
1110
1111 sub dbconnect {
1112   $main::lxdebug->enter_sub();
1113
1114   my ($self, $myconfig) = @_;
1115
1116   # connect to database
1117   my $dbh =
1118     DBI->connect($myconfig->{dbconnect},
1119                  $myconfig->{dbuser}, $myconfig->{dbpasswd})
1120     or $self->dberror;
1121
1122   # set db options
1123   if ($myconfig->{dboptions}) {
1124     $dbh->do($myconfig->{dboptions}) || $self->dberror($myconfig->{dboptions});
1125   }
1126
1127   $main::lxdebug->leave_sub();
1128
1129   return $dbh;
1130 }
1131
1132 sub dbconnect_noauto {
1133   $main::lxdebug->enter_sub();
1134
1135   my ($self, $myconfig) = @_;
1136
1137   # connect to database
1138   $dbh =
1139     DBI->connect($myconfig->{dbconnect}, $myconfig->{dbuser},
1140                  $myconfig->{dbpasswd}, { AutoCommit => 0 })
1141     or $self->dberror;
1142
1143   # set db options
1144   if ($myconfig->{dboptions}) {
1145     $dbh->do($myconfig->{dboptions}) || $self->dberror($myconfig->{dboptions});
1146   }
1147
1148   $main::lxdebug->leave_sub();
1149
1150   return $dbh;
1151 }
1152
1153 sub update_balance {
1154   $main::lxdebug->enter_sub();
1155
1156   my ($self, $dbh, $table, $field, $where, $value) = @_;
1157
1158   # if we have a value, go do it
1159   if ($value != 0) {
1160
1161     # retrieve balance from table
1162     my $query = "SELECT $field FROM $table WHERE $where FOR UPDATE";
1163     my $sth   = $dbh->prepare($query);
1164
1165     $sth->execute || $self->dberror($query);
1166     my ($balance) = $sth->fetchrow_array;
1167     $sth->finish;
1168
1169     $balance += $value;
1170
1171     # update balance
1172     $query = "UPDATE $table SET $field = $balance WHERE $where";
1173     $dbh->do($query) || $self->dberror($query);
1174   }
1175   $main::lxdebug->leave_sub();
1176 }
1177
1178 sub update_exchangerate {
1179   $main::lxdebug->enter_sub();
1180
1181   my ($self, $dbh, $curr, $transdate, $buy, $sell) = @_;
1182
1183   # some sanity check for currency
1184   if ($curr eq '') {
1185     $main::lxdebug->leave_sub();
1186     return;
1187   }
1188
1189   my $query = qq|SELECT e.curr FROM exchangerate e
1190                  WHERE e.curr = '$curr'
1191                  AND e.transdate = '$transdate'
1192                  FOR UPDATE|;
1193   my $sth = $dbh->prepare($query);
1194   $sth->execute || $self->dberror($query);
1195
1196   my $set;
1197   if ($buy != 0 && $sell != 0) {
1198     $set = "buy = $buy, sell = $sell";
1199   } elsif ($buy != 0) {
1200     $set = "buy = $buy";
1201   } elsif ($sell != 0) {
1202     $set = "sell = $sell";
1203   }
1204
1205   if ($sth->fetchrow_array) {
1206     $query = qq|UPDATE exchangerate
1207                 SET $set
1208                 WHERE curr = '$curr'
1209                 AND transdate = '$transdate'|;
1210   } else {
1211     $query = qq|INSERT INTO exchangerate (curr, buy, sell, transdate)
1212                 VALUES ('$curr', $buy, $sell, '$transdate')|;
1213   }
1214   $sth->finish;
1215   $dbh->do($query) || $self->dberror($query);
1216
1217   $main::lxdebug->leave_sub();
1218 }
1219
1220 sub save_exchangerate {
1221   $main::lxdebug->enter_sub();
1222
1223   my ($self, $myconfig, $currency, $transdate, $rate, $fld) = @_;
1224
1225   my $dbh = $self->dbconnect($myconfig);
1226
1227   my ($buy, $sell) = (0, 0);
1228   $buy  = $rate if $fld eq 'buy';
1229   $sell = $rate if $fld eq 'sell';
1230
1231   $self->update_exchangerate($dbh, $currency, $transdate, $buy, $sell);
1232
1233   $dbh->disconnect;
1234
1235   $main::lxdebug->leave_sub();
1236 }
1237
1238 sub get_exchangerate {
1239   $main::lxdebug->enter_sub();
1240
1241   my ($self, $dbh, $curr, $transdate, $fld) = @_;
1242
1243   my $query = qq|SELECT e.$fld FROM exchangerate e
1244                  WHERE e.curr = '$curr'
1245                  AND e.transdate = '$transdate'|;
1246   my $sth = $dbh->prepare($query);
1247   $sth->execute || $self->dberror($query);
1248
1249   my ($exchangerate) = $sth->fetchrow_array;
1250   $sth->finish;
1251
1252   $main::lxdebug->leave_sub();
1253
1254   return $exchangerate;
1255 }
1256
1257 sub check_exchangerate {
1258   $main::lxdebug->enter_sub();
1259
1260   my ($self, $myconfig, $currency, $transdate, $fld) = @_;
1261
1262   unless ($transdate) {
1263     $main::lxdebug->leave_sub();
1264     return "";
1265   }
1266
1267   my $dbh = $self->dbconnect($myconfig);
1268
1269   my $query = qq|SELECT e.$fld FROM exchangerate e
1270                  WHERE e.curr = '$currency'
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   $dbh->disconnect;
1278
1279   $main::lxdebug->leave_sub();
1280
1281   return $exchangerate;
1282 }
1283
1284 sub add_shipto {
1285   $main::lxdebug->enter_sub();
1286
1287   my ($self, $dbh, $id) = @_;
1288 ##LINET
1289   my $shipto;
1290   foreach
1291     my $item (qw(name department_1 department_2 street zipcode city country contact phone fax email)) {
1292     if ($self->{"shipto$item"}) {
1293       $shipto = 1 if ($self->{$item} ne $self->{"shipto$item"});
1294     }
1295     $self->{"shipto$item"} =~ s/\'/\'\'/g;
1296   }
1297
1298   if ($shipto) {
1299     my $query = qq|INSERT INTO shipto (trans_id, shiptoname, shiptodepartment_1, shiptodepartment_2, shiptostreet,
1300                    shiptozipcode, shiptocity, shiptocountry, shiptocontact,
1301                    shiptophone, shiptofax, shiptoemail) VALUES ($id,
1302                    '$self->{shiptoname}', '$self->{shiptodepartment_1}', '$self->{shiptodepartment_2}', '$self->{shiptostreet}',
1303                    '$self->{shiptozipcode}', '$self->{shiptocity}',
1304                    '$self->{shiptocountry}', '$self->{shiptocontact}',
1305                    '$self->{shiptophone}', '$self->{shiptofax}',
1306                    '$self->{shiptoemail}')|;
1307     $dbh->do($query) || $self->dberror($query);
1308   }
1309 ##/LINET
1310   $main::lxdebug->leave_sub();
1311 }
1312
1313 sub get_employee {
1314   $main::lxdebug->enter_sub();
1315
1316   my ($self, $dbh) = @_;
1317
1318   my $query = qq|SELECT e.id, e.name FROM employee e
1319                  WHERE e.login = '$self->{login}'|;
1320   my $sth = $dbh->prepare($query);
1321   $sth->execute || $self->dberror($query);
1322
1323   ($self->{employee_id}, $self->{employee}) = $sth->fetchrow_array;
1324   $self->{employee_id} *= 1;
1325
1326   $sth->finish;
1327
1328   $main::lxdebug->leave_sub();
1329 }
1330
1331 # get other contact for transaction and form - html/tex
1332 sub get_contact {
1333   $main::lxdebug->enter_sub();
1334
1335   my ($self, $dbh, $id) = @_;
1336
1337   my $query = qq|SELECT c.*
1338               FROM contacts c
1339               WHERE cp_id=$id|;
1340   $sth = $dbh->prepare($query);
1341   $sth->execute || $self->dberror($query);
1342
1343   $ref = $sth->fetchrow_hashref(NAME_lc);
1344
1345   push @{ $self->{$_} }, $ref;
1346
1347   $sth->finish;
1348   $main::lxdebug->leave_sub();
1349 }
1350
1351 # get contacts for id, if no contact return {"","","","",""}
1352 sub get_contacts {
1353   $main::lxdebug->enter_sub();
1354
1355   my ($self, $dbh, $id) = @_;
1356
1357   my $query = qq|SELECT c.cp_id, c.cp_cv_id, c.cp_name, c.cp_givenname
1358               FROM contacts c
1359               WHERE cp_cv_id=$id|;
1360   my $sth = $dbh->prepare($query);
1361   $sth->execute || $self->dberror($query);
1362
1363   my $i = 0;
1364   while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
1365     push @{ $self->{all_contacts} }, $ref;
1366     $i++;
1367   }
1368
1369   if ($i == 0) {
1370     push @{ $self->{all_contacts} }, { { "", "", "", "", "" } };
1371   }
1372   $sth->finish;
1373   $main::lxdebug->leave_sub();
1374 }
1375
1376 # this sub gets the id and name from $table
1377 sub get_name {
1378   $main::lxdebug->enter_sub();
1379
1380   my ($self, $myconfig, $table) = @_;
1381
1382   # connect to database
1383   my $dbh = $self->dbconnect($myconfig);
1384
1385   my $name           = $self->like(lc $self->{$table});
1386   my $customernumber = $self->like(lc $self->{customernumber});
1387
1388   if ($self->{customernumber} ne "") {
1389     $query = qq~SELECT c.id, c.name,
1390                   c.street || ' ' || c.zipcode || ' ' || c.city || ' ' || c.country AS address
1391                   FROM $table c
1392                   WHERE (lower(c.customernumber) LIKE '$customernumber') AND (not c.obsolete)
1393                   ORDER BY c.name~;
1394   } else {
1395     $query = qq~SELECT c.id, c.name,
1396                  c.street || ' ' || c.zipcode || ' ' || c.city || ' ' || c.country AS address
1397                  FROM $table c
1398                  WHERE (lower(c.name) LIKE '$name') AND (not c.obsolete)
1399                  ORDER BY c.name~;
1400   }
1401
1402   if ($self->{openinvoices}) {
1403     $query = qq~SELECT DISTINCT c.id, c.name,
1404                 c.street || ' ' || c.zipcode || ' ' || c.city || ' ' || c.country AS address
1405                 FROM $self->{arap} a
1406                 JOIN $table c ON (a.${table}_id = c.id)
1407                 WHERE NOT a.amount = a.paid
1408                 AND lower(c.name) LIKE '$name'
1409                 ORDER BY c.name~;
1410   }
1411   my $sth = $dbh->prepare($query);
1412
1413   $sth->execute || $self->dberror($query);
1414
1415   my $i = 0;
1416   while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
1417     push(@{ $self->{name_list} }, $ref);
1418     $i++;
1419   }
1420   $sth->finish;
1421   $dbh->disconnect;
1422
1423   $main::lxdebug->leave_sub();
1424
1425   return $i;
1426 }
1427
1428 # the selection sub is used in the AR, AP, IS, IR and OE module
1429 #
1430 sub all_vc {
1431   $main::lxdebug->enter_sub();
1432
1433   my ($self, $myconfig, $table, $module) = @_;
1434
1435   my $ref;
1436   my $dbh = $self->dbconnect($myconfig);
1437
1438   my $query = qq|SELECT count(*) FROM $table|;
1439   my $sth   = $dbh->prepare($query);
1440   $sth->execute || $self->dberror($query);
1441   my ($count) = $sth->fetchrow_array;
1442   $sth->finish;
1443
1444   # build selection list
1445   if ($count < $myconfig->{vclimit}) {
1446     $query = qq|SELECT id, name
1447                 FROM $table WHERE not obsolete
1448                 ORDER BY name|;
1449     $sth = $dbh->prepare($query);
1450     $sth->execute || $self->dberror($query);
1451
1452     while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
1453       push @{ $self->{"all_$table"} }, $ref;
1454     }
1455
1456     $sth->finish;
1457
1458   }
1459
1460   # get self
1461   $self->get_employee($dbh);
1462
1463   # setup sales contacts
1464   $query = qq|SELECT e.id, e.name
1465               FROM employee e
1466               WHERE e.sales = '1'
1467               AND NOT e.id = $self->{employee_id}|;
1468   $sth = $dbh->prepare($query);
1469   $sth->execute || $self->dberror($query);
1470
1471   while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
1472     push @{ $self->{all_employees} }, $ref;
1473   }
1474   $sth->finish;
1475
1476   # this is for self
1477   push @{ $self->{all_employees} },
1478     { id   => $self->{employee_id},
1479       name => $self->{employee} };
1480
1481   # sort the whole thing
1482   @{ $self->{all_employees} } =
1483     sort { $a->{name} cmp $b->{name} } @{ $self->{all_employees} };
1484
1485   if ($module eq 'AR') {
1486
1487     # prepare query for departments
1488     $query = qq|SELECT d.id, d.description
1489                 FROM department d
1490                 WHERE d.role = 'P'
1491                 ORDER BY 2|;
1492
1493   } else {
1494     $query = qq|SELECT d.id, d.description
1495                 FROM department d
1496                 ORDER BY 2|;
1497   }
1498
1499   $sth = $dbh->prepare($query);
1500   $sth->execute || $self->dberror($query);
1501
1502   while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
1503     push @{ $self->{all_departments} }, $ref;
1504   }
1505   $sth->finish;
1506
1507   $dbh->disconnect;
1508   $main::lxdebug->leave_sub();
1509 }
1510
1511 # this is only used for reports
1512 sub all_departments {
1513   $main::lxdebug->enter_sub();
1514
1515   my ($self, $myconfig, $table) = @_;
1516
1517   my $dbh   = $self->dbconnect($myconfig);
1518   my $where = "1 = 1";
1519
1520   if (defined $table) {
1521     if ($table eq 'customer') {
1522       $where = " d.role = 'P'";
1523     }
1524   }
1525
1526   my $query = qq|SELECT d.id, d.description
1527                  FROM department d
1528                  WHERE $where
1529                  ORDER BY 2|;
1530   my $sth = $dbh->prepare($query);
1531   $sth->execute || $self->dberror($query);
1532
1533   while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
1534     push @{ $self->{all_departments} }, $ref;
1535   }
1536   $sth->finish;
1537
1538   $dbh->disconnect;
1539
1540   $main::lxdebug->leave_sub();
1541 }
1542
1543 sub create_links {
1544   $main::lxdebug->enter_sub();
1545
1546   my ($self, $module, $myconfig, $table) = @_;
1547
1548   $self->all_vc($myconfig, $table, $module);
1549
1550   # get last customers or vendors
1551   my ($query, $sth);
1552
1553   my $dbh = $self->dbconnect($myconfig);
1554
1555   my %xkeyref = ();
1556
1557   # now get the account numbers
1558   $query =
1559     qq|SELECT c.accno, SUBSTRING(c.description,1,50) as description, c.link, c.taxkey_id
1560               FROM chart c
1561               WHERE c.link LIKE '%$module%'
1562               ORDER BY c.accno|;
1563
1564   $sth = $dbh->prepare($query);
1565   $sth->execute || $self->dberror($query);
1566
1567   $self->{accounts} = "";
1568   while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
1569
1570     foreach my $key (split /:/, $ref->{link}) {
1571       if ($key =~ /$module/) {
1572
1573         # cross reference for keys
1574         $xkeyref{ $ref->{accno} } = $key;
1575
1576         push @{ $self->{"${module}_links"}{$key} },
1577           { accno       => $ref->{accno},
1578             description => $ref->{description},
1579             taxkey      => $ref->{taxkey_id} };
1580
1581         $self->{accounts} .= "$ref->{accno} " unless $key =~ /tax/;
1582       }
1583     }
1584   }
1585   $sth->finish;
1586
1587   if (($module eq "AP") || ($module eq "AR")) {
1588
1589     # get tax rates and description
1590     $query = qq| SELECT * FROM tax t|;
1591     $sth   = $dbh->prepare($query);
1592     $sth->execute || $self->dberror($query);
1593     $form->{TAX} = ();
1594     while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
1595       push @{ $self->{TAX} }, $ref;
1596     }
1597     $sth->finish;
1598   }
1599
1600   if ($self->{id}) {
1601     my $arap = ($table eq 'customer') ? 'ar' : 'ap';
1602
1603     $query = qq|SELECT a.cp_id, a.invnumber, a.transdate,
1604                 a.${table}_id, a.datepaid, a.duedate, a.ordnumber,
1605                 a.taxincluded, a.curr AS currency, a.notes, a.intnotes,
1606                 c.name AS $table, a.department_id, d.description AS department,
1607                 a.amount AS oldinvtotal, a.paid AS oldtotalpaid,
1608                 a.employee_id, e.name AS employee, a.gldate
1609                 FROM $arap a
1610                 JOIN $table c ON (a.${table}_id = c.id)
1611                 LEFT JOIN employee e ON (e.id = a.employee_id)
1612                 LEFT JOIN department d ON (d.id = a.department_id)
1613                 WHERE a.id = $self->{id}|;
1614     $sth = $dbh->prepare($query);
1615     $sth->execute || $self->dberror($query);
1616
1617     $ref = $sth->fetchrow_hashref(NAME_lc);
1618     foreach $key (keys %$ref) {
1619       $self->{$key} = $ref->{$key};
1620     }
1621     $sth->finish;
1622
1623     # get amounts from individual entries
1624     $query = qq|SELECT c.accno, c.description, a.source, a.amount, a.memo,
1625                 a.transdate, a.cleared, a.project_id, p.projectnumber, a.taxkey, t.rate
1626                 FROM acc_trans a
1627                 JOIN chart c ON (c.id = a.chart_id)
1628                 LEFT JOIN project p ON (p.id = a.project_id)
1629                 LEFT Join tax t ON (a.taxkey = t.taxkey)
1630                 WHERE a.trans_id = $self->{id}
1631                 AND a.fx_transaction = '0'
1632                 ORDER BY a.transdate|;
1633     $sth = $dbh->prepare($query);
1634     $sth->execute || $self->dberror($query);
1635
1636     my $fld = ($table eq 'customer') ? 'buy' : 'sell';
1637
1638     # get exchangerate for currency
1639     $self->{exchangerate} =
1640       $self->get_exchangerate($dbh, $self->{currency}, $self->{transdate},
1641                               $fld);
1642
1643     # store amounts in {acc_trans}{$key} for multiple accounts
1644     while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
1645       $ref->{exchangerate} =
1646         $self->get_exchangerate($dbh, $self->{currency}, $ref->{transdate},
1647                                 $fld);
1648
1649       push @{ $self->{acc_trans}{ $xkeyref{ $ref->{accno} } } }, $ref;
1650     }
1651     $sth->finish;
1652
1653     $query = qq|SELECT d.curr AS currencies, d.closedto, d.revtrans,
1654                   (SELECT c.accno FROM chart c
1655                    WHERE d.fxgain_accno_id = c.id) AS fxgain_accno,
1656                   (SELECT c.accno FROM chart c
1657                    WHERE d.fxloss_accno_id = c.id) AS fxloss_accno
1658                 FROM defaults d|;
1659     $sth = $dbh->prepare($query);
1660     $sth->execute || $self->dberror($query);
1661
1662     $ref = $sth->fetchrow_hashref(NAME_lc);
1663     map { $self->{$_} = $ref->{$_} } keys %$ref;
1664     $sth->finish;
1665
1666   } else {
1667
1668     # get date
1669     $query = qq|SELECT current_date AS transdate,
1670                 d.curr AS currencies, d.closedto, d.revtrans,
1671                   (SELECT c.accno FROM chart c
1672                    WHERE d.fxgain_accno_id = c.id) AS fxgain_accno,
1673                   (SELECT c.accno FROM chart c
1674                    WHERE d.fxloss_accno_id = c.id) AS fxloss_accno
1675                 FROM defaults d|;
1676     $sth = $dbh->prepare($query);
1677     $sth->execute || $self->dberror($query);
1678
1679     $ref = $sth->fetchrow_hashref(NAME_lc);
1680     map { $self->{$_} = $ref->{$_} } keys %$ref;
1681     $sth->finish;
1682
1683     if ($self->{"$self->{vc}_id"}) {
1684
1685       # only setup currency
1686       ($self->{currency}) = split /:/, $self->{currencies};
1687
1688     } else {
1689
1690       $self->lastname_used($dbh, $myconfig, $table, $module);
1691
1692       my $fld = ($table eq 'customer') ? 'buy' : 'sell';
1693
1694       # get exchangerate for currency
1695       $self->{exchangerate} =
1696         $self->get_exchangerate($dbh, $self->{currency}, $self->{transdate},
1697                                 $fld);
1698
1699     }
1700
1701   }
1702
1703   $dbh->disconnect;
1704
1705   $main::lxdebug->leave_sub();
1706 }
1707
1708 sub lastname_used {
1709   $main::lxdebug->enter_sub();
1710
1711   my ($self, $dbh, $myconfig, $table, $module) = @_;
1712
1713   my $arap  = ($table eq 'customer') ? "ar" : "ap";
1714   my $where = "1 = 1";
1715
1716   if ($self->{type} =~ /_order/) {
1717     $arap  = 'oe';
1718     $where = "quotation = '0'";
1719   }
1720   if ($self->{type} =~ /_quotation/) {
1721     $arap  = 'oe';
1722     $where = "quotation = '1'";
1723   }
1724
1725   my $query = qq|SELECT id FROM $arap
1726                  WHERE id IN (SELECT MAX(id) FROM $arap
1727                               WHERE $where
1728                               AND ${table}_id > 0)|;
1729   my $sth = $dbh->prepare($query);
1730   $sth->execute || $self->dberror($query);
1731
1732   my ($trans_id) = $sth->fetchrow_array;
1733   $sth->finish;
1734
1735   $trans_id *= 1;
1736   $query = qq|SELECT ct.name, a.curr, a.${table}_id,
1737               current_date + ct.terms AS duedate, a.department_id,
1738               d.description AS department
1739               FROM $arap a
1740               JOIN $table ct ON (a.${table}_id = ct.id)
1741               LEFT JOIN department d ON (a.department_id = d.id)
1742               WHERE a.id = $trans_id|;
1743   $sth = $dbh->prepare($query);
1744   $sth->execute || $self->dberror($query);
1745
1746   ($self->{$table},  $self->{currency},      $self->{"${table}_id"},
1747    $self->{duedate}, $self->{department_id}, $self->{department})
1748     = $sth->fetchrow_array;
1749   $sth->finish;
1750
1751   $main::lxdebug->leave_sub();
1752 }
1753
1754 sub current_date {
1755   $main::lxdebug->enter_sub();
1756
1757   my ($self, $myconfig, $thisdate, $days) = @_;
1758
1759   my $dbh = $self->dbconnect($myconfig);
1760   my ($sth, $query);
1761
1762   $days *= 1;
1763   if ($thisdate) {
1764     my $dateformat = $myconfig->{dateformat};
1765     $dateformat .= "yy" if $myconfig->{dateformat} !~ /^y/;
1766
1767     $query = qq|SELECT to_date('$thisdate', '$dateformat') + $days AS thisdate
1768                 FROM defaults|;
1769     $sth = $dbh->prepare($query);
1770     $sth->execute || $self->dberror($query);
1771   } else {
1772     $query = qq|SELECT current_date AS thisdate
1773                 FROM defaults|;
1774     $sth = $dbh->prepare($query);
1775     $sth->execute || $self->dberror($query);
1776   }
1777
1778   ($thisdate) = $sth->fetchrow_array;
1779   $sth->finish;
1780
1781   $dbh->disconnect;
1782
1783   $main::lxdebug->leave_sub();
1784
1785   return $thisdate;
1786 }
1787
1788 sub like {
1789   $main::lxdebug->enter_sub();
1790
1791   my ($self, $string) = @_;
1792
1793   if ($string !~ /%/) {
1794     $string = "%$string%";
1795   }
1796
1797   $string =~ s/\'/\'\'/g;
1798
1799   $main::lxdebug->leave_sub();
1800
1801   return $string;
1802 }
1803
1804 sub redo_rows {
1805   $main::lxdebug->enter_sub();
1806
1807   my ($self, $flds, $new, $count, $numrows) = @_;
1808
1809   my @ndx = ();
1810
1811   map { push @ndx, { num => $new->[$_ - 1]->{runningnumber}, ndx => $_ } }
1812     (1 .. $count);
1813
1814   my $i = 0;
1815
1816   # fill rows
1817   foreach my $item (sort { $a->{num} <=> $b->{num} } @ndx) {
1818     $i++;
1819     $j = $item->{ndx} - 1;
1820     map { $self->{"${_}_$i"} = $new->[$j]->{$_} } @{$flds};
1821   }
1822
1823   # delete empty rows
1824   for $i ($count + 1 .. $numrows) {
1825     map { delete $self->{"${_}_$i"} } @{$flds};
1826   }
1827
1828   $main::lxdebug->leave_sub();
1829 }
1830
1831 sub update_status {
1832   $main::lxdebug->enter_sub();
1833
1834   my ($self, $myconfig) = @_;
1835
1836   my ($i, $id);
1837
1838   my $dbh = $self->dbconnect_noauto($myconfig);
1839
1840   my $query = qq|DELETE FROM status
1841                  WHERE formname = '$self->{formname}'
1842                  AND trans_id = ?|;
1843   my $sth = $dbh->prepare($query) || $self->dberror($query);
1844
1845   if ($self->{formname} =~ /(check|receipt)/) {
1846     for $i (1 .. $self->{rowcount}) {
1847       $sth->execute($self->{"id_$i"} * 1) || $self->dberror($query);
1848       $sth->finish;
1849     }
1850   } else {
1851     $sth->execute($self->{id}) || $self->dberror($query);
1852     $sth->finish;
1853   }
1854
1855   my $printed = ($self->{printed} =~ /$self->{formname}/) ? "1" : "0";
1856   my $emailed = ($self->{emailed} =~ /$self->{formname}/) ? "1" : "0";
1857
1858   my %queued = split / /, $self->{queued};
1859
1860   if ($self->{formname} =~ /(check|receipt)/) {
1861
1862     # this is a check or receipt, add one entry for each lineitem
1863     my ($accno) = split /--/, $self->{account};
1864     $query = qq|INSERT INTO status (trans_id, printed, spoolfile, formname,
1865                 chart_id) VALUES (?, '$printed',
1866                 '$queued{$self->{formname}}', '$self->{prinform}',
1867                 (SELECT c.id FROM chart c WHERE c.accno = '$accno'))|;
1868     $sth = $dbh->prepare($query) || $self->dberror($query);
1869
1870     for $i (1 .. $self->{rowcount}) {
1871       if ($self->{"checked_$i"}) {
1872         $sth->execute($self->{"id_$i"}) || $self->dberror($query);
1873         $sth->finish;
1874       }
1875     }
1876   } else {
1877     $query = qq|INSERT INTO status (trans_id, printed, emailed,
1878                 spoolfile, formname)
1879                 VALUES ($self->{id}, '$printed', '$emailed',
1880                 '$queued{$self->{formname}}', '$self->{formname}')|;
1881     $dbh->do($query) || $self->dberror($query);
1882   }
1883
1884   $dbh->commit;
1885   $dbh->disconnect;
1886
1887   $main::lxdebug->leave_sub();
1888 }
1889
1890 sub save_status {
1891   $main::lxdebug->enter_sub();
1892
1893   my ($self, $dbh) = @_;
1894
1895   my ($query, $printed, $emailed);
1896
1897   my $formnames  = $self->{printed};
1898   my $emailforms = $self->{emailed};
1899
1900   my $query = qq|DELETE FROM status
1901                  WHERE formname = '$self->{formname}'
1902                  AND trans_id = $self->{id}|;
1903   $dbh->do($query) || $self->dberror($query);
1904
1905   # this only applies to the forms
1906   # checks and receipts are posted when printed or queued
1907
1908   if ($self->{queued}) {
1909     my %queued = split / /, $self->{queued};
1910
1911     foreach my $formname (keys %queued) {
1912       $printed = ($self->{printed} =~ /$self->{formname}/) ? "1" : "0";
1913       $emailed = ($self->{emailed} =~ /$self->{formname}/) ? "1" : "0";
1914
1915       $query = qq|INSERT INTO status (trans_id, printed, emailed,
1916                   spoolfile, formname)
1917                   VALUES ($self->{id}, '$printed', '$emailed',
1918                   '$queued{$formname}', '$formname')|;
1919       $dbh->do($query) || $self->dberror($query);
1920
1921       $formnames  =~ s/$self->{formname}//;
1922       $emailforms =~ s/$self->{formname}//;
1923
1924     }
1925   }
1926
1927   # save printed, emailed info
1928   $formnames  =~ s/^ +//g;
1929   $emailforms =~ s/^ +//g;
1930
1931   my %status = ();
1932   map { $status{$_}{printed} = 1 } split / +/, $formnames;
1933   map { $status{$_}{emailed} = 1 } split / +/, $emailforms;
1934
1935   foreach my $formname (keys %status) {
1936     $printed = ($formnames  =~ /$self->{formname}/) ? "1" : "0";
1937     $emailed = ($emailforms =~ /$self->{formname}/) ? "1" : "0";
1938
1939     $query = qq|INSERT INTO status (trans_id, printed, emailed, formname)
1940                 VALUES ($self->{id}, '$printed', '$emailed', '$formname')|;
1941     $dbh->do($query) || $self->dberror($query);
1942   }
1943
1944   $main::lxdebug->leave_sub();
1945 }
1946
1947 sub update_defaults {
1948   $main::lxdebug->enter_sub();
1949
1950   my ($self, $myconfig, $fld) = @_;
1951
1952   my $dbh   = $self->dbconnect_noauto($myconfig);
1953   my $query = qq|SELECT $fld FROM defaults FOR UPDATE|;
1954   my $sth   = $dbh->prepare($query);
1955
1956   $sth->execute || $self->dberror($query);
1957   my ($var) = $sth->fetchrow_array;
1958   $sth->finish;
1959
1960   $var++;
1961
1962   $query = qq|UPDATE defaults
1963               SET $fld = '$var'|;
1964   $dbh->do($query) || $form->dberror($query);
1965
1966   $dbh->commit;
1967   $dbh->disconnect;
1968
1969   $main::lxdebug->leave_sub();
1970
1971   return $var;
1972 }
1973
1974 sub update_business {
1975   $main::lxdebug->enter_sub();
1976
1977   my ($self, $myconfig, $business_id) = @_;
1978
1979   my $dbh   = $self->dbconnect_noauto($myconfig);
1980   my $query =
1981     qq|SELECT customernumberinit FROM business  WHERE id=$business_id FOR UPDATE|;
1982   my $sth = $dbh->prepare($query);
1983
1984   $sth->execute || $self->dberror($query);
1985   my ($var) = $sth->fetchrow_array;
1986   $sth->finish;
1987   if ($var ne "") {
1988     $var++;
1989   }
1990   $query = qq|UPDATE business
1991               SET customernumberinit = '$var' WHERE id=$business_id|;
1992   $dbh->do($query) || $form->dberror($query);
1993
1994   $dbh->commit;
1995   $dbh->disconnect;
1996
1997   $main::lxdebug->leave_sub();
1998
1999   return $var;
2000 }
2001
2002 sub get_salesman {
2003   $main::lxdebug->enter_sub();
2004
2005   my ($self, $myconfig, $salesman) = @_;
2006
2007   my $dbh   = $self->dbconnect($myconfig);
2008   my $query =
2009     qq|SELECT id, name FROM customer  WHERE (customernumber ilike '%$salesman%' OR name ilike '%$salesman%') AND business_id in (SELECT id from business WHERE salesman)|;
2010   my $sth = $dbh->prepare($query);
2011   $sth->execute || $self->dberror($query);
2012
2013   my $i = 0;
2014   while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
2015     push(@{ $self->{salesman_list} }, $ref);
2016     $i++;
2017   }
2018   $dbh->commit;
2019   $main::lxdebug->leave_sub();
2020
2021   return $i;
2022 }
2023
2024 sub get_partsgroup {
2025   $main::lxdebug->enter_sub();
2026
2027   my ($self, $myconfig, $p) = @_;
2028
2029   my $dbh = $self->dbconnect($myconfig);
2030
2031   my $query = qq|SELECT DISTINCT pg.id, pg.partsgroup
2032                  FROM partsgroup pg
2033                  JOIN parts p ON (p.partsgroup_id = pg.id)|;
2034
2035   if ($p->{searchitems} eq 'part') {
2036     $query .= qq|
2037                  WHERE p.inventory_accno_id > 0|;
2038   }
2039   if ($p->{searchitems} eq 'service') {
2040     $query .= qq|
2041                  WHERE p.inventory_accno_id IS NULL|;
2042   }
2043   if ($p->{searchitems} eq 'assembly') {
2044     $query .= qq|
2045                  WHERE p.assembly = '1'|;
2046   }
2047   if ($p->{searchitems} eq 'labor') {
2048     $query .= qq|
2049                  WHERE p.inventory_accno_id > 0 AND p.income_accno_id IS NULL|;
2050   }
2051
2052   $query .= qq|
2053                  ORDER BY partsgroup|;
2054
2055   if ($p->{all}) {
2056     $query = qq|SELECT id, partsgroup FROM partsgroup
2057                 ORDER BY partsgroup|;
2058   }
2059
2060   if ($p->{language_code}) {
2061     $query = qq|SELECT DISTINCT pg.id, pg.partsgroup,
2062                 t.description AS translation
2063                 FROM partsgroup pg
2064                 JOIN parts p ON (p.partsgroup_id = pg.id)
2065                 LEFT JOIN translation t ON (t.trans_id = pg.id AND t.language_code = '$p->{language_code}')
2066                 ORDER BY translation|;
2067   }
2068
2069   my $sth = $dbh->prepare($query);
2070   $sth->execute || $self->dberror($query);
2071
2072   $self->{all_partsgroup} = ();
2073   while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
2074     push @{ $self->{all_partsgroup} }, $ref;
2075   }
2076   $sth->finish;
2077   $dbh->disconnect;
2078   $main::lxdebug->leave_sub();
2079 }
2080
2081
2082 sub audittrail {
2083   my ($self, $dbh, $myconfig, $audittrail) = @_;
2084   
2085 # table, $reference, $formname, $action, $id, $transdate) = @_;
2086
2087   my $query;
2088   my $rv;
2089   my $disconnect;
2090
2091   if (! $dbh) {
2092     $dbh = $self->dbconnect($myconfig);
2093     $disconnect = 1;
2094   }
2095     
2096   # if we have an id add audittrail, otherwise get a new timestamp
2097   
2098   if ($audittrail->{id}) {
2099     
2100     $query = qq|SELECT audittrail FROM defaults|;
2101     
2102     if ($dbh->selectrow_array($query)) {
2103       my ($null, $employee_id) = $self->get_employee($dbh);
2104
2105       if ($self->{audittrail} && !$myconfig) {
2106         chop $self->{audittrail};
2107         
2108         my @a = split /\|/, $self->{audittrail};
2109         my %newtrail = ();
2110         my $key;
2111         my $i;
2112         my @flds = qw(tablename reference formname action transdate);
2113
2114         # put into hash and remove dups
2115         while (@a) {
2116           $key = "$a[2]$a[3]";
2117           $i = 0;
2118           $newtrail{$key} = { map { $_ => $a[$i++] } @flds };
2119           splice @a, 0, 5;
2120         }
2121         
2122         $query = qq|INSERT INTO audittrail (trans_id, tablename, reference,
2123                     formname, action, employee_id, transdate)
2124                     VALUES ($audittrail->{id}, ?, ?,
2125                     ?, ?, $employee_id, ?)|;
2126         my $sth = $dbh->prepare($query) || $self->dberror($query);
2127
2128         foreach $key (sort { $newtrail{$a}{transdate} cmp $newtrail{$b}{transdate} } keys %newtrail) {
2129           $i = 1;
2130           for (@flds) { $sth->bind_param($i++, $newtrail{$key}{$_}) }
2131
2132           $sth->execute || $self->dberror;
2133           $sth->finish;
2134         }
2135       }
2136
2137      
2138       if ($audittrail->{transdate}) {
2139         $query = qq|INSERT INTO audittrail (trans_id, tablename, reference,
2140                     formname, action, employee_id, transdate) VALUES (
2141                     $audittrail->{id}, '$audittrail->{tablename}', |
2142                     .$dbh->quote($audittrail->{reference}).qq|',
2143                     '$audittrail->{formname}', '$audittrail->{action}',
2144                     $employee_id, '$audittrail->{transdate}')|;
2145       } else {
2146         $query = qq|INSERT INTO audittrail (trans_id, tablename, reference,
2147                     formname, action, employee_id) VALUES ($audittrail->{id},
2148                     '$audittrail->{tablename}', |
2149                     .$dbh->quote($audittrail->{reference}).qq|,
2150                     '$audittrail->{formname}', '$audittrail->{action}',
2151                     $employee_id)|;
2152       }
2153       $dbh->do($query);
2154     }
2155   } else {
2156     
2157     $query = qq|SELECT current_timestamp FROM defaults|;
2158     my ($timestamp) = $dbh->selectrow_array($query);
2159
2160     $rv = "$audittrail->{tablename}|$audittrail->{reference}|$audittrail->{formname}|$audittrail->{action}|$timestamp|";
2161   }
2162
2163   $dbh->disconnect if $disconnect;
2164   
2165   $rv;
2166   
2167 }
2168
2169 package Locale;
2170
2171 sub new {
2172   $main::lxdebug->enter_sub();
2173
2174   my ($type, $country, $NLS_file) = @_;
2175   my $self = {};
2176
2177   %self = ();
2178   if ($country && -d "locale/$country") {
2179     $self->{countrycode} = $country;
2180     eval { require "locale/$country/$NLS_file"; };
2181   }
2182
2183   $self->{NLS_file} = $NLS_file;
2184
2185   push @{ $self->{LONG_MONTH} },
2186     ("January",   "February", "March",    "April",
2187      "May ",      "June",     "July",     "August",
2188      "September", "October",  "November", "December");
2189   push @{ $self->{SHORT_MONTH} },
2190     (qw(Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec));
2191
2192   $main::lxdebug->leave_sub();
2193
2194   bless $self, $type;
2195 }
2196
2197 sub text {
2198   my ($self, $text) = @_;
2199
2200   return (exists $self{texts}{$text}) ? $self{texts}{$text} : $text;
2201 }
2202
2203 sub findsub {
2204   $main::lxdebug->enter_sub();
2205
2206   my ($self, $text) = @_;
2207
2208   if (exists $self{subs}{$text}) {
2209     $text = $self{subs}{$text};
2210   } else {
2211     if ($self->{countrycode} && $self->{NLS_file}) {
2212       Form->error(
2213          "$text not defined in locale/$self->{countrycode}/$self->{NLS_file}");
2214     }
2215   }
2216
2217   $main::lxdebug->leave_sub();
2218
2219   return $text;
2220 }
2221
2222 sub date {
2223   $main::lxdebug->enter_sub();
2224
2225   my ($self, $myconfig, $date, $longformat) = @_;
2226
2227   my $longdate  = "";
2228   my $longmonth = ($longformat) ? 'LONG_MONTH' : 'SHORT_MONTH';
2229
2230   if ($date) {
2231
2232     # get separator
2233     $spc = $myconfig->{dateformat};
2234     $spc =~ s/\w//g;
2235     $spc = substr($spc, 1, 1);
2236
2237     if ($date =~ /\D/) {
2238       if ($myconfig->{dateformat} =~ /^yy/) {
2239         ($yy, $mm, $dd) = split /\D/, $date;
2240       }
2241       if ($myconfig->{dateformat} =~ /^mm/) {
2242         ($mm, $dd, $yy) = split /\D/, $date;
2243       }
2244       if ($myconfig->{dateformat} =~ /^dd/) {
2245         ($dd, $mm, $yy) = split /\D/, $date;
2246       }
2247     } else {
2248       $date = substr($date, 2);
2249       ($yy, $mm, $dd) = ($date =~ /(..)(..)(..)/);
2250     }
2251
2252     $dd *= 1;
2253     $mm--;
2254     $yy = ($yy < 70) ? $yy + 2000 : $yy;
2255     $yy = ($yy >= 70 && $yy <= 99) ? $yy + 1900 : $yy;
2256
2257     if ($myconfig->{dateformat} =~ /^dd/) {
2258       if (defined $longformat && $longformat == 0) {
2259         $mm++;
2260         $dd = "0$dd" if ($dd < 10);
2261         $mm = "0$mm" if ($mm < 10);
2262         $longdate = "$dd$spc$mm$spc$yy";
2263       } else {
2264         $longdate = "$dd";
2265         $longdate .= ($spc eq '.') ? ". " : " ";
2266         $longdate .= &text($self, $self->{$longmonth}[$mm]) . " $yy";
2267       }
2268     } elsif ($myconfig->{dateformat} eq "yyyy-mm-dd") {
2269
2270       # Use German syntax with the ISO date style "yyyy-mm-dd" because
2271       # Lx-Office is mainly used in Germany or German speaking countries.
2272       if (defined $longformat && $longformat == 0) {
2273         $mm++;
2274         $dd = "0$dd" if ($dd < 10);
2275         $mm = "0$mm" if ($mm < 10);
2276         $longdate = "$yy-$mm-$dd";
2277       } else {
2278         $longdate = "$dd. ";
2279         $longdate .= &text($self, $self->{$longmonth}[$mm]) . " $yy";
2280       }
2281     } else {
2282       if (defined $longformat && $longformat == 0) {
2283         $mm++;
2284         $dd = "0$dd" if ($dd < 10);
2285         $mm = "0$mm" if ($mm < 10);
2286         $longdate = "$mm$spc$dd$spc$yy";
2287       } else {
2288         $longdate = &text($self, $self->{$longmonth}[$mm]) . " $dd, $yy";
2289       }
2290     }
2291
2292   }
2293
2294   $main::lxdebug->leave_sub();
2295
2296   return $longdate;
2297 }
2298
2299 sub parse_date {
2300   $main::lxdebug->enter_sub();
2301
2302   my ($self, $myconfig, $date, $longformat) = @_;
2303
2304   unless ($date) {
2305     $main::lxdebug->leave_sub();
2306     return ();
2307   }
2308
2309   # get separator
2310   $spc = $myconfig->{dateformat};
2311   $spc =~ s/\w//g;
2312   $spc = substr($spc, 1, 1);
2313
2314   if ($date =~ /\D/) {
2315     if ($myconfig->{dateformat} =~ /^yy/) {
2316       ($yy, $mm, $dd) = split /\D/, $date;
2317     } elsif ($myconfig->{dateformat} =~ /^mm/) {
2318       ($mm, $dd, $yy) = split /\D/, $date;
2319     } elsif ($myconfig->{dateformat} =~ /^dd/) {
2320       ($dd, $mm, $yy) = split /\D/, $date;
2321     }
2322   } else {
2323     $date = substr($date, 2);
2324     ($yy, $mm, $dd) = ($date =~ /(..)(..)(..)/);
2325   }
2326
2327   $dd *= 1;
2328   $mm *= 1;
2329   $yy = ($yy < 70) ? $yy + 2000 : $yy;
2330   $yy = ($yy >= 70 && $yy <= 99) ? $yy + 1900 : $yy;
2331
2332   $main::lxdebug->leave_sub();
2333   return ($yy, $mm, $dd);
2334 }
2335
2336 1;