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