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