707540ed7928358ef2fc072e280ddc3de8c667f0
[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   my $encoding     = $self->{INPUT_ENCODING} || $db_charset;
261   delete $self->{INPUT_ENCODING};
262
263   _recode_recursively(SL::Iconv->new($encoding, $db_charset), $self);
264
265   $self->{action}  =  lc $self->{action};
266   $self->{action}  =~ s/( |-|,|\#)/_/g;
267
268   $self->{version} =  "2.6.1";
269
270   $main::lxdebug->leave_sub();
271
272   return $self;
273 }
274
275 sub _flatten_variables_rec {
276   $main::lxdebug->enter_sub(2);
277
278   my $self   = shift;
279   my $curr   = shift;
280   my $prefix = shift;
281   my $key    = shift;
282
283   my @result;
284
285   if ('' eq ref $curr->{$key}) {
286     @result = ({ 'key' => $prefix . $key, 'value' => $curr->{$key} });
287
288   } elsif ('HASH' eq ref $curr->{$key}) {
289     foreach my $hash_key (sort keys %{ $curr->{$key} }) {
290       push @result, $self->_flatten_variables_rec($curr->{$key}, $prefix . $key . '.', $hash_key);
291     }
292
293   } else {
294     foreach my $idx (0 .. scalar @{ $curr->{$key} } - 1) {
295       my $first_array_entry = 1;
296
297       foreach my $hash_key (sort keys %{ $curr->{$key}->[$idx] }) {
298         push @result, $self->_flatten_variables_rec($curr->{$key}->[$idx], $prefix . $key . ($first_array_entry ? '[+].' : '[].'), $hash_key);
299         $first_array_entry = 0;
300       }
301     }
302   }
303
304   $main::lxdebug->leave_sub(2);
305
306   return @result;
307 }
308
309 sub flatten_variables {
310   $main::lxdebug->enter_sub(2);
311
312   my $self = shift;
313   my @keys = @_;
314
315   my @variables;
316
317   foreach (@keys) {
318     push @variables, $self->_flatten_variables_rec($self, '', $_);
319   }
320
321   $main::lxdebug->leave_sub(2);
322
323   return @variables;
324 }
325
326 sub flatten_standard_variables {
327   $main::lxdebug->enter_sub(2);
328
329   my $self      = shift;
330   my %skip_keys = map { $_ => 1 } (qw(login password header stylesheet titlebar version), @_);
331
332   my @variables;
333
334   foreach (grep { ! $skip_keys{$_} } keys %{ $self }) {
335     push @variables, $self->_flatten_variables_rec($self, '', $_);
336   }
337
338   $main::lxdebug->leave_sub(2);
339
340   return @variables;
341 }
342
343 sub debug {
344   $main::lxdebug->enter_sub();
345
346   my ($self) = @_;
347
348   print "\n";
349
350   map { print "$_ = $self->{$_}\n" } (sort keys %{$self});
351
352   $main::lxdebug->leave_sub();
353 }
354
355 sub dumper {
356   $main::lxdebug->enter_sub(2);
357
358   my $self          = shift;
359   my $password      = $self->{password};
360
361   $self->{password} = 'X' x 8;
362
363   local $Data::Dumper::Sortkeys = 1;
364   my $output                    = Dumper($self);
365
366   $self->{password} = $password;
367
368   $main::lxdebug->leave_sub(2);
369
370   return $output;
371 }
372
373 sub escape {
374   $main::lxdebug->enter_sub(2);
375
376   my ($self, $str) = @_;
377
378   $str =~ s/([^a-zA-Z0-9_.-])/sprintf("%%%02x", ord($1))/ge;
379
380   $main::lxdebug->leave_sub(2);
381
382   return $str;
383 }
384
385 sub unescape {
386   $main::lxdebug->enter_sub(2);
387
388   my ($self, $str) = @_;
389
390   $str =~ tr/+/ /;
391   $str =~ s/\\$//;
392
393   $str =~ s/%([0-9a-fA-Z]{2})/pack("c",hex($1))/eg;
394
395   $main::lxdebug->leave_sub(2);
396
397   return $str;
398 }
399
400 sub quote {
401   $main::lxdebug->enter_sub();
402   my ($self, $str) = @_;
403
404   if ($str && !ref($str)) {
405     $str =~ s/\"/&quot;/g;
406   }
407
408   $main::lxdebug->leave_sub();
409
410   return $str;
411 }
412
413 sub unquote {
414   $main::lxdebug->enter_sub();
415   my ($self, $str) = @_;
416
417   if ($str && !ref($str)) {
418     $str =~ s/&quot;/\"/g;
419   }
420
421   $main::lxdebug->leave_sub();
422
423   return $str;
424 }
425
426 sub hide_form {
427   $main::lxdebug->enter_sub();
428   my $self = shift;
429
430   if (@_) {
431     map({ print($main::cgi->hidden("-name" => $_, "-default" => $self->{$_}) . "\n"); } @_);
432   } else {
433     for (sort keys %$self) {
434       next if (($_ eq "header") || (ref($self->{$_}) ne ""));
435       print($main::cgi->hidden("-name" => $_, "-default" => $self->{$_}) . "\n");
436     }
437   }
438   $main::lxdebug->leave_sub();
439 }
440
441 sub error {
442   $main::lxdebug->enter_sub();
443
444   $main::lxdebug->show_backtrace();
445
446   my ($self, $msg) = @_;
447   if ($ENV{HTTP_USER_AGENT}) {
448     $msg =~ s/\n/<br>/g;
449     $self->show_generic_error($msg);
450
451   } else {
452     print STDERR "Error: $msg\n";
453     ::end_of_request();
454   }
455
456   $main::lxdebug->leave_sub();
457 }
458
459 sub info {
460   $main::lxdebug->enter_sub();
461
462   my ($self, $msg) = @_;
463
464   if ($ENV{HTTP_USER_AGENT}) {
465     $msg =~ s/\n/<br>/g;
466
467     if (!$self->{header}) {
468       $self->header;
469       print qq|<body>|;
470     }
471
472     print qq|
473     <p class="message_ok"><b>$msg</b></p>
474     
475     <script type="text/javascript">
476     <!--
477     setTimeout("parent.frames.main_window.location.href='login.pl?action=company_logo'",1000);
478     //-->
479     </script>
480     
481 </body>
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_options {
1557   my $self    = shift;
1558   my $options = { pg_enable_utf8 => $::locale->is_utf8,
1559                   @_ };
1560
1561   return $options;
1562 }
1563
1564 sub dbconnect {
1565   $main::lxdebug->enter_sub(2);
1566
1567   my ($self, $myconfig) = @_;
1568
1569   # connect to database
1570   my $dbh = DBI->connect($myconfig->{dbconnect}, $myconfig->{dbuser}, $myconfig->{dbpasswd}, $self->_dbconnect_options)
1571     or $self->dberror;
1572
1573   # set db options
1574   if ($myconfig->{dboptions}) {
1575     $dbh->do($myconfig->{dboptions}) || $self->dberror($myconfig->{dboptions});
1576   }
1577
1578   $main::lxdebug->leave_sub(2);
1579
1580   return $dbh;
1581 }
1582
1583 sub dbconnect_noauto {
1584   $main::lxdebug->enter_sub();
1585
1586   my ($self, $myconfig) = @_;
1587
1588   # connect to database
1589   my $dbh = DBI->connect($myconfig->{dbconnect}, $myconfig->{dbuser}, $myconfig->{dbpasswd}, $self->_dbconnect_options(AutoCommit => 0))
1590     or $self->dberror;
1591
1592   # set db options
1593   if ($myconfig->{dboptions}) {
1594     $dbh->do($myconfig->{dboptions}) || $self->dberror($myconfig->{dboptions});
1595   }
1596
1597   $main::lxdebug->leave_sub();
1598
1599   return $dbh;
1600 }
1601
1602 sub get_standard_dbh {
1603   $main::lxdebug->enter_sub(2);
1604
1605   my $self     = shift;
1606   my $myconfig = shift || \%::myconfig;
1607
1608   if ($standard_dbh && !$standard_dbh->{Active}) {
1609     $main::lxdebug->message(LXDebug->INFO(), "get_standard_dbh: \$standard_dbh is defined but not Active anymore");
1610     undef $standard_dbh;
1611   }
1612
1613   $standard_dbh ||= $self->dbconnect_noauto($myconfig);
1614
1615   $main::lxdebug->leave_sub(2);
1616
1617   return $standard_dbh;
1618 }
1619
1620 sub date_closed {
1621   $main::lxdebug->enter_sub();
1622
1623   my ($self, $date, $myconfig) = @_;
1624   my $dbh = $self->dbconnect($myconfig);
1625
1626   my $query = "SELECT 1 FROM defaults WHERE ? < closedto";
1627   my $sth = prepare_execute_query($self, $dbh, $query, $date);
1628   my ($closed) = $sth->fetchrow_array;
1629
1630   $main::lxdebug->leave_sub();
1631
1632   return $closed;
1633 }
1634
1635 sub update_balance {
1636   $main::lxdebug->enter_sub();
1637
1638   my ($self, $dbh, $table, $field, $where, $value, @values) = @_;
1639
1640   # if we have a value, go do it
1641   if ($value != 0) {
1642
1643     # retrieve balance from table
1644     my $query = "SELECT $field FROM $table WHERE $where FOR UPDATE";
1645     my $sth = prepare_execute_query($self, $dbh, $query, @values);
1646     my ($balance) = $sth->fetchrow_array;
1647     $sth->finish;
1648
1649     $balance += $value;
1650
1651     # update balance
1652     $query = "UPDATE $table SET $field = $balance WHERE $where";
1653     do_query($self, $dbh, $query, @values);
1654   }
1655   $main::lxdebug->leave_sub();
1656 }
1657
1658 sub update_exchangerate {
1659   $main::lxdebug->enter_sub();
1660
1661   my ($self, $dbh, $curr, $transdate, $buy, $sell) = @_;
1662   my ($query);
1663   # some sanity check for currency
1664   if ($curr eq '') {
1665     $main::lxdebug->leave_sub();
1666     return;
1667   }
1668   $query = qq|SELECT curr FROM defaults|;
1669
1670   my ($currency) = selectrow_query($self, $dbh, $query);
1671   my ($defaultcurrency) = split m/:/, $currency;
1672
1673
1674   if ($curr eq $defaultcurrency) {
1675     $main::lxdebug->leave_sub();
1676     return;
1677   }
1678
1679   $query = qq|SELECT e.curr FROM exchangerate e
1680                  WHERE e.curr = ? AND e.transdate = ?
1681                  FOR UPDATE|;
1682   my $sth = prepare_execute_query($self, $dbh, $query, $curr, $transdate);
1683
1684   if ($buy == 0) {
1685     $buy = "";
1686   }
1687   if ($sell == 0) {
1688     $sell = "";
1689   }
1690
1691   $buy = conv_i($buy, "NULL");
1692   $sell = conv_i($sell, "NULL");
1693
1694   my $set;
1695   if ($buy != 0 && $sell != 0) {
1696     $set = "buy = $buy, sell = $sell";
1697   } elsif ($buy != 0) {
1698     $set = "buy = $buy";
1699   } elsif ($sell != 0) {
1700     $set = "sell = $sell";
1701   }
1702
1703   if ($sth->fetchrow_array) {
1704     $query = qq|UPDATE exchangerate
1705                 SET $set
1706                 WHERE curr = ?
1707                 AND transdate = ?|;
1708
1709   } else {
1710     $query = qq|INSERT INTO exchangerate (curr, buy, sell, transdate)
1711                 VALUES (?, $buy, $sell, ?)|;
1712   }
1713   $sth->finish;
1714   do_query($self, $dbh, $query, $curr, $transdate);
1715
1716   $main::lxdebug->leave_sub();
1717 }
1718
1719 sub save_exchangerate {
1720   $main::lxdebug->enter_sub();
1721
1722   my ($self, $myconfig, $currency, $transdate, $rate, $fld) = @_;
1723
1724   my $dbh = $self->dbconnect($myconfig);
1725
1726   my ($buy, $sell);
1727
1728   $buy  = $rate if $fld eq 'buy';
1729   $sell = $rate if $fld eq 'sell';
1730
1731
1732   $self->update_exchangerate($dbh, $currency, $transdate, $buy, $sell);
1733
1734
1735   $dbh->disconnect;
1736
1737   $main::lxdebug->leave_sub();
1738 }
1739
1740 sub get_exchangerate {
1741   $main::lxdebug->enter_sub();
1742
1743   my ($self, $dbh, $curr, $transdate, $fld) = @_;
1744   my ($query);
1745
1746   unless ($transdate) {
1747     $main::lxdebug->leave_sub();
1748     return 1;
1749   }
1750
1751   $query = qq|SELECT curr FROM defaults|;
1752
1753   my ($currency) = selectrow_query($self, $dbh, $query);
1754   my ($defaultcurrency) = split m/:/, $currency;
1755
1756   if ($currency eq $defaultcurrency) {
1757     $main::lxdebug->leave_sub();
1758     return 1;
1759   }
1760
1761   $query = qq|SELECT e.$fld FROM exchangerate e
1762                  WHERE e.curr = ? AND e.transdate = ?|;
1763   my ($exchangerate) = selectrow_query($self, $dbh, $query, $curr, $transdate);
1764
1765
1766
1767   $main::lxdebug->leave_sub();
1768
1769   return $exchangerate;
1770 }
1771
1772 sub check_exchangerate {
1773   $main::lxdebug->enter_sub();
1774
1775   my ($self, $myconfig, $currency, $transdate, $fld) = @_;
1776
1777   if ($fld !~/^buy|sell$/) {
1778     $self->error('Fatal: check_exchangerate called with invalid buy/sell argument');
1779   }
1780
1781   unless ($transdate) {
1782     $main::lxdebug->leave_sub();
1783     return "";
1784   }
1785
1786   my ($defaultcurrency) = $self->get_default_currency($myconfig);
1787
1788   if ($currency eq $defaultcurrency) {
1789     $main::lxdebug->leave_sub();
1790     return 1;
1791   }
1792
1793   my $dbh   = $self->get_standard_dbh($myconfig);
1794   my $query = qq|SELECT e.$fld FROM exchangerate e
1795                  WHERE e.curr = ? AND e.transdate = ?|;
1796
1797   my ($exchangerate) = selectrow_query($self, $dbh, $query, $currency, $transdate);
1798
1799   $main::lxdebug->leave_sub();
1800
1801   return $exchangerate;
1802 }
1803
1804 sub get_all_currencies {
1805   $main::lxdebug->enter_sub();
1806
1807   my $self     = shift;
1808   my $myconfig = shift || \%::myconfig;
1809   my $dbh      = $self->get_standard_dbh($myconfig);
1810
1811   my $query = qq|SELECT curr FROM defaults|;
1812
1813   my ($curr)     = selectrow_query($self, $dbh, $query);
1814   my @currencies = grep { $_ } map { s/\s//g; $_ } split m/:/, $curr;
1815
1816   $main::lxdebug->leave_sub();
1817
1818   return @currencies;
1819 }
1820
1821 sub get_default_currency {
1822   $main::lxdebug->enter_sub();
1823
1824   my ($self, $myconfig) = @_;
1825   my @currencies        = $self->get_all_currencies($myconfig);
1826
1827   $main::lxdebug->leave_sub();
1828
1829   return $currencies[0];
1830 }
1831
1832 sub set_payment_options {
1833   $main::lxdebug->enter_sub();
1834
1835   my ($self, $myconfig, $transdate) = @_;
1836
1837   return $main::lxdebug->leave_sub() unless ($self->{payment_id});
1838
1839   my $dbh = $self->get_standard_dbh($myconfig);
1840
1841   my $query =
1842     qq|SELECT p.terms_netto, p.terms_skonto, p.percent_skonto, p.description_long | .
1843     qq|FROM payment_terms p | .
1844     qq|WHERE p.id = ?|;
1845
1846   ($self->{terms_netto}, $self->{terms_skonto}, $self->{percent_skonto},
1847    $self->{payment_terms}) =
1848      selectrow_query($self, $dbh, $query, $self->{payment_id});
1849
1850   if ($transdate eq "") {
1851     if ($self->{invdate}) {
1852       $transdate = $self->{invdate};
1853     } else {
1854       $transdate = $self->{transdate};
1855     }
1856   }
1857
1858   $query =
1859     qq|SELECT ?::date + ?::integer AS netto_date, ?::date + ?::integer AS skonto_date | .
1860     qq|FROM payment_terms|;
1861   ($self->{netto_date}, $self->{skonto_date}) =
1862     selectrow_query($self, $dbh, $query, $transdate, $self->{terms_netto}, $transdate, $self->{terms_skonto});
1863
1864   my ($invtotal, $total);
1865   my (%amounts, %formatted_amounts);
1866
1867   if ($self->{type} =~ /_order$/) {
1868     $amounts{invtotal} = $self->{ordtotal};
1869     $amounts{total}    = $self->{ordtotal};
1870
1871   } elsif ($self->{type} =~ /_quotation$/) {
1872     $amounts{invtotal} = $self->{quototal};
1873     $amounts{total}    = $self->{quototal};
1874
1875   } else {
1876     $amounts{invtotal} = $self->{invtotal};
1877     $amounts{total}    = $self->{total};
1878   }
1879   $amounts{skonto_in_percent} = 100.0 * $self->{percent_skonto};
1880
1881   map { $amounts{$_} = $self->parse_amount($myconfig, $amounts{$_}) } keys %amounts;
1882
1883   $amounts{skonto_amount}      = $amounts{invtotal} * $self->{percent_skonto};
1884   $amounts{invtotal_wo_skonto} = $amounts{invtotal} * (1 - $self->{percent_skonto});
1885   $amounts{total_wo_skonto}    = $amounts{total}    * (1 - $self->{percent_skonto});
1886
1887   foreach (keys %amounts) {
1888     $amounts{$_}           = $self->round_amount($amounts{$_}, 2);
1889     $formatted_amounts{$_} = $self->format_amount($myconfig, $amounts{$_}, 2);
1890   }
1891
1892   if ($self->{"language_id"}) {
1893     $query =
1894       qq|SELECT t.description_long, l.output_numberformat, l.output_dateformat, l.output_longdates | .
1895       qq|FROM translation_payment_terms t | .
1896       qq|LEFT JOIN language l ON t.language_id = l.id | .
1897       qq|WHERE (t.language_id = ?) AND (t.payment_terms_id = ?)|;
1898     my ($description_long, $output_numberformat, $output_dateformat,
1899       $output_longdates) =
1900       selectrow_query($self, $dbh, $query,
1901                       $self->{"language_id"}, $self->{"payment_id"});
1902
1903     $self->{payment_terms} = $description_long if ($description_long);
1904
1905     if ($output_dateformat) {
1906       foreach my $key (qw(netto_date skonto_date)) {
1907         $self->{$key} =
1908           $main::locale->reformat_date($myconfig, $self->{$key},
1909                                        $output_dateformat,
1910                                        $output_longdates);
1911       }
1912     }
1913
1914     if ($output_numberformat &&
1915         ($output_numberformat ne $myconfig->{"numberformat"})) {
1916       my $saved_numberformat = $myconfig->{"numberformat"};
1917       $myconfig->{"numberformat"} = $output_numberformat;
1918       map { $formatted_amounts{$_} = $self->format_amount($myconfig, $amounts{$_}) } keys %amounts;
1919       $myconfig->{"numberformat"} = $saved_numberformat;
1920     }
1921   }
1922
1923   $self->{payment_terms} =~ s/<%netto_date%>/$self->{netto_date}/g;
1924   $self->{payment_terms} =~ s/<%skonto_date%>/$self->{skonto_date}/g;
1925   $self->{payment_terms} =~ s/<%currency%>/$self->{currency}/g;
1926   $self->{payment_terms} =~ s/<%terms_netto%>/$self->{terms_netto}/g;
1927   $self->{payment_terms} =~ s/<%account_number%>/$self->{account_number}/g;
1928   $self->{payment_terms} =~ s/<%bank%>/$self->{bank}/g;
1929   $self->{payment_terms} =~ s/<%bank_code%>/$self->{bank_code}/g;
1930
1931   map { $self->{payment_terms} =~ s/<%${_}%>/$formatted_amounts{$_}/g; } keys %formatted_amounts;
1932
1933   $self->{skonto_in_percent} = $formatted_amounts{skonto_in_percent};
1934
1935   $main::lxdebug->leave_sub();
1936
1937 }
1938
1939 sub get_template_language {
1940   $main::lxdebug->enter_sub();
1941
1942   my ($self, $myconfig) = @_;
1943
1944   my $template_code = "";
1945
1946   if ($self->{language_id}) {
1947     my $dbh = $self->get_standard_dbh($myconfig);
1948     my $query = qq|SELECT template_code FROM language WHERE id = ?|;
1949     ($template_code) = selectrow_query($self, $dbh, $query, $self->{language_id});
1950   }
1951
1952   $main::lxdebug->leave_sub();
1953
1954   return $template_code;
1955 }
1956
1957 sub get_printer_code {
1958   $main::lxdebug->enter_sub();
1959
1960   my ($self, $myconfig) = @_;
1961
1962   my $template_code = "";
1963
1964   if ($self->{printer_id}) {
1965     my $dbh = $self->get_standard_dbh($myconfig);
1966     my $query = qq|SELECT template_code, printer_command FROM printers WHERE id = ?|;
1967     ($template_code, $self->{printer_command}) = selectrow_query($self, $dbh, $query, $self->{printer_id});
1968   }
1969
1970   $main::lxdebug->leave_sub();
1971
1972   return $template_code;
1973 }
1974
1975 sub get_shipto {
1976   $main::lxdebug->enter_sub();
1977
1978   my ($self, $myconfig) = @_;
1979
1980   my $template_code = "";
1981
1982   if ($self->{shipto_id}) {
1983     my $dbh = $self->get_standard_dbh($myconfig);
1984     my $query = qq|SELECT * FROM shipto WHERE shipto_id = ?|;
1985     my $ref = selectfirst_hashref_query($self, $dbh, $query, $self->{shipto_id});
1986     map({ $self->{$_} = $ref->{$_} } keys(%$ref));
1987   }
1988
1989   $main::lxdebug->leave_sub();
1990 }
1991
1992 sub add_shipto {
1993   $main::lxdebug->enter_sub();
1994
1995   my ($self, $dbh, $id, $module) = @_;
1996
1997   my $shipto;
1998   my @values;
1999
2000   foreach my $item (qw(name department_1 department_2 street zipcode city country
2001                        contact phone fax email)) {
2002     if ($self->{"shipto$item"}) {
2003       $shipto = 1 if ($self->{$item} ne $self->{"shipto$item"});
2004     }
2005     push(@values, $self->{"shipto${item}"});
2006   }
2007
2008   if ($shipto) {
2009     if ($self->{shipto_id}) {
2010       my $query = qq|UPDATE shipto set
2011                        shiptoname = ?,
2012                        shiptodepartment_1 = ?,
2013                        shiptodepartment_2 = ?,
2014                        shiptostreet = ?,
2015                        shiptozipcode = ?,
2016                        shiptocity = ?,
2017                        shiptocountry = ?,
2018                        shiptocontact = ?,
2019                        shiptophone = ?,
2020                        shiptofax = ?,
2021                        shiptoemail = ?
2022                      WHERE shipto_id = ?|;
2023       do_query($self, $dbh, $query, @values, $self->{shipto_id});
2024     } else {
2025       my $query = qq|SELECT * FROM shipto
2026                      WHERE shiptoname = ? AND
2027                        shiptodepartment_1 = ? AND
2028                        shiptodepartment_2 = ? AND
2029                        shiptostreet = ? AND
2030                        shiptozipcode = ? AND
2031                        shiptocity = ? AND
2032                        shiptocountry = ? AND
2033                        shiptocontact = ? AND
2034                        shiptophone = ? AND
2035                        shiptofax = ? AND
2036                        shiptoemail = ? AND
2037                        module = ? AND
2038                        trans_id = ?|;
2039       my $insert_check = selectfirst_hashref_query($self, $dbh, $query, @values, $module, $id);
2040       if(!$insert_check){
2041         $query =
2042           qq|INSERT INTO shipto (trans_id, shiptoname, shiptodepartment_1, shiptodepartment_2,
2043                                  shiptostreet, shiptozipcode, shiptocity, shiptocountry,
2044                                  shiptocontact, shiptophone, shiptofax, shiptoemail, module)
2045              VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)|;
2046         do_query($self, $dbh, $query, $id, @values, $module);
2047       }
2048     }
2049   }
2050
2051   $main::lxdebug->leave_sub();
2052 }
2053
2054 sub get_employee {
2055   $main::lxdebug->enter_sub();
2056
2057   my ($self, $dbh) = @_;
2058
2059   $dbh ||= $self->get_standard_dbh(\%main::myconfig);
2060
2061   my $query = qq|SELECT id, name FROM employee WHERE login = ?|;
2062   ($self->{"employee_id"}, $self->{"employee"}) = selectrow_query($self, $dbh, $query, $self->{login});
2063   $self->{"employee_id"} *= 1;
2064
2065   $main::lxdebug->leave_sub();
2066 }
2067
2068 sub get_employee_data {
2069   $main::lxdebug->enter_sub();
2070
2071   my $self     = shift;
2072   my %params   = @_;
2073
2074   Common::check_params(\%params, qw(prefix));
2075   Common::check_params_x(\%params, qw(id));
2076
2077   if (!$params{id}) {
2078     $main::lxdebug->leave_sub();
2079     return;
2080   }
2081
2082   my $myconfig = \%main::myconfig;
2083   my $dbh      = $params{dbh} || $self->get_standard_dbh($myconfig);
2084
2085   my ($login)  = selectrow_query($self, $dbh, qq|SELECT login FROM employee WHERE id = ?|, conv_i($params{id}));
2086
2087   if ($login) {
2088     my $user = User->new($login);
2089     map { $self->{$params{prefix} . "_${_}"} = $user->{$_}; } qw(address businessnumber co_ustid company duns email fax name signature taxnumber tel);
2090
2091     $self->{$params{prefix} . '_login'}   = $login;
2092     $self->{$params{prefix} . '_name'}  ||= $login;
2093   }
2094
2095   $main::lxdebug->leave_sub();
2096 }
2097
2098 sub get_duedate {
2099   $main::lxdebug->enter_sub();
2100
2101   my ($self, $myconfig, $reference_date) = @_;
2102
2103   $reference_date = $reference_date ? conv_dateq($reference_date) . '::DATE' : 'current_date';
2104
2105   my $dbh         = $self->get_standard_dbh($myconfig);
2106   my $query       = qq|SELECT ${reference_date} + terms_netto FROM payment_terms WHERE id = ?|;
2107   my ($duedate)   = selectrow_query($self, $dbh, $query, $self->{payment_id});
2108
2109   $main::lxdebug->leave_sub();
2110
2111   return $duedate;
2112 }
2113
2114 sub _get_contacts {
2115   $main::lxdebug->enter_sub();
2116
2117   my ($self, $dbh, $id, $key) = @_;
2118
2119   $key = "all_contacts" unless ($key);
2120
2121   if (!$id) {
2122     $self->{$key} = [];
2123     $main::lxdebug->leave_sub();
2124     return;
2125   }
2126
2127   my $query =
2128     qq|SELECT cp_id, cp_cv_id, cp_name, cp_givenname, cp_abteilung | .
2129     qq|FROM contacts | .
2130     qq|WHERE cp_cv_id = ? | .
2131     qq|ORDER BY lower(cp_name)|;
2132
2133   $self->{$key} = selectall_hashref_query($self, $dbh, $query, $id);
2134
2135   $main::lxdebug->leave_sub();
2136 }
2137
2138 sub _get_projects {
2139   $main::lxdebug->enter_sub();
2140
2141   my ($self, $dbh, $key) = @_;
2142
2143   my ($all, $old_id, $where, @values);
2144
2145   if (ref($key) eq "HASH") {
2146     my $params = $key;
2147
2148     $key = "ALL_PROJECTS";
2149
2150     foreach my $p (keys(%{$params})) {
2151       if ($p eq "all") {
2152         $all = $params->{$p};
2153       } elsif ($p eq "old_id") {
2154         $old_id = $params->{$p};
2155       } elsif ($p eq "key") {
2156         $key = $params->{$p};
2157       }
2158     }
2159   }
2160
2161   if (!$all) {
2162     $where = "WHERE active ";
2163     if ($old_id) {
2164       if (ref($old_id) eq "ARRAY") {
2165         my @ids = grep({ $_ } @{$old_id});
2166         if (@ids) {
2167           $where .= " OR id IN (" . join(",", map({ "?" } @ids)) . ") ";
2168           push(@values, @ids);
2169         }
2170       } else {
2171         $where .= " OR (id = ?) ";
2172         push(@values, $old_id);
2173       }
2174     }
2175   }
2176
2177   my $query =
2178     qq|SELECT id, projectnumber, description, active | .
2179     qq|FROM project | .
2180     $where .
2181     qq|ORDER BY lower(projectnumber)|;
2182
2183   $self->{$key} = selectall_hashref_query($self, $dbh, $query, @values);
2184
2185   $main::lxdebug->leave_sub();
2186 }
2187
2188 sub _get_shipto {
2189   $main::lxdebug->enter_sub();
2190
2191   my ($self, $dbh, $vc_id, $key) = @_;
2192
2193   $key = "all_shipto" unless ($key);
2194
2195   if ($vc_id) {
2196     # get shipping addresses
2197     my $query = qq|SELECT * FROM shipto WHERE trans_id = ?|;
2198
2199     $self->{$key} = selectall_hashref_query($self, $dbh, $query, $vc_id);
2200
2201   } else {
2202     $self->{$key} = [];
2203   }
2204
2205   $main::lxdebug->leave_sub();
2206 }
2207
2208 sub _get_printers {
2209   $main::lxdebug->enter_sub();
2210
2211   my ($self, $dbh, $key) = @_;
2212
2213   $key = "all_printers" unless ($key);
2214
2215   my $query = qq|SELECT id, printer_description, printer_command, template_code FROM printers|;
2216
2217   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2218
2219   $main::lxdebug->leave_sub();
2220 }
2221
2222 sub _get_charts {
2223   $main::lxdebug->enter_sub();
2224
2225   my ($self, $dbh, $params) = @_;
2226   my ($key);
2227
2228   $key = $params->{key};
2229   $key = "all_charts" unless ($key);
2230
2231   my $transdate = quote_db_date($params->{transdate});
2232
2233   my $query =
2234     qq|SELECT c.id, c.accno, c.description, c.link, c.charttype, tk.taxkey_id, tk.tax_id | .
2235     qq|FROM chart c | .
2236     qq|LEFT JOIN taxkeys tk ON | .
2237     qq|(tk.id = (SELECT id FROM taxkeys | .
2238     qq|          WHERE taxkeys.chart_id = c.id AND startdate <= $transdate | .
2239     qq|          ORDER BY startdate DESC LIMIT 1)) | .
2240     qq|ORDER BY c.accno|;
2241
2242   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2243
2244   $main::lxdebug->leave_sub();
2245 }
2246
2247 sub _get_taxcharts {
2248   $main::lxdebug->enter_sub();
2249
2250   my ($self, $dbh, $params) = @_;
2251
2252   my $key = "all_taxcharts";
2253   my @where;
2254
2255   if (ref $params eq 'HASH') {
2256     $key = $params->{key} if ($params->{key});
2257     if ($params->{module} eq 'AR') {
2258       push @where, 'taxkey NOT IN (8, 9, 18, 19)';
2259
2260     } elsif ($params->{module} eq 'AP') {
2261       push @where, 'taxkey NOT IN (1, 2, 3, 12, 13)';
2262     }
2263
2264   } elsif ($params) {
2265     $key = $params;
2266   }
2267
2268   my $where = ' WHERE ' . join(' AND ', map { "($_)" } @where) if (@where);
2269
2270   my $query = qq|SELECT * FROM tax $where ORDER BY taxkey|;
2271
2272   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2273
2274   $main::lxdebug->leave_sub();
2275 }
2276
2277 sub _get_taxzones {
2278   $main::lxdebug->enter_sub();
2279
2280   my ($self, $dbh, $key) = @_;
2281
2282   $key = "all_taxzones" unless ($key);
2283
2284   my $query = qq|SELECT * FROM tax_zones ORDER BY id|;
2285
2286   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2287
2288   $main::lxdebug->leave_sub();
2289 }
2290
2291 sub _get_employees {
2292   $main::lxdebug->enter_sub();
2293
2294   my ($self, $dbh, $default_key, $key) = @_;
2295
2296   $key = $default_key unless ($key);
2297   $self->{$key} = selectall_hashref_query($self, $dbh, qq|SELECT * FROM employee ORDER BY lower(name)|);
2298
2299   $main::lxdebug->leave_sub();
2300 }
2301
2302 sub _get_business_types {
2303   $main::lxdebug->enter_sub();
2304
2305   my ($self, $dbh, $key) = @_;
2306
2307   my $options       = ref $key eq 'HASH' ? $key : { key => $key };
2308   $options->{key} ||= "all_business_types";
2309   my $where         = '';
2310
2311   if (exists $options->{salesman}) {
2312     $where = 'WHERE ' . ($options->{salesman} ? '' : 'NOT ') . 'COALESCE(salesman)';
2313   }
2314
2315   $self->{ $options->{key} } = selectall_hashref_query($self, $dbh, qq|SELECT * FROM business $where ORDER BY lower(description)|);
2316
2317   $main::lxdebug->leave_sub();
2318 }
2319
2320 sub _get_languages {
2321   $main::lxdebug->enter_sub();
2322
2323   my ($self, $dbh, $key) = @_;
2324
2325   $key = "all_languages" unless ($key);
2326
2327   my $query = qq|SELECT * FROM language ORDER BY id|;
2328
2329   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2330
2331   $main::lxdebug->leave_sub();
2332 }
2333
2334 sub _get_dunning_configs {
2335   $main::lxdebug->enter_sub();
2336
2337   my ($self, $dbh, $key) = @_;
2338
2339   $key = "all_dunning_configs" unless ($key);
2340
2341   my $query = qq|SELECT * FROM dunning_config ORDER BY dunning_level|;
2342
2343   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2344
2345   $main::lxdebug->leave_sub();
2346 }
2347
2348 sub _get_currencies {
2349 $main::lxdebug->enter_sub();
2350
2351   my ($self, $dbh, $key) = @_;
2352
2353   $key = "all_currencies" unless ($key);
2354
2355   my $query = qq|SELECT curr AS currency FROM defaults|;
2356
2357   $self->{$key} = [split(/\:/ , selectfirst_hashref_query($self, $dbh, $query)->{currency})];
2358
2359   $main::lxdebug->leave_sub();
2360 }
2361
2362 sub _get_payments {
2363 $main::lxdebug->enter_sub();
2364
2365   my ($self, $dbh, $key) = @_;
2366
2367   $key = "all_payments" unless ($key);
2368
2369   my $query = qq|SELECT * FROM payment_terms ORDER BY id|;
2370
2371   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2372
2373   $main::lxdebug->leave_sub();
2374 }
2375
2376 sub _get_customers {
2377   $main::lxdebug->enter_sub();
2378
2379   my ($self, $dbh, $key) = @_;
2380
2381   my $options        = ref $key eq 'HASH' ? $key : { key => $key };
2382   $options->{key}  ||= "all_customers";
2383   my $limit_clause   = "LIMIT $options->{limit}" if $options->{limit};
2384
2385   my @where;
2386   push @where, qq|business_id IN (SELECT id FROM business WHERE salesman)| if  $options->{business_is_salesman};
2387   push @where, qq|NOT obsolete|                                            if !$options->{with_obsolete};
2388   my $where_str = @where ? "WHERE " . join(" AND ", map { "($_)" } @where) : '';
2389
2390   my $query = qq|SELECT * FROM customer $where_str ORDER BY name $limit_clause|;
2391   $self->{ $options->{key} } = selectall_hashref_query($self, $dbh, $query);
2392
2393   $main::lxdebug->leave_sub();
2394 }
2395
2396 sub _get_vendors {
2397   $main::lxdebug->enter_sub();
2398
2399   my ($self, $dbh, $key) = @_;
2400
2401   $key = "all_vendors" unless ($key);
2402
2403   my $query = qq|SELECT * FROM vendor WHERE NOT obsolete ORDER BY name|;
2404
2405   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2406
2407   $main::lxdebug->leave_sub();
2408 }
2409
2410 sub _get_departments {
2411   $main::lxdebug->enter_sub();
2412
2413   my ($self, $dbh, $key) = @_;
2414
2415   $key = "all_departments" unless ($key);
2416
2417   my $query = qq|SELECT * FROM department ORDER BY description|;
2418
2419   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2420
2421   $main::lxdebug->leave_sub();
2422 }
2423
2424 sub _get_warehouses {
2425   $main::lxdebug->enter_sub();
2426
2427   my ($self, $dbh, $param) = @_;
2428
2429   my ($key, $bins_key);
2430
2431   if ('' eq ref $param) {
2432     $key = $param;
2433
2434   } else {
2435     $key      = $param->{key};
2436     $bins_key = $param->{bins};
2437   }
2438
2439   my $query = qq|SELECT w.* FROM warehouse w
2440                  WHERE (NOT w.invalid) AND
2441                    ((SELECT COUNT(b.*) FROM bin b WHERE b.warehouse_id = w.id) > 0)
2442                  ORDER BY w.sortkey|;
2443
2444   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2445
2446   if ($bins_key) {
2447     $query = qq|SELECT id, description FROM bin WHERE warehouse_id = ?|;
2448     my $sth = prepare_query($self, $dbh, $query);
2449
2450     foreach my $warehouse (@{ $self->{$key} }) {
2451       do_statement($self, $sth, $query, $warehouse->{id});
2452       $warehouse->{$bins_key} = [];
2453
2454       while (my $ref = $sth->fetchrow_hashref()) {
2455         push @{ $warehouse->{$bins_key} }, $ref;
2456       }
2457     }
2458     $sth->finish();
2459   }
2460
2461   $main::lxdebug->leave_sub();
2462 }
2463
2464 sub _get_simple {
2465   $main::lxdebug->enter_sub();
2466
2467   my ($self, $dbh, $table, $key, $sortkey) = @_;
2468
2469   my $query  = qq|SELECT * FROM $table|;
2470   $query    .= qq| ORDER BY $sortkey| if ($sortkey);
2471
2472   $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2473
2474   $main::lxdebug->leave_sub();
2475 }
2476
2477 #sub _get_groups {
2478 #  $main::lxdebug->enter_sub();
2479 #
2480 #  my ($self, $dbh, $key) = @_;
2481 #
2482 #  $key ||= "all_groups";
2483 #
2484 #  my $groups = $main::auth->read_groups();
2485 #
2486 #  $self->{$key} = selectall_hashref_query($self, $dbh, $query);
2487 #
2488 #  $main::lxdebug->leave_sub();
2489 #}
2490
2491 sub get_lists {
2492   $main::lxdebug->enter_sub();
2493
2494   my $self = shift;
2495   my %params = @_;
2496
2497   my $dbh = $self->get_standard_dbh(\%main::myconfig);
2498   my ($sth, $query, $ref);
2499
2500   my $vc = $self->{"vc"} eq "customer" ? "customer" : "vendor";
2501   my $vc_id = $self->{"${vc}_id"};
2502
2503   if ($params{"contacts"}) {
2504     $self->_get_contacts($dbh, $vc_id, $params{"contacts"});
2505   }
2506
2507   if ($params{"shipto"}) {
2508     $self->_get_shipto($dbh, $vc_id, $params{"shipto"});
2509   }
2510
2511   if ($params{"projects"} || $params{"all_projects"}) {
2512     $self->_get_projects($dbh, $params{"all_projects"} ?
2513                          $params{"all_projects"} : $params{"projects"},
2514                          $params{"all_projects"} ? 1 : 0);
2515   }
2516
2517   if ($params{"printers"}) {
2518     $self->_get_printers($dbh, $params{"printers"});
2519   }
2520
2521   if ($params{"languages"}) {
2522     $self->_get_languages($dbh, $params{"languages"});
2523   }
2524
2525   if ($params{"charts"}) {
2526     $self->_get_charts($dbh, $params{"charts"});
2527   }
2528
2529   if ($params{"taxcharts"}) {
2530     $self->_get_taxcharts($dbh, $params{"taxcharts"});
2531   }
2532
2533   if ($params{"taxzones"}) {
2534     $self->_get_taxzones($dbh, $params{"taxzones"});
2535   }
2536
2537   if ($params{"employees"}) {
2538     $self->_get_employees($dbh, "all_employees", $params{"employees"});
2539   }
2540
2541   if ($params{"salesmen"}) {
2542     $self->_get_employees($dbh, "all_salesmen", $params{"salesmen"});
2543   }
2544
2545   if ($params{"business_types"}) {
2546     $self->_get_business_types($dbh, $params{"business_types"});
2547   }
2548
2549   if ($params{"dunning_configs"}) {
2550     $self->_get_dunning_configs($dbh, $params{"dunning_configs"});
2551   }
2552
2553   if($params{"currencies"}) {
2554     $self->_get_currencies($dbh, $params{"currencies"});
2555   }
2556
2557   if($params{"customers"}) {
2558     $self->_get_customers($dbh, $params{"customers"});
2559   }
2560
2561   if($params{"vendors"}) {
2562     if (ref $params{"vendors"} eq 'HASH') {
2563       $self->_get_vendors($dbh, $params{"vendors"}{key}, $params{"vendors"}{limit});
2564     } else {
2565       $self->_get_vendors($dbh, $params{"vendors"});
2566     }
2567   }
2568
2569   if($params{"payments"}) {
2570     $self->_get_payments($dbh, $params{"payments"});
2571   }
2572
2573   if($params{"departments"}) {
2574     $self->_get_departments($dbh, $params{"departments"});
2575   }
2576
2577   if ($params{price_factors}) {
2578     $self->_get_simple($dbh, 'price_factors', $params{price_factors}, 'sortkey');
2579   }
2580
2581   if ($params{warehouses}) {
2582     $self->_get_warehouses($dbh, $params{warehouses});
2583   }
2584
2585 #  if ($params{groups}) {
2586 #    $self->_get_groups($dbh, $params{groups});
2587 #  }
2588
2589   if ($params{partsgroup}) {
2590     $self->get_partsgroup(\%main::myconfig, { all => 1, target => $params{partsgroup} });
2591   }
2592
2593   $main::lxdebug->leave_sub();
2594 }
2595
2596 # this sub gets the id and name from $table
2597 sub get_name {
2598   $main::lxdebug->enter_sub();
2599
2600   my ($self, $myconfig, $table) = @_;
2601
2602   # connect to database
2603   my $dbh = $self->get_standard_dbh($myconfig);
2604
2605   $table = $table eq "customer" ? "customer" : "vendor";
2606   my $arap = $self->{arap} eq "ar" ? "ar" : "ap";
2607
2608   my ($query, @values);
2609
2610   if (!$self->{openinvoices}) {
2611     my $where;
2612     if ($self->{customernumber} ne "") {
2613       $where = qq|(vc.customernumber ILIKE ?)|;
2614       push(@values, '%' . $self->{customernumber} . '%');
2615     } else {
2616       $where = qq|(vc.name ILIKE ?)|;
2617       push(@values, '%' . $self->{$table} . '%');
2618     }
2619
2620     $query =
2621       qq~SELECT vc.id, vc.name,
2622            vc.street || ' ' || vc.zipcode || ' ' || vc.city || ' ' || vc.country AS address
2623          FROM $table vc
2624          WHERE $where AND (NOT vc.obsolete)
2625          ORDER BY vc.name~;
2626   } else {
2627     $query =
2628       qq~SELECT DISTINCT vc.id, vc.name,
2629            vc.street || ' ' || vc.zipcode || ' ' || vc.city || ' ' || vc.country AS address
2630          FROM $arap a
2631          JOIN $table vc ON (a.${table}_id = vc.id)
2632          WHERE NOT (a.amount = a.paid) AND (vc.name ILIKE ?)
2633          ORDER BY vc.name~;
2634     push(@values, '%' . $self->{$table} . '%');
2635   }
2636
2637   $self->{name_list} = selectall_hashref_query($self, $dbh, $query, @values);
2638
2639   $main::lxdebug->leave_sub();
2640
2641   return scalar(@{ $self->{name_list} });
2642 }
2643
2644 # the selection sub is used in the AR, AP, IS, IR and OE module
2645 #
2646 sub all_vc {
2647   $main::lxdebug->enter_sub();
2648
2649   my ($self, $myconfig, $table, $module) = @_;
2650
2651   my $ref;
2652   my $dbh = $self->get_standard_dbh;
2653
2654   $table = $table eq "customer" ? "customer" : "vendor";
2655
2656   my $query = qq|SELECT count(*) FROM $table|;
2657   my ($count) = selectrow_query($self, $dbh, $query);
2658
2659   # build selection list
2660   if ($count <= $myconfig->{vclimit}) {
2661     $query = qq|SELECT id, name, salesman_id
2662                 FROM $table WHERE NOT obsolete
2663                 ORDER BY name|;
2664     $self->{"all_$table"} = selectall_hashref_query($self, $dbh, $query);
2665   }
2666
2667   # get self
2668   $self->get_employee($dbh);
2669
2670   # setup sales contacts
2671   $query = qq|SELECT e.id, e.name
2672               FROM employee e
2673               WHERE (e.sales = '1') AND (NOT e.id = ?)|;
2674   $self->{all_employees} = selectall_hashref_query($self, $dbh, $query, $self->{employee_id});
2675
2676   # this is for self
2677   push(@{ $self->{all_employees} },
2678        { id   => $self->{employee_id},
2679          name => $self->{employee} });
2680
2681   # sort the whole thing
2682   @{ $self->{all_employees} } =
2683     sort { $a->{name} cmp $b->{name} } @{ $self->{all_employees} };
2684
2685   if ($module eq 'AR') {
2686
2687     # prepare query for departments
2688     $query = qq|SELECT id, description
2689                 FROM department
2690                 WHERE role = 'P'
2691                 ORDER BY description|;
2692
2693   } else {
2694     $query = qq|SELECT id, description
2695                 FROM department
2696                 ORDER BY description|;
2697   }
2698
2699   $self->{all_departments} = selectall_hashref_query($self, $dbh, $query);
2700
2701   # get languages
2702   $query = qq|SELECT id, description
2703               FROM language
2704               ORDER BY id|;
2705
2706   $self->{languages} = selectall_hashref_query($self, $dbh, $query);
2707
2708   # get printer
2709   $query = qq|SELECT printer_description, id
2710               FROM printers
2711               ORDER BY printer_description|;
2712
2713   $self->{printers} = selectall_hashref_query($self, $dbh, $query);
2714
2715   # get payment terms
2716   $query = qq|SELECT id, description
2717               FROM payment_terms
2718               ORDER BY sortkey|;
2719
2720   $self->{payment_terms} = selectall_hashref_query($self, $dbh, $query);
2721
2722   $main::lxdebug->leave_sub();
2723 }
2724
2725 sub language_payment {
2726   $main::lxdebug->enter_sub();
2727
2728   my ($self, $myconfig) = @_;
2729
2730   my $dbh = $self->get_standard_dbh($myconfig);
2731   # get languages
2732   my $query = qq|SELECT id, description
2733                  FROM language
2734                  ORDER BY id|;
2735
2736   $self->{languages} = selectall_hashref_query($self, $dbh, $query);
2737
2738   # get printer
2739   $query = qq|SELECT printer_description, id
2740               FROM printers
2741               ORDER BY printer_description|;
2742
2743   $self->{printers} = selectall_hashref_query($self, $dbh, $query);
2744
2745   # get payment terms
2746   $query = qq|SELECT id, description
2747               FROM payment_terms
2748               ORDER BY sortkey|;
2749
2750   $self->{payment_terms} = selectall_hashref_query($self, $dbh, $query);
2751
2752   # get buchungsgruppen
2753   $query = qq|SELECT id, description
2754               FROM buchungsgruppen|;
2755
2756   $self->{BUCHUNGSGRUPPEN} = selectall_hashref_query($self, $dbh, $query);
2757
2758   $main::lxdebug->leave_sub();
2759 }
2760
2761 # this is only used for reports
2762 sub all_departments {
2763   $main::lxdebug->enter_sub();
2764
2765   my ($self, $myconfig, $table) = @_;
2766
2767   my $dbh = $self->get_standard_dbh($myconfig);
2768   my $where;
2769
2770   if ($table eq 'customer') {
2771     $where = "WHERE role = 'P' ";
2772   }
2773
2774   my $query = qq|SELECT id, description
2775                  FROM department
2776                  $where
2777                  ORDER BY description|;
2778   $self->{all_departments} = selectall_hashref_query($self, $dbh, $query);
2779
2780   delete($self->{all_departments}) unless (@{ $self->{all_departments} || [] });
2781
2782   $main::lxdebug->leave_sub();
2783 }
2784
2785 sub create_links {
2786   $main::lxdebug->enter_sub();
2787
2788   my ($self, $module, $myconfig, $table, $provided_dbh) = @_;
2789
2790   my ($fld, $arap);
2791   if ($table eq "customer") {
2792     $fld = "buy";
2793     $arap = "ar";
2794   } else {
2795     $table = "vendor";
2796     $fld = "sell";
2797     $arap = "ap";
2798   }
2799
2800   $self->all_vc($myconfig, $table, $module);
2801
2802   # get last customers or vendors
2803   my ($query, $sth, $ref);
2804
2805   my $dbh = $provided_dbh ? $provided_dbh : $self->get_standard_dbh($myconfig);
2806   my %xkeyref = ();
2807
2808   if (!$self->{id}) {
2809
2810     my $transdate = "current_date";
2811     if ($self->{transdate}) {
2812       $transdate = $dbh->quote($self->{transdate});
2813     }
2814
2815     # now get the account numbers
2816     $query = qq|SELECT c.accno, c.description, c.link, c.taxkey_id, tk.tax_id
2817                 FROM chart c, taxkeys tk
2818                 WHERE (c.link LIKE ?) AND (c.id = tk.chart_id) AND tk.id =
2819                   (SELECT id FROM taxkeys WHERE (taxkeys.chart_id = c.id) AND (startdate <= $transdate) ORDER BY startdate DESC LIMIT 1)
2820                 ORDER BY c.accno|;
2821
2822     $sth = $dbh->prepare($query);
2823
2824     do_statement($self, $sth, $query, '%' . $module . '%');
2825
2826     $self->{accounts} = "";
2827     while ($ref = $sth->fetchrow_hashref("NAME_lc")) {
2828
2829       foreach my $key (split(/:/, $ref->{link})) {
2830         if ($key =~ /\Q$module\E/) {
2831
2832           # cross reference for keys
2833           $xkeyref{ $ref->{accno} } = $key;
2834
2835           push @{ $self->{"${module}_links"}{$key} },
2836             { accno       => $ref->{accno},
2837               description => $ref->{description},
2838               taxkey      => $ref->{taxkey_id},
2839               tax_id      => $ref->{tax_id} };
2840
2841           $self->{accounts} .= "$ref->{accno} " unless $key =~ /tax/;
2842         }
2843       }
2844     }
2845   }
2846
2847   # get taxkeys and description
2848   $query = qq|SELECT id, taxkey, taxdescription FROM tax|;
2849   $self->{TAXKEY} = selectall_hashref_query($self, $dbh, $query);
2850
2851   if (($module eq "AP") || ($module eq "AR")) {
2852     # get tax rates and description
2853     $query = qq|SELECT * FROM tax|;
2854     $self->{TAX} = selectall_hashref_query($self, $dbh, $query);
2855   }
2856
2857   if ($self->{id}) {
2858     $query =
2859       qq|SELECT
2860            a.cp_id, a.invnumber, a.transdate, a.${table}_id, a.datepaid,
2861            a.duedate, a.ordnumber, a.taxincluded, a.curr AS currency, a.notes,
2862            a.intnotes, a.department_id, a.amount AS oldinvtotal,
2863            a.paid AS oldtotalpaid, a.employee_id, a.gldate, a.type,
2864            c.name AS $table,
2865            d.description AS department,
2866            e.name AS employee
2867          FROM $arap a
2868          JOIN $table c ON (a.${table}_id = c.id)
2869          LEFT JOIN employee e ON (e.id = a.employee_id)
2870          LEFT JOIN department d ON (d.id = a.department_id)
2871          WHERE a.id = ?|;
2872     $ref = selectfirst_hashref_query($self, $dbh, $query, $self->{id});
2873
2874     foreach my $key (keys %$ref) {
2875       $self->{$key} = $ref->{$key};
2876     }
2877
2878     my $transdate = "current_date";
2879     if ($self->{transdate}) {
2880       $transdate = $dbh->quote($self->{transdate});
2881     }
2882
2883     # now get the account numbers
2884     $query = qq|SELECT c.accno, c.description, c.link, c.taxkey_id, tk.tax_id
2885                 FROM chart c
2886                 LEFT JOIN taxkeys tk ON (tk.chart_id = c.id)
2887                 WHERE c.link LIKE ?
2888                   AND (tk.id = (SELECT id FROM taxkeys WHERE taxkeys.chart_id = c.id AND startdate <= $transdate ORDER BY startdate DESC LIMIT 1)
2889                     OR c.link LIKE '%_tax%' OR c.taxkey_id IS NULL)
2890                 ORDER BY c.accno|;
2891
2892     $sth = $dbh->prepare($query);
2893     do_statement($self, $sth, $query, "%$module%");
2894
2895     $self->{accounts} = "";
2896     while ($ref = $sth->fetchrow_hashref("NAME_lc")) {
2897
2898       foreach my $key (split(/:/, $ref->{link})) {
2899         if ($key =~ /\Q$module\E/) {
2900
2901           # cross reference for keys
2902           $xkeyref{ $ref->{accno} } = $key;
2903
2904           push @{ $self->{"${module}_links"}{$key} },
2905             { accno       => $ref->{accno},
2906               description => $ref->{description},
2907               taxkey      => $ref->{taxkey_id},
2908               tax_id      => $ref->{tax_id} };
2909
2910           $self->{accounts} .= "$ref->{accno} " unless $key =~ /tax/;
2911         }
2912       }
2913     }
2914
2915
2916     # get amounts from individual entries
2917     $query =
2918       qq|SELECT
2919            c.accno, c.description,
2920            a.source, a.amount, a.memo, a.transdate, a.cleared, a.project_id, a.taxkey,
2921            p.projectnumber,
2922            t.rate, t.id
2923          FROM acc_trans a
2924          LEFT JOIN chart c ON (c.id = a.chart_id)
2925          LEFT JOIN project p ON (p.id = a.project_id)
2926          LEFT JOIN tax t ON (t.id= (SELECT tk.tax_id FROM taxkeys tk
2927                                     WHERE (tk.taxkey_id=a.taxkey) AND
2928                                       ((CASE WHEN a.chart_id IN (SELECT chart_id FROM taxkeys WHERE taxkey_id = a.taxkey)
2929                                         THEN tk.chart_id = a.chart_id
2930                                         ELSE 1 = 1
2931                                         END)
2932                                        OR (c.link='%tax%')) AND
2933                                       (startdate <= a.transdate) ORDER BY startdate DESC LIMIT 1))
2934          WHERE a.trans_id = ?
2935          AND a.fx_transaction = '0'
2936          ORDER BY a.acc_trans_id, a.transdate|;
2937     $sth = $dbh->prepare($query);
2938     do_statement($self, $sth, $query, $self->{id});
2939
2940     # get exchangerate for currency
2941     $self->{exchangerate} =
2942       $self->get_exchangerate($dbh, $self->{currency}, $self->{transdate}, $fld);
2943     my $index = 0;
2944
2945     # store amounts in {acc_trans}{$key} for multiple accounts
2946     while (my $ref = $sth->fetchrow_hashref("NAME_lc")) {
2947       $ref->{exchangerate} =
2948         $self->get_exchangerate($dbh, $self->{currency}, $ref->{transdate}, $fld);
2949       if (!($xkeyref{ $ref->{accno} } =~ /tax/)) {
2950         $index++;
2951       }
2952       if (($xkeyref{ $ref->{accno} } =~ /paid/) && ($self->{type} eq "credit_note")) {
2953         $ref->{amount} *= -1;
2954       }
2955       $ref->{index} = $index;
2956
2957       push @{ $self->{acc_trans}{ $xkeyref{ $ref->{accno} } } }, $ref;
2958     }
2959
2960     $sth->finish;
2961     $query =
2962       qq|SELECT
2963            d.curr AS currencies, d.closedto, d.revtrans,
2964            (SELECT c.accno FROM chart c WHERE d.fxgain_accno_id = c.id) AS fxgain_accno,
2965            (SELECT c.accno FROM chart c WHERE d.fxloss_accno_id = c.id) AS fxloss_accno
2966          FROM defaults d|;
2967     $ref = selectfirst_hashref_query($self, $dbh, $query);
2968     map { $self->{$_} = $ref->{$_} } keys %$ref;
2969
2970   } else {
2971
2972     # get date
2973     $query =
2974        qq|SELECT
2975             current_date AS transdate, d.curr AS currencies, d.closedto, d.revtrans,
2976             (SELECT c.accno FROM chart c WHERE d.fxgain_accno_id = c.id) AS fxgain_accno,
2977             (SELECT c.accno FROM chart c WHERE d.fxloss_accno_id = c.id) AS fxloss_accno
2978           FROM defaults d|;
2979     $ref = selectfirst_hashref_query($self, $dbh, $query);
2980     map { $self->{$_} = $ref->{$_} } keys %$ref;
2981
2982     if ($self->{"$self->{vc}_id"}) {
2983
2984       # only setup currency
2985       ($self->{currency}) = split(/:/, $self->{currencies});
2986
2987     } else {
2988
2989       $self->lastname_used($dbh, $myconfig, $table, $module);
2990
2991       # get exchangerate for currency
2992       $self->{exchangerate} =
2993         $self->get_exchangerate($dbh, $self->{currency}, $self->{transdate}, $fld);
2994
2995     }
2996
2997   }
2998
2999   $main::lxdebug->leave_sub();
3000 }
3001
3002 sub lastname_used {
3003   $main::lxdebug->enter_sub();
3004
3005   my ($self, $dbh, $myconfig, $table, $module) = @_;
3006
3007   my ($arap, $where);
3008
3009   $table         = $table eq "customer" ? "customer" : "vendor";
3010   my %column_map = ("a.curr"                  => "currency",
3011                     "a.${table}_id"           => "${table}_id",
3012                     "a.department_id"         => "department_id",
3013                     "d.description"           => "department",
3014                     "ct.name"                 => $table,
3015                     "current_date + ct.terms" => "duedate",
3016     );
3017
3018   if ($self->{type} =~ /delivery_order/) {
3019     $arap  = 'delivery_orders';
3020     delete $column_map{"a.curr"};
3021
3022   } elsif ($self->{type} =~ /_order/) {
3023     $arap  = 'oe';
3024     $where = "quotation = '0'";
3025
3026   } elsif ($self->{type} =~ /_quotation/) {
3027     $arap  = 'oe';
3028     $where = "quotation = '1'";
3029
3030   } elsif ($table eq 'customer') {
3031     $arap  = 'ar';
3032
3033   } else {
3034     $arap  = 'ap';
3035
3036   }
3037
3038   $where           = "($where) AND" if ($where);
3039   my $query        = qq|SELECT MAX(id) FROM $arap
3040                         WHERE $where ${table}_id > 0|;
3041   my ($trans_id)   = selectrow_query($self, $dbh, $query);
3042   $trans_id       *= 1;
3043
3044   my $column_spec  = join(', ', map { "${_} AS $column_map{$_}" } keys %column_map);
3045   $query           = qq|SELECT $column_spec
3046                         FROM $arap a
3047                         LEFT JOIN $table     ct ON (a.${table}_id = ct.id)
3048                         LEFT JOIN department d  ON (a.department_id = d.id)
3049                         WHERE a.id = ?|;
3050   my $ref          = selectfirst_hashref_query($self, $dbh, $query, $trans_id);
3051
3052   map { $self->{$_} = $ref->{$_} } values %column_map;
3053
3054   $main::lxdebug->leave_sub();
3055 }
3056
3057 sub current_date {
3058   $main::lxdebug->enter_sub();
3059
3060   my $self     = shift;
3061   my $myconfig = shift || \%::myconfig;
3062   my ($thisdate, $days) = @_;
3063
3064   my $dbh = $self->get_standard_dbh($myconfig);
3065   my $query;
3066
3067   $days *= 1;
3068   if ($thisdate) {
3069     my $dateformat = $myconfig->{dateformat};
3070     $dateformat .= "yy" if $myconfig->{dateformat} !~ /^y/;
3071     $thisdate = $dbh->quote($thisdate);
3072     $query = qq|SELECT to_date($thisdate, '$dateformat') + $days AS thisdate|;
3073   } else {
3074     $query = qq|SELECT current_date AS thisdate|;
3075   }
3076
3077   ($thisdate) = selectrow_query($self, $dbh, $query);
3078
3079   $main::lxdebug->leave_sub();
3080
3081   return $thisdate;
3082 }
3083
3084 sub like {
3085   $main::lxdebug->enter_sub();
3086
3087   my ($self, $string) = @_;
3088
3089   if ($string !~ /%/) {
3090     $string = "%$string%";
3091   }
3092
3093   $string =~ s/\'/\'\'/g;
3094
3095   $main::lxdebug->leave_sub();
3096
3097   return $string;
3098 }
3099
3100 sub redo_rows {
3101   $main::lxdebug->enter_sub();
3102
3103   my ($self, $flds, $new, $count, $numrows) = @_;
3104
3105   my @ndx = ();
3106
3107   map { push @ndx, { num => $new->[$_ - 1]->{runningnumber}, ndx => $_ } } 1 .. $count;
3108
3109   my $i = 0;
3110
3111   # fill rows
3112   foreach my $item (sort { $a->{num} <=> $b->{num} } @ndx) {
3113     $i++;
3114     my $j = $item->{ndx} - 1;
3115     map { $self->{"${_}_$i"} = $new->[$j]->{$_} } @{$flds};
3116   }
3117
3118   # delete empty rows
3119   for $i ($count + 1 .. $numrows) {
3120     map { delete $self->{"${_}_$i"} } @{$flds};
3121   }
3122
3123   $main::lxdebug->leave_sub();
3124 }
3125
3126 sub update_status {
3127   $main::lxdebug->enter_sub();
3128
3129   my ($self, $myconfig) = @_;
3130
3131   my ($i, $id);
3132
3133   my $dbh = $self->dbconnect_noauto($myconfig);
3134
3135   my $query = qq|DELETE FROM status
3136                  WHERE (formname = ?) AND (trans_id = ?)|;
3137   my $sth = prepare_query($self, $dbh, $query);
3138
3139   if ($self->{formname} =~ /(check|receipt)/) {
3140     for $i (1 .. $self->{rowcount}) {
3141       do_statement($self, $sth, $query, $self->{formname}, $self->{"id_$i"} * 1);
3142     }
3143   } else {
3144     do_statement($self, $sth, $query, $self->{formname}, $self->{id});
3145   }
3146   $sth->finish();
3147
3148   my $printed = ($self->{printed} =~ /\Q$self->{formname}\E/) ? "1" : "0";
3149   my $emailed = ($self->{emailed} =~ /\Q$self->{formname}\E/) ? "1" : "0";
3150
3151   my %queued = split / /, $self->{queued};
3152   my @values;
3153
3154   if ($self->{formname} =~ /(check|receipt)/) {
3155
3156     # this is a check or receipt, add one entry for each lineitem
3157     my ($accno) = split /--/, $self->{account};
3158     $query = qq|INSERT INTO status (trans_id, printed, spoolfile, formname, chart_id)
3159                 VALUES (?, ?, ?, ?, (SELECT c.id FROM chart c WHERE c.accno = ?))|;
3160     @values = ($printed, $queued{$self->{formname}}, $self->{prinform}, $accno);
3161     $sth = prepare_query($self, $dbh, $query);
3162
3163     for $i (1 .. $self->{rowcount}) {
3164       if ($self->{"checked_$i"}) {
3165         do_statement($self, $sth, $query, $self->{"id_$i"}, @values);
3166       }
3167     }
3168     $sth->finish();
3169
3170   } else {
3171     $query = qq|INSERT INTO status (trans_id, printed, emailed, spoolfile, formname)
3172                 VALUES (?, ?, ?, ?, ?)|;
3173     do_query($self, $dbh, $query, $self->{id}, $printed, $emailed,
3174              $queued{$self->{formname}}, $self->{formname});
3175   }
3176
3177   $dbh->commit;
3178   $dbh->disconnect;
3179
3180   $main::lxdebug->leave_sub();
3181 }
3182
3183 sub save_status {
3184   $main::lxdebug->enter_sub();
3185
3186   my ($self, $dbh) = @_;
3187
3188   my ($query, $printed, $emailed);
3189
3190   my $formnames  = $self->{printed};
3191   my $emailforms = $self->{emailed};
3192
3193   $query = qq|DELETE FROM status
3194                  WHERE (formname = ?) AND (trans_id = ?)|;
3195   do_query($self, $dbh, $query, $self->{formname}, $self->{id});
3196
3197   # this only applies to the forms
3198   # checks and receipts are posted when printed or queued
3199
3200   if ($self->{queued}) {
3201     my %queued = split / /, $self->{queued};
3202
3203     foreach my $formname (keys %queued) {
3204       $printed = ($self->{printed} =~ /\Q$self->{formname}\E/) ? "1" : "0";
3205       $emailed = ($self->{emailed} =~ /\Q$self->{formname}\E/) ? "1" : "0";
3206
3207       $query = qq|INSERT INTO status (trans_id, printed, emailed, spoolfile, formname)
3208                   VALUES (?, ?, ?, ?, ?)|;
3209       do_query($self, $dbh, $query, $self->{id}, $printed, $emailed, $queued{$formname}, $formname);
3210
3211       $formnames  =~ s/\Q$self->{formname}\E//;
3212       $emailforms =~ s/\Q$self->{formname}\E//;
3213
3214     }
3215   }
3216
3217   # save printed, emailed info
3218   $formnames  =~ s/^ +//g;
3219   $emailforms =~ s/^ +//g;
3220
3221   my %status = ();
3222   map { $status{$_}{printed} = 1 } split / +/, $formnames;
3223   map { $status{$_}{emailed} = 1 } split / +/, $emailforms;
3224
3225   foreach my $formname (keys %status) {
3226     $printed = ($formnames  =~ /\Q$self->{formname}\E/) ? "1" : "0";
3227     $emailed = ($emailforms =~ /\Q$self->{formname}\E/) ? "1" : "0";
3228
3229     $query = qq|INSERT INTO status (trans_id, printed, emailed, formname)
3230                 VALUES (?, ?, ?, ?)|;
3231     do_query($self, $dbh, $query, $self->{id}, $printed, $emailed, $formname);
3232   }
3233
3234   $main::lxdebug->leave_sub();
3235 }
3236
3237 #--- 4 locale ---#
3238 # $main::locale->text('SAVED')
3239 # $main::locale->text('DELETED')
3240 # $main::locale->text('ADDED')
3241 # $main::locale->text('PAYMENT POSTED')
3242 # $main::locale->text('POSTED')
3243 # $main::locale->text('POSTED AS NEW')
3244 # $main::locale->text('ELSE')
3245 # $main::locale->text('SAVED FOR DUNNING')
3246 # $main::locale->text('DUNNING STARTED')
3247 # $main::locale->text('PRINTED')
3248 # $main::locale->text('MAILED')
3249 # $main::locale->text('SCREENED')
3250 # $main::locale->text('CANCELED')
3251 # $main::locale->text('invoice')
3252 # $main::locale->text('proforma')
3253 # $main::locale->text('sales_order')
3254 # $main::locale->text('packing_list')
3255 # $main::locale->text('pick_list')
3256 # $main::locale->text('purchase_order')
3257 # $main::locale->text('bin_list')
3258 # $main::locale->text('sales_quotation')
3259 # $main::locale->text('request_quotation')
3260
3261 sub save_history {
3262   $main::lxdebug->enter_sub();
3263
3264   my $self = shift;
3265   my $dbh  = shift || $self->get_standard_dbh;
3266
3267   if(!exists $self->{employee_id}) {
3268     &get_employee($self, $dbh);
3269   }
3270
3271   my $query =
3272    qq|INSERT INTO history_erp (trans_id, employee_id, addition, what_done, snumbers) | .
3273    qq|VALUES (?, (SELECT id FROM employee WHERE login = ?), ?, ?, ?)|;
3274   my @values = (conv_i($self->{id}), $self->{login},
3275                 $self->{addition}, $self->{what_done}, "$self->{snumbers}");
3276   do_query($self, $dbh, $query, @values);
3277
3278   $dbh->commit;
3279
3280   $main::lxdebug->leave_sub();
3281 }
3282
3283 sub get_history {
3284   $main::lxdebug->enter_sub();
3285
3286   my ($self, $dbh, $trans_id, $restriction, $order) = @_;
3287   my ($orderBy, $desc) = split(/\-\-/, $order);
3288   $order = " ORDER BY " . ($order eq "" ? " h.itime " : ($desc == 1 ? $orderBy . " DESC " : $orderBy . " "));
3289   my @tempArray;
3290   my $i = 0;
3291   if ($trans_id ne "") {
3292     my $query =
3293       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 | .
3294       qq|FROM history_erp h | .
3295       qq|LEFT JOIN employee emp ON (emp.id = h.employee_id) | .
3296       qq|WHERE (trans_id = | . $trans_id . qq|) $restriction | .
3297       $order;
3298
3299     my $sth = $dbh->prepare($query) || $self->dberror($query);
3300
3301     $sth->execute() || $self->dberror("$query");
3302
3303     while(my $hash_ref = $sth->fetchrow_hashref()) {
3304       $hash_ref->{addition} = $main::locale->text($hash_ref->{addition});
3305       $hash_ref->{what_done} = $main::locale->text($hash_ref->{what_done});
3306       $hash_ref->{snumbers} =~ s/^.+_(.*)$/$1/g;
3307       $tempArray[$i++] = $hash_ref;
3308     }
3309     $main::lxdebug->leave_sub() and return \@tempArray
3310       if ($i > 0 && $tempArray[0] ne "");
3311   }
3312   $main::lxdebug->leave_sub();
3313   return 0;
3314 }
3315
3316 sub update_defaults {
3317   $main::lxdebug->enter_sub();
3318
3319   my ($self, $myconfig, $fld, $provided_dbh) = @_;
3320
3321   my $dbh;
3322   if ($provided_dbh) {
3323     $dbh = $provided_dbh;
3324   } else {
3325     $dbh = $self->dbconnect_noauto($myconfig);
3326   }
3327   my $query = qq|SELECT $fld FROM defaults FOR UPDATE|;
3328   my $sth   = $dbh->prepare($query);
3329
3330   $sth->execute || $self->dberror($query);
3331   my ($var) = $sth->fetchrow_array;
3332   $sth->finish;
3333
3334   if ($var =~ m/\d+$/) {
3335     my $new_var  = (substr $var, $-[0]) * 1 + 1;
3336     my $len_diff = length($var) - $-[0] - length($new_var);
3337     $var         = substr($var, 0, $-[0]) . ($len_diff > 0 ? '0' x $len_diff : '') . $new_var;
3338
3339   } else {
3340     $var = $var . '1';
3341   }
3342
3343   $query = qq|UPDATE defaults SET $fld = ?|;
3344   do_query($self, $dbh, $query, $var);
3345
3346   if (!$provided_dbh) {
3347     $dbh->commit;
3348     $dbh->disconnect;
3349   }
3350
3351   $main::lxdebug->leave_sub();
3352
3353   return $var;
3354 }
3355
3356 sub update_business {
3357   $main::lxdebug->enter_sub();
3358
3359   my ($self, $myconfig, $business_id, $provided_dbh) = @_;
3360
3361   my $dbh;
3362   if ($provided_dbh) {
3363     $dbh = $provided_dbh;
3364   } else {
3365     $dbh = $self->dbconnect_noauto($myconfig);
3366   }
3367   my $query =
3368     qq|SELECT customernumberinit FROM business
3369        WHERE id = ? FOR UPDATE|;
3370   my ($var) = selectrow_query($self, $dbh, $query, $business_id);
3371
3372   return undef unless $var;
3373
3374   if ($var =~ m/\d+$/) {
3375     my $new_var  = (substr $var, $-[0]) * 1 + 1;
3376     my $len_diff = length($var) - $-[0] - length($new_var);
3377     $var         = substr($var, 0, $-[0]) . ($len_diff > 0 ? '0' x $len_diff : '') . $new_var;
3378
3379   } else {
3380     $var = $var . '1';
3381   }
3382
3383   $query = qq|UPDATE business
3384               SET customernumberinit = ?
3385               WHERE id = ?|;
3386   do_query($self, $dbh, $query, $var, $business_id);
3387
3388   if (!$provided_dbh) {
3389     $dbh->commit;
3390     $dbh->disconnect;
3391   }
3392
3393   $main::lxdebug->leave_sub();
3394
3395   return $var;
3396 }
3397
3398 sub get_partsgroup {
3399   $main::lxdebug->enter_sub();
3400
3401   my ($self, $myconfig, $p) = @_;
3402   my $target = $p->{target} || 'all_partsgroup';
3403
3404   my $dbh = $self->get_standard_dbh($myconfig);
3405
3406   my $query = qq|SELECT DISTINCT pg.id, pg.partsgroup
3407                  FROM partsgroup pg
3408                  JOIN parts p ON (p.partsgroup_id = pg.id) |;
3409   my @values;
3410
3411   if ($p->{searchitems} eq 'part') {
3412     $query .= qq|WHERE p.inventory_accno_id > 0|;
3413   }
3414   if ($p->{searchitems} eq 'service') {
3415     $query .= qq|WHERE p.inventory_accno_id IS NULL|;
3416   }
3417   if ($p->{searchitems} eq 'assembly') {
3418     $query .= qq|WHERE p.assembly = '1'|;
3419   }
3420   if ($p->{searchitems} eq 'labor') {
3421     $query .= qq|WHERE (p.inventory_accno_id > 0) AND (p.income_accno_id IS NULL)|;
3422   }
3423
3424   $query .= qq|ORDER BY partsgroup|;
3425
3426   if ($p->{all}) {
3427     $query = qq|SELECT id, partsgroup FROM partsgroup
3428                 ORDER BY partsgroup|;
3429   }
3430
3431   if ($p->{language_code}) {
3432     $query = qq|SELECT DISTINCT pg.id, pg.partsgroup,
3433                   t.description AS translation
3434                 FROM partsgroup pg
3435                 JOIN parts p ON (p.partsgroup_id = pg.id)
3436                 LEFT JOIN translation t ON ((t.trans_id = pg.id) AND (t.language_code = ?))
3437                 ORDER BY translation|;
3438     @values = ($p->{language_code});
3439   }
3440
3441   $self->{$target} = selectall_hashref_query($self, $dbh, $query, @values);
3442
3443   $main::lxdebug->leave_sub();
3444 }
3445
3446 sub get_pricegroup {
3447   $main::lxdebug->enter_sub();
3448
3449   my ($self, $myconfig, $p) = @_;
3450
3451   my $dbh = $self->get_standard_dbh($myconfig);
3452
3453   my $query = qq|SELECT p.id, p.pricegroup
3454                  FROM pricegroup p|;
3455
3456   $query .= qq| ORDER BY pricegroup|;
3457
3458   if ($p->{all}) {
3459     $query = qq|SELECT id, pricegroup FROM pricegroup
3460                 ORDER BY pricegroup|;
3461   }
3462
3463   $self->{all_pricegroup} = selectall_hashref_query($self, $dbh, $query);
3464
3465   $main::lxdebug->leave_sub();
3466 }
3467
3468 sub all_years {
3469 # usage $form->all_years($myconfig, [$dbh])
3470 # return list of all years where bookings found
3471 # (@all_years)
3472
3473   $main::lxdebug->enter_sub();
3474
3475   my ($self, $myconfig, $dbh) = @_;
3476
3477   $dbh ||= $self->get_standard_dbh($myconfig);
3478
3479   # get years
3480   my $query = qq|SELECT (SELECT MIN(transdate) FROM acc_trans),
3481                    (SELECT MAX(transdate) FROM acc_trans)|;
3482   my ($startdate, $enddate) = selectrow_query($self, $dbh, $query);
3483
3484   if ($myconfig->{dateformat} =~ /^yy/) {
3485     ($startdate) = split /\W/, $startdate;
3486     ($enddate) = split /\W/, $enddate;
3487   } else {
3488     (@_) = split /\W/, $startdate;
3489     $startdate = $_[2];
3490     (@_) = split /\W/, $enddate;
3491     $enddate = $_[2];
3492   }
3493
3494   my @all_years;
3495   $startdate = substr($startdate,0,4);
3496   $enddate = substr($enddate,0,4);
3497
3498   while ($enddate >= $startdate) {
3499     push @all_years, $enddate--;
3500   }
3501
3502   return @all_years;
3503
3504   $main::lxdebug->leave_sub();
3505 }
3506
3507 sub backup_vars {
3508   $main::lxdebug->enter_sub();
3509   my $self = shift;
3510   my @vars = @_;
3511
3512   map { $self->{_VAR_BACKUP}->{$_} = $self->{$_} if exists $self->{$_} } @vars;
3513
3514   $main::lxdebug->leave_sub();
3515 }
3516
3517 sub restore_vars {
3518   $main::lxdebug->enter_sub();
3519
3520   my $self = shift;
3521   my @vars = @_;
3522
3523   map { $self->{$_} = $self->{_VAR_BACKUP}->{$_} if exists $self->{_VAR_BACKUP}->{$_} } @vars;
3524
3525   $main::lxdebug->leave_sub();
3526 }
3527
3528 1;
3529
3530 __END__
3531
3532 =head1 NAME
3533
3534 SL::Form.pm - main data object.
3535
3536 =head1 SYNOPSIS
3537
3538 This is the main data object of Lx-Office.
3539 Unfortunately it also acts as a god object for certain data retrieval procedures used in the entry points.
3540 Points of interest for a beginner are:
3541
3542  - $form->error            - renders a generic error in html. accepts an error message
3543  - $form->get_standard_dbh - returns a database connection for the
3544
3545 =head1 SPECIAL FUNCTIONS
3546
3547 =over 4
3548
3549 =item _store_value()
3550
3551 parses a complex var name, and stores it in the form.
3552
3553 syntax:
3554   $form->_store_value($key, $value);
3555
3556 keys must start with a string, and can contain various tokens.
3557 supported key structures are:
3558
3559 1. simple access
3560   simple key strings work as expected
3561
3562   id => $form->{id}
3563
3564 2. hash access.
3565   separating two keys by a dot (.) will result in a hash lookup for the inner value
3566   this is similar to the behaviour of java and templating mechanisms.
3567
3568   filter.description => $form->{filter}->{description}
3569
3570 3. array+hashref access
3571
3572   adding brackets ([]) before the dot will cause the next hash to be put into an array.
3573   using [+] instead of [] will force a new array index. this is useful for recurring
3574   data structures like part lists. put a [+] into the first varname, and use [] on the
3575   following ones.
3576
3577   repeating these names in your template:
3578
3579     invoice.items[+].id
3580     invoice.items[].parts_id
3581
3582   will result in:
3583
3584     $form->{invoice}->{items}->[
3585       {
3586         id       => ...
3587         parts_id => ...
3588       },
3589       {
3590         id       => ...
3591         parts_id => ...
3592       }
3593       ...
3594     ]
3595
3596 4. arrays
3597
3598   using brackets at the end of a name will result in a pure array to be created.
3599   note that you mustn't use [+], which is reserved for array+hash access and will
3600   result in undefined behaviour in array context.
3601
3602   filter.status[]  => $form->{status}->[ val1, val2, ... ]
3603
3604 =item update_business PARAMS
3605
3606 PARAMS (not named):
3607  \%config,     - config hashref
3608  $business_id, - business id
3609  $dbh          - optional database handle
3610
3611 handles business (thats customer/vendor types) sequences.
3612
3613 special behaviour for empty strings in customerinitnumber field:
3614 will in this case not increase the value, and return undef.
3615
3616 =item redirect_header $url
3617
3618 Generates a HTTP redirection header for the new C<$url>. Constructs an
3619 absolute URL including scheme, host name and port. If C<$url> is a
3620 relative URL then it is considered relative to Lx-Office base URL.
3621
3622 This function C<die>s if headers have already been created with
3623 C<$::form-E<gt>header>.
3624
3625 Examples:
3626
3627   print $::form->redirect_header('oe.pl?action=edit&id=1234');
3628   print $::form->redirect_header('http://www.lx-office.org/');
3629
3630 =back
3631
3632 =cut