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