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