Template Objekt cachen.
[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'  => $main::template_compile_ext,
876      'COMPILE_DIR'  => $main::template_compile_dir,
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   my $where          = $options->{business_is_salesman} ? qq| AND business_id IN (SELECT id FROM business WHERE salesman)| : '';
2377
2378   my $query = qq|SELECT * FROM customer WHERE NOT obsolete $where ORDER BY name $limit_clause|;
2379   $self->{ $options->{key} } = selectall_hashref_query($self, $dbh, $query);
2380
2381   $main::lxdebug->leave_sub();
2382 }
2383
2384 sub _get_vendors {
2385   $main::lxdebug->enter_sub();
2386
2387   my ($self, $dbh, $key) = @_;
2388
2389   $key = "all_vendors" unless ($key);
2390
2391   my $query = qq|SELECT * FROM vendor WHERE NOT obsolete ORDER BY name|;
2392
2393   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2394
2395   $main::lxdebug->leave_sub();
2396 }
2397
2398 sub _get_departments {
2399   $main::lxdebug->enter_sub();
2400
2401   my ($self, $dbh, $key) = @_;
2402
2403   $key = "all_departments" unless ($key);
2404
2405   my $query = qq|SELECT * FROM department ORDER BY description|;
2406
2407   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2408
2409   $main::lxdebug->leave_sub();
2410 }
2411
2412 sub _get_warehouses {
2413   $main::lxdebug->enter_sub();
2414
2415   my ($self, $dbh, $param) = @_;
2416
2417   my ($key, $bins_key);
2418
2419   if ('' eq ref $param) {
2420     $key = $param;
2421
2422   } else {
2423     $key      = $param->{key};
2424     $bins_key = $param->{bins};
2425   }
2426
2427   my $query = qq|SELECT w.* FROM warehouse w
2428                  WHERE (NOT w.invalid) AND
2429                    ((SELECT COUNT(b.*) FROM bin b WHERE b.warehouse_id = w.id) > 0)
2430                  ORDER BY w.sortkey|;
2431
2432   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2433
2434   if ($bins_key) {
2435     $query = qq|SELECT id, description FROM bin WHERE warehouse_id = ?|;
2436     my $sth = prepare_query($self, $dbh, $query);
2437
2438     foreach my $warehouse (@{ $self->{$key} }) {
2439       do_statement($self, $sth, $query, $warehouse->{id});
2440       $warehouse->{$bins_key} = [];
2441
2442       while (my $ref = $sth->fetchrow_hashref()) {
2443         push @{ $warehouse->{$bins_key} }, $ref;
2444       }
2445     }
2446     $sth->finish();
2447   }
2448
2449   $main::lxdebug->leave_sub();
2450 }
2451
2452 sub _get_simple {
2453   $main::lxdebug->enter_sub();
2454
2455   my ($self, $dbh, $table, $key, $sortkey) = @_;
2456
2457   my $query  = qq|SELECT * FROM $table|;
2458   $query    .= qq| ORDER BY $sortkey| if ($sortkey);
2459
2460   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2461
2462   $main::lxdebug->leave_sub();
2463 }
2464
2465 #sub _get_groups {
2466 #  $main::lxdebug->enter_sub();
2467 #
2468 #  my ($self, $dbh, $key) = @_;
2469 #
2470 #  $key ||= "all_groups";
2471 #
2472 #  my $groups = $main::auth->read_groups();
2473 #
2474 #  $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2475 #
2476 #  $main::lxdebug->leave_sub();
2477 #}
2478
2479 sub get_lists {
2480   $main::lxdebug->enter_sub();
2481
2482   my $self = shift;
2483   my %params = @_;
2484
2485   my $dbh = $self->get_standard_dbh(\%main::myconfig);
2486   my ($sth, $query, $ref);
2487
2488   my $vc = $self->{"vc"} eq "customer" ? "customer" : "vendor";
2489   my $vc_id = $self->{"${vc}_id"};
2490
2491   if ($params{"contacts"}) {
2492     $self->_get_contacts($dbh, $vc_id, $params{"contacts"});
2493   }
2494
2495   if ($params{"shipto"}) {
2496     $self->_get_shipto($dbh, $vc_id, $params{"shipto"});
2497   }
2498
2499   if ($params{"projects"} || $params{"all_projects"}) {
2500     $self->_get_projects($dbh, $params{"all_projects"} ?
2501                          $params{"all_projects"} : $params{"projects"},
2502                          $params{"all_projects"} ? 1 : 0);
2503   }
2504
2505   if ($params{"printers"}) {
2506     $self->_get_printers($dbh, $params{"printers"});
2507   }
2508
2509   if ($params{"languages"}) {
2510     $self->_get_languages($dbh, $params{"languages"});
2511   }
2512
2513   if ($params{"charts"}) {
2514     $self->_get_charts($dbh, $params{"charts"});
2515   }
2516
2517   if ($params{"taxcharts"}) {
2518     $self->_get_taxcharts($dbh, $params{"taxcharts"});
2519   }
2520
2521   if ($params{"taxzones"}) {
2522     $self->_get_taxzones($dbh, $params{"taxzones"});
2523   }
2524
2525   if ($params{"employees"}) {
2526     $self->_get_employees($dbh, "all_employees", $params{"employees"});
2527   }
2528
2529   if ($params{"salesmen"}) {
2530     $self->_get_employees($dbh, "all_salesmen", $params{"salesmen"});
2531   }
2532
2533   if ($params{"business_types"}) {
2534     $self->_get_business_types($dbh, $params{"business_types"});
2535   }
2536
2537   if ($params{"dunning_configs"}) {
2538     $self->_get_dunning_configs($dbh, $params{"dunning_configs"});
2539   }
2540
2541   if($params{"currencies"}) {
2542     $self->_get_currencies($dbh, $params{"currencies"});
2543   }
2544
2545   if($params{"customers"}) {
2546     $self->_get_customers($dbh, $params{"customers"});
2547   }
2548
2549   if($params{"vendors"}) {
2550     if (ref $params{"vendors"} eq 'HASH') {
2551       $self->_get_vendors($dbh, $params{"vendors"}{key}, $params{"vendors"}{limit});
2552     } else {
2553       $self->_get_vendors($dbh, $params{"vendors"});
2554     }
2555   }
2556
2557   if($params{"payments"}) {
2558     $self->_get_payments($dbh, $params{"payments"});
2559   }
2560
2561   if($params{"departments"}) {
2562     $self->_get_departments($dbh, $params{"departments"});
2563   }
2564
2565   if ($params{price_factors}) {
2566     $self->_get_simple($dbh, 'price_factors', $params{price_factors}, 'sortkey');
2567   }
2568
2569   if ($params{warehouses}) {
2570     $self->_get_warehouses($dbh, $params{warehouses});
2571   }
2572
2573 #  if ($params{groups}) {
2574 #    $self->_get_groups($dbh, $params{groups});
2575 #  }
2576
2577   if ($params{partsgroup}) {
2578     $self->get_partsgroup(\%main::myconfig, { all => 1, target => $params{partsgroup} });
2579   }
2580
2581   $main::lxdebug->leave_sub();
2582 }
2583
2584 # this sub gets the id and name from $table
2585 sub get_name {
2586   $main::lxdebug->enter_sub();
2587
2588   my ($self, $myconfig, $table) = @_;
2589
2590   # connect to database
2591   my $dbh = $self->get_standard_dbh($myconfig);
2592
2593   $table = $table eq "customer" ? "customer" : "vendor";
2594   my $arap = $self->{arap} eq "ar" ? "ar" : "ap";
2595
2596   my ($query, @values);
2597
2598   if (!$self->{openinvoices}) {
2599     my $where;
2600     if ($self->{customernumber} ne "") {
2601       $where = qq|(vc.customernumber ILIKE ?)|;
2602       push(@values, '%' . $self->{customernumber} . '%');
2603     } else {
2604       $where = qq|(vc.name ILIKE ?)|;
2605       push(@values, '%' . $self->{$table} . '%');
2606     }
2607
2608     $query =
2609       qq~SELECT vc.id, vc.name,
2610            vc.street || ' ' || vc.zipcode || ' ' || vc.city || ' ' || vc.country AS address
2611          FROM $table vc
2612          WHERE $where AND (NOT vc.obsolete)
2613          ORDER BY vc.name~;
2614   } else {
2615     $query =
2616       qq~SELECT DISTINCT vc.id, vc.name,
2617            vc.street || ' ' || vc.zipcode || ' ' || vc.city || ' ' || vc.country AS address
2618          FROM $arap a
2619          JOIN $table vc ON (a.${table}_id = vc.id)
2620          WHERE NOT (a.amount = a.paid) AND (vc.name ILIKE ?)
2621          ORDER BY vc.name~;
2622     push(@values, '%' . $self->{$table} . '%');
2623   }
2624
2625   $self->{name_list} = selectall_hashref_query($self, $dbh, $query, @values);
2626
2627   $main::lxdebug->leave_sub();
2628
2629   return scalar(@{ $self->{name_list} });
2630 }
2631
2632 # the selection sub is used in the AR, AP, IS, IR and OE module
2633 #
2634 sub all_vc {
2635   $main::lxdebug->enter_sub();
2636
2637   my ($self, $myconfig, $table, $module) = @_;
2638
2639   my $ref;
2640   my $dbh = $self->get_standard_dbh;
2641
2642   $table = $table eq "customer" ? "customer" : "vendor";
2643
2644   my $query = qq|SELECT count(*) FROM $table|;
2645   my ($count) = selectrow_query($self, $dbh, $query);
2646
2647   # build selection list
2648   if ($count <= $myconfig->{vclimit}) {
2649     $query = qq|SELECT id, name, salesman_id
2650                 FROM $table WHERE NOT obsolete
2651                 ORDER BY name|;
2652     $self->{"all_$table"} = selectall_hashref_query($self, $dbh, $query);
2653   }
2654
2655   # get self
2656   $self->get_employee($dbh);
2657
2658   # setup sales contacts
2659   $query = qq|SELECT e.id, e.name
2660               FROM employee e
2661               WHERE (e.sales = '1') AND (NOT e.id = ?)|;
2662   $self->{all_employees} = selectall_hashref_query($self, $dbh, $query, $self->{employee_id});
2663
2664   # this is for self
2665   push(@{ $self->{all_employees} },
2666        { id   => $self->{employee_id},
2667          name => $self->{employee} });
2668
2669   # sort the whole thing
2670   @{ $self->{all_employees} } =
2671     sort { $a->{name} cmp $b->{name} } @{ $self->{all_employees} };
2672
2673   if ($module eq 'AR') {
2674
2675     # prepare query for departments
2676     $query = qq|SELECT id, description
2677                 FROM department
2678                 WHERE role = 'P'
2679                 ORDER BY description|;
2680
2681   } else {
2682     $query = qq|SELECT id, description
2683                 FROM department
2684                 ORDER BY description|;
2685   }
2686
2687   $self->{all_departments} = selectall_hashref_query($self, $dbh, $query);
2688
2689   # get languages
2690   $query = qq|SELECT id, description
2691               FROM language
2692               ORDER BY id|;
2693
2694   $self->{languages} = selectall_hashref_query($self, $dbh, $query);
2695
2696   # get printer
2697   $query = qq|SELECT printer_description, id
2698               FROM printers
2699               ORDER BY printer_description|;
2700
2701   $self->{printers} = selectall_hashref_query($self, $dbh, $query);
2702
2703   # get payment terms
2704   $query = qq|SELECT id, description
2705               FROM payment_terms
2706               ORDER BY sortkey|;
2707
2708   $self->{payment_terms} = selectall_hashref_query($self, $dbh, $query);
2709
2710   $main::lxdebug->leave_sub();
2711 }
2712
2713 sub language_payment {
2714   $main::lxdebug->enter_sub();
2715
2716   my ($self, $myconfig) = @_;
2717
2718   my $dbh = $self->get_standard_dbh($myconfig);
2719   # get languages
2720   my $query = qq|SELECT id, description
2721                  FROM language
2722                  ORDER BY id|;
2723
2724   $self->{languages} = selectall_hashref_query($self, $dbh, $query);
2725
2726   # get printer
2727   $query = qq|SELECT printer_description, id
2728               FROM printers
2729               ORDER BY printer_description|;
2730
2731   $self->{printers} = selectall_hashref_query($self, $dbh, $query);
2732
2733   # get payment terms
2734   $query = qq|SELECT id, description
2735               FROM payment_terms
2736               ORDER BY sortkey|;
2737
2738   $self->{payment_terms} = selectall_hashref_query($self, $dbh, $query);
2739
2740   # get buchungsgruppen
2741   $query = qq|SELECT id, description
2742               FROM buchungsgruppen|;
2743
2744   $self->{BUCHUNGSGRUPPEN} = selectall_hashref_query($self, $dbh, $query);
2745
2746   $main::lxdebug->leave_sub();
2747 }
2748
2749 # this is only used for reports
2750 sub all_departments {
2751   $main::lxdebug->enter_sub();
2752
2753   my ($self, $myconfig, $table) = @_;
2754
2755   my $dbh = $self->get_standard_dbh($myconfig);
2756   my $where;
2757
2758   if ($table eq 'customer') {
2759     $where = "WHERE role = 'P' ";
2760   }
2761
2762   my $query = qq|SELECT id, description
2763                  FROM department
2764                  $where
2765                  ORDER BY description|;
2766   $self->{all_departments} = selectall_hashref_query($self, $dbh, $query);
2767
2768   delete($self->{all_departments}) unless (@{ $self->{all_departments} || [] });
2769
2770   $main::lxdebug->leave_sub();
2771 }
2772
2773 sub create_links {
2774   $main::lxdebug->enter_sub();
2775
2776   my ($self, $module, $myconfig, $table, $provided_dbh) = @_;
2777
2778   my ($fld, $arap);
2779   if ($table eq "customer") {
2780     $fld = "buy";
2781     $arap = "ar";
2782   } else {
2783     $table = "vendor";
2784     $fld = "sell";
2785     $arap = "ap";
2786   }
2787
2788   $self->all_vc($myconfig, $table, $module);
2789
2790   # get last customers or vendors
2791   my ($query, $sth, $ref);
2792
2793   my $dbh = $provided_dbh ? $provided_dbh : $self->get_standard_dbh($myconfig);
2794   my %xkeyref = ();
2795
2796   if (!$self->{id}) {
2797
2798     my $transdate = "current_date";
2799     if ($self->{transdate}) {
2800       $transdate = $dbh->quote($self->{transdate});
2801     }
2802
2803     # now get the account numbers
2804     $query = qq|SELECT c.accno, c.description, c.link, c.taxkey_id, tk.tax_id
2805                 FROM chart c, taxkeys tk
2806                 WHERE (c.link LIKE ?) AND (c.id = tk.chart_id) AND tk.id =
2807                   (SELECT id FROM taxkeys WHERE (taxkeys.chart_id = c.id) AND (startdate <= $transdate) ORDER BY startdate DESC LIMIT 1)
2808                 ORDER BY c.accno|;
2809
2810     $sth = $dbh->prepare($query);
2811
2812     do_statement($self, $sth, $query, '%' . $module . '%');
2813
2814     $self->{accounts} = "";
2815     while ($ref = $sth->fetchrow_hashref("NAME_lc")) {
2816
2817       foreach my $key (split(/:/, $ref->{link})) {
2818         if ($key =~ /\Q$module\E/) {
2819
2820           # cross reference for keys
2821           $xkeyref{ $ref->{accno} } = $key;
2822
2823           push @{ $self->{"${module}_links"}{$key} },
2824             { accno       => $ref->{accno},
2825               description => $ref->{description},
2826               taxkey      => $ref->{taxkey_id},
2827               tax_id      => $ref->{tax_id} };
2828
2829           $self->{accounts} .= "$ref->{accno} " unless $key =~ /tax/;
2830         }
2831       }
2832     }
2833   }
2834
2835   # get taxkeys and description
2836   $query = qq|SELECT id, taxkey, taxdescription FROM tax|;
2837   $self->{TAXKEY} = selectall_hashref_query($self, $dbh, $query);
2838
2839   if (($module eq "AP") || ($module eq "AR")) {
2840     # get tax rates and description
2841     $query = qq|SELECT * FROM tax|;
2842     $self->{TAX} = selectall_hashref_query($self, $dbh, $query);
2843   }
2844
2845   if ($self->{id}) {
2846     $query =
2847       qq|SELECT
2848            a.cp_id, a.invnumber, a.transdate, a.${table}_id, a.datepaid,
2849            a.duedate, a.ordnumber, a.taxincluded, a.curr AS currency, a.notes,
2850            a.intnotes, a.department_id, a.amount AS oldinvtotal,
2851            a.paid AS oldtotalpaid, a.employee_id, a.gldate, a.type,
2852            c.name AS $table,
2853            d.description AS department,
2854            e.name AS employee
2855          FROM $arap a
2856          JOIN $table c ON (a.${table}_id = c.id)
2857          LEFT JOIN employee e ON (e.id = a.employee_id)
2858          LEFT JOIN department d ON (d.id = a.department_id)
2859          WHERE a.id = ?|;
2860     $ref = selectfirst_hashref_query($self, $dbh, $query, $self->{id});
2861
2862     foreach my $key (keys %$ref) {
2863       $self->{$key} = $ref->{$key};
2864     }
2865
2866     my $transdate = "current_date";
2867     if ($self->{transdate}) {
2868       $transdate = $dbh->quote($self->{transdate});
2869     }
2870
2871     # now get the account numbers
2872     $query = qq|SELECT c.accno, c.description, c.link, c.taxkey_id, tk.tax_id
2873                 FROM chart c
2874                 LEFT JOIN taxkeys tk ON (tk.chart_id = c.id)
2875                 WHERE c.link LIKE ?
2876                   AND (tk.id = (SELECT id FROM taxkeys WHERE taxkeys.chart_id = c.id AND startdate <= $transdate ORDER BY startdate DESC LIMIT 1)
2877                     OR c.link LIKE '%_tax%' OR c.taxkey_id IS NULL)
2878                 ORDER BY c.accno|;
2879
2880     $sth = $dbh->prepare($query);
2881     do_statement($self, $sth, $query, "%$module%");
2882
2883     $self->{accounts} = "";
2884     while ($ref = $sth->fetchrow_hashref("NAME_lc")) {
2885
2886       foreach my $key (split(/:/, $ref->{link})) {
2887         if ($key =~ /\Q$module\E/) {
2888
2889           # cross reference for keys
2890           $xkeyref{ $ref->{accno} } = $key;
2891
2892           push @{ $self->{"${module}_links"}{$key} },
2893             { accno       => $ref->{accno},
2894               description => $ref->{description},
2895               taxkey      => $ref->{taxkey_id},
2896               tax_id      => $ref->{tax_id} };
2897
2898           $self->{accounts} .= "$ref->{accno} " unless $key =~ /tax/;
2899         }
2900       }
2901     }
2902
2903
2904     # get amounts from individual entries
2905     $query =
2906       qq|SELECT
2907            c.accno, c.description,
2908            a.source, a.amount, a.memo, a.transdate, a.cleared, a.project_id, a.taxkey,
2909            p.projectnumber,
2910            t.rate, t.id
2911          FROM acc_trans a
2912          LEFT JOIN chart c ON (c.id = a.chart_id)
2913          LEFT JOIN project p ON (p.id = a.project_id)
2914          LEFT JOIN tax t ON (t.id= (SELECT tk.tax_id FROM taxkeys tk
2915                                     WHERE (tk.taxkey_id=a.taxkey) AND
2916                                       ((CASE WHEN a.chart_id IN (SELECT chart_id FROM taxkeys WHERE taxkey_id = a.taxkey)
2917                                         THEN tk.chart_id = a.chart_id
2918                                         ELSE 1 = 1
2919                                         END)
2920                                        OR (c.link='%tax%')) AND
2921                                       (startdate <= a.transdate) ORDER BY startdate DESC LIMIT 1))
2922          WHERE a.trans_id = ?
2923          AND a.fx_transaction = '0'
2924          ORDER BY a.acc_trans_id, a.transdate|;
2925     $sth = $dbh->prepare($query);
2926     do_statement($self, $sth, $query, $self->{id});
2927
2928     # get exchangerate for currency
2929     $self->{exchangerate} =
2930       $self->get_exchangerate($dbh, $self->{currency}, $self->{transdate}, $fld);
2931     my $index = 0;
2932
2933     # store amounts in {acc_trans}{$key} for multiple accounts
2934     while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
2935       $ref->{exchangerate} =
2936         $self->get_exchangerate($dbh, $self->{currency}, $ref->{transdate}, $fld);
2937       if (!($xkeyref{ $ref->{accno} } =~ /tax/)) {
2938         $index++;
2939       }
2940       if (($xkeyref{ $ref->{accno} } =~ /paid/) && ($self->{type} eq "credit_note")) {
2941         $ref->{amount} *= -1;
2942       }
2943       $ref->{index} = $index;
2944
2945       push @{ $self->{acc_trans}{ $xkeyref{ $ref->{accno} } } }, $ref;
2946     }
2947
2948     $sth->finish;
2949     $query =
2950       qq|SELECT
2951            d.curr AS currencies, d.closedto, d.revtrans,
2952            (SELECT c.accno FROM chart c WHERE d.fxgain_accno_id = c.id) AS fxgain_accno,
2953            (SELECT c.accno FROM chart c WHERE d.fxloss_accno_id = c.id) AS fxloss_accno
2954          FROM defaults d|;
2955     $ref = selectfirst_hashref_query($self, $dbh, $query);
2956     map { $self->{$_} = $ref->{$_} } keys %$ref;
2957
2958   } else {
2959
2960     # get date
2961     $query =
2962        qq|SELECT
2963             current_date AS transdate, d.curr AS currencies, d.closedto, d.revtrans,
2964             (SELECT c.accno FROM chart c WHERE d.fxgain_accno_id = c.id) AS fxgain_accno,
2965             (SELECT c.accno FROM chart c WHERE d.fxloss_accno_id = c.id) AS fxloss_accno
2966           FROM defaults d|;
2967     $ref = selectfirst_hashref_query($self, $dbh, $query);
2968     map { $self->{$_} = $ref->{$_} } keys %$ref;
2969
2970     if ($self->{"$self->{vc}_id"}) {
2971
2972       # only setup currency
2973       ($self->{currency}) = split(/:/, $self->{currencies});
2974
2975     } else {
2976
2977       $self->lastname_used($dbh, $myconfig, $table, $module);
2978
2979       # get exchangerate for currency
2980       $self->{exchangerate} =
2981         $self->get_exchangerate($dbh, $self->{currency}, $self->{transdate}, $fld);
2982
2983     }
2984
2985   }
2986
2987   $main::lxdebug->leave_sub();
2988 }
2989
2990 sub lastname_used {
2991   $main::lxdebug->enter_sub();
2992
2993   my ($self, $dbh, $myconfig, $table, $module) = @_;
2994
2995   my ($arap, $where);
2996
2997   $table         = $table eq "customer" ? "customer" : "vendor";
2998   my %column_map = ("a.curr"                  => "currency",
2999                     "a.${table}_id"           => "${table}_id",
3000                     "a.department_id"         => "department_id",
3001                     "d.description"           => "department",
3002                     "ct.name"                 => $table,
3003                     "current_date + ct.terms" => "duedate",
3004     );
3005
3006   if ($self->{type} =~ /delivery_order/) {
3007     $arap  = 'delivery_orders';
3008     delete $column_map{"a.curr"};
3009
3010   } elsif ($self->{type} =~ /_order/) {
3011     $arap  = 'oe';
3012     $where = "quotation = '0'";
3013
3014   } elsif ($self->{type} =~ /_quotation/) {
3015     $arap  = 'oe';
3016     $where = "quotation = '1'";
3017
3018   } elsif ($table eq 'customer') {
3019     $arap  = 'ar';
3020
3021   } else {
3022     $arap  = 'ap';
3023
3024   }
3025
3026   $where           = "($where) AND" if ($where);
3027   my $query        = qq|SELECT MAX(id) FROM $arap
3028                         WHERE $where ${table}_id > 0|;
3029   my ($trans_id)   = selectrow_query($self, $dbh, $query);
3030   $trans_id       *= 1;
3031
3032   my $column_spec  = join(', ', map { "${_} AS $column_map{$_}" } keys %column_map);
3033   $query           = qq|SELECT $column_spec
3034                         FROM $arap a
3035                         LEFT JOIN $table     ct ON (a.${table}_id = ct.id)
3036                         LEFT JOIN department d  ON (a.department_id = d.id)
3037                         WHERE a.id = ?|;
3038   my $ref          = selectfirst_hashref_query($self, $dbh, $query, $trans_id);
3039
3040   map { $self->{$_} = $ref->{$_} } values %column_map;
3041
3042   $main::lxdebug->leave_sub();
3043 }
3044
3045 sub current_date {
3046   $main::lxdebug->enter_sub();
3047
3048   my $self     = shift;
3049   my $myconfig = shift || \%::myconfig;
3050   my ($thisdate, $days) = @_;
3051
3052   my $dbh = $self->get_standard_dbh($myconfig);
3053   my $query;
3054
3055   $days *= 1;
3056   if ($thisdate) {
3057     my $dateformat = $myconfig->{dateformat};
3058     $dateformat .= "yy" if $myconfig->{dateformat} !~ /^y/;
3059     $thisdate = $dbh->quote($thisdate);
3060     $query = qq|SELECT to_date($thisdate, '$dateformat') + $days AS thisdate|;
3061   } else {
3062     $query = qq|SELECT current_date AS thisdate|;
3063   }
3064
3065   ($thisdate) = selectrow_query($self, $dbh, $query);
3066
3067   $main::lxdebug->leave_sub();
3068
3069   return $thisdate;
3070 }
3071
3072 sub like {
3073   $main::lxdebug->enter_sub();
3074
3075   my ($self, $string) = @_;
3076
3077   if ($string !~ /%/) {
3078     $string = "%$string%";
3079   }
3080
3081   $string =~ s/\'/\'\'/g;
3082
3083   $main::lxdebug->leave_sub();
3084
3085   return $string;
3086 }
3087
3088 sub redo_rows {
3089   $main::lxdebug->enter_sub();
3090
3091   my ($self, $flds, $new, $count, $numrows) = @_;
3092
3093   my @ndx = ();
3094
3095   map { push @ndx, { num => $new->[$_ - 1]->{runningnumber}, ndx => $_ } } 1 .. $count;
3096
3097   my $i = 0;
3098
3099   # fill rows
3100   foreach my $item (sort { $a->{num} <=> $b->{num} } @ndx) {
3101     $i++;
3102     my $j = $item->{ndx} - 1;
3103     map { $self->{"${_}_$i"} = $new->[$j]->{$_} } @{$flds};
3104   }
3105
3106   # delete empty rows
3107   for $i ($count + 1 .. $numrows) {
3108     map { delete $self->{"${_}_$i"} } @{$flds};
3109   }
3110
3111   $main::lxdebug->leave_sub();
3112 }
3113
3114 sub update_status {
3115   $main::lxdebug->enter_sub();
3116
3117   my ($self, $myconfig) = @_;
3118
3119   my ($i, $id);
3120
3121   my $dbh = $self->dbconnect_noauto($myconfig);
3122
3123   my $query = qq|DELETE FROM status
3124                  WHERE (formname = ?) AND (trans_id = ?)|;
3125   my $sth = prepare_query($self, $dbh, $query);
3126
3127   if ($self->{formname} =~ /(check|receipt)/) {
3128     for $i (1 .. $self->{rowcount}) {
3129       do_statement($self, $sth, $query, $self->{formname}, $self->{"id_$i"} * 1);
3130     }
3131   } else {
3132     do_statement($self, $sth, $query, $self->{formname}, $self->{id});
3133   }
3134   $sth->finish();
3135
3136   my $printed = ($self->{printed} =~ /\Q$self->{formname}\E/) ? "1" : "0";
3137   my $emailed = ($self->{emailed} =~ /\Q$self->{formname}\E/) ? "1" : "0";
3138
3139   my %queued = split / /, $self->{queued};
3140   my @values;
3141
3142   if ($self->{formname} =~ /(check|receipt)/) {
3143
3144     # this is a check or receipt, add one entry for each lineitem
3145     my ($accno) = split /--/, $self->{account};
3146     $query = qq|INSERT INTO status (trans_id, printed, spoolfile, formname, chart_id)
3147                 VALUES (?, ?, ?, ?, (SELECT c.id FROM chart c WHERE c.accno = ?))|;
3148     @values = ($printed, $queued{$self->{formname}}, $self->{prinform}, $accno);
3149     $sth = prepare_query($self, $dbh, $query);
3150
3151     for $i (1 .. $self->{rowcount}) {
3152       if ($self->{"checked_$i"}) {
3153         do_statement($self, $sth, $query, $self->{"id_$i"}, @values);
3154       }
3155     }
3156     $sth->finish();
3157
3158   } else {
3159     $query = qq|INSERT INTO status (trans_id, printed, emailed, spoolfile, formname)
3160                 VALUES (?, ?, ?, ?, ?)|;
3161     do_query($self, $dbh, $query, $self->{id}, $printed, $emailed,
3162              $queued{$self->{formname}}, $self->{formname});
3163   }
3164
3165   $dbh->commit;
3166   $dbh->disconnect;
3167
3168   $main::lxdebug->leave_sub();
3169 }
3170
3171 sub save_status {
3172   $main::lxdebug->enter_sub();
3173
3174   my ($self, $dbh) = @_;
3175
3176   my ($query, $printed, $emailed);
3177
3178   my $formnames  = $self->{printed};
3179   my $emailforms = $self->{emailed};
3180
3181   $query = qq|DELETE FROM status
3182                  WHERE (formname = ?) AND (trans_id = ?)|;
3183   do_query($self, $dbh, $query, $self->{formname}, $self->{id});
3184
3185   # this only applies to the forms
3186   # checks and receipts are posted when printed or queued
3187
3188   if ($self->{queued}) {
3189     my %queued = split / /, $self->{queued};
3190
3191     foreach my $formname (keys %queued) {
3192       $printed = ($self->{printed} =~ /\Q$self->{formname}\E/) ? "1" : "0";
3193       $emailed = ($self->{emailed} =~ /\Q$self->{formname}\E/) ? "1" : "0";
3194
3195       $query = qq|INSERT INTO status (trans_id, printed, emailed, spoolfile, formname)
3196                   VALUES (?, ?, ?, ?, ?)|;
3197       do_query($self, $dbh, $query, $self->{id}, $printed, $emailed, $queued{$formname}, $formname);
3198
3199       $formnames  =~ s/\Q$self->{formname}\E//;
3200       $emailforms =~ s/\Q$self->{formname}\E//;
3201
3202     }
3203   }
3204
3205   # save printed, emailed info
3206   $formnames  =~ s/^ +//g;
3207   $emailforms =~ s/^ +//g;
3208
3209   my %status = ();
3210   map { $status{$_}{printed} = 1 } split / +/, $formnames;
3211   map { $status{$_}{emailed} = 1 } split / +/, $emailforms;
3212
3213   foreach my $formname (keys %status) {
3214     $printed = ($formnames  =~ /\Q$self->{formname}\E/) ? "1" : "0";
3215     $emailed = ($emailforms =~ /\Q$self->{formname}\E/) ? "1" : "0";
3216
3217     $query = qq|INSERT INTO status (trans_id, printed, emailed, formname)
3218                 VALUES (?, ?, ?, ?)|;
3219     do_query($self, $dbh, $query, $self->{id}, $printed, $emailed, $formname);
3220   }
3221
3222   $main::lxdebug->leave_sub();
3223 }
3224
3225 #--- 4 locale ---#
3226 # $main::locale->text('SAVED')
3227 # $main::locale->text('DELETED')
3228 # $main::locale->text('ADDED')
3229 # $main::locale->text('PAYMENT POSTED')
3230 # $main::locale->text('POSTED')
3231 # $main::locale->text('POSTED AS NEW')
3232 # $main::locale->text('ELSE')
3233 # $main::locale->text('SAVED FOR DUNNING')
3234 # $main::locale->text('DUNNING STARTED')
3235 # $main::locale->text('PRINTED')
3236 # $main::locale->text('MAILED')
3237 # $main::locale->text('SCREENED')
3238 # $main::locale->text('CANCELED')
3239 # $main::locale->text('invoice')
3240 # $main::locale->text('proforma')
3241 # $main::locale->text('sales_order')
3242 # $main::locale->text('packing_list')
3243 # $main::locale->text('pick_list')
3244 # $main::locale->text('purchase_order')
3245 # $main::locale->text('bin_list')
3246 # $main::locale->text('sales_quotation')
3247 # $main::locale->text('request_quotation')
3248
3249 sub save_history {
3250   $main::lxdebug->enter_sub();
3251
3252   my $self = shift;
3253   my $dbh  = shift || $self->get_standard_dbh;
3254
3255   if(!exists $self->{employee_id}) {
3256     &get_employee($self, $dbh);
3257   }
3258
3259   my $query =
3260    qq|INSERT INTO history_erp (trans_id, employee_id, addition, what_done, snumbers) | .
3261    qq|VALUES (?, (SELECT id FROM employee WHERE login = ?), ?, ?, ?)|;
3262   my @values = (conv_i($self->{id}), $self->{login},
3263                 $self->{addition}, $self->{what_done}, "$self->{snumbers}");
3264   do_query($self, $dbh, $query, @values);
3265
3266   $dbh->commit;
3267
3268   $main::lxdebug->leave_sub();
3269 }
3270
3271 sub get_history {
3272   $main::lxdebug->enter_sub();
3273
3274   my ($self, $dbh, $trans_id, $restriction, $order) = @_;
3275   my ($orderBy, $desc) = split(/\-\-/, $order);
3276   $order = " ORDER BY " . ($order eq "" ? " h.itime " : ($desc == 1 ? $orderBy . " DESC " : $orderBy . " "));
3277   my @tempArray;
3278   my $i = 0;
3279   if ($trans_id ne "") {
3280     my $query =
3281       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 | .
3282       qq|FROM history_erp h | .
3283       qq|LEFT JOIN employee emp ON (emp.id = h.employee_id) | .
3284       qq|WHERE (trans_id = | . $trans_id . qq|) $restriction | .
3285       $order;
3286
3287     my $sth = $dbh->prepare($query) || $self->dberror($query);
3288
3289     $sth->execute() || $self->dberror("$query");
3290
3291     while(my $hash_ref = $sth->fetchrow_hashref()) {
3292       $hash_ref->{addition} = $main::locale->text($hash_ref->{addition});
3293       $hash_ref->{what_done} = $main::locale->text($hash_ref->{what_done});
3294       $hash_ref->{snumbers} =~ s/^.+_(.*)$/$1/g;
3295       $tempArray[$i++] = $hash_ref;
3296     }
3297     $main::lxdebug->leave_sub() and return \@tempArray
3298       if ($i > 0 && $tempArray[0] ne "");
3299   }
3300   $main::lxdebug->leave_sub();
3301   return 0;
3302 }
3303
3304 sub update_defaults {
3305   $main::lxdebug->enter_sub();
3306
3307   my ($self, $myconfig, $fld, $provided_dbh) = @_;
3308
3309   my $dbh;
3310   if ($provided_dbh) {
3311     $dbh = $provided_dbh;
3312   } else {
3313     $dbh = $self->dbconnect_noauto($myconfig);
3314   }
3315   my $query = qq|SELECT $fld FROM defaults FOR UPDATE|;
3316   my $sth   = $dbh->prepare($query);
3317
3318   $sth->execute || $self->dberror($query);
3319   my ($var) = $sth->fetchrow_array;
3320   $sth->finish;
3321
3322   if ($var =~ m/\d+$/) {
3323     my $new_var  = (substr $var, $-[0]) * 1 + 1;
3324     my $len_diff = length($var) - $-[0] - length($new_var);
3325     $var         = substr($var, 0, $-[0]) . ($len_diff > 0 ? '0' x $len_diff : '') . $new_var;
3326
3327   } else {
3328     $var = $var . '1';
3329   }
3330
3331   $query = qq|UPDATE defaults SET $fld = ?|;
3332   do_query($self, $dbh, $query, $var);
3333
3334   if (!$provided_dbh) {
3335     $dbh->commit;
3336     $dbh->disconnect;
3337   }
3338
3339   $main::lxdebug->leave_sub();
3340
3341   return $var;
3342 }
3343
3344 sub update_business {
3345   $main::lxdebug->enter_sub();
3346
3347   my ($self, $myconfig, $business_id, $provided_dbh) = @_;
3348
3349   my $dbh;
3350   if ($provided_dbh) {
3351     $dbh = $provided_dbh;
3352   } else {
3353     $dbh = $self->dbconnect_noauto($myconfig);
3354   }
3355   my $query =
3356     qq|SELECT customernumberinit FROM business
3357        WHERE id = ? FOR UPDATE|;
3358   my ($var) = selectrow_query($self, $dbh, $query, $business_id);
3359
3360   return undef unless $var;
3361
3362   if ($var =~ m/\d+$/) {
3363     my $new_var  = (substr $var, $-[0]) * 1 + 1;
3364     my $len_diff = length($var) - $-[0] - length($new_var);
3365     $var         = substr($var, 0, $-[0]) . ($len_diff > 0 ? '0' x $len_diff : '') . $new_var;
3366
3367   } else {
3368     $var = $var . '1';
3369   }
3370
3371   $query = qq|UPDATE business
3372               SET customernumberinit = ?
3373               WHERE id = ?|;
3374   do_query($self, $dbh, $query, $var, $business_id);
3375
3376   if (!$provided_dbh) {
3377     $dbh->commit;
3378     $dbh->disconnect;
3379   }
3380
3381   $main::lxdebug->leave_sub();
3382
3383   return $var;
3384 }
3385
3386 sub get_partsgroup {
3387   $main::lxdebug->enter_sub();
3388
3389   my ($self, $myconfig, $p) = @_;
3390   my $target = $p->{target} || 'all_partsgroup';
3391
3392   my $dbh = $self->get_standard_dbh($myconfig);
3393
3394   my $query = qq|SELECT DISTINCT pg.id, pg.partsgroup
3395                  FROM partsgroup pg
3396                  JOIN parts p ON (p.partsgroup_id = pg.id) |;
3397   my @values;
3398
3399   if ($p->{searchitems} eq 'part') {
3400     $query .= qq|WHERE p.inventory_accno_id > 0|;
3401   }
3402   if ($p->{searchitems} eq 'service') {
3403     $query .= qq|WHERE p.inventory_accno_id IS NULL|;
3404   }
3405   if ($p->{searchitems} eq 'assembly') {
3406     $query .= qq|WHERE p.assembly = '1'|;
3407   }
3408   if ($p->{searchitems} eq 'labor') {
3409     $query .= qq|WHERE (p.inventory_accno_id > 0) AND (p.income_accno_id IS NULL)|;
3410   }
3411
3412   $query .= qq|ORDER BY partsgroup|;
3413
3414   if ($p->{all}) {
3415     $query = qq|SELECT id, partsgroup FROM partsgroup
3416                 ORDER BY partsgroup|;
3417   }
3418
3419   if ($p->{language_code}) {
3420     $query = qq|SELECT DISTINCT pg.id, pg.partsgroup,
3421                   t.description AS translation
3422                 FROM partsgroup pg
3423                 JOIN parts p ON (p.partsgroup_id = pg.id)
3424                 LEFT JOIN translation t ON ((t.trans_id = pg.id) AND (t.language_code = ?))
3425                 ORDER BY translation|;
3426     @values = ($p->{language_code});
3427   }
3428
3429   $self->{$target} = selectall_hashref_query($self, $dbh, $query, @values);
3430
3431   $main::lxdebug->leave_sub();
3432 }
3433
3434 sub get_pricegroup {
3435   $main::lxdebug->enter_sub();
3436
3437   my ($self, $myconfig, $p) = @_;
3438
3439   my $dbh = $self->get_standard_dbh($myconfig);
3440
3441   my $query = qq|SELECT p.id, p.pricegroup
3442                  FROM pricegroup p|;
3443
3444   $query .= qq| ORDER BY pricegroup|;
3445
3446   if ($p->{all}) {
3447     $query = qq|SELECT id, pricegroup FROM pricegroup
3448                 ORDER BY pricegroup|;
3449   }
3450
3451   $self->{all_pricegroup} = selectall_hashref_query($self, $dbh, $query);
3452
3453   $main::lxdebug->leave_sub();
3454 }
3455
3456 sub all_years {
3457 # usage $form->all_years($myconfig, [$dbh])
3458 # return list of all years where bookings found
3459 # (@all_years)
3460
3461   $main::lxdebug->enter_sub();
3462
3463   my ($self, $myconfig, $dbh) = @_;
3464
3465   $dbh ||= $self->get_standard_dbh($myconfig);
3466
3467   # get years
3468   my $query = qq|SELECT (SELECT MIN(transdate) FROM acc_trans),
3469                    (SELECT MAX(transdate) FROM acc_trans)|;
3470   my ($startdate, $enddate) = selectrow_query($self, $dbh, $query);
3471
3472   if ($myconfig->{dateformat} =~ /^yy/) {
3473     ($startdate) = split /\W/, $startdate;
3474     ($enddate) = split /\W/, $enddate;
3475   } else {
3476     (@_) = split /\W/, $startdate;
3477     $startdate = $_[2];
3478     (@_) = split /\W/, $enddate;
3479     $enddate = $_[2];
3480   }
3481
3482   my @all_years;
3483   $startdate = substr($startdate,0,4);
3484   $enddate = substr($enddate,0,4);
3485
3486   while ($enddate >= $startdate) {
3487     push @all_years, $enddate--;
3488   }
3489
3490   return @all_years;
3491
3492   $main::lxdebug->leave_sub();
3493 }
3494
3495 sub backup_vars {
3496   $main::lxdebug->enter_sub();
3497   my $self = shift;
3498   my @vars = @_;
3499
3500   map { $self->{_VAR_BACKUP}->{$_} = $self->{$_} if exists $self->{$_} } @vars;
3501
3502   $main::lxdebug->leave_sub();
3503 }
3504
3505 sub restore_vars {
3506   $main::lxdebug->enter_sub();
3507
3508   my $self = shift;
3509   my @vars = @_;
3510
3511   map { $self->{$_} = $self->{_VAR_BACKUP}->{$_} if exists $self->{_VAR_BACKUP}->{$_} } @vars;
3512
3513   $main::lxdebug->leave_sub();
3514 }
3515
3516 1;
3517
3518 __END__
3519
3520 =head1 NAME
3521
3522 SL::Form.pm - main data object.
3523
3524 =head1 SYNOPSIS
3525
3526 This is the main data object of Lx-Office.
3527 Unfortunately it also acts as a god object for certain data retrieval procedures used in the entry points.
3528 Points of interest for a beginner are:
3529
3530  - $form->error            - renders a generic error in html. accepts an error message
3531  - $form->get_standard_dbh - returns a database connection for the
3532
3533 =head1 SPECIAL FUNCTIONS
3534
3535 =over 4
3536
3537 =item _store_value()
3538
3539 parses a complex var name, and stores it in the form.
3540
3541 syntax:
3542   $form->_store_value($key, $value);
3543
3544 keys must start with a string, and can contain various tokens.
3545 supported key structures are:
3546
3547 1. simple access
3548   simple key strings work as expected
3549
3550   id => $form->{id}
3551
3552 2. hash access.
3553   separating two keys by a dot (.) will result in a hash lookup for the inner value
3554   this is similar to the behaviour of java and templating mechanisms.
3555
3556   filter.description => $form->{filter}->{description}
3557
3558 3. array+hashref access
3559
3560   adding brackets ([]) before the dot will cause the next hash to be put into an array.
3561   using [+] instead of [] will force a new array index. this is useful for recurring
3562   data structures like part lists. put a [+] into the first varname, and use [] on the
3563   following ones.
3564
3565   repeating these names in your template:
3566
3567     invoice.items[+].id
3568     invoice.items[].parts_id
3569
3570   will result in:
3571
3572     $form->{invoice}->{items}->[
3573       {
3574         id       => ...
3575         parts_id => ...
3576       },
3577       {
3578         id       => ...
3579         parts_id => ...
3580       }
3581       ...
3582     ]
3583
3584 4. arrays
3585
3586   using brackets at the end of a name will result in a pure array to be created.
3587   note that you mustn't use [+], which is reserved for array+hash access and will
3588   result in undefined behaviour in array context.
3589
3590   filter.status[]  => $form->{status}->[ val1, val2, ... ]
3591
3592 =item update_business PARAMS
3593
3594 PARAMS (not named):
3595  \%config,     - config hashref
3596  $business_id, - business id
3597  $dbh          - optional database handle
3598
3599 handles business (thats customer/vendor types) sequences.
3600
3601 special behaviour for empty strings in customerinitnumber field:
3602 will in this case not increase the value, and return undef.
3603
3604 =item redirect_header $url
3605
3606 Generates a HTTP redirection header for the new C<$url>. Constructs an
3607 absolute URL including scheme, host name and port. If C<$url> is a
3608 relative URL then it is considered relative to Lx-Office base URL.
3609
3610 This function C<die>s if headers have already been created with
3611 C<$::form-E<gt>header>.
3612
3613 Examples:
3614
3615   print $::form->redirect_header('oe.pl?action=edit&id=1234');
3616   print $::form->redirect_header('http://www.lx-office.org/');
3617
3618 =back
3619
3620 =cut