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