5540b95557de98a7cbbf3b8d63dd8b85a4b153cc
[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 Data::Dumper;
41
42 use CGI;
43 use CGI::Ajax;
44 use Cwd;
45 use IO::File;
46 use SL::Auth;
47 use SL::Auth::DB;
48 use SL::Auth::LDAP;
49 use SL::AM;
50 use SL::Common;
51 use SL::DBUtils;
52 use SL::Mailer;
53 use SL::Menu;
54 use SL::Template;
55 use SL::User;
56 use Template;
57 use URI;
58 use List::Util qw(first max min sum);
59 use List::MoreUtils qw(any);
60
61 use strict;
62
63 my $standard_dbh;
64
65 END {
66   disconnect_standard_dbh();
67 }
68
69 sub disconnect_standard_dbh {
70   return unless $standard_dbh;
71   $standard_dbh->disconnect();
72   undef $standard_dbh;
73 }
74
75 sub _store_value {
76   $main::lxdebug->enter_sub(2);
77
78   my $self  = shift;
79   my $key   = shift;
80   my $value = shift;
81
82   my @tokens = split /((?:\[\+?\])?(?:\.|$))/, $key;
83
84   my $curr;
85
86   if (scalar @tokens) {
87      $curr = \ $self->{ shift @tokens };
88   }
89
90   while (@tokens) {
91     my $sep = shift @tokens;
92     my $key = shift @tokens;
93
94     $curr = \ $$curr->[++$#$$curr], next if $sep eq '[]';
95     $curr = \ $$curr->[max 0, $#$$curr]  if $sep eq '[].';
96     $curr = \ $$curr->[++$#$$curr]       if $sep eq '[+].';
97     $curr = \ $$curr->{$key}
98   }
99
100   $$curr = $value;
101
102   $main::lxdebug->leave_sub(2);
103
104   return $curr;
105 }
106
107 sub _input_to_hash {
108   $main::lxdebug->enter_sub(2);
109
110   my $self  = shift;
111   my $input = shift;
112
113   my @pairs = split(/&/, $input);
114
115   foreach (@pairs) {
116     my ($key, $value) = split(/=/, $_, 2);
117     $self->_store_value($self->unescape($key), $self->unescape($value)) if ($key);
118   }
119
120   $main::lxdebug->leave_sub(2);
121 }
122
123 sub _request_to_hash {
124   $main::lxdebug->enter_sub(2);
125
126   my $self  = shift;
127   my $input = shift;
128
129   if (!$ENV{'CONTENT_TYPE'}
130       || ($ENV{'CONTENT_TYPE'} !~ /multipart\/form-data\s*;\s*boundary\s*=\s*(.+)$/)) {
131
132     $self->_input_to_hash($input);
133
134     $main::lxdebug->leave_sub(2);
135     return;
136   }
137
138   my ($name, $filename, $headers_done, $content_type, $boundary_found, $need_cr, $previous);
139
140   my $boundary = '--' . $1;
141
142   foreach my $line (split m/\n/, $input) {
143     last if (($line eq "${boundary}--") || ($line eq "${boundary}--\r"));
144
145     if (($line eq $boundary) || ($line eq "$boundary\r")) {
146       ${ $previous } =~ s|\r?\n$|| if $previous;
147
148       undef $previous;
149       undef $filename;
150
151       $headers_done   = 0;
152       $content_type   = "text/plain";
153       $boundary_found = 1;
154       $need_cr        = 0;
155
156       next;
157     }
158
159     next unless $boundary_found;
160
161     if (!$headers_done) {
162       $line =~ s/[\r\n]*$//;
163
164       if (!$line) {
165         $headers_done = 1;
166         next;
167       }
168
169       if ($line =~ m|^content-disposition\s*:.*?form-data\s*;|i) {
170         if ($line =~ m|filename\s*=\s*"(.*?)"|i) {
171           $filename = $1;
172           substr $line, $-[0], $+[0] - $-[0], "";
173         }
174
175         if ($line =~ m|name\s*=\s*"(.*?)"|i) {
176           $name = $1;
177           substr $line, $-[0], $+[0] - $-[0], "";
178         }
179
180         $previous         = $self->_store_value($name, '') if ($name);
181         $self->{FILENAME} = $filename if ($filename);
182
183         next;
184       }
185
186       if ($line =~ m|^content-type\s*:\s*(.*?)$|i) {
187         $content_type = $1;
188       }
189
190       next;
191     }
192
193     next unless $previous;
194
195     ${ $previous } .= "${line}\n";
196   }
197
198   ${ $previous } =~ s|\r?\n$|| if $previous;
199
200   $main::lxdebug->leave_sub(2);
201 }
202
203 sub _recode_recursively {
204   $main::lxdebug->enter_sub();
205   my ($iconv, $param) = @_;
206
207   if (any { ref $param eq $_ } qw(Form HASH)) {
208     foreach my $key (keys %{ $param }) {
209       if (!ref $param->{$key}) {
210         # Workaround for a bug: converting $param->{$key} directly
211         # leads to 'undef'. I don't know why. Converting a copy works,
212         # though.
213         $param->{$key} = $iconv->convert("" . $param->{$key});
214       } else {
215         _recode_recursively($iconv, $param->{$key});
216       }
217     }
218
219   } elsif (ref $param eq 'ARRAY') {
220     foreach my $idx (0 .. scalar(@{ $param }) - 1) {
221       if (!ref $param->[$idx]) {
222         # Workaround for a bug: converting $param->[$idx] directly
223         # leads to 'undef'. I don't know why. Converting a copy works,
224         # though.
225         $param->[$idx] = $iconv->convert("" . $param->[$idx]);
226       } else {
227         _recode_recursively($iconv, $param->[$idx]);
228       }
229     }
230   }
231   $main::lxdebug->leave_sub();
232 }
233
234 sub new {
235   $main::lxdebug->enter_sub();
236
237   my $type = shift;
238
239   my $self = {};
240
241   if ($LXDebug::watch_form) {
242     require SL::Watchdog;
243     tie %{ $self }, 'SL::Watchdog';
244   }
245
246   bless $self, $type;
247
248   $self->_input_to_hash($ENV{QUERY_STRING}) if $ENV{QUERY_STRING};
249   $self->_input_to_hash($ARGV[0])           if @ARGV && $ARGV[0];
250
251   if ($ENV{CONTENT_LENGTH}) {
252     my $content;
253     read STDIN, $content, $ENV{CONTENT_LENGTH};
254     $self->_request_to_hash($content);
255   }
256
257   my $db_charset   = $main::dbcharset;
258   $db_charset    ||= Common::DEFAULT_CHARSET;
259
260   if ($self->{INPUT_ENCODING}) {
261     if (lc $self->{INPUT_ENCODING} ne lc $db_charset) {
262       require Text::Iconv;
263       my $iconv = Text::Iconv->new($self->{INPUT_ENCODING}, $db_charset);
264
265       _recode_recursively($iconv, $self);
266     }
267
268     delete $self->{INPUT_ENCODING};
269   }
270
271   $self->{action}  =  lc $self->{action};
272   $self->{action}  =~ s/( |-|,|\#)/_/g;
273
274   $self->{version} =  "2.6.1";
275
276   $main::lxdebug->leave_sub();
277
278   return $self;
279 }
280
281 sub _flatten_variables_rec {
282   $main::lxdebug->enter_sub(2);
283
284   my $self   = shift;
285   my $curr   = shift;
286   my $prefix = shift;
287   my $key    = shift;
288
289   my @result;
290
291   if ('' eq ref $curr->{$key}) {
292     @result = ({ 'key' => $prefix . $key, 'value' => $curr->{$key} });
293
294   } elsif ('HASH' eq ref $curr->{$key}) {
295     foreach my $hash_key (sort keys %{ $curr->{$key} }) {
296       push @result, $self->_flatten_variables_rec($curr->{$key}, $prefix . $key . '.', $hash_key);
297     }
298
299   } else {
300     foreach my $idx (0 .. scalar @{ $curr->{$key} } - 1) {
301       my $first_array_entry = 1;
302
303       foreach my $hash_key (sort keys %{ $curr->{$key}->[$idx] }) {
304         push @result, $self->_flatten_variables_rec($curr->{$key}->[$idx], $prefix . $key . ($first_array_entry ? '[+].' : '[].'), $hash_key);
305         $first_array_entry = 0;
306       }
307     }
308   }
309
310   $main::lxdebug->leave_sub(2);
311
312   return @result;
313 }
314
315 sub flatten_variables {
316   $main::lxdebug->enter_sub(2);
317
318   my $self = shift;
319   my @keys = @_;
320
321   my @variables;
322
323   foreach (@keys) {
324     push @variables, $self->_flatten_variables_rec($self, '', $_);
325   }
326
327   $main::lxdebug->leave_sub(2);
328
329   return @variables;
330 }
331
332 sub flatten_standard_variables {
333   $main::lxdebug->enter_sub(2);
334
335   my $self      = shift;
336   my %skip_keys = map { $_ => 1 } (qw(login password header stylesheet titlebar version), @_);
337
338   my @variables;
339
340   foreach (grep { ! $skip_keys{$_} } keys %{ $self }) {
341     push @variables, $self->_flatten_variables_rec($self, '', $_);
342   }
343
344   $main::lxdebug->leave_sub(2);
345
346   return @variables;
347 }
348
349 sub debug {
350   $main::lxdebug->enter_sub();
351
352   my ($self) = @_;
353
354   print "\n";
355
356   map { print "$_ = $self->{$_}\n" } (sort keys %{$self});
357
358   $main::lxdebug->leave_sub();
359 }
360
361 sub dumper {
362   $main::lxdebug->enter_sub(2);
363
364   my $self          = shift;
365   my $password      = $self->{password};
366
367   $self->{password} = 'X' x 8;
368
369   local $Data::Dumper::Sortkeys = 1;
370   my $output                    = Dumper($self);
371
372   $self->{password} = $password;
373
374   $main::lxdebug->leave_sub(2);
375
376   return $output;
377 }
378
379 sub escape {
380   $main::lxdebug->enter_sub(2);
381
382   my ($self, $str) = @_;
383
384   $str =~ s/([^a-zA-Z0-9_.-])/sprintf("%%%02x", ord($1))/ge;
385
386   $main::lxdebug->leave_sub(2);
387
388   return $str;
389 }
390
391 sub unescape {
392   $main::lxdebug->enter_sub(2);
393
394   my ($self, $str) = @_;
395
396   $str =~ tr/+/ /;
397   $str =~ s/\\$//;
398
399   $str =~ s/%([0-9a-fA-Z]{2})/pack("c",hex($1))/eg;
400
401   $main::lxdebug->leave_sub(2);
402
403   return $str;
404 }
405
406 sub quote {
407   $main::lxdebug->enter_sub();
408   my ($self, $str) = @_;
409
410   if ($str && !ref($str)) {
411     $str =~ s/\"/&quot;/g;
412   }
413
414   $main::lxdebug->leave_sub();
415
416   return $str;
417 }
418
419 sub unquote {
420   $main::lxdebug->enter_sub();
421   my ($self, $str) = @_;
422
423   if ($str && !ref($str)) {
424     $str =~ s/&quot;/\"/g;
425   }
426
427   $main::lxdebug->leave_sub();
428
429   return $str;
430 }
431
432 sub hide_form {
433   $main::lxdebug->enter_sub();
434   my $self = shift;
435
436   if (@_) {
437     map({ print($main::cgi->hidden("-name" => $_, "-default" => $self->{$_}) . "\n"); } @_);
438   } else {
439     for (sort keys %$self) {
440       next if (($_ eq "header") || (ref($self->{$_}) ne ""));
441       print($main::cgi->hidden("-name" => $_, "-default" => $self->{$_}) . "\n");
442     }
443   }
444   $main::lxdebug->leave_sub();
445 }
446
447 sub error {
448   $main::lxdebug->enter_sub();
449
450   $main::lxdebug->show_backtrace();
451
452   my ($self, $msg) = @_;
453   if ($ENV{HTTP_USER_AGENT}) {
454     $msg =~ s/\n/<br>/g;
455     $self->show_generic_error($msg);
456
457   } else {
458     print STDERR "Error: $msg\n";
459     ::end_of_request();
460   }
461
462   $main::lxdebug->leave_sub();
463 }
464
465 sub info {
466   $main::lxdebug->enter_sub();
467
468   my ($self, $msg) = @_;
469
470   if ($ENV{HTTP_USER_AGENT}) {
471     $msg =~ s/\n/<br>/g;
472
473     if (!$self->{header}) {
474       $self->header;
475       print qq|
476       <body>|;
477     }
478
479     print qq|
480
481     <p><b>$msg</b>
482     |;
483
484   } else {
485
486     if ($self->{info_function}) {
487       &{ $self->{info_function} }($msg);
488     } else {
489       print "$msg\n";
490     }
491   }
492
493   $main::lxdebug->leave_sub();
494 }
495
496 # calculates the number of rows in a textarea based on the content and column number
497 # can be capped with maxrows
498 sub numtextrows {
499   $main::lxdebug->enter_sub();
500   my ($self, $str, $cols, $maxrows, $minrows) = @_;
501
502   $minrows ||= 1;
503
504   my $rows   = sum map { int((length() - 2) / $cols) + 1 } split /\r/, $str;
505   $maxrows ||= $rows;
506
507   $main::lxdebug->leave_sub();
508
509   return max(min($rows, $maxrows), $minrows);
510 }
511
512 sub dberror {
513   $main::lxdebug->enter_sub();
514
515   my ($self, $msg) = @_;
516
517   $self->error("$msg\n" . $DBI::errstr);
518
519   $main::lxdebug->leave_sub();
520 }
521
522 sub isblank {
523   $main::lxdebug->enter_sub();
524
525   my ($self, $name, $msg) = @_;
526
527   my $curr = $self;
528   foreach my $part (split m/\./, $name) {
529     if (!$curr->{$part} || ($curr->{$part} =~ /^\s*$/)) {
530       $self->error($msg);
531     }
532     $curr = $curr->{$part};
533   }
534
535   $main::lxdebug->leave_sub();
536 }
537
538 sub _get_request_uri {
539   my $self = shift;
540
541   return URI->new($ENV{HTTP_REFERER})->canonical() if $ENV{HTTP_X_FORWARDED_FOR};
542
543   my $scheme =  $ENV{HTTPS} && (lc $ENV{HTTPS} eq 'on') ? 'https' : 'http';
544   my $port   =  $ENV{SERVER_PORT} || '';
545   $port      =  undef if (($scheme eq 'http' ) && ($port == 80))
546                       || (($scheme eq 'https') && ($port == 443));
547
548   my $uri    =  URI->new("${scheme}://");
549   $uri->scheme($scheme);
550   $uri->port($port);
551   $uri->host($ENV{HTTP_HOST} || $ENV{SERVER_ADDR});
552   $uri->path_query($ENV{REQUEST_URI});
553   $uri->query('');
554
555   return $uri;
556 }
557
558 sub _add_to_request_uri {
559   my $self              = shift;
560
561   my $relative_new_path = shift;
562   my $request_uri       = shift || $self->_get_request_uri;
563   my $relative_new_uri  = URI->new($relative_new_path);
564   my @request_segments  = $request_uri->path_segments;
565
566   my $new_uri           = $request_uri->clone;
567   $new_uri->path_segments(@request_segments[0..scalar(@request_segments) - 2], $relative_new_uri->path_segments);
568
569   return $new_uri;
570 }
571
572 sub create_http_response {
573   $main::lxdebug->enter_sub();
574
575   my $self     = shift;
576   my %params   = @_;
577
578   my $cgi      = $main::cgi;
579   $cgi       ||= CGI->new('');
580
581   my $session_cookie;
582   if (defined $main::auth) {
583     my $uri      = $self->_get_request_uri;
584     my @segments = $uri->path_segments;
585     pop @segments;
586     $uri->path_segments(@segments);
587
588     my $session_cookie_value   = $main::auth->get_session_id();
589     $session_cookie_value    ||= 'NO_SESSION';
590
591     $session_cookie = $cgi->cookie('-name'   => $main::auth->get_session_cookie_name(),
592                                    '-value'  => $session_cookie_value,
593                                    '-path'   => $uri->path,
594                                    '-secure' => $ENV{HTTPS});
595   }
596
597   my %cgi_params = ('-type' => $params{content_type});
598   $cgi_params{'-charset'} = $params{charset} if ($params{charset});
599
600   my $output = $cgi->header('-cookie' => $session_cookie,
601                             %cgi_params);
602
603   $main::lxdebug->leave_sub();
604
605   return $output;
606 }
607
608
609 sub header {
610   $main::lxdebug->enter_sub();
611
612   # extra code ist currently only used by menuv3 and menuv4 to set their css.
613   # it is strongly deprecated, and will be changed in a future version.
614   my ($self, $extra_code) = @_;
615
616   if ($self->{header}) {
617     $main::lxdebug->leave_sub();
618     return;
619   }
620
621   my ($stylesheet, $favicon, $pagelayout);
622
623   if ($ENV{HTTP_USER_AGENT}) {
624     my $doctype;
625
626     if ($ENV{'HTTP_USER_AGENT'} =~ m/MSIE\s+\d/) {
627       # Only set the DOCTYPE for Internet Explorer. Other browsers have problems displaying the menu otherwise.
628       $doctype = qq|<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">\n|;
629     }
630
631     my $stylesheets = "$self->{stylesheet} $self->{stylesheets}";
632
633     $stylesheets =~ s|^\s*||;
634     $stylesheets =~ s|\s*$||;
635     foreach my $file (split m/\s+/, $stylesheets) {
636       $file =~ s|.*/||;
637       next if (! -f "css/$file");
638
639       $stylesheet .= qq|<link rel="stylesheet" href="css/$file" TYPE="text/css" TITLE="Lx-Office stylesheet">\n|;
640     }
641
642     $self->{favicon}    = "favicon.ico" unless $self->{favicon};
643
644     if ($self->{favicon} && (-f "$self->{favicon}")) {
645       $favicon =
646         qq|<LINK REL="shortcut icon" HREF="$self->{favicon}" TYPE="image/x-icon">
647   |;
648     }
649
650     my $db_charset = $main::dbcharset ? $main::dbcharset : Common::DEFAULT_CHARSET;
651
652     if ($self->{landscape}) {
653       $pagelayout = qq|<style type="text/css">
654                         \@page { size:landscape; }
655                         </style>|;
656     }
657
658     my $fokus = qq|
659     <script type="text/javascript">
660     <!--
661       function fokus() {
662         document.$self->{fokus}.focus();
663       }
664     //-->
665     </script>
666     | if $self->{"fokus"};
667
668     #Set Calendar
669     my $jsscript = "";
670     if ($self->{jsscript} == 1) {
671
672       $jsscript = qq|
673         <script type="text/javascript" src="js/jquery.js"></script>
674         <script type="text/javascript" src="js/common.js"></script>
675         <style type="text/css">\@import url(js/jscalendar/calendar-win2k-1.css);</style>
676         <script type="text/javascript" src="js/jscalendar/calendar.js"></script>
677         <script type="text/javascript" src="js/jscalendar/lang/calendar-de.js"></script>
678         <script type="text/javascript" src="js/jscalendar/calendar-setup.js"></script>
679         $self->{javascript}
680        |;
681     }
682
683     $self->{titlebar} =
684       ($self->{title})
685       ? "$self->{title} - $self->{titlebar}"
686       : $self->{titlebar};
687     my $ajax = "";
688     for my $item (@ { $self->{AJAX} || [] }) {
689       $ajax .= $item->show_javascript();
690     }
691
692     print $self->create_http_response('content_type' => 'text/html',
693                                       'charset'      => $db_charset,);
694     print qq|${doctype}<html>
695 <head>
696   <META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=${db_charset}">
697   <title>$self->{titlebar}</title>
698   $stylesheet
699   $pagelayout
700   $favicon
701   $jsscript
702   $ajax
703
704   $fokus
705
706   <link rel="stylesheet" href="css/jquery.autocomplete.css" type="text/css" />
707
708   <meta name="robots" content="noindex,nofollow" />
709   <script type="text/javascript" src="js/highlight_input.js"></script>
710
711   <link rel="stylesheet" type="text/css" href="css/tabcontent.css" />
712   <script type="text/javascript" src="js/tabcontent.js">
713
714   /***********************************************
715    * Tab Content script v2.2- Â© Dynamic Drive DHTML code library (www.dynamicdrive.com)
716    * This notice MUST stay intact for legal use
717    * Visit Dynamic Drive at http://www.dynamicdrive.com/ for full source code
718    ***********************************************/
719
720   </script>
721
722   $extra_code
723 </head>
724
725 |;
726   }
727   $self->{header} = 1;
728
729   $main::lxdebug->leave_sub();
730 }
731
732 sub ajax_response_header {
733   $main::lxdebug->enter_sub();
734
735   my ($self) = @_;
736
737   my $db_charset = $main::dbcharset ? $main::dbcharset : Common::DEFAULT_CHARSET;
738   my $cgi        = $main::cgi || CGI->new('');
739   my $output     = $cgi->header('-charset' => $db_charset);
740
741   $main::lxdebug->leave_sub();
742
743   return $output;
744 }
745
746 sub redirect_header {
747   my $self     = shift;
748   my $new_url  = shift;
749
750   my $base_uri = $self->_get_request_uri;
751   my $new_uri  = URI->new_abs($new_url, $base_uri);
752
753   die "Headers already sent" if $::self->{header};
754   $self->{header} = 1;
755
756   my $cgi = $main::cgi || CGI->new('');
757   return $cgi->redirect($new_uri);
758 }
759
760 sub set_standard_title {
761   $::lxdebug->enter_sub;
762   my $self = shift;
763
764   $self->{titlebar}  = "Lx-Office " . $::locale->text('Version') . " $self->{version}";
765   $self->{titlebar} .= "- $::myconfig{name}"   if $::myconfig{name};
766   $self->{titlebar} .= "- $::myconfig{dbname}" if $::myconfig{name};
767
768   $::lxdebug->leave_sub;
769 }
770
771 sub _prepare_html_template {
772   $main::lxdebug->enter_sub();
773
774   my ($self, $file, $additional_params) = @_;
775   my $language;
776
777   if (!%::myconfig || !$::myconfig{"countrycode"}) {
778     $language = $main::language;
779   } else {
780     $language = $main::myconfig{"countrycode"};
781   }
782   $language = "de" unless ($language);
783
784   if (-f "templates/webpages/${file}.html") {
785     if ((-f ".developer") && ((stat("templates/webpages/${file}.html"))[9] > (stat("locale/${language}/all"))[9])) {
786       my $info = "Developer information: templates/webpages/${file}.html is newer than the translation file locale/${language}/all.\n" .
787         "Please re-run 'locales.pl' in 'locale/${language}'.";
788       print(qq|<pre>$info</pre>|);
789       ::end_of_request();
790     }
791
792     $file = "templates/webpages/${file}.html";
793
794   } else {
795     my $info = "Web page template '${file}' not found.\n" .
796       "Please re-run 'locales.pl' in 'locale/${language}'.";
797     print(qq|<pre>$info</pre>|);
798     ::end_of_request();
799   }
800
801   if ($self->{"DEBUG"}) {
802     $additional_params->{"DEBUG"} = $self->{"DEBUG"};
803   }
804
805   if ($additional_params->{"DEBUG"}) {
806     $additional_params->{"DEBUG"} =
807       "<br><em>DEBUG INFORMATION:</em><pre>" . $additional_params->{"DEBUG"} . "</pre>";
808   }
809
810   if (%main::myconfig) {
811     map({ $additional_params->{"myconfig_${_}"} = $main::myconfig{$_}; } keys(%main::myconfig));
812     my $jsc_dateformat = $main::myconfig{"dateformat"};
813     $jsc_dateformat =~ s/d+/\%d/gi;
814     $jsc_dateformat =~ s/m+/\%m/gi;
815     $jsc_dateformat =~ s/y+/\%Y/gi;
816     $additional_params->{"myconfig_jsc_dateformat"} = $jsc_dateformat;
817     $additional_params->{"myconfig"} ||= \%::myconfig;
818   }
819
820   $additional_params->{"conf_dbcharset"}              = $main::dbcharset;
821   $additional_params->{"conf_webdav"}                 = $main::webdav;
822   $additional_params->{"conf_lizenzen"}               = $main::lizenzen;
823   $additional_params->{"conf_latex_templates"}        = $main::latex;
824   $additional_params->{"conf_opendocument_templates"} = $main::opendocument_templates;
825   $additional_params->{"conf_vertreter"}              = $main::vertreter;
826   $additional_params->{"conf_show_best_before"}       = $main::show_best_before;
827
828   if (%main::debug_options) {
829     map { $additional_params->{'DEBUG_' . uc($_)} = $main::debug_options{$_} } keys %main::debug_options;
830   }
831
832   if ($main::auth && $main::auth->{RIGHTS} && $main::auth->{RIGHTS}->{$self->{login}}) {
833     while (my ($key, $value) = each %{ $main::auth->{RIGHTS}->{$self->{login}} }) {
834       $additional_params->{"AUTH_RIGHTS_" . uc($key)} = $value;
835     }
836   }
837
838   $main::lxdebug->leave_sub();
839
840   return $file;
841 }
842
843 sub parse_html_template {
844   $main::lxdebug->enter_sub();
845
846   my ($self, $file, $additional_params) = @_;
847
848   $additional_params ||= { };
849
850   my $real_file = $self->_prepare_html_template($file, $additional_params);
851   my $template  = $self->template || $self->init_template;
852
853   map { $additional_params->{$_} ||= $self->{$_} } keys %{ $self };
854
855   my $output;
856   $template->process($real_file, $additional_params, \$output) || die $template->error;
857
858   $main::lxdebug->leave_sub();
859
860   return $output;
861 }
862
863 sub init_template {
864   my $self = shift;
865
866   return if $self->template;
867
868   return $self->template(Template->new({
869      'INTERPOLATE'  => 0,
870      'EVAL_PERL'    => 0,
871      'ABSOLUTE'     => 1,
872      'CACHE_SIZE'   => 0,
873      'PLUGIN_BASE'  => 'SL::Template::Plugin',
874      'INCLUDE_PATH' => '.:templates/webpages',
875      'COMPILE_EXT'  => '.tcc',
876      'COMPILE_DIR'  => $::userspath . '/templates-cache',
877   })) || die;
878 }
879
880 sub template {
881   my $self = shift;
882   $self->{template_object} = shift if @_;
883   return $self->{template_object};
884 }
885
886 sub show_generic_error {
887   $main::lxdebug->enter_sub();
888
889   my ($self, $error, %params) = @_;
890
891   my $add_params = {
892     'title_error' => $params{title},
893     'label_error' => $error,
894   };
895
896   if ($params{action}) {
897     my @vars;
898
899     map { delete($self->{$_}); } qw(action);
900     map { push @vars, { "name" => $_, "value" => $self->{$_} } if (!ref($self->{$_})); } keys %{ $self };
901
902     $add_params->{SHOW_BUTTON}  = 1;
903     $add_params->{BUTTON_LABEL} = $params{label} || $params{action};
904     $add_params->{VARIABLES}    = \@vars;
905
906   } elsif ($params{back_button}) {
907     $add_params->{SHOW_BACK_BUTTON} = 1;
908   }
909
910   $self->{title} = $params{title} if $params{title};
911
912   $self->header();
913   print $self->parse_html_template("generic/error", $add_params);
914
915   print STDERR "Error: $error\n";
916
917   $main::lxdebug->leave_sub();
918
919   ::end_of_request();
920 }
921
922 sub show_generic_information {
923   $main::lxdebug->enter_sub();
924
925   my ($self, $text, $title) = @_;
926
927   my $add_params = {
928     'title_information' => $title,
929     'label_information' => $text,
930   };
931
932   $self->{title} = $title if ($title);
933
934   $self->header();
935   print $self->parse_html_template("generic/information", $add_params);
936
937   $main::lxdebug->leave_sub();
938
939   ::end_of_request();
940 }
941
942 # write Trigger JavaScript-Code ($qty = quantity of Triggers)
943 # changed it to accept an arbitrary number of triggers - sschoeling
944 sub write_trigger {
945   $main::lxdebug->enter_sub();
946
947   my $self     = shift;
948   my $myconfig = shift;
949   my $qty      = shift;
950
951   # set dateform for jsscript
952   # default
953   my %dateformats = (
954     "dd.mm.yy" => "%d.%m.%Y",
955     "dd-mm-yy" => "%d-%m-%Y",
956     "dd/mm/yy" => "%d/%m/%Y",
957     "mm/dd/yy" => "%m/%d/%Y",
958     "mm-dd-yy" => "%m-%d-%Y",
959     "yyyy-mm-dd" => "%Y-%m-%d",
960     );
961
962   my $ifFormat = defined($dateformats{$myconfig->{"dateformat"}}) ?
963     $dateformats{$myconfig->{"dateformat"}} : "%d.%m.%Y";
964
965   my @triggers;
966   while ($#_ >= 2) {
967     push @triggers, qq|
968        Calendar.setup(
969       {
970       inputField : "| . (shift) . qq|",
971       ifFormat :"$ifFormat",
972       align : "| .  (shift) . qq|",
973       button : "| . (shift) . qq|"
974       }
975       );
976        |;
977   }
978   my $jsscript = qq|
979        <script type="text/javascript">
980        <!--| . join("", @triggers) . qq|//-->
981         </script>
982         |;
983
984   $main::lxdebug->leave_sub();
985
986   return $jsscript;
987 }    #end sub write_trigger
988
989 sub redirect {
990   $main::lxdebug->enter_sub();
991
992   my ($self, $msg) = @_;
993
994   if (!$self->{callback}) {
995
996     $self->info($msg);
997     ::end_of_request();
998   }
999
1000 #  my ($script, $argv) = split(/\?/, $self->{callback}, 2);
1001 #  $script =~ s|.*/||;
1002 #  $script =~ s|[^a-zA-Z0-9_\.]||g;
1003 #  exec("perl", "$script", $argv);
1004
1005   print $::form->redirect_header($self->{callback});
1006
1007   $main::lxdebug->leave_sub();
1008 }
1009
1010 # sort of columns removed - empty sub
1011 sub sort_columns {
1012   $main::lxdebug->enter_sub();
1013
1014   my ($self, @columns) = @_;
1015
1016   $main::lxdebug->leave_sub();
1017
1018   return @columns;
1019 }
1020 #
1021 sub format_amount {
1022   $main::lxdebug->enter_sub(2);
1023
1024   my ($self, $myconfig, $amount, $places, $dash) = @_;
1025
1026   if ($amount eq "") {
1027     $amount = 0;
1028   }
1029
1030   # Hey watch out! The amount can be an exponential term like 1.13686837721616e-13
1031
1032   my $neg = ($amount =~ s/^-//);
1033   my $exp = ($amount =~ m/[e]/) ? 1 : 0;
1034
1035   if (defined($places) && ($places ne '')) {
1036     if (not $exp) {
1037       if ($places < 0) {
1038         $amount *= 1;
1039         $places *= -1;
1040
1041         my ($actual_places) = ($amount =~ /\.(\d+)/);
1042         $actual_places = length($actual_places);
1043         $places = $actual_places > $places ? $actual_places : $places;
1044       }
1045     }
1046     $amount = $self->round_amount($amount, $places);
1047   }
1048
1049   my @d = map { s/\d//g; reverse split // } my $tmp = $myconfig->{numberformat}; # get delim chars
1050   my @p = split(/\./, $amount); # split amount at decimal point
1051
1052   $p[0] =~ s/\B(?=(...)*$)/$d[1]/g if $d[1]; # add 1,000 delimiters
1053
1054   $amount = $p[0];
1055   $amount .= $d[0].$p[1].(0 x ($places - length $p[1])) if ($places || $p[1] ne '');
1056
1057   $amount = do {
1058     ($dash =~ /-/)    ? ($neg ? "($amount)"                            : "$amount" )                              :
1059     ($dash =~ /DRCR/) ? ($neg ? "$amount " . $main::locale->text('DR') : "$amount " . $main::locale->text('CR') ) :
1060                         ($neg ? "-$amount"                             : "$amount" )                              ;
1061   };
1062
1063
1064   $main::lxdebug->leave_sub(2);
1065   return $amount;
1066 }
1067
1068 sub format_amount_units {
1069   $main::lxdebug->enter_sub();
1070
1071   my $self             = shift;
1072   my %params           = @_;
1073
1074   my $myconfig         = \%main::myconfig;
1075   my $amount           = $params{amount} * 1;
1076   my $places           = $params{places};
1077   my $part_unit_name   = $params{part_unit};
1078   my $amount_unit_name = $params{amount_unit};
1079   my $conv_units       = $params{conv_units};
1080   my $max_places       = $params{max_places};
1081
1082   if (!$part_unit_name) {
1083     $main::lxdebug->leave_sub();
1084     return '';
1085   }
1086
1087   AM->retrieve_all_units();
1088   my $all_units        = $main::all_units;
1089
1090   if (('' eq ref $conv_units) && ($conv_units =~ /convertible/)) {
1091     $conv_units = AM->convertible_units($all_units, $part_unit_name, $conv_units eq 'convertible_not_smaller');
1092   }
1093
1094   if (!scalar @{ $conv_units }) {
1095     my $result = $self->format_amount($myconfig, $amount, $places, undef, $max_places) . " " . $part_unit_name;
1096     $main::lxdebug->leave_sub();
1097     return $result;
1098   }
1099
1100   my $part_unit  = $all_units->{$part_unit_name};
1101   my $conv_unit  = ($amount_unit_name && ($amount_unit_name ne $part_unit_name)) ? $all_units->{$amount_unit_name} : $part_unit;
1102
1103   $amount       *= $conv_unit->{factor};
1104
1105   my @values;
1106   my $num;
1107
1108   foreach my $unit (@$conv_units) {
1109     my $last = $unit->{name} eq $part_unit->{name};
1110     if (!$last) {
1111       $num     = int($amount / $unit->{factor});
1112       $amount -= $num * $unit->{factor};
1113     }
1114
1115     if ($last ? $amount : $num) {
1116       push @values, { "unit"   => $unit->{name},
1117                       "amount" => $last ? $amount / $unit->{factor} : $num,
1118                       "places" => $last ? $places : 0 };
1119     }
1120
1121     last if $last;
1122   }
1123
1124   if (!@values) {
1125     push @values, { "unit"   => $part_unit_name,
1126                     "amount" => 0,
1127                     "places" => 0 };
1128   }
1129
1130   my $result = join " ", map { $self->format_amount($myconfig, $_->{amount}, $_->{places}, undef, $max_places), $_->{unit} } @values;
1131
1132   $main::lxdebug->leave_sub();
1133
1134   return $result;
1135 }
1136
1137 sub format_string {
1138   $main::lxdebug->enter_sub(2);
1139
1140   my $self  = shift;
1141   my $input = shift;
1142
1143   $input =~ s/(^|[^\#]) \#  (\d+)  /$1$_[$2 - 1]/gx;
1144   $input =~ s/(^|[^\#]) \#\{(\d+)\}/$1$_[$2 - 1]/gx;
1145   $input =~ s/\#\#/\#/g;
1146
1147   $main::lxdebug->leave_sub(2);
1148
1149   return $input;
1150 }
1151
1152 #
1153
1154 sub parse_amount {
1155   $main::lxdebug->enter_sub(2);
1156
1157   my ($self, $myconfig, $amount) = @_;
1158
1159   if (   ($myconfig->{numberformat} eq '1.000,00')
1160       || ($myconfig->{numberformat} eq '1000,00')) {
1161     $amount =~ s/\.//g;
1162     $amount =~ s/,/\./;
1163   }
1164
1165   if ($myconfig->{numberformat} eq "1'000.00") {
1166     $amount =~ s/\'//g;
1167   }
1168
1169   $amount =~ s/,//g;
1170
1171   $main::lxdebug->leave_sub(2);
1172
1173   return ($amount * 1);
1174 }
1175
1176 sub round_amount {
1177   $main::lxdebug->enter_sub(2);
1178
1179   my ($self, $amount, $places) = @_;
1180   my $round_amount;
1181
1182   # Rounding like "Kaufmannsrunden" (see http://de.wikipedia.org/wiki/Rundung )
1183
1184   # Round amounts to eight places before rounding to the requested
1185   # number of places. This gets rid of errors due to internal floating
1186   # point representation.
1187   $amount       = $self->round_amount($amount, 8) if $places < 8;
1188   $amount       = $amount * (10**($places));
1189   $round_amount = int($amount + .5 * ($amount <=> 0)) / (10**($places));
1190
1191   $main::lxdebug->leave_sub(2);
1192
1193   return $round_amount;
1194
1195 }
1196
1197 sub parse_template {
1198   $main::lxdebug->enter_sub();
1199
1200   my ($self, $myconfig, $userspath) = @_;
1201   my ($template, $out);
1202
1203   local (*IN, *OUT);
1204
1205   $self->{"cwd"} = getcwd();
1206   $self->{"tmpdir"} = $self->{cwd} . "/${userspath}";
1207
1208   my $ext_for_format;
1209
1210   if ($self->{"format"} =~ /(opendocument|oasis)/i) {
1211     $template       = OpenDocumentTemplate->new($self->{"IN"}, $self, $myconfig, $userspath);
1212     $ext_for_format = $self->{"format"} =~ m/pdf/ ? 'pdf' : 'odt';
1213
1214   } elsif ($self->{"format"} =~ /(postscript|pdf)/i) {
1215     $ENV{"TEXINPUTS"} = ".:" . getcwd() . "/" . $myconfig->{"templates"} . ":" . $ENV{"TEXINPUTS"};
1216     $template         = LaTeXTemplate->new($self->{"IN"}, $self, $myconfig, $userspath);
1217     $ext_for_format   = 'pdf';
1218
1219   } elsif (($self->{"format"} =~ /html/i) || (!$self->{"format"} && ($self->{"IN"} =~ /html$/i))) {
1220     $template       = HTMLTemplate->new($self->{"IN"}, $self, $myconfig, $userspath);
1221     $ext_for_format = 'html';
1222
1223   } elsif (($self->{"format"} =~ /xml/i) || (!$self->{"format"} && ($self->{"IN"} =~ /xml$/i))) {
1224     $template       = XMLTemplate->new($self->{"IN"}, $self, $myconfig, $userspath);
1225     $ext_for_format = 'xml';
1226
1227   } elsif ( $self->{"format"} =~ /elsterwinston/i ) {
1228     $template = XMLTemplate->new($self->{"IN"}, $self, $myconfig, $userspath);
1229
1230   } elsif ( $self->{"format"} =~ /elstertaxbird/i ) {
1231     $template = XMLTemplate->new($self->{"IN"}, $self, $myconfig, $userspath);
1232
1233   } elsif ( $self->{"format"} =~ /excel/i ) {
1234     $template = ExcelTemplate->new($self->{"IN"}, $self, $myconfig, $userspath);
1235     $ext_for_format = 'xls';
1236
1237   } elsif ( defined $self->{'format'}) {
1238     $self->error("Outputformat not defined. This may be a future feature: $self->{'format'}");
1239
1240   } elsif ( $self->{'format'} eq '' ) {
1241     $self->error("No Outputformat given: $self->{'format'}");
1242
1243   } else { #Catch the rest
1244     $self->error("Outputformat not defined: $self->{'format'}");
1245   }
1246
1247   # Copy the notes from the invoice/sales order etc. back to the variable "notes" because that is where most templates expect it to be.
1248   $self->{"notes"} = $self->{ $self->{"formname"} . "notes" };
1249
1250   if (!$self->{employee_id}) {
1251     map { $self->{"employee_${_}"} = $myconfig->{$_}; } qw(email tel fax name signature company address businessnumber co_ustid taxnumber duns);
1252   }
1253
1254   map { $self->{"${_}"} = $myconfig->{$_}; } qw(co_ustid);
1255
1256   $self->{copies} = 1 if (($self->{copies} *= 1) <= 0);
1257
1258   # OUT is used for the media, screen, printer, email
1259   # for postscript we store a copy in a temporary file
1260   my $fileid = time;
1261   my $prepend_userspath;
1262
1263   if (!$self->{tmpfile}) {
1264     $self->{tmpfile}   = "${fileid}.$self->{IN}";
1265     $prepend_userspath = 1;
1266   }
1267
1268   $prepend_userspath = 1 if substr($self->{tmpfile}, 0, length $userspath) eq $userspath;
1269
1270   $self->{tmpfile} =~ s|.*/||;
1271   $self->{tmpfile} =~ s/[^a-zA-Z0-9\._\ \-]//g;
1272   $self->{tmpfile} = "$userspath/$self->{tmpfile}" if $prepend_userspath;
1273
1274   if ($template->uses_temp_file() || $self->{media} eq 'email') {
1275     $out = $self->{OUT};
1276     $self->{OUT} = ">$self->{tmpfile}";
1277   }
1278
1279   my $result;
1280
1281   if ($self->{OUT}) {
1282     open OUT, "$self->{OUT}" or $self->error("$self->{OUT} : $!");
1283     $result = $template->parse(*OUT);
1284     close OUT;
1285
1286   } else {
1287     $self->header;
1288     $result = $template->parse(*STDOUT);
1289   }
1290
1291   if (!$result) {
1292     $self->cleanup();
1293     $self->error("$self->{IN} : " . $template->get_error());
1294   }
1295
1296   if ($template->uses_temp_file() || $self->{media} eq 'email') {
1297
1298     if ($self->{media} eq 'email') {
1299
1300       my $mail = new Mailer;
1301
1302       map { $mail->{$_} = $self->{$_} }
1303         qw(cc bcc subject message version format);
1304       $mail->{charset} = $main::dbcharset ? $main::dbcharset : Common::DEFAULT_CHARSET;
1305       $mail->{to} = $self->{EMAIL_RECIPIENT} ? $self->{EMAIL_RECIPIENT} : $self->{email};
1306       $mail->{from}   = qq|"$myconfig->{name}" <$myconfig->{email}>|;
1307       $mail->{fileid} = "$fileid.";
1308       $myconfig->{signature} =~ s/\r//g;
1309
1310       # if we send html or plain text inline
1311       if (($self->{format} eq 'html') && ($self->{sendmode} eq 'inline')) {
1312         $mail->{contenttype} = "text/html";
1313
1314         $mail->{message}       =~ s/\r//g;
1315         $mail->{message}       =~ s/\n/<br>\n/g;
1316         $myconfig->{signature} =~ s/\n/<br>\n/g;
1317         $mail->{message} .= "<br>\n-- <br>\n$myconfig->{signature}\n<br>";
1318
1319         open(IN, $self->{tmpfile})
1320           or $self->error($self->cleanup . "$self->{tmpfile} : $!");
1321         while (<IN>) {
1322           $mail->{message} .= $_;
1323         }
1324
1325         close(IN);
1326
1327       } else {
1328
1329         if (!$self->{"do_not_attach"}) {
1330           my $attachment_name  =  $self->{attachment_filename} || $self->{tmpfile};
1331           $attachment_name     =~ s/\.(.+?)$/.${ext_for_format}/ if ($ext_for_format);
1332           $mail->{attachments} =  [{ "filename" => $self->{tmpfile},
1333                                      "name"     => $attachment_name }];
1334         }
1335
1336         $mail->{message}  =~ s/\r//g;
1337         $mail->{message} .=  "\n-- \n$myconfig->{signature}";
1338
1339       }
1340
1341       my $err = $mail->send();
1342       $self->error($self->cleanup . "$err") if ($err);
1343
1344     } else {
1345
1346       $self->{OUT} = $out;
1347
1348       my $numbytes = (-s $self->{tmpfile});
1349       open(IN, $self->{tmpfile})
1350         or $self->error($self->cleanup . "$self->{tmpfile} : $!");
1351
1352       $self->{copies} = 1 unless $self->{media} eq 'printer';
1353
1354       chdir("$self->{cwd}");
1355       #print(STDERR "Kopien $self->{copies}\n");
1356       #print(STDERR "OUT $self->{OUT}\n");
1357       for my $i (1 .. $self->{copies}) {
1358         if ($self->{OUT}) {
1359           open OUT, $self->{OUT} or $self->error($self->cleanup . "$self->{OUT} : $!");
1360           print OUT while <IN>;
1361           close OUT;
1362           seek IN, 0, 0;
1363
1364         } else {
1365           $self->{attachment_filename} = ($self->{attachment_filename})
1366                                        ? $self->{attachment_filename}
1367                                        : $self->generate_attachment_filename();
1368
1369           # launch application
1370           print qq|Content-Type: | . $template->get_mime_type() . qq|
1371 Content-Disposition: attachment; filename="$self->{attachment_filename}"
1372 Content-Length: $numbytes
1373
1374 |;
1375
1376           $::locale->with_raw_io(\*STDOUT, sub { print while <IN> });
1377         }
1378       }
1379
1380       close(IN);
1381     }
1382
1383   }
1384
1385   $self->cleanup;
1386
1387   chdir("$self->{cwd}");
1388   $main::lxdebug->leave_sub();
1389 }
1390
1391 sub get_formname_translation {
1392   $main::lxdebug->enter_sub();
1393   my ($self, $formname) = @_;
1394
1395   $formname ||= $self->{formname};
1396
1397   my %formname_translations = (
1398     bin_list                => $main::locale->text('Bin List'),
1399     credit_note             => $main::locale->text('Credit Note'),
1400     invoice                 => $main::locale->text('Invoice'),
1401     packing_list            => $main::locale->text('Packing List'),
1402     pick_list               => $main::locale->text('Pick List'),
1403     proforma                => $main::locale->text('Proforma Invoice'),
1404     purchase_order          => $main::locale->text('Purchase Order'),
1405     request_quotation       => $main::locale->text('RFQ'),
1406     sales_order             => $main::locale->text('Confirmation'),
1407     sales_quotation         => $main::locale->text('Quotation'),
1408     storno_invoice          => $main::locale->text('Storno Invoice'),
1409     storno_packing_list     => $main::locale->text('Storno Packing List'),
1410     sales_delivery_order    => $main::locale->text('Delivery Order'),
1411     purchase_delivery_order => $main::locale->text('Delivery Order'),
1412     dunning                 => $main::locale->text('Dunning'),
1413   );
1414
1415   $main::lxdebug->leave_sub();
1416   return $formname_translations{$formname}
1417 }
1418
1419 sub get_number_prefix_for_type {
1420   $main::lxdebug->enter_sub();
1421   my ($self) = @_;
1422
1423   my $prefix =
1424       (first { $self->{type} eq $_ } qw(invoice credit_note)) ? 'inv'
1425     : ($self->{type} =~ /_quotation$/)                        ? 'quo'
1426     : ($self->{type} =~ /_delivery_order$/)                   ? 'do'
1427     :                                                           'ord';
1428
1429   $main::lxdebug->leave_sub();
1430   return $prefix;
1431 }
1432
1433 sub get_extension_for_format {
1434   $main::lxdebug->enter_sub();
1435   my ($self)    = @_;
1436
1437   my $extension = $self->{format} =~ /pdf/i          ? ".pdf"
1438                 : $self->{format} =~ /postscript/i   ? ".ps"
1439                 : $self->{format} =~ /opendocument/i ? ".odt"
1440                 : $self->{format} =~ /excel/i        ? ".xls"
1441                 : $self->{format} =~ /html/i         ? ".html"
1442                 :                                      "";
1443
1444   $main::lxdebug->leave_sub();
1445   return $extension;
1446 }
1447
1448 sub generate_attachment_filename {
1449   $main::lxdebug->enter_sub();
1450   my ($self) = @_;
1451
1452   my $attachment_filename = $main::locale->unquote_special_chars('HTML', $self->get_formname_translation());
1453   my $prefix              = $self->get_number_prefix_for_type();
1454
1455   if ($self->{preview} && (first { $self->{type} eq $_ } qw(invoice credit_note))) {
1456     $attachment_filename .= ' (' . $main::locale->text('Preview') . ')' . $self->get_extension_for_format();
1457
1458   } elsif ($attachment_filename && $self->{"${prefix}number"}) {
1459     $attachment_filename .=  "_" . $self->{"${prefix}number"} . $self->get_extension_for_format();
1460
1461   } else {
1462     $attachment_filename = "";
1463   }
1464
1465   $attachment_filename =  $main::locale->quote_special_chars('filenames', $attachment_filename);
1466   $attachment_filename =~ s|[\s/\\]+|_|g;
1467
1468   $main::lxdebug->leave_sub();
1469   return $attachment_filename;
1470 }
1471
1472 sub generate_email_subject {
1473   $main::lxdebug->enter_sub();
1474   my ($self) = @_;
1475
1476   my $subject = $main::locale->unquote_special_chars('HTML', $self->get_formname_translation());
1477   my $prefix  = $self->get_number_prefix_for_type();
1478
1479   if ($subject && $self->{"${prefix}number"}) {
1480     $subject .= " " . $self->{"${prefix}number"}
1481   }
1482
1483   $main::lxdebug->leave_sub();
1484   return $subject;
1485 }
1486
1487 sub cleanup {
1488   $main::lxdebug->enter_sub();
1489
1490   my $self = shift;
1491
1492   chdir("$self->{tmpdir}");
1493
1494   my @err = ();
1495   if (-f "$self->{tmpfile}.err") {
1496     open(FH, "$self->{tmpfile}.err");
1497     @err = <FH>;
1498     close(FH);
1499   }
1500
1501   if ($self->{tmpfile} && ! $::keep_temp_files) {
1502     $self->{tmpfile} =~ s|.*/||g;
1503     # strip extension
1504     $self->{tmpfile} =~ s/\.\w+$//g;
1505     my $tmpfile = $self->{tmpfile};
1506     unlink(<$tmpfile.*>);
1507   }
1508
1509   chdir("$self->{cwd}");
1510
1511   $main::lxdebug->leave_sub();
1512
1513   return "@err";
1514 }
1515
1516 sub datetonum {
1517   $main::lxdebug->enter_sub();
1518
1519   my ($self, $date, $myconfig) = @_;
1520   my ($yy, $mm, $dd);
1521
1522   if ($date && $date =~ /\D/) {
1523
1524     if ($myconfig->{dateformat} =~ /^yy/) {
1525       ($yy, $mm, $dd) = split /\D/, $date;
1526     }
1527     if ($myconfig->{dateformat} =~ /^mm/) {
1528       ($mm, $dd, $yy) = split /\D/, $date;
1529     }
1530     if ($myconfig->{dateformat} =~ /^dd/) {
1531       ($dd, $mm, $yy) = split /\D/, $date;
1532     }
1533
1534     $dd *= 1;
1535     $mm *= 1;
1536     $yy = ($yy < 70) ? $yy + 2000 : $yy;
1537     $yy = ($yy >= 70 && $yy <= 99) ? $yy + 1900 : $yy;
1538
1539     $dd = "0$dd" if ($dd < 10);
1540     $mm = "0$mm" if ($mm < 10);
1541
1542     $date = "$yy$mm$dd";
1543   }
1544
1545   $main::lxdebug->leave_sub();
1546
1547   return $date;
1548 }
1549
1550 # Database routines used throughout
1551
1552 sub dbconnect {
1553   $main::lxdebug->enter_sub(2);
1554
1555   my ($self, $myconfig) = @_;
1556
1557   # connect to database
1558   my $dbh =
1559     DBI->connect($myconfig->{dbconnect},
1560                  $myconfig->{dbuser}, $myconfig->{dbpasswd})
1561     or $self->dberror;
1562
1563   # set db options
1564   if ($myconfig->{dboptions}) {
1565     $dbh->do($myconfig->{dboptions}) || $self->dberror($myconfig->{dboptions});
1566   }
1567
1568   $main::lxdebug->leave_sub(2);
1569
1570   return $dbh;
1571 }
1572
1573 sub dbconnect_noauto {
1574   $main::lxdebug->enter_sub();
1575
1576   my ($self, $myconfig) = @_;
1577
1578   # connect to database
1579   my $dbh =
1580     DBI->connect($myconfig->{dbconnect}, $myconfig->{dbuser},
1581                  $myconfig->{dbpasswd}, { AutoCommit => 0 })
1582     or $self->dberror;
1583
1584   # set db options
1585   if ($myconfig->{dboptions}) {
1586     $dbh->do($myconfig->{dboptions}) || $self->dberror($myconfig->{dboptions});
1587   }
1588
1589   $main::lxdebug->leave_sub();
1590
1591   return $dbh;
1592 }
1593
1594 sub get_standard_dbh {
1595   $main::lxdebug->enter_sub(2);
1596
1597   my $self     = shift;
1598   my $myconfig = shift || \%::myconfig;
1599
1600   if ($standard_dbh && !$standard_dbh->{Active}) {
1601     $main::lxdebug->message(LXDebug->INFO(), "get_standard_dbh: \$standard_dbh is defined but not Active anymore");
1602     undef $standard_dbh;
1603   }
1604
1605   $standard_dbh ||= $self->dbconnect_noauto($myconfig);
1606
1607   $main::lxdebug->leave_sub(2);
1608
1609   return $standard_dbh;
1610 }
1611
1612 sub date_closed {
1613   $main::lxdebug->enter_sub();
1614
1615   my ($self, $date, $myconfig) = @_;
1616   my $dbh = $self->dbconnect($myconfig);
1617
1618   my $query = "SELECT 1 FROM defaults WHERE ? < closedto";
1619   my $sth = prepare_execute_query($self, $dbh, $query, $date);
1620   my ($closed) = $sth->fetchrow_array;
1621
1622   $main::lxdebug->leave_sub();
1623
1624   return $closed;
1625 }
1626
1627 sub update_balance {
1628   $main::lxdebug->enter_sub();
1629
1630   my ($self, $dbh, $table, $field, $where, $value, @values) = @_;
1631
1632   # if we have a value, go do it
1633   if ($value != 0) {
1634
1635     # retrieve balance from table
1636     my $query = "SELECT $field FROM $table WHERE $where FOR UPDATE";
1637     my $sth = prepare_execute_query($self, $dbh, $query, @values);
1638     my ($balance) = $sth->fetchrow_array;
1639     $sth->finish;
1640
1641     $balance += $value;
1642
1643     # update balance
1644     $query = "UPDATE $table SET $field = $balance WHERE $where";
1645     do_query($self, $dbh, $query, @values);
1646   }
1647   $main::lxdebug->leave_sub();
1648 }
1649
1650 sub update_exchangerate {
1651   $main::lxdebug->enter_sub();
1652
1653   my ($self, $dbh, $curr, $transdate, $buy, $sell) = @_;
1654   my ($query);
1655   # some sanity check for currency
1656   if ($curr eq '') {
1657     $main::lxdebug->leave_sub();
1658     return;
1659   }
1660   $query = qq|SELECT curr FROM defaults|;
1661
1662   my ($currency) = selectrow_query($self, $dbh, $query);
1663   my ($defaultcurrency) = split m/:/, $currency;
1664
1665
1666   if ($curr eq $defaultcurrency) {
1667     $main::lxdebug->leave_sub();
1668     return;
1669   }
1670
1671   $query = qq|SELECT e.curr FROM exchangerate e
1672                  WHERE e.curr = ? AND e.transdate = ?
1673                  FOR UPDATE|;
1674   my $sth = prepare_execute_query($self, $dbh, $query, $curr, $transdate);
1675
1676   if ($buy == 0) {
1677     $buy = "";
1678   }
1679   if ($sell == 0) {
1680     $sell = "";
1681   }
1682
1683   $buy = conv_i($buy, "NULL");
1684   $sell = conv_i($sell, "NULL");
1685
1686   my $set;
1687   if ($buy != 0 && $sell != 0) {
1688     $set = "buy = $buy, sell = $sell";
1689   } elsif ($buy != 0) {
1690     $set = "buy = $buy";
1691   } elsif ($sell != 0) {
1692     $set = "sell = $sell";
1693   }
1694
1695   if ($sth->fetchrow_array) {
1696     $query = qq|UPDATE exchangerate
1697                 SET $set
1698                 WHERE curr = ?
1699                 AND transdate = ?|;
1700
1701   } else {
1702     $query = qq|INSERT INTO exchangerate (curr, buy, sell, transdate)
1703                 VALUES (?, $buy, $sell, ?)|;
1704   }
1705   $sth->finish;
1706   do_query($self, $dbh, $query, $curr, $transdate);
1707
1708   $main::lxdebug->leave_sub();
1709 }
1710
1711 sub save_exchangerate {
1712   $main::lxdebug->enter_sub();
1713
1714   my ($self, $myconfig, $currency, $transdate, $rate, $fld) = @_;
1715
1716   my $dbh = $self->dbconnect($myconfig);
1717
1718   my ($buy, $sell);
1719
1720   $buy  = $rate if $fld eq 'buy';
1721   $sell = $rate if $fld eq 'sell';
1722
1723
1724   $self->update_exchangerate($dbh, $currency, $transdate, $buy, $sell);
1725
1726
1727   $dbh->disconnect;
1728
1729   $main::lxdebug->leave_sub();
1730 }
1731
1732 sub get_exchangerate {
1733   $main::lxdebug->enter_sub();
1734
1735   my ($self, $dbh, $curr, $transdate, $fld) = @_;
1736   my ($query);
1737
1738   unless ($transdate) {
1739     $main::lxdebug->leave_sub();
1740     return 1;
1741   }
1742
1743   $query = qq|SELECT curr FROM defaults|;
1744
1745   my ($currency) = selectrow_query($self, $dbh, $query);
1746   my ($defaultcurrency) = split m/:/, $currency;
1747
1748   if ($currency eq $defaultcurrency) {
1749     $main::lxdebug->leave_sub();
1750     return 1;
1751   }
1752
1753   $query = qq|SELECT e.$fld FROM exchangerate e
1754                  WHERE e.curr = ? AND e.transdate = ?|;
1755   my ($exchangerate) = selectrow_query($self, $dbh, $query, $curr, $transdate);
1756
1757
1758
1759   $main::lxdebug->leave_sub();
1760
1761   return $exchangerate;
1762 }
1763
1764 sub check_exchangerate {
1765   $main::lxdebug->enter_sub();
1766
1767   my ($self, $myconfig, $currency, $transdate, $fld) = @_;
1768
1769   if ($fld !~/^buy|sell$/) {
1770     $self->error('Fatal: check_exchangerate called with invalid buy/sell argument');
1771   }
1772
1773   unless ($transdate) {
1774     $main::lxdebug->leave_sub();
1775     return "";
1776   }
1777
1778   my ($defaultcurrency) = $self->get_default_currency($myconfig);
1779
1780   if ($currency eq $defaultcurrency) {
1781     $main::lxdebug->leave_sub();
1782     return 1;
1783   }
1784
1785   my $dbh   = $self->get_standard_dbh($myconfig);
1786   my $query = qq|SELECT e.$fld FROM exchangerate e
1787                  WHERE e.curr = ? AND e.transdate = ?|;
1788
1789   my ($exchangerate) = selectrow_query($self, $dbh, $query, $currency, $transdate);
1790
1791   $main::lxdebug->leave_sub();
1792
1793   return $exchangerate;
1794 }
1795
1796 sub get_all_currencies {
1797   $main::lxdebug->enter_sub();
1798
1799   my $self     = shift;
1800   my $myconfig = shift || \%::myconfig;
1801   my $dbh      = $self->get_standard_dbh($myconfig);
1802
1803   my $query = qq|SELECT curr FROM defaults|;
1804
1805   my ($curr)     = selectrow_query($self, $dbh, $query);
1806   my @currencies = grep { $_ } map { s/\s//g; $_ } split m/:/, $curr;
1807
1808   $main::lxdebug->leave_sub();
1809
1810   return @currencies;
1811 }
1812
1813 sub get_default_currency {
1814   $main::lxdebug->enter_sub();
1815
1816   my ($self, $myconfig) = @_;
1817   my @currencies        = $self->get_all_currencies($myconfig);
1818
1819   $main::lxdebug->leave_sub();
1820
1821   return $currencies[0];
1822 }
1823
1824 sub set_payment_options {
1825   $main::lxdebug->enter_sub();
1826
1827   my ($self, $myconfig, $transdate) = @_;
1828
1829   return $main::lxdebug->leave_sub() unless ($self->{payment_id});
1830
1831   my $dbh = $self->get_standard_dbh($myconfig);
1832
1833   my $query =
1834     qq|SELECT p.terms_netto, p.terms_skonto, p.percent_skonto, p.description_long | .
1835     qq|FROM payment_terms p | .
1836     qq|WHERE p.id = ?|;
1837
1838   ($self->{terms_netto}, $self->{terms_skonto}, $self->{percent_skonto},
1839    $self->{payment_terms}) =
1840      selectrow_query($self, $dbh, $query, $self->{payment_id});
1841
1842   if ($transdate eq "") {
1843     if ($self->{invdate}) {
1844       $transdate = $self->{invdate};
1845     } else {
1846       $transdate = $self->{transdate};
1847     }
1848   }
1849
1850   $query =
1851     qq|SELECT ?::date + ?::integer AS netto_date, ?::date + ?::integer AS skonto_date | .
1852     qq|FROM payment_terms|;
1853   ($self->{netto_date}, $self->{skonto_date}) =
1854     selectrow_query($self, $dbh, $query, $transdate, $self->{terms_netto}, $transdate, $self->{terms_skonto});
1855
1856   my ($invtotal, $total);
1857   my (%amounts, %formatted_amounts);
1858
1859   if ($self->{type} =~ /_order$/) {
1860     $amounts{invtotal} = $self->{ordtotal};
1861     $amounts{total}    = $self->{ordtotal};
1862
1863   } elsif ($self->{type} =~ /_quotation$/) {
1864     $amounts{invtotal} = $self->{quototal};
1865     $amounts{total}    = $self->{quototal};
1866
1867   } else {
1868     $amounts{invtotal} = $self->{invtotal};
1869     $amounts{total}    = $self->{total};
1870   }
1871   $amounts{skonto_in_percent} = 100.0 * $self->{percent_skonto};
1872
1873   map { $amounts{$_} = $self->parse_amount($myconfig, $amounts{$_}) } keys %amounts;
1874
1875   $amounts{skonto_amount}      = $amounts{invtotal} * $self->{percent_skonto};
1876   $amounts{invtotal_wo_skonto} = $amounts{invtotal} * (1 - $self->{percent_skonto});
1877   $amounts{total_wo_skonto}    = $amounts{total}    * (1 - $self->{percent_skonto});
1878
1879   foreach (keys %amounts) {
1880     $amounts{$_}           = $self->round_amount($amounts{$_}, 2);
1881     $formatted_amounts{$_} = $self->format_amount($myconfig, $amounts{$_}, 2);
1882   }
1883
1884   if ($self->{"language_id"}) {
1885     $query =
1886       qq|SELECT t.description_long, l.output_numberformat, l.output_dateformat, l.output_longdates | .
1887       qq|FROM translation_payment_terms t | .
1888       qq|LEFT JOIN language l ON t.language_id = l.id | .
1889       qq|WHERE (t.language_id = ?) AND (t.payment_terms_id = ?)|;
1890     my ($description_long, $output_numberformat, $output_dateformat,
1891       $output_longdates) =
1892       selectrow_query($self, $dbh, $query,
1893                       $self->{"language_id"}, $self->{"payment_id"});
1894
1895     $self->{payment_terms} = $description_long if ($description_long);
1896
1897     if ($output_dateformat) {
1898       foreach my $key (qw(netto_date skonto_date)) {
1899         $self->{$key} =
1900           $main::locale->reformat_date($myconfig, $self->{$key},
1901                                        $output_dateformat,
1902                                        $output_longdates);
1903       }
1904     }
1905
1906     if ($output_numberformat &&
1907         ($output_numberformat ne $myconfig->{"numberformat"})) {
1908       my $saved_numberformat = $myconfig->{"numberformat"};
1909       $myconfig->{"numberformat"} = $output_numberformat;
1910       map { $formatted_amounts{$_} = $self->format_amount($myconfig, $amounts{$_}) } keys %amounts;
1911       $myconfig->{"numberformat"} = $saved_numberformat;
1912     }
1913   }
1914
1915   $self->{payment_terms} =~ s/<%netto_date%>/$self->{netto_date}/g;
1916   $self->{payment_terms} =~ s/<%skonto_date%>/$self->{skonto_date}/g;
1917   $self->{payment_terms} =~ s/<%currency%>/$self->{currency}/g;
1918   $self->{payment_terms} =~ s/<%terms_netto%>/$self->{terms_netto}/g;
1919   $self->{payment_terms} =~ s/<%account_number%>/$self->{account_number}/g;
1920   $self->{payment_terms} =~ s/<%bank%>/$self->{bank}/g;
1921   $self->{payment_terms} =~ s/<%bank_code%>/$self->{bank_code}/g;
1922
1923   map { $self->{payment_terms} =~ s/<%${_}%>/$formatted_amounts{$_}/g; } keys %formatted_amounts;
1924
1925   $self->{skonto_in_percent} = $formatted_amounts{skonto_in_percent};
1926
1927   $main::lxdebug->leave_sub();
1928
1929 }
1930
1931 sub get_template_language {
1932   $main::lxdebug->enter_sub();
1933
1934   my ($self, $myconfig) = @_;
1935
1936   my $template_code = "";
1937
1938   if ($self->{language_id}) {
1939     my $dbh = $self->get_standard_dbh($myconfig);
1940     my $query = qq|SELECT template_code FROM language WHERE id = ?|;
1941     ($template_code) = selectrow_query($self, $dbh, $query, $self->{language_id});
1942   }
1943
1944   $main::lxdebug->leave_sub();
1945
1946   return $template_code;
1947 }
1948
1949 sub get_printer_code {
1950   $main::lxdebug->enter_sub();
1951
1952   my ($self, $myconfig) = @_;
1953
1954   my $template_code = "";
1955
1956   if ($self->{printer_id}) {
1957     my $dbh = $self->get_standard_dbh($myconfig);
1958     my $query = qq|SELECT template_code, printer_command FROM printers WHERE id = ?|;
1959     ($template_code, $self->{printer_command}) = selectrow_query($self, $dbh, $query, $self->{printer_id});
1960   }
1961
1962   $main::lxdebug->leave_sub();
1963
1964   return $template_code;
1965 }
1966
1967 sub get_shipto {
1968   $main::lxdebug->enter_sub();
1969
1970   my ($self, $myconfig) = @_;
1971
1972   my $template_code = "";
1973
1974   if ($self->{shipto_id}) {
1975     my $dbh = $self->get_standard_dbh($myconfig);
1976     my $query = qq|SELECT * FROM shipto WHERE shipto_id = ?|;
1977     my $ref = selectfirst_hashref_query($self, $dbh, $query, $self->{shipto_id});
1978     map({ $self->{$_} = $ref->{$_} } keys(%$ref));
1979   }
1980
1981   $main::lxdebug->leave_sub();
1982 }
1983
1984 sub add_shipto {
1985   $main::lxdebug->enter_sub();
1986
1987   my ($self, $dbh, $id, $module) = @_;
1988
1989   my $shipto;
1990   my @values;
1991
1992   foreach my $item (qw(name department_1 department_2 street zipcode city country
1993                        contact phone fax email)) {
1994     if ($self->{"shipto$item"}) {
1995       $shipto = 1 if ($self->{$item} ne $self->{"shipto$item"});
1996     }
1997     push(@values, $self->{"shipto${item}"});
1998   }
1999
2000   if ($shipto) {
2001     if ($self->{shipto_id}) {
2002       my $query = qq|UPDATE shipto set
2003                        shiptoname = ?,
2004                        shiptodepartment_1 = ?,
2005                        shiptodepartment_2 = ?,
2006                        shiptostreet = ?,
2007                        shiptozipcode = ?,
2008                        shiptocity = ?,
2009                        shiptocountry = ?,
2010                        shiptocontact = ?,
2011                        shiptophone = ?,
2012                        shiptofax = ?,
2013                        shiptoemail = ?
2014                      WHERE shipto_id = ?|;
2015       do_query($self, $dbh, $query, @values, $self->{shipto_id});
2016     } else {
2017       my $query = qq|SELECT * FROM shipto
2018                      WHERE shiptoname = ? AND
2019                        shiptodepartment_1 = ? AND
2020                        shiptodepartment_2 = ? AND
2021                        shiptostreet = ? AND
2022                        shiptozipcode = ? AND
2023                        shiptocity = ? AND
2024                        shiptocountry = ? AND
2025                        shiptocontact = ? AND
2026                        shiptophone = ? AND
2027                        shiptofax = ? AND
2028                        shiptoemail = ? AND
2029                        module = ? AND
2030                        trans_id = ?|;
2031       my $insert_check = selectfirst_hashref_query($self, $dbh, $query, @values, $module, $id);
2032       if(!$insert_check){
2033         $query =
2034           qq|INSERT INTO shipto (trans_id, shiptoname, shiptodepartment_1, shiptodepartment_2,
2035                                  shiptostreet, shiptozipcode, shiptocity, shiptocountry,
2036                                  shiptocontact, shiptophone, shiptofax, shiptoemail, module)
2037              VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)|;
2038         do_query($self, $dbh, $query, $id, @values, $module);
2039       }
2040     }
2041   }
2042
2043   $main::lxdebug->leave_sub();
2044 }
2045
2046 sub get_employee {
2047   $main::lxdebug->enter_sub();
2048
2049   my ($self, $dbh) = @_;
2050
2051   $dbh ||= $self->get_standard_dbh(\%main::myconfig);
2052
2053   my $query = qq|SELECT id, name FROM employee WHERE login = ?|;
2054   ($self->{"employee_id"}, $self->{"employee"}) = selectrow_query($self, $dbh, $query, $self->{login});
2055   $self->{"employee_id"} *= 1;
2056
2057   $main::lxdebug->leave_sub();
2058 }
2059
2060 sub get_employee_data {
2061   $main::lxdebug->enter_sub();
2062
2063   my $self     = shift;
2064   my %params   = @_;
2065
2066   Common::check_params(\%params, qw(prefix));
2067   Common::check_params_x(\%params, qw(id));
2068
2069   if (!$params{id}) {
2070     $main::lxdebug->leave_sub();
2071     return;
2072   }
2073
2074   my $myconfig = \%main::myconfig;
2075   my $dbh      = $params{dbh} || $self->get_standard_dbh($myconfig);
2076
2077   my ($login)  = selectrow_query($self, $dbh, qq|SELECT login FROM employee WHERE id = ?|, conv_i($params{id}));
2078
2079   if ($login) {
2080     my $user = User->new($login);
2081     map { $self->{$params{prefix} . "_${_}"} = $user->{$_}; } qw(address businessnumber co_ustid company duns email fax name signature taxnumber tel);
2082
2083     $self->{$params{prefix} . '_login'}   = $login;
2084     $self->{$params{prefix} . '_name'}  ||= $login;
2085   }
2086
2087   $main::lxdebug->leave_sub();
2088 }
2089
2090 sub get_duedate {
2091   $main::lxdebug->enter_sub();
2092
2093   my ($self, $myconfig, $reference_date) = @_;
2094
2095   $reference_date = $reference_date ? conv_dateq($reference_date) . '::DATE' : 'current_date';
2096
2097   my $dbh         = $self->get_standard_dbh($myconfig);
2098   my $query       = qq|SELECT ${reference_date} + terms_netto FROM payment_terms WHERE id = ?|;
2099   my ($duedate)   = selectrow_query($self, $dbh, $query, $self->{payment_id});
2100
2101   $main::lxdebug->leave_sub();
2102
2103   return $duedate;
2104 }
2105
2106 sub _get_contacts {
2107   $main::lxdebug->enter_sub();
2108
2109   my ($self, $dbh, $id, $key) = @_;
2110
2111   $key = "all_contacts" unless ($key);
2112
2113   if (!$id) {
2114     $self->{$key} = [];
2115     $main::lxdebug->leave_sub();
2116     return;
2117   }
2118
2119   my $query =
2120     qq|SELECT cp_id, cp_cv_id, cp_name, cp_givenname, cp_abteilung | .
2121     qq|FROM contacts | .
2122     qq|WHERE cp_cv_id = ? | .
2123     qq|ORDER BY lower(cp_name)|;
2124
2125   $self->{$key} = selectall_hashref_query($self, $dbh, $query, $id);
2126
2127   $main::lxdebug->leave_sub();
2128 }
2129
2130 sub _get_projects {
2131   $main::lxdebug->enter_sub();
2132
2133   my ($self, $dbh, $key) = @_;
2134
2135   my ($all, $old_id, $where, @values);
2136
2137   if (ref($key) eq "HASH") {
2138     my $params = $key;
2139
2140     $key = "ALL_PROJECTS";
2141
2142     foreach my $p (keys(%{$params})) {
2143       if ($p eq "all") {
2144         $all = $params->{$p};
2145       } elsif ($p eq "old_id") {
2146         $old_id = $params->{$p};
2147       } elsif ($p eq "key") {
2148         $key = $params->{$p};
2149       }
2150     }
2151   }
2152
2153   if (!$all) {
2154     $where = "WHERE active ";
2155     if ($old_id) {
2156       if (ref($old_id) eq "ARRAY") {
2157         my @ids = grep({ $_ } @{$old_id});
2158         if (@ids) {
2159           $where .= " OR id IN (" . join(",", map({ "?" } @ids)) . ") ";
2160           push(@values, @ids);
2161         }
2162       } else {
2163         $where .= " OR (id = ?) ";
2164         push(@values, $old_id);
2165       }
2166     }
2167   }
2168
2169   my $query =
2170     qq|SELECT id, projectnumber, description, active | .
2171     qq|FROM project | .
2172     $where .
2173     qq|ORDER BY lower(projectnumber)|;
2174
2175   $self->{$key} = selectall_hashref_query($self, $dbh, $query, @values);
2176
2177   $main::lxdebug->leave_sub();
2178 }
2179
2180 sub _get_shipto {
2181   $main::lxdebug->enter_sub();
2182
2183   my ($self, $dbh, $vc_id, $key) = @_;
2184
2185   $key = "all_shipto" unless ($key);
2186
2187   if ($vc_id) {
2188     # get shipping addresses
2189     my $query = qq|SELECT * FROM shipto WHERE trans_id = ?|;
2190
2191     $self->{$key} = selectall_hashref_query($self, $dbh, $query, $vc_id);
2192
2193   } else {
2194     $self->{$key} = [];
2195   }
2196
2197   $main::lxdebug->leave_sub();
2198 }
2199
2200 sub _get_printers {
2201   $main::lxdebug->enter_sub();
2202
2203   my ($self, $dbh, $key) = @_;
2204
2205   $key = "all_printers" unless ($key);
2206
2207   my $query = qq|SELECT id, printer_description, printer_command, template_code FROM printers|;
2208
2209   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2210
2211   $main::lxdebug->leave_sub();
2212 }
2213
2214 sub _get_charts {
2215   $main::lxdebug->enter_sub();
2216
2217   my ($self, $dbh, $params) = @_;
2218   my ($key);
2219
2220   $key = $params->{key};
2221   $key = "all_charts" unless ($key);
2222
2223   my $transdate = quote_db_date($params->{transdate});
2224
2225   my $query =
2226     qq|SELECT c.id, c.accno, c.description, c.link, c.charttype, tk.taxkey_id, tk.tax_id | .
2227     qq|FROM chart c | .
2228     qq|LEFT JOIN taxkeys tk ON | .
2229     qq|(tk.id = (SELECT id FROM taxkeys | .
2230     qq|          WHERE taxkeys.chart_id = c.id AND startdate <= $transdate | .
2231     qq|          ORDER BY startdate DESC LIMIT 1)) | .
2232     qq|ORDER BY c.accno|;
2233
2234   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2235
2236   $main::lxdebug->leave_sub();
2237 }
2238
2239 sub _get_taxcharts {
2240   $main::lxdebug->enter_sub();
2241
2242   my ($self, $dbh, $params) = @_;
2243
2244   my $key = "all_taxcharts";
2245   my @where;
2246
2247   if (ref $params eq 'HASH') {
2248     $key = $params->{key} if ($params->{key});
2249     if ($params->{module} eq 'AR') {
2250       push @where, 'taxkey NOT IN (8, 9, 18, 19)';
2251
2252     } elsif ($params->{module} eq 'AP') {
2253       push @where, 'taxkey NOT IN (1, 2, 3, 12, 13)';
2254     }
2255
2256   } elsif ($params) {
2257     $key = $params;
2258   }
2259
2260   my $where = ' WHERE ' . join(' AND ', map { "($_)" } @where) if (@where);
2261
2262   my $query = qq|SELECT * FROM tax $where ORDER BY taxkey|;
2263
2264   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2265
2266   $main::lxdebug->leave_sub();
2267 }
2268
2269 sub _get_taxzones {
2270   $main::lxdebug->enter_sub();
2271
2272   my ($self, $dbh, $key) = @_;
2273
2274   $key = "all_taxzones" unless ($key);
2275
2276   my $query = qq|SELECT * FROM tax_zones ORDER BY id|;
2277
2278   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2279
2280   $main::lxdebug->leave_sub();
2281 }
2282
2283 sub _get_employees {
2284   $main::lxdebug->enter_sub();
2285
2286   my ($self, $dbh, $default_key, $key) = @_;
2287
2288   $key = $default_key unless ($key);
2289   $self->{$key} = selectall_hashref_query($self, $dbh, qq|SELECT * FROM employee ORDER BY lower(name)|);
2290
2291   $main::lxdebug->leave_sub();
2292 }
2293
2294 sub _get_business_types {
2295   $main::lxdebug->enter_sub();
2296
2297   my ($self, $dbh, $key) = @_;
2298
2299   my $options       = ref $key eq 'HASH' ? $key : { key => $key };
2300   $options->{key} ||= "all_business_types";
2301   my $where         = '';
2302
2303   if (exists $options->{salesman}) {
2304     $where = 'WHERE ' . ($options->{salesman} ? '' : 'NOT ') . 'COALESCE(salesman)';
2305   }
2306
2307   $self->{ $options->{key} } = selectall_hashref_query($self, $dbh, qq|SELECT * FROM business $where ORDER BY lower(description)|);
2308
2309   $main::lxdebug->leave_sub();
2310 }
2311
2312 sub _get_languages {
2313   $main::lxdebug->enter_sub();
2314
2315   my ($self, $dbh, $key) = @_;
2316
2317   $key = "all_languages" unless ($key);
2318
2319   my $query = qq|SELECT * FROM language ORDER BY id|;
2320
2321   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2322
2323   $main::lxdebug->leave_sub();
2324 }
2325
2326 sub _get_dunning_configs {
2327   $main::lxdebug->enter_sub();
2328
2329   my ($self, $dbh, $key) = @_;
2330
2331   $key = "all_dunning_configs" unless ($key);
2332
2333   my $query = qq|SELECT * FROM dunning_config ORDER BY dunning_level|;
2334
2335   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2336
2337   $main::lxdebug->leave_sub();
2338 }
2339
2340 sub _get_currencies {
2341 $main::lxdebug->enter_sub();
2342
2343   my ($self, $dbh, $key) = @_;
2344
2345   $key = "all_currencies" unless ($key);
2346
2347   my $query = qq|SELECT curr AS currency FROM defaults|;
2348
2349   $self->{$key} = [split(/\:/ , selectfirst_hashref_query($self, $dbh, $query)->{currency})];
2350
2351   $main::lxdebug->leave_sub();
2352 }
2353
2354 sub _get_payments {
2355 $main::lxdebug->enter_sub();
2356
2357   my ($self, $dbh, $key) = @_;
2358
2359   $key = "all_payments" unless ($key);
2360
2361   my $query = qq|SELECT * FROM payment_terms ORDER BY id|;
2362
2363   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2364
2365   $main::lxdebug->leave_sub();
2366 }
2367
2368 sub _get_customers {
2369   $main::lxdebug->enter_sub();
2370
2371   my ($self, $dbh, $key) = @_;
2372
2373   my $options        = ref $key eq 'HASH' ? $key : { key => $key };
2374   $options->{key}  ||= "all_customers";
2375   my $limit_clause   = "LIMIT $options->{limit}" if $options->{limit};
2376
2377   my @where;
2378   push @where, qq|business_id IN (SELECT id FROM business WHERE salesman)| if  $options->{business_is_salesman};
2379   push @where, qq|NOT obsolete|                                            if !$options->{with_obsolete};
2380   my $where_str = @where ? "WHERE " . join(" AND ", map { "($_)" } @where) : '';
2381
2382   my $query = qq|SELECT * FROM customer $where_str ORDER BY name $limit_clause|;
2383   $self->{ $options->{key} } = selectall_hashref_query($self, $dbh, $query);
2384
2385   $main::lxdebug->leave_sub();
2386 }
2387
2388 sub _get_vendors {
2389   $main::lxdebug->enter_sub();
2390
2391   my ($self, $dbh, $key) = @_;
2392
2393   $key = "all_vendors" unless ($key);
2394
2395   my $query = qq|SELECT * FROM vendor WHERE NOT obsolete ORDER BY name|;
2396
2397   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2398
2399   $main::lxdebug->leave_sub();
2400 }
2401
2402 sub _get_departments {
2403   $main::lxdebug->enter_sub();
2404
2405   my ($self, $dbh, $key) = @_;
2406
2407   $key = "all_departments" unless ($key);
2408
2409   my $query = qq|SELECT * FROM department ORDER BY description|;
2410
2411   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2412
2413   $main::lxdebug->leave_sub();
2414 }
2415
2416 sub _get_warehouses {
2417   $main::lxdebug->enter_sub();
2418
2419   my ($self, $dbh, $param) = @_;
2420
2421   my ($key, $bins_key);
2422
2423   if ('' eq ref $param) {
2424     $key = $param;
2425
2426   } else {
2427     $key      = $param->{key};
2428     $bins_key = $param->{bins};
2429   }
2430
2431   my $query = qq|SELECT w.* FROM warehouse w
2432                  WHERE (NOT w.invalid) AND
2433                    ((SELECT COUNT(b.*) FROM bin b WHERE b.warehouse_id = w.id) > 0)
2434                  ORDER BY w.sortkey|;
2435
2436   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2437
2438   if ($bins_key) {
2439     $query = qq|SELECT id, description FROM bin WHERE warehouse_id = ?|;
2440     my $sth = prepare_query($self, $dbh, $query);
2441
2442     foreach my $warehouse (@{ $self->{$key} }) {
2443       do_statement($self, $sth, $query, $warehouse->{id});
2444       $warehouse->{$bins_key} = [];
2445
2446       while (my $ref = $sth->fetchrow_hashref()) {
2447         push @{ $warehouse->{$bins_key} }, $ref;
2448       }
2449     }
2450     $sth->finish();
2451   }
2452
2453   $main::lxdebug->leave_sub();
2454 }
2455
2456 sub _get_simple {
2457   $main::lxdebug->enter_sub();
2458
2459   my ($self, $dbh, $table, $key, $sortkey) = @_;
2460
2461   my $query  = qq|SELECT * FROM $table|;
2462   $query    .= qq| ORDER BY $sortkey| if ($sortkey);
2463
2464   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2465
2466   $main::lxdebug->leave_sub();
2467 }
2468
2469 #sub _get_groups {
2470 #  $main::lxdebug->enter_sub();
2471 #
2472 #  my ($self, $dbh, $key) = @_;
2473 #
2474 #  $key ||= "all_groups";
2475 #
2476 #  my $groups = $main::auth->read_groups();
2477 #
2478 #  $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2479 #
2480 #  $main::lxdebug->leave_sub();
2481 #}
2482
2483 sub get_lists {
2484   $main::lxdebug->enter_sub();
2485
2486   my $self = shift;
2487   my %params = @_;
2488
2489   my $dbh = $self->get_standard_dbh(\%main::myconfig);
2490   my ($sth, $query, $ref);
2491
2492   my $vc = $self->{"vc"} eq "customer" ? "customer" : "vendor";
2493   my $vc_id = $self->{"${vc}_id"};
2494
2495   if ($params{"contacts"}) {
2496     $self->_get_contacts($dbh, $vc_id, $params{"contacts"});
2497   }
2498
2499   if ($params{"shipto"}) {
2500     $self->_get_shipto($dbh, $vc_id, $params{"shipto"});
2501   }
2502
2503   if ($params{"projects"} || $params{"all_projects"}) {
2504     $self->_get_projects($dbh, $params{"all_projects"} ?
2505                          $params{"all_projects"} : $params{"projects"},
2506                          $params{"all_projects"} ? 1 : 0);
2507   }
2508
2509   if ($params{"printers"}) {
2510     $self->_get_printers($dbh, $params{"printers"});
2511   }
2512
2513   if ($params{"languages"}) {
2514     $self->_get_languages($dbh, $params{"languages"});
2515   }
2516
2517   if ($params{"charts"}) {
2518     $self->_get_charts($dbh, $params{"charts"});
2519   }
2520
2521   if ($params{"taxcharts"}) {
2522     $self->_get_taxcharts($dbh, $params{"taxcharts"});
2523   }
2524
2525   if ($params{"taxzones"}) {
2526     $self->_get_taxzones($dbh, $params{"taxzones"});
2527   }
2528
2529   if ($params{"employees"}) {
2530     $self->_get_employees($dbh, "all_employees", $params{"employees"});
2531   }
2532
2533   if ($params{"salesmen"}) {
2534     $self->_get_employees($dbh, "all_salesmen", $params{"salesmen"});
2535   }
2536
2537   if ($params{"business_types"}) {
2538     $self->_get_business_types($dbh, $params{"business_types"});
2539   }
2540
2541   if ($params{"dunning_configs"}) {
2542     $self->_get_dunning_configs($dbh, $params{"dunning_configs"});
2543   }
2544
2545   if($params{"currencies"}) {
2546     $self->_get_currencies($dbh, $params{"currencies"});
2547   }
2548
2549   if($params{"customers"}) {
2550     $self->_get_customers($dbh, $params{"customers"});
2551   }
2552
2553   if($params{"vendors"}) {
2554     if (ref $params{"vendors"} eq 'HASH') {
2555       $self->_get_vendors($dbh, $params{"vendors"}{key}, $params{"vendors"}{limit});
2556     } else {
2557       $self->_get_vendors($dbh, $params{"vendors"});
2558     }
2559   }
2560
2561   if($params{"payments"}) {
2562     $self->_get_payments($dbh, $params{"payments"});
2563   }
2564
2565   if($params{"departments"}) {
2566     $self->_get_departments($dbh, $params{"departments"});
2567   }
2568
2569   if ($params{price_factors}) {
2570     $self->_get_simple($dbh, 'price_factors', $params{price_factors}, 'sortkey');
2571   }
2572
2573   if ($params{warehouses}) {
2574     $self->_get_warehouses($dbh, $params{warehouses});
2575   }
2576
2577 #  if ($params{groups}) {
2578 #    $self->_get_groups($dbh, $params{groups});
2579 #  }
2580
2581   if ($params{partsgroup}) {
2582     $self->get_partsgroup(\%main::myconfig, { all => 1, target => $params{partsgroup} });
2583   }
2584
2585   $main::lxdebug->leave_sub();
2586 }
2587
2588 # this sub gets the id and name from $table
2589 sub get_name {
2590   $main::lxdebug->enter_sub();
2591
2592   my ($self, $myconfig, $table) = @_;
2593
2594   # connect to database
2595   my $dbh = $self->get_standard_dbh($myconfig);
2596
2597   $table = $table eq "customer" ? "customer" : "vendor";
2598   my $arap = $self->{arap} eq "ar" ? "ar" : "ap";
2599
2600   my ($query, @values);
2601
2602   if (!$self->{openinvoices}) {
2603     my $where;
2604     if ($self->{customernumber} ne "") {
2605       $where = qq|(vc.customernumber ILIKE ?)|;
2606       push(@values, '%' . $self->{customernumber} . '%');
2607     } else {
2608       $where = qq|(vc.name ILIKE ?)|;
2609       push(@values, '%' . $self->{$table} . '%');
2610     }
2611
2612     $query =
2613       qq~SELECT vc.id, vc.name,
2614            vc.street || ' ' || vc.zipcode || ' ' || vc.city || ' ' || vc.country AS address
2615          FROM $table vc
2616          WHERE $where AND (NOT vc.obsolete)
2617          ORDER BY vc.name~;
2618   } else {
2619     $query =
2620       qq~SELECT DISTINCT vc.id, vc.name,
2621            vc.street || ' ' || vc.zipcode || ' ' || vc.city || ' ' || vc.country AS address
2622          FROM $arap a
2623          JOIN $table vc ON (a.${table}_id = vc.id)
2624          WHERE NOT (a.amount = a.paid) AND (vc.name ILIKE ?)
2625          ORDER BY vc.name~;
2626     push(@values, '%' . $self->{$table} . '%');
2627   }
2628
2629   $self->{name_list} = selectall_hashref_query($self, $dbh, $query, @values);
2630
2631   $main::lxdebug->leave_sub();
2632
2633   return scalar(@{ $self->{name_list} });
2634 }
2635
2636 # the selection sub is used in the AR, AP, IS, IR and OE module
2637 #
2638 sub all_vc {
2639   $main::lxdebug->enter_sub();
2640
2641   my ($self, $myconfig, $table, $module) = @_;
2642
2643   my $ref;
2644   my $dbh = $self->get_standard_dbh;
2645
2646   $table = $table eq "customer" ? "customer" : "vendor";
2647
2648   my $query = qq|SELECT count(*) FROM $table|;
2649   my ($count) = selectrow_query($self, $dbh, $query);
2650
2651   # build selection list
2652   if ($count <= $myconfig->{vclimit}) {
2653     $query = qq|SELECT id, name, salesman_id
2654                 FROM $table WHERE NOT obsolete
2655                 ORDER BY name|;
2656     $self->{"all_$table"} = selectall_hashref_query($self, $dbh, $query);
2657   }
2658
2659   # get self
2660   $self->get_employee($dbh);
2661
2662   # setup sales contacts
2663   $query = qq|SELECT e.id, e.name
2664               FROM employee e
2665               WHERE (e.sales = '1') AND (NOT e.id = ?)|;
2666   $self->{all_employees} = selectall_hashref_query($self, $dbh, $query, $self->{employee_id});
2667
2668   # this is for self
2669   push(@{ $self->{all_employees} },
2670        { id   => $self->{employee_id},
2671          name => $self->{employee} });
2672
2673   # sort the whole thing
2674   @{ $self->{all_employees} } =
2675     sort { $a->{name} cmp $b->{name} } @{ $self->{all_employees} };
2676
2677   if ($module eq 'AR') {
2678
2679     # prepare query for departments
2680     $query = qq|SELECT id, description
2681                 FROM department
2682                 WHERE role = 'P'
2683                 ORDER BY description|;
2684
2685   } else {
2686     $query = qq|SELECT id, description
2687                 FROM department
2688                 ORDER BY description|;
2689   }
2690
2691   $self->{all_departments} = selectall_hashref_query($self, $dbh, $query);
2692
2693   # get languages
2694   $query = qq|SELECT id, description
2695               FROM language
2696               ORDER BY id|;
2697
2698   $self->{languages} = selectall_hashref_query($self, $dbh, $query);
2699
2700   # get printer
2701   $query = qq|SELECT printer_description, id
2702               FROM printers
2703               ORDER BY printer_description|;
2704
2705   $self->{printers} = selectall_hashref_query($self, $dbh, $query);
2706
2707   # get payment terms
2708   $query = qq|SELECT id, description
2709               FROM payment_terms
2710               ORDER BY sortkey|;
2711
2712   $self->{payment_terms} = selectall_hashref_query($self, $dbh, $query);
2713
2714   $main::lxdebug->leave_sub();
2715 }
2716
2717 sub language_payment {
2718   $main::lxdebug->enter_sub();
2719
2720   my ($self, $myconfig) = @_;
2721
2722   my $dbh = $self->get_standard_dbh($myconfig);
2723   # get languages
2724   my $query = qq|SELECT id, description
2725                  FROM language
2726                  ORDER BY id|;
2727
2728   $self->{languages} = selectall_hashref_query($self, $dbh, $query);
2729
2730   # get printer
2731   $query = qq|SELECT printer_description, id
2732               FROM printers
2733               ORDER BY printer_description|;
2734
2735   $self->{printers} = selectall_hashref_query($self, $dbh, $query);
2736
2737   # get payment terms
2738   $query = qq|SELECT id, description
2739               FROM payment_terms
2740               ORDER BY sortkey|;
2741
2742   $self->{payment_terms} = selectall_hashref_query($self, $dbh, $query);
2743
2744   # get buchungsgruppen
2745   $query = qq|SELECT id, description
2746               FROM buchungsgruppen|;
2747
2748   $self->{BUCHUNGSGRUPPEN} = selectall_hashref_query($self, $dbh, $query);
2749
2750   $main::lxdebug->leave_sub();
2751 }
2752
2753 # this is only used for reports
2754 sub all_departments {
2755   $main::lxdebug->enter_sub();
2756
2757   my ($self, $myconfig, $table) = @_;
2758
2759   my $dbh = $self->get_standard_dbh($myconfig);
2760   my $where;
2761
2762   if ($table eq 'customer') {
2763     $where = "WHERE role = 'P' ";
2764   }
2765
2766   my $query = qq|SELECT id, description
2767                  FROM department
2768                  $where
2769                  ORDER BY description|;
2770   $self->{all_departments} = selectall_hashref_query($self, $dbh, $query);
2771
2772   delete($self->{all_departments}) unless (@{ $self->{all_departments} || [] });
2773
2774   $main::lxdebug->leave_sub();
2775 }
2776
2777 sub create_links {
2778   $main::lxdebug->enter_sub();
2779
2780   my ($self, $module, $myconfig, $table, $provided_dbh) = @_;
2781
2782   my ($fld, $arap);
2783   if ($table eq "customer") {
2784     $fld = "buy";
2785     $arap = "ar";
2786   } else {
2787     $table = "vendor";
2788     $fld = "sell";
2789     $arap = "ap";
2790   }
2791
2792   $self->all_vc($myconfig, $table, $module);
2793
2794   # get last customers or vendors
2795   my ($query, $sth, $ref);
2796
2797   my $dbh = $provided_dbh ? $provided_dbh : $self->get_standard_dbh($myconfig);
2798   my %xkeyref = ();
2799
2800   if (!$self->{id}) {
2801
2802     my $transdate = "current_date";
2803     if ($self->{transdate}) {
2804       $transdate = $dbh->quote($self->{transdate});
2805     }
2806
2807     # now get the account numbers
2808     $query = qq|SELECT c.accno, c.description, c.link, c.taxkey_id, tk.tax_id
2809                 FROM chart c, taxkeys tk
2810                 WHERE (c.link LIKE ?) AND (c.id = tk.chart_id) AND tk.id =
2811                   (SELECT id FROM taxkeys WHERE (taxkeys.chart_id = c.id) AND (startdate <= $transdate) ORDER BY startdate DESC LIMIT 1)
2812                 ORDER BY c.accno|;
2813
2814     $sth = $dbh->prepare($query);
2815
2816     do_statement($self, $sth, $query, '%' . $module . '%');
2817
2818     $self->{accounts} = "";
2819     while ($ref = $sth->fetchrow_hashref("NAME_lc")) {
2820
2821       foreach my $key (split(/:/, $ref->{link})) {
2822         if ($key =~ /\Q$module\E/) {
2823
2824           # cross reference for keys
2825           $xkeyref{ $ref->{accno} } = $key;
2826
2827           push @{ $self->{"${module}_links"}{$key} },
2828             { accno       => $ref->{accno},
2829               description => $ref->{description},
2830               taxkey      => $ref->{taxkey_id},
2831               tax_id      => $ref->{tax_id} };
2832
2833           $self->{accounts} .= "$ref->{accno} " unless $key =~ /tax/;
2834         }
2835       }
2836     }
2837   }
2838
2839   # get taxkeys and description
2840   $query = qq|SELECT id, taxkey, taxdescription FROM tax|;
2841   $self->{TAXKEY} = selectall_hashref_query($self, $dbh, $query);
2842
2843   if (($module eq "AP") || ($module eq "AR")) {
2844     # get tax rates and description
2845     $query = qq|SELECT * FROM tax|;
2846     $self->{TAX} = selectall_hashref_query($self, $dbh, $query);
2847   }
2848
2849   if ($self->{id}) {
2850     $query =
2851       qq|SELECT
2852            a.cp_id, a.invnumber, a.transdate, a.${table}_id, a.datepaid,
2853            a.duedate, a.ordnumber, a.taxincluded, a.curr AS currency, a.notes,
2854            a.intnotes, a.department_id, a.amount AS oldinvtotal,
2855            a.paid AS oldtotalpaid, a.employee_id, a.gldate, a.type,
2856            c.name AS $table,
2857            d.description AS department,
2858            e.name AS employee
2859          FROM $arap a
2860          JOIN $table c ON (a.${table}_id = c.id)
2861          LEFT JOIN employee e ON (e.id = a.employee_id)
2862          LEFT JOIN department d ON (d.id = a.department_id)
2863          WHERE a.id = ?|;
2864     $ref = selectfirst_hashref_query($self, $dbh, $query, $self->{id});
2865
2866     foreach my $key (keys %$ref) {
2867       $self->{$key} = $ref->{$key};
2868     }
2869
2870     my $transdate = "current_date";
2871     if ($self->{transdate}) {
2872       $transdate = $dbh->quote($self->{transdate});
2873     }
2874
2875     # now get the account numbers
2876     $query = qq|SELECT c.accno, c.description, c.link, c.taxkey_id, tk.tax_id
2877                 FROM chart c
2878                 LEFT JOIN taxkeys tk ON (tk.chart_id = c.id)
2879                 WHERE c.link LIKE ?
2880                   AND (tk.id = (SELECT id FROM taxkeys WHERE taxkeys.chart_id = c.id AND startdate <= $transdate ORDER BY startdate DESC LIMIT 1)
2881                     OR c.link LIKE '%_tax%' OR c.taxkey_id IS NULL)
2882                 ORDER BY c.accno|;
2883
2884     $sth = $dbh->prepare($query);
2885     do_statement($self, $sth, $query, "%$module%");
2886
2887     $self->{accounts} = "";
2888     while ($ref = $sth->fetchrow_hashref("NAME_lc")) {
2889
2890       foreach my $key (split(/:/, $ref->{link})) {
2891         if ($key =~ /\Q$module\E/) {
2892
2893           # cross reference for keys
2894           $xkeyref{ $ref->{accno} } = $key;
2895
2896           push @{ $self->{"${module}_links"}{$key} },
2897             { accno       => $ref->{accno},
2898               description => $ref->{description},
2899               taxkey      => $ref->{taxkey_id},
2900               tax_id      => $ref->{tax_id} };
2901
2902           $self->{accounts} .= "$ref->{accno} " unless $key =~ /tax/;
2903         }
2904       }
2905     }
2906
2907
2908     # get amounts from individual entries
2909     $query =
2910       qq|SELECT
2911            c.accno, c.description,
2912            a.source, a.amount, a.memo, a.transdate, a.cleared, a.project_id, a.taxkey,
2913            p.projectnumber,
2914            t.rate, t.id
2915          FROM acc_trans a
2916          LEFT JOIN chart c ON (c.id = a.chart_id)
2917          LEFT JOIN project p ON (p.id = a.project_id)
2918          LEFT JOIN tax t ON (t.id= (SELECT tk.tax_id FROM taxkeys tk
2919                                     WHERE (tk.taxkey_id=a.taxkey) AND
2920                                       ((CASE WHEN a.chart_id IN (SELECT chart_id FROM taxkeys WHERE taxkey_id = a.taxkey)
2921                                         THEN tk.chart_id = a.chart_id
2922                                         ELSE 1 = 1
2923                                         END)
2924                                        OR (c.link='%tax%')) AND
2925                                       (startdate <= a.transdate) ORDER BY startdate DESC LIMIT 1))
2926          WHERE a.trans_id = ?
2927          AND a.fx_transaction = '0'
2928          ORDER BY a.acc_trans_id, a.transdate|;
2929     $sth = $dbh->prepare($query);
2930     do_statement($self, $sth, $query, $self->{id});
2931
2932     # get exchangerate for currency
2933     $self->{exchangerate} =
2934       $self->get_exchangerate($dbh, $self->{currency}, $self->{transdate}, $fld);
2935     my $index = 0;
2936
2937     # store amounts in {acc_trans}{$key} for multiple accounts
2938     while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
2939       $ref->{exchangerate} =
2940         $self->get_exchangerate($dbh, $self->{currency}, $ref->{transdate}, $fld);
2941       if (!($xkeyref{ $ref->{accno} } =~ /tax/)) {
2942         $index++;
2943       }
2944       if (($xkeyref{ $ref->{accno} } =~ /paid/) && ($self->{type} eq "credit_note")) {
2945         $ref->{amount} *= -1;
2946       }
2947       $ref->{index} = $index;
2948
2949       push @{ $self->{acc_trans}{ $xkeyref{ $ref->{accno} } } }, $ref;
2950     }
2951
2952     $sth->finish;
2953     $query =
2954       qq|SELECT
2955            d.curr AS currencies, d.closedto, d.revtrans,
2956            (SELECT c.accno FROM chart c WHERE d.fxgain_accno_id = c.id) AS fxgain_accno,
2957            (SELECT c.accno FROM chart c WHERE d.fxloss_accno_id = c.id) AS fxloss_accno
2958          FROM defaults d|;
2959     $ref = selectfirst_hashref_query($self, $dbh, $query);
2960     map { $self->{$_} = $ref->{$_} } keys %$ref;
2961
2962   } else {
2963
2964     # get date
2965     $query =
2966        qq|SELECT
2967             current_date AS transdate, d.curr AS currencies, d.closedto, d.revtrans,
2968             (SELECT c.accno FROM chart c WHERE d.fxgain_accno_id = c.id) AS fxgain_accno,
2969             (SELECT c.accno FROM chart c WHERE d.fxloss_accno_id = c.id) AS fxloss_accno
2970           FROM defaults d|;
2971     $ref = selectfirst_hashref_query($self, $dbh, $query);
2972     map { $self->{$_} = $ref->{$_} } keys %$ref;
2973
2974     if ($self->{"$self->{vc}_id"}) {
2975
2976       # only setup currency
2977       ($self->{currency}) = split(/:/, $self->{currencies});
2978
2979     } else {
2980
2981       $self->lastname_used($dbh, $myconfig, $table, $module);
2982
2983       # get exchangerate for currency
2984       $self->{exchangerate} =
2985         $self->get_exchangerate($dbh, $self->{currency}, $self->{transdate}, $fld);
2986
2987     }
2988
2989   }
2990
2991   $main::lxdebug->leave_sub();
2992 }
2993
2994 sub lastname_used {
2995   $main::lxdebug->enter_sub();
2996
2997   my ($self, $dbh, $myconfig, $table, $module) = @_;
2998
2999   my ($arap, $where);
3000
3001   $table         = $table eq "customer" ? "customer" : "vendor";
3002   my %column_map = ("a.curr"                  => "currency",
3003                     "a.${table}_id"           => "${table}_id",
3004                     "a.department_id"         => "department_id",
3005                     "d.description"           => "department",
3006                     "ct.name"                 => $table,
3007                     "current_date + ct.terms" => "duedate",
3008     );
3009
3010   if ($self->{type} =~ /delivery_order/) {
3011     $arap  = 'delivery_orders';
3012     delete $column_map{"a.curr"};
3013
3014   } elsif ($self->{type} =~ /_order/) {
3015     $arap  = 'oe';
3016     $where = "quotation = '0'";
3017
3018   } elsif ($self->{type} =~ /_quotation/) {
3019     $arap  = 'oe';
3020     $where = "quotation = '1'";
3021
3022   } elsif ($table eq 'customer') {
3023     $arap  = 'ar';
3024
3025   } else {
3026     $arap  = 'ap';
3027
3028   }
3029
3030   $where           = "($where) AND" if ($where);
3031   my $query        = qq|SELECT MAX(id) FROM $arap
3032                         WHERE $where ${table}_id > 0|;
3033   my ($trans_id)   = selectrow_query($self, $dbh, $query);
3034   $trans_id       *= 1;
3035
3036   my $column_spec  = join(', ', map { "${_} AS $column_map{$_}" } keys %column_map);
3037   $query           = qq|SELECT $column_spec
3038                         FROM $arap a
3039                         LEFT JOIN $table     ct ON (a.${table}_id = ct.id)
3040                         LEFT JOIN department d  ON (a.department_id = d.id)
3041                         WHERE a.id = ?|;
3042   my $ref          = selectfirst_hashref_query($self, $dbh, $query, $trans_id);
3043
3044   map { $self->{$_} = $ref->{$_} } values %column_map;
3045
3046   $main::lxdebug->leave_sub();
3047 }
3048
3049 sub current_date {
3050   $main::lxdebug->enter_sub();
3051
3052   my $self     = shift;
3053   my $myconfig = shift || \%::myconfig;
3054   my ($thisdate, $days) = @_;
3055
3056   my $dbh = $self->get_standard_dbh($myconfig);
3057   my $query;
3058
3059   $days *= 1;
3060   if ($thisdate) {
3061     my $dateformat = $myconfig->{dateformat};
3062     $dateformat .= "yy" if $myconfig->{dateformat} !~ /^y/;
3063     $thisdate = $dbh->quote($thisdate);
3064     $query = qq|SELECT to_date($thisdate, '$dateformat') + $days AS thisdate|;
3065   } else {
3066     $query = qq|SELECT current_date AS thisdate|;
3067   }
3068
3069   ($thisdate) = selectrow_query($self, $dbh, $query);
3070
3071   $main::lxdebug->leave_sub();
3072
3073   return $thisdate;
3074 }
3075
3076 sub like {
3077   $main::lxdebug->enter_sub();
3078
3079   my ($self, $string) = @_;
3080
3081   if ($string !~ /%/) {
3082     $string = "%$string%";
3083   }
3084
3085   $string =~ s/\'/\'\'/g;
3086
3087   $main::lxdebug->leave_sub();
3088
3089   return $string;
3090 }
3091
3092 sub redo_rows {
3093   $main::lxdebug->enter_sub();
3094
3095   my ($self, $flds, $new, $count, $numrows) = @_;
3096
3097   my @ndx = ();
3098
3099   map { push @ndx, { num => $new->[$_ - 1]->{runningnumber}, ndx => $_ } } 1 .. $count;
3100
3101   my $i = 0;
3102
3103   # fill rows
3104   foreach my $item (sort { $a->{num} <=> $b->{num} } @ndx) {
3105     $i++;
3106     my $j = $item->{ndx} - 1;
3107     map { $self->{"${_}_$i"} = $new->[$j]->{$_} } @{$flds};
3108   }
3109
3110   # delete empty rows
3111   for $i ($count + 1 .. $numrows) {
3112     map { delete $self->{"${_}_$i"} } @{$flds};
3113   }
3114
3115   $main::lxdebug->leave_sub();
3116 }
3117
3118 sub update_status {
3119   $main::lxdebug->enter_sub();
3120
3121   my ($self, $myconfig) = @_;
3122
3123   my ($i, $id);
3124
3125   my $dbh = $self->dbconnect_noauto($myconfig);
3126
3127   my $query = qq|DELETE FROM status
3128                  WHERE (formname = ?) AND (trans_id = ?)|;
3129   my $sth = prepare_query($self, $dbh, $query);
3130
3131   if ($self->{formname} =~ /(check|receipt)/) {
3132     for $i (1 .. $self->{rowcount}) {
3133       do_statement($self, $sth, $query, $self->{formname}, $self->{"id_$i"} * 1);
3134     }
3135   } else {
3136     do_statement($self, $sth, $query, $self->{formname}, $self->{id});
3137   }
3138   $sth->finish();
3139
3140   my $printed = ($self->{printed} =~ /\Q$self->{formname}\E/) ? "1" : "0";
3141   my $emailed = ($self->{emailed} =~ /\Q$self->{formname}\E/) ? "1" : "0";
3142
3143   my %queued = split / /, $self->{queued};
3144   my @values;
3145
3146   if ($self->{formname} =~ /(check|receipt)/) {
3147
3148     # this is a check or receipt, add one entry for each lineitem
3149     my ($accno) = split /--/, $self->{account};
3150     $query = qq|INSERT INTO status (trans_id, printed, spoolfile, formname, chart_id)
3151                 VALUES (?, ?, ?, ?, (SELECT c.id FROM chart c WHERE c.accno = ?))|;
3152     @values = ($printed, $queued{$self->{formname}}, $self->{prinform}, $accno);
3153     $sth = prepare_query($self, $dbh, $query);
3154
3155     for $i (1 .. $self->{rowcount}) {
3156       if ($self->{"checked_$i"}) {
3157         do_statement($self, $sth, $query, $self->{"id_$i"}, @values);
3158       }
3159     }
3160     $sth->finish();
3161
3162   } else {
3163     $query = qq|INSERT INTO status (trans_id, printed, emailed, spoolfile, formname)
3164                 VALUES (?, ?, ?, ?, ?)|;
3165     do_query($self, $dbh, $query, $self->{id}, $printed, $emailed,
3166              $queued{$self->{formname}}, $self->{formname});
3167   }
3168
3169   $dbh->commit;
3170   $dbh->disconnect;
3171
3172   $main::lxdebug->leave_sub();
3173 }
3174
3175 sub save_status {
3176   $main::lxdebug->enter_sub();
3177
3178   my ($self, $dbh) = @_;
3179
3180   my ($query, $printed, $emailed);
3181
3182   my $formnames  = $self->{printed};
3183   my $emailforms = $self->{emailed};
3184
3185   $query = qq|DELETE FROM status
3186                  WHERE (formname = ?) AND (trans_id = ?)|;
3187   do_query($self, $dbh, $query, $self->{formname}, $self->{id});
3188
3189   # this only applies to the forms
3190   # checks and receipts are posted when printed or queued
3191
3192   if ($self->{queued}) {
3193     my %queued = split / /, $self->{queued};
3194
3195     foreach my $formname (keys %queued) {
3196       $printed = ($self->{printed} =~ /\Q$self->{formname}\E/) ? "1" : "0";
3197       $emailed = ($self->{emailed} =~ /\Q$self->{formname}\E/) ? "1" : "0";
3198
3199       $query = qq|INSERT INTO status (trans_id, printed, emailed, spoolfile, formname)
3200                   VALUES (?, ?, ?, ?, ?)|;
3201       do_query($self, $dbh, $query, $self->{id}, $printed, $emailed, $queued{$formname}, $formname);
3202
3203       $formnames  =~ s/\Q$self->{formname}\E//;
3204       $emailforms =~ s/\Q$self->{formname}\E//;
3205
3206     }
3207   }
3208
3209   # save printed, emailed info
3210   $formnames  =~ s/^ +//g;
3211   $emailforms =~ s/^ +//g;
3212
3213   my %status = ();
3214   map { $status{$_}{printed} = 1 } split / +/, $formnames;
3215   map { $status{$_}{emailed} = 1 } split / +/, $emailforms;
3216
3217   foreach my $formname (keys %status) {
3218     $printed = ($formnames  =~ /\Q$self->{formname}\E/) ? "1" : "0";
3219     $emailed = ($emailforms =~ /\Q$self->{formname}\E/) ? "1" : "0";
3220
3221     $query = qq|INSERT INTO status (trans_id, printed, emailed, formname)
3222                 VALUES (?, ?, ?, ?)|;
3223     do_query($self, $dbh, $query, $self->{id}, $printed, $emailed, $formname);
3224   }
3225
3226   $main::lxdebug->leave_sub();
3227 }
3228
3229 #--- 4 locale ---#
3230 # $main::locale->text('SAVED')
3231 # $main::locale->text('DELETED')
3232 # $main::locale->text('ADDED')
3233 # $main::locale->text('PAYMENT POSTED')
3234 # $main::locale->text('POSTED')
3235 # $main::locale->text('POSTED AS NEW')
3236 # $main::locale->text('ELSE')
3237 # $main::locale->text('SAVED FOR DUNNING')
3238 # $main::locale->text('DUNNING STARTED')
3239 # $main::locale->text('PRINTED')
3240 # $main::locale->text('MAILED')
3241 # $main::locale->text('SCREENED')
3242 # $main::locale->text('CANCELED')
3243 # $main::locale->text('invoice')
3244 # $main::locale->text('proforma')
3245 # $main::locale->text('sales_order')
3246 # $main::locale->text('packing_list')
3247 # $main::locale->text('pick_list')
3248 # $main::locale->text('purchase_order')
3249 # $main::locale->text('bin_list')
3250 # $main::locale->text('sales_quotation')
3251 # $main::locale->text('request_quotation')
3252
3253 sub save_history {
3254   $main::lxdebug->enter_sub();
3255
3256   my $self = shift;
3257   my $dbh  = shift || $self->get_standard_dbh;
3258
3259   if(!exists $self->{employee_id}) {
3260     &get_employee($self, $dbh);
3261   }
3262
3263   my $query =
3264    qq|INSERT INTO history_erp (trans_id, employee_id, addition, what_done, snumbers) | .
3265    qq|VALUES (?, (SELECT id FROM employee WHERE login = ?), ?, ?, ?)|;
3266   my @values = (conv_i($self->{id}), $self->{login},
3267                 $self->{addition}, $self->{what_done}, "$self->{snumbers}");
3268   do_query($self, $dbh, $query, @values);
3269
3270   $dbh->commit;
3271
3272   $main::lxdebug->leave_sub();
3273 }
3274
3275 sub get_history {
3276   $main::lxdebug->enter_sub();
3277
3278   my ($self, $dbh, $trans_id, $restriction, $order) = @_;
3279   my ($orderBy, $desc) = split(/\-\-/, $order);
3280   $order = " ORDER BY " . ($order eq "" ? " h.itime " : ($desc == 1 ? $orderBy . " DESC " : $orderBy . " "));
3281   my @tempArray;
3282   my $i = 0;
3283   if ($trans_id ne "") {
3284     my $query =
3285       qq|SELECT h.employee_id, h.itime::timestamp(0) AS itime, h.addition, h.what_done, emp.name, h.snumbers, h.trans_id AS id | .
3286       qq|FROM history_erp h | .
3287       qq|LEFT JOIN employee emp ON (emp.id = h.employee_id) | .
3288       qq|WHERE (trans_id = | . $trans_id . qq|) $restriction | .
3289       $order;
3290
3291     my $sth = $dbh->prepare($query) || $self->dberror($query);
3292
3293     $sth->execute() || $self->dberror("$query");
3294
3295     while(my $hash_ref = $sth->fetchrow_hashref()) {
3296       $hash_ref->{addition} = $main::locale->text($hash_ref->{addition});
3297       $hash_ref->{what_done} = $main::locale->text($hash_ref->{what_done});
3298       $hash_ref->{snumbers} =~ s/^.+_(.*)$/$1/g;
3299       $tempArray[$i++] = $hash_ref;
3300     }
3301     $main::lxdebug->leave_sub() and return \@tempArray
3302       if ($i > 0 && $tempArray[0] ne "");
3303   }
3304   $main::lxdebug->leave_sub();
3305   return 0;
3306 }
3307
3308 sub update_defaults {
3309   $main::lxdebug->enter_sub();
3310
3311   my ($self, $myconfig, $fld, $provided_dbh) = @_;
3312
3313   my $dbh;
3314   if ($provided_dbh) {
3315     $dbh = $provided_dbh;
3316   } else {
3317     $dbh = $self->dbconnect_noauto($myconfig);
3318   }
3319   my $query = qq|SELECT $fld FROM defaults FOR UPDATE|;
3320   my $sth   = $dbh->prepare($query);
3321
3322   $sth->execute || $self->dberror($query);
3323   my ($var) = $sth->fetchrow_array;
3324   $sth->finish;
3325
3326   if ($var =~ m/\d+$/) {
3327     my $new_var  = (substr $var, $-[0]) * 1 + 1;
3328     my $len_diff = length($var) - $-[0] - length($new_var);
3329     $var         = substr($var, 0, $-[0]) . ($len_diff > 0 ? '0' x $len_diff : '') . $new_var;
3330
3331   } else {
3332     $var = $var . '1';
3333   }
3334
3335   $query = qq|UPDATE defaults SET $fld = ?|;
3336   do_query($self, $dbh, $query, $var);
3337
3338   if (!$provided_dbh) {
3339     $dbh->commit;
3340     $dbh->disconnect;
3341   }
3342
3343   $main::lxdebug->leave_sub();
3344
3345   return $var;
3346 }
3347
3348 sub update_business {
3349   $main::lxdebug->enter_sub();
3350
3351   my ($self, $myconfig, $business_id, $provided_dbh) = @_;
3352
3353   my $dbh;
3354   if ($provided_dbh) {
3355     $dbh = $provided_dbh;
3356   } else {
3357     $dbh = $self->dbconnect_noauto($myconfig);
3358   }
3359   my $query =
3360     qq|SELECT customernumberinit FROM business
3361        WHERE id = ? FOR UPDATE|;
3362   my ($var) = selectrow_query($self, $dbh, $query, $business_id);
3363
3364   return undef unless $var;
3365
3366   if ($var =~ m/\d+$/) {
3367     my $new_var  = (substr $var, $-[0]) * 1 + 1;
3368     my $len_diff = length($var) - $-[0] - length($new_var);
3369     $var         = substr($var, 0, $-[0]) . ($len_diff > 0 ? '0' x $len_diff : '') . $new_var;
3370
3371   } else {
3372     $var = $var . '1';
3373   }
3374
3375   $query = qq|UPDATE business
3376               SET customernumberinit = ?
3377               WHERE id = ?|;
3378   do_query($self, $dbh, $query, $var, $business_id);
3379
3380   if (!$provided_dbh) {
3381     $dbh->commit;
3382     $dbh->disconnect;
3383   }
3384
3385   $main::lxdebug->leave_sub();
3386
3387   return $var;
3388 }
3389
3390 sub get_partsgroup {
3391   $main::lxdebug->enter_sub();
3392
3393   my ($self, $myconfig, $p) = @_;
3394   my $target = $p->{target} || 'all_partsgroup';
3395
3396   my $dbh = $self->get_standard_dbh($myconfig);
3397
3398   my $query = qq|SELECT DISTINCT pg.id, pg.partsgroup
3399                  FROM partsgroup pg
3400                  JOIN parts p ON (p.partsgroup_id = pg.id) |;
3401   my @values;
3402
3403   if ($p->{searchitems} eq 'part') {
3404     $query .= qq|WHERE p.inventory_accno_id > 0|;
3405   }
3406   if ($p->{searchitems} eq 'service') {
3407     $query .= qq|WHERE p.inventory_accno_id IS NULL|;
3408   }
3409   if ($p->{searchitems} eq 'assembly') {
3410     $query .= qq|WHERE p.assembly = '1'|;
3411   }
3412   if ($p->{searchitems} eq 'labor') {
3413     $query .= qq|WHERE (p.inventory_accno_id > 0) AND (p.income_accno_id IS NULL)|;
3414   }
3415
3416   $query .= qq|ORDER BY partsgroup|;
3417
3418   if ($p->{all}) {
3419     $query = qq|SELECT id, partsgroup FROM partsgroup
3420                 ORDER BY partsgroup|;
3421   }
3422
3423   if ($p->{language_code}) {
3424     $query = qq|SELECT DISTINCT pg.id, pg.partsgroup,
3425                   t.description AS translation
3426                 FROM partsgroup pg
3427                 JOIN parts p ON (p.partsgroup_id = pg.id)
3428                 LEFT JOIN translation t ON ((t.trans_id = pg.id) AND (t.language_code = ?))
3429                 ORDER BY translation|;
3430     @values = ($p->{language_code});
3431   }
3432
3433   $self->{$target} = selectall_hashref_query($self, $dbh, $query, @values);
3434
3435   $main::lxdebug->leave_sub();
3436 }
3437
3438 sub get_pricegroup {
3439   $main::lxdebug->enter_sub();
3440
3441   my ($self, $myconfig, $p) = @_;
3442
3443   my $dbh = $self->get_standard_dbh($myconfig);
3444
3445   my $query = qq|SELECT p.id, p.pricegroup
3446                  FROM pricegroup p|;
3447
3448   $query .= qq| ORDER BY pricegroup|;
3449
3450   if ($p->{all}) {
3451     $query = qq|SELECT id, pricegroup FROM pricegroup
3452                 ORDER BY pricegroup|;
3453   }
3454
3455   $self->{all_pricegroup} = selectall_hashref_query($self, $dbh, $query);
3456
3457   $main::lxdebug->leave_sub();
3458 }
3459
3460 sub all_years {
3461 # usage $form->all_years($myconfig, [$dbh])
3462 # return list of all years where bookings found
3463 # (@all_years)
3464
3465   $main::lxdebug->enter_sub();
3466
3467   my ($self, $myconfig, $dbh) = @_;
3468
3469   $dbh ||= $self->get_standard_dbh($myconfig);
3470
3471   # get years
3472   my $query = qq|SELECT (SELECT MIN(transdate) FROM acc_trans),
3473                    (SELECT MAX(transdate) FROM acc_trans)|;
3474   my ($startdate, $enddate) = selectrow_query($self, $dbh, $query);
3475
3476   if ($myconfig->{dateformat} =~ /^yy/) {
3477     ($startdate) = split /\W/, $startdate;
3478     ($enddate) = split /\W/, $enddate;
3479   } else {
3480     (@_) = split /\W/, $startdate;
3481     $startdate = $_[2];
3482     (@_) = split /\W/, $enddate;
3483     $enddate = $_[2];
3484   }
3485
3486   my @all_years;
3487   $startdate = substr($startdate,0,4);
3488   $enddate = substr($enddate,0,4);
3489
3490   while ($enddate >= $startdate) {
3491     push @all_years, $enddate--;
3492   }
3493
3494   return @all_years;
3495
3496   $main::lxdebug->leave_sub();
3497 }
3498
3499 sub backup_vars {
3500   $main::lxdebug->enter_sub();
3501   my $self = shift;
3502   my @vars = @_;
3503
3504   map { $self->{_VAR_BACKUP}->{$_} = $self->{$_} if exists $self->{$_} } @vars;
3505
3506   $main::lxdebug->leave_sub();
3507 }
3508
3509 sub restore_vars {
3510   $main::lxdebug->enter_sub();
3511
3512   my $self = shift;
3513   my @vars = @_;
3514
3515   map { $self->{$_} = $self->{_VAR_BACKUP}->{$_} if exists $self->{_VAR_BACKUP}->{$_} } @vars;
3516
3517   $main::lxdebug->leave_sub();
3518 }
3519
3520 1;
3521
3522 __END__
3523
3524 =head1 NAME
3525
3526 SL::Form.pm - main data object.
3527
3528 =head1 SYNOPSIS
3529
3530 This is the main data object of Lx-Office.
3531 Unfortunately it also acts as a god object for certain data retrieval procedures used in the entry points.
3532 Points of interest for a beginner are:
3533
3534  - $form->error            - renders a generic error in html. accepts an error message
3535  - $form->get_standard_dbh - returns a database connection for the
3536
3537 =head1 SPECIAL FUNCTIONS
3538
3539 =over 4
3540
3541 =item _store_value()
3542
3543 parses a complex var name, and stores it in the form.
3544
3545 syntax:
3546   $form->_store_value($key, $value);
3547
3548 keys must start with a string, and can contain various tokens.
3549 supported key structures are:
3550
3551 1. simple access
3552   simple key strings work as expected
3553
3554   id => $form->{id}
3555
3556 2. hash access.
3557   separating two keys by a dot (.) will result in a hash lookup for the inner value
3558   this is similar to the behaviour of java and templating mechanisms.
3559
3560   filter.description => $form->{filter}->{description}
3561
3562 3. array+hashref access
3563
3564   adding brackets ([]) before the dot will cause the next hash to be put into an array.
3565   using [+] instead of [] will force a new array index. this is useful for recurring
3566   data structures like part lists. put a [+] into the first varname, and use [] on the
3567   following ones.
3568
3569   repeating these names in your template:
3570
3571     invoice.items[+].id
3572     invoice.items[].parts_id
3573
3574   will result in:
3575
3576     $form->{invoice}->{items}->[
3577       {
3578         id       => ...
3579         parts_id => ...
3580       },
3581       {
3582         id       => ...
3583         parts_id => ...
3584       }
3585       ...
3586     ]
3587
3588 4. arrays
3589
3590   using brackets at the end of a name will result in a pure array to be created.
3591   note that you mustn't use [+], which is reserved for array+hash access and will
3592   result in undefined behaviour in array context.
3593
3594   filter.status[]  => $form->{status}->[ val1, val2, ... ]
3595
3596 =item update_business PARAMS
3597
3598 PARAMS (not named):
3599  \%config,     - config hashref
3600  $business_id, - business id
3601  $dbh          - optional database handle
3602
3603 handles business (thats customer/vendor types) sequences.
3604
3605 special behaviour for empty strings in customerinitnumber field:
3606 will in this case not increase the value, and return undef.
3607
3608 =item redirect_header $url
3609
3610 Generates a HTTP redirection header for the new C<$url>. Constructs an
3611 absolute URL including scheme, host name and port. If C<$url> is a
3612 relative URL then it is considered relative to Lx-Office base URL.
3613
3614 This function C<die>s if headers have already been created with
3615 C<$::form-E<gt>header>.
3616
3617 Examples:
3618
3619   print $::form->redirect_header('oe.pl?action=edit&id=1234');
3620   print $::form->redirect_header('http://www.lx-office.org/');
3621
3622 =back
3623
3624 =cut