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