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