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