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