Form::quote_html gibt es nicht mehr.
[kivitendo-erp.git] / SL / Form.pm
index c504f71..a6ce5af 100644 (file)
 package Form;
 use Data::Dumper;
 
-use Cwd;
-use HTML::Template;
-use SL::Template;
+use CGI;
 use CGI::Ajax;
+use Cwd;
+use List::Util qw(min max);
+use SL::Auth;
+use SL::Auth::DB;
+use SL::Auth::LDAP;
+use SL::AM;
+use SL::Common;
 use SL::DBUtils;
+use SL::Mailer;
 use SL::Menu;
+use SL::Template;
 use SL::User;
-use CGI;
+use Template;
+use List::Util qw(first max min sum);
+
+my $standard_dbh;
+
+sub DESTROY {
+  if ($standard_dbh) {
+    $standard_dbh->disconnect();
+    undef $standard_dbh;
+  }
+}
+
+sub _store_value {
+  $main::lxdebug->enter_sub(2);
+
+  my $self  = shift;
+  my $key   = shift;
+  my $value = shift;
+
+  my $curr  = $self;
+
+  while ($key =~ /\[\+?\]\.|\./) {
+    substr($key, 0, $+[0]) = '';
+
+    if ($& eq '.') {
+      $curr->{$`} ||= { };
+      $curr         = $curr->{$`};
+
+    } else {
+      $curr->{$`} ||= [ ];
+      if (!scalar @{ $curr->{$`} } || $& eq '[+].') {
+        push @{ $curr->{$`} }, { };
+      }
+
+      $curr = $curr->{$`}->[-1];
+    }
+  }
+
+  $curr->{$key} = $value;
+
+  $main::lxdebug->leave_sub(2);
+
+  return \$curr->{$key};
+}
 
 sub _input_to_hash {
   $main::lxdebug->enter_sub(2);
 
-  my $input = $_[0];
-  my %in    = ();
+  my $self  = shift;
+  my $input = shift;
+
   my @pairs = split(/&/, $input);
 
   foreach (@pairs) {
-    my ($name, $value) = split(/=/, $_, 2);
-    $in{$name} = unescape(undef, $value);
+    my ($key, $value) = split(/=/, $_, 2);
+    $self->_store_value($self->unescape($key), $self->unescape($value));
   }
 
   $main::lxdebug->leave_sub(2);
-
-  return %in;
 }
 
 sub _request_to_hash {
   $main::lxdebug->enter_sub(2);
 
-  my ($input) = @_;
-  my ($i,        $loc,  $key,    $val);
-  my (%ATTACH,   $f,    $header, $header_body, $len, $buf);
-  my ($boundary, @list, $size,   $body, $x, $blah, $name);
-
-  if ($ENV{'CONTENT_TYPE'}
-      && ($ENV{'CONTENT_TYPE'} =~ /multipart\/form-data; boundary=(.+)$/)) {
-    $boundary = quotemeta('--' . $1);
-    @list     = split(/$boundary/, $input);
-
-    # For some reason there are always 2 extra, that are empty
-    $size = @list - 2;
-
-    for ($x = 1; $x <= $size; $x++) {
-      $header_body = $list[$x];
-      $header_body =~ /\r\n\r\n|\n\n/;
-
-      # Here we split the header and body
-      $header = $`;
-      $body   = $';    #'
-      $body =~ s/\r\n$//;
-
-      # Now we try to get the file name
-      $name = $header;
-      $name =~ /name=\"(.+)\"/;
-      ($name, $blah) = split(/\"/, $1);
-
-      # If the form name is not attach, then we need to parse this like
-      # regular form data
-      if ($name ne "attach") {
-        $body =~ s/%([0-9a-fA-Z]{2})/pack("c",hex($1))/eg;
-        $ATTACH{$name} = $body;
-
-        # Otherwise it is an attachment and we need to finish it up
-      } elsif ($name eq "attach") {
-        $header =~ /filename=\"(.+)\"/;
-        $ATTACH{'FILE_NAME'} = $1;
-        $ATTACH{'FILE_NAME'} =~ s/\"//g;
-        $ATTACH{'FILE_NAME'} =~ s/\s//g;
-        $ATTACH{'FILE_CONTENT'} = $body;
-
-        for ($i = $x; $list[$i]; $i++) {
-          $list[$i] =~ s/^.+name=$//;
-          $list[$i] =~ /\"(\w+)\"/;
-          $ATTACH{$1} = $';    #'
+  my $self  = shift;
+  my $input = shift;
+
+  if (!$ENV{'CONTENT_TYPE'}
+      || ($ENV{'CONTENT_TYPE'} !~ /multipart\/form-data\s*;\s*boundary\s*=\s*(.+)$/)) {
+
+    $self->_input_to_hash($input);
+
+    $main::lxdebug->leave_sub(2);
+    return;
+  }
+
+  my ($name, $filename, $headers_done, $content_type, $boundary_found, $need_cr, $previous);
+
+  my $boundary = '--' . $1;
+
+  foreach my $line (split m/\n/, $input) {
+    last if (($line eq "${boundary}--") || ($line eq "${boundary}--\r"));
+
+    if (($line eq $boundary) || ($line eq "$boundary\r")) {
+      ${ $previous } =~ s|\r?\n$|| if $previous;
+
+      undef $previous;
+      undef $filename;
+
+      $headers_done   = 0;
+      $content_type   = "text/plain";
+      $boundary_found = 1;
+      $need_cr        = 0;
+
+      next;
+    }
+
+    next unless $boundary_found;
+
+    if (!$headers_done) {
+      $line =~ s/[\r\n]*$//;
+
+      if (!$line) {
+        $headers_done = 1;
+        next;
+      }
+
+      if ($line =~ m|^content-disposition\s*:.*?form-data\s*;|i) {
+        if ($line =~ m|filename\s*=\s*"(.*?)"|i) {
+          $filename = $1;
+          substr $line, $-[0], $+[0] - $-[0], "";
+        }
+
+        if ($line =~ m|name\s*=\s*"(.*?)"|i) {
+          $name = $1;
+          substr $line, $-[0], $+[0] - $-[0], "";
         }
+
+        $previous         = $self->_store_value($name, '');
+        $self->{FILENAME} = $filename if ($filename);
+
+        next;
+      }
+
+      if ($line =~ m|^content-type\s*:\s*(.*?)$|i) {
+        $content_type = $1;
       }
+
+      next;
     }
 
-    $main::lxdebug->leave_sub(2);
-    return %ATTACH;
+    next unless $previous;
 
-      } else {
-    $main::lxdebug->leave_sub(2);
-    return _input_to_hash($input);
+    ${ $previous } .= "${line}\n";
   }
+
+  ${ $previous } =~ s|\r?\n$|| if $previous;
+
+  $main::lxdebug->leave_sub(2);
 }
 
 sub new {
@@ -132,6 +200,11 @@ sub new {
 
   my $self = {};
 
+  if ($LXDebug::watch_form) {
+    require SL::Watchdog;
+    tie %{ $self }, 'SL::Watchdog';
+  }
+
   read(STDIN, $_, $ENV{CONTENT_LENGTH});
 
   if ($ENV{QUERY_STRING}) {
@@ -142,17 +215,86 @@ sub new {
     $_ = $ARGV[0];
   }
 
-  my %parameters = _request_to_hash($_);
-  map({ $self->{$_} = $parameters{$_}; } keys(%parameters));
+  bless $self, $type;
+
+  $self->_request_to_hash($_);
 
-  $self->{action} = lc $self->{action};
-  $self->{action} =~ s/( |-|,|\#)/_/g;
+  $self->{action}  =  lc $self->{action};
+  $self->{action}  =~ s/( |-|,|\#)/_/g;
 
-  $self->{version}   = "2.4.2";
+  $self->{version} =  "2.4.3";
 
   $main::lxdebug->leave_sub();
 
-  bless $self, $type;
+  return $self;
+}
+
+sub _flatten_variables_rec {
+  $main::lxdebug->enter_sub(2);
+
+  my $self   = shift;
+  my $curr   = shift;
+  my $prefix = shift;
+  my $key    = shift;
+
+  my @result;
+
+  if ('' eq ref $curr->{$key}) {
+    @result = ({ 'key' => $prefix . $key, 'value' => $curr->{$key} });
+
+  } elsif ('HASH' eq ref $curr->{$key}) {
+    foreach my $hash_key (sort keys %{ $curr->{$key} }) {
+      push @result, $self->_flatten_variables_rec($curr->{$key}, $prefix . $key . '.', $hash_key);
+    }
+
+  } else {
+    foreach my $idx (0 .. scalar @{ $curr->{$key} } - 1) {
+      my $first_array_entry = 1;
+
+      foreach my $hash_key (sort keys %{ $curr->{$key}->[$idx] }) {
+        push @result, $self->_flatten_variables_rec($curr->{$key}->[$idx], $prefix . $key . ($first_array_entry ? '[+].' : '[].'), $hash_key);
+        $first_array_entry = 0;
+      }
+    }
+  }
+
+  $main::lxdebug->leave_sub(2);
+
+  return @result;
+}
+
+sub flatten_variables {
+  $main::lxdebug->enter_sub(2);
+
+  my $self = shift;
+  my @keys = @_;
+
+  my @variables;
+
+  foreach (@keys) {
+    push @variables, $self->_flatten_variables_rec($self, '', $_);
+  }
+
+  $main::lxdebug->leave_sub(2);
+
+  return @variables;
+}
+
+sub flatten_standard_variables {
+  $main::lxdebug->enter_sub(2);
+
+  my $self      = shift;
+  my %skip_keys = map { $_ => 1 } (qw(login password header stylesheet titlebar version), @_);
+
+  my @variables;
+
+  foreach (grep { ! $skip_keys{$_} } keys %{ $self }) {
+    push @variables, $self->_flatten_variables_rec($self, '', $_);
+  }
+
+  $main::lxdebug->leave_sub(2);
+
+  return @variables;
 }
 
 sub debug {
@@ -167,6 +309,24 @@ sub debug {
   $main::lxdebug->leave_sub();
 }
 
+sub dumper {
+  $main::lxdebug->enter_sub(2);
+
+  my $self          = shift;
+  my $password      = $self->{password};
+
+  $self->{password} = 'X' x 8;
+
+  local $Data::Dumper::Sortkeys = 1;
+  my $output                    = Dumper($self);
+
+  $self->{password} = $password;
+
+  $main::lxdebug->leave_sub(2);
+
+  return $output;
+}
+
 sub escape {
   $main::lxdebug->enter_sub(2);
 
@@ -216,25 +376,6 @@ sub unquote {
 
 }
 
-sub quote_html {
-  $main::lxdebug->enter_sub(2);
-
-  my ($self, $str) = @_;
-
-  my %replace =
-    ('order' => ['"', '<', '>'],
-     '<'             => '&lt;',
-     '>'             => '&gt;',
-     '"'             => '&quot;',
-    );
-
-  map({ $str =~ s/$_/$replace{$_}/g; } @{ $replace{"order"} });
-
-  $main::lxdebug->leave_sub(2);
-
-  return $str;
-}
-
 sub hide_form {
   my $self = shift;
 
@@ -252,6 +393,8 @@ sub hide_form {
 sub error {
   $main::lxdebug->enter_sub();
 
+  $main::lxdebug->show_backtrace();
+
   my ($self, $msg) = @_;
   if ($ENV{HTTP_USER_AGENT}) {
     $msg =~ s/\n/<br>/g;
@@ -259,11 +402,7 @@ sub error {
 
   } else {
 
-    if ($self->{error_function}) {
-      &{ $self->{error_function} }($msg);
-    } else {
-      die "Error: $msg\n";
-    }
+    die "Error: $msg\n";
   }
 
   $main::lxdebug->leave_sub();
@@ -300,20 +439,20 @@ sub info {
   $main::lxdebug->leave_sub();
 }
 
+# calculates the number of rows in a textarea based on the content and column number
+# can be capped with maxrows
 sub numtextrows {
   $main::lxdebug->enter_sub();
+  my ($self, $str, $cols, $maxrows, $minrows) = @_;
 
-  my ($self, $str, $cols, $maxrows) = @_;
+  $minrows ||= 1;
 
-  my $rows = 0;
-
-  map { $rows += int(((length) - 2) / $cols) + 1 } split /\r/, $str;
-
-  $maxrows = $rows unless defined $maxrows;
+  my $rows   = sum map { int((length() - 2) / $cols) + 1 } split /\r/, $str;
+  $maxrows ||= $rows;
 
   $main::lxdebug->leave_sub();
 
-  return ($rows > $maxrows) ? $maxrows : $rows;
+  return max(min($rows, $maxrows), $minrows);
 }
 
 sub dberror {
@@ -331,12 +470,59 @@ sub isblank {
 
   my ($self, $name, $msg) = @_;
 
-  if ($self->{$name} =~ /^\s*$/) {
-    $self->error($msg);
+  my $curr = $self;
+  foreach my $part (split '.', $name) {
+    if (!$curr->{$part} || ($curr->{$part} =~ /^\s*$/)) {
+      $self->error($msg);
+    }
+    $curr = $curr->{$part};
   }
+
   $main::lxdebug->leave_sub();
 }
 
+sub create_http_response {
+  $main::lxdebug->enter_sub();
+
+  my $self     = shift;
+  my %params   = @_;
+
+  my $cgi      = $main::cgi;
+  $cgi       ||= CGI->new('');
+
+  my $base_path;
+
+  if ($ENV{HTTP_X_FORWARDED_FOR}) {
+    $base_path =  $ENV{HTTP_REFERER};
+    $base_path =~ s|^.*?://.*?/|/|;
+  } else {
+    $base_path =  $ENV{REQUEST_URI};
+  }
+  $base_path =~ s|[^/]+$||;
+  $base_path =~ s|/$||;
+
+  my $session_cookie;
+  if (defined $main::auth) {
+    my $session_cookie_value   = $main::auth->get_session_id();
+    $session_cookie_value    ||= 'NO_SESSION';
+
+    $session_cookie = $cgi->cookie('-name'  => $main::auth->get_session_cookie_name(),
+                                   '-value' => $session_cookie_value,
+                                   '-path'  => $base_path);
+  }
+
+  my %cgi_params = ('-type' => $params{content_type});
+  $cgi_params{'-charset'} = $params{charset} if ($parmas{charset});
+
+  my $output = $cgi->header('-cookie' => $session_cookie,
+                            %cgi_params);
+
+  $main::lxdebug->leave_sub();
+
+  return $output;
+}
+
+
 sub header {
   $main::lxdebug->enter_sub();
 
@@ -347,14 +533,25 @@ sub header {
     return;
   }
 
-  my ($stylesheet, $favicon, $charset);
+  my ($stylesheet, $favicon);
 
   if ($ENV{HTTP_USER_AGENT}) {
+    my $doctype;
 
-    if ($self->{stylesheet} && (-f "css/$self->{stylesheet}")) {
-      $stylesheet =
-        qq|<LINK REL="stylesheet" HREF="css/$self->{stylesheet}" TYPE="text/css" TITLE="Lx-Office stylesheet">
- |;
+    if ($ENV{'HTTP_USER_AGENT'} =~ m/MSIE\s+\d/) {
+      # Only set the DOCTYPE for Internet Explorer. Other browsers have problems displaying the menu otherwise.
+      $doctype = qq|<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">\n|;
+    }
+
+    my $stylesheets = "$self->{stylesheet} $self->{stylesheets}";
+
+    $stylesheets =~ s|^\s*||;
+    $stylesheets =~ s|\s*$||;
+    foreach my $file (split m/\s+/, $stylesheets) {
+      $file =~ s|.*/||;
+      next if (! -f "css/$file");
+
+      $stylesheet .= qq|<link rel="stylesheet" href="css/$file" TYPE="text/css" TITLE="Lx-Office stylesheet">\n|;
     }
 
     $self->{favicon}    = "favicon.ico" unless $self->{favicon};
@@ -365,11 +562,8 @@ sub header {
   |;
     }
 
-    if ($self->{charset}) {
-      $charset =
-        qq|<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=$self->{charset}">
-  |;
-    }
+    my $db_charset = $main::dbcharset ? $main::dbcharset : Common::DEFAULT_CHARSET;
+
     if ($self->{landscape}) {
       $pagelayout = qq|<style type="text/css">
                         \@page { size:landscape; }
@@ -399,15 +593,16 @@ sub header {
     foreach $item (@ { $self->{AJAX} }) {
       $ajax .= $item->show_javascript();
     }
-    print qq|Content-Type: text/html
 
-<html>
+    print $self->create_http_response('content_type' => 'text/html',
+                                      'charset'      => $db_charset,);
+    print qq|${doctype}<html>
 <head>
   <title>$self->{titlebar}</title>
   $stylesheet
   $pagelayout
   $favicon
-  $charset
+  <META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=${db_charset}">
   $jsscript
   $ajax
 
@@ -443,7 +638,7 @@ sub header {
   $main::lxdebug->leave_sub();
 }
 
-sub parse_html_template {
+sub _prepare_html_template {
   $main::lxdebug->enter_sub();
 
   my ($self, $file, $additional_params) = @_;
@@ -461,7 +656,7 @@ sub parse_html_template {
         (-f "templates/webpages/${file}_master.html") &&
         ((stat("templates/webpages/${file}_master.html"))[9] >
          (stat("templates/webpages/${file}_${language}.html"))[9])) {
-      my $info = "Developper information: templates/webpages/${file}_master.html is newer than the localized version.\n" .
+      my $info = "Developer information: templates/webpages/${file}_master.html is newer than the localized version.\n" .
         "Please re-run 'locales.pl' in 'locale/${language}'.";
       print(qq|<pre>$info</pre>|);
       die($info);
@@ -477,14 +672,6 @@ sub parse_html_template {
     die($info);
   }
 
-  my $template = HTML::Template->new("filename" => $file,
-                                     "die_on_bad_params" => 0,
-                                     "strict" => 0,
-                                     "case_sensitive" => 1,
-                                     "loop_context_vars" => 1,
-                                     "global_vars" => 1);
-
-  $additional_params = {} unless ($additional_params);
   if ($self->{"DEBUG"}) {
     $additional_params->{"DEBUG"} = $self->{"DEBUG"};
   }
@@ -503,20 +690,51 @@ sub parse_html_template {
     $additional_params->{"myconfig_jsc_dateformat"} = $jsc_dateformat;
   }
 
-  $additional_params->{"conf_jscalendar"} = $main::jscalendar;
-  $additional_params->{"conf_lizenzen"} = $main::lizenzen;
-  $additional_params->{"conf_latex_templates"} = $main::latex;
+  $additional_params->{"conf_webdav"}                 = $main::webdav;
+  $additional_params->{"conf_lizenzen"}               = $main::lizenzen;
+  $additional_params->{"conf_latex_templates"}        = $main::latex;
   $additional_params->{"conf_opendocument_templates"} = $main::opendocument_templates;
 
-  my @additional_param_names = keys(%{$additional_params});
-  foreach my $key ($template->param()) {
-    my $param = $self->{$key};
-    $param = $additional_params->{$key} if (grep(/^${key}$/, @additional_param_names));
-    $param = [] if (($template->query("name" => $key) eq "LOOP") && (ref($param) ne "ARRAY"));
-    $template->param($key => $param);
+  if (%main::debug_options) {
+    map { $additional_params->{'DEBUG_' . uc($_)} = $main::debug_options{$_} } keys %main::debug_options;
   }
 
-  my $output = $template->output();
+  if ($main::auth && $main::auth->{RIGHTS} && $main::auth->{RIGHTS}->{$self->{login}}) {
+    while (my ($key, $value) = each %{ $main::auth->{RIGHTS}->{$self->{login}} }) {
+      $additional_params->{"AUTH_RIGHTS_" . uc($key)} = $value;
+    }
+  }
+
+  $main::lxdebug->leave_sub();
+
+  return $file;
+}
+
+sub parse_html_template {
+  $main::lxdebug->enter_sub();
+
+  my ($self, $file, $additional_params) = @_;
+
+  $additional_params ||= { };
+
+  $file = $self->_prepare_html_template($file, $additional_params);
+
+  my $template = Template->new({ 'INTERPOLATE'  => 0,
+                                 'EVAL_PERL'    => 0,
+                                 'ABSOLUTE'     => 1,
+                                 'CACHE_SIZE'   => 0,
+                                 'PLUGIN_BASE'  => 'SL::Template::Plugin',
+                                 'INCLUDE_PATH' => '.:templates/webpages',
+                               }) || die;
+
+  map { $additional_params->{$_} ||= $self->{$_} } keys %{ $self };
+
+  my $output;
+  if (!$template->process($file, $additional_params, \$output)) {
+    print STDERR $template->error();
+  }
+
+  $output = $main::locale->{iconv}->convert($output) if ($main::locale);
 
   $main::lxdebug->leave_sub();
 
@@ -524,38 +742,47 @@ sub parse_html_template {
 }
 
 sub show_generic_error {
-  my ($self, $error, $title, $action) = @_;
+  my ($self, $error, %params) = @_;
+
+  my $add_params = {
+    'title_error' => $params{title},
+    'label_error' => $error,
+  };
 
-  my $add_params = {};
-  $add_params->{"title"} = $title if ($title);
-  $self->{"label_error"} = $error;
+  if ($params{action}) {
+    my @vars;
 
-  my @vars;
-  if ($action) {
-    map({ delete($self->{$_}); } qw(action));
-    map({ push(@vars, { "name" => $_, "value" => $self->{$_} })
-            if (!ref($self->{$_})); }
-        keys(%{$self}));
-    $add_params->{"SHOW_BUTTON"} = 1;
-    $add_params->{"BUTTON_LABEL"} = $action;
+    map { delete($self->{$_}); } qw(action);
+    map { push @vars, { "name" => $_, "value" => $self->{$_} } if (!ref($self->{$_})); } keys %{ $self };
+
+    $add_params->{SHOW_BUTTON}  = 1;
+    $add_params->{BUTTON_LABEL} = $params{label} || $params{action};
+    $add_params->{VARIABLES}    = \@vars;
+
+  } elsif ($params{back_button}) {
+    $add_params->{SHOW_BACK_BUTTON} = 1;
   }
-  $add_params->{"VARIABLES"} = \@vars;
+
+  $self->{title} = $title if ($title);
 
   $self->header();
-  print($self->parse_html_template("generic/error", $add_params));
+  print $self->parse_html_template("generic/error", $add_params);
 
   die("Error: $error\n");
 }
 
 sub show_generic_information {
-  my ($self, $error, $title) = @_;
+  my ($self, $text, $title) = @_;
+
+  my $add_params = {
+    'title_information' => $title,
+    'label_information' => $text,
+  };
 
-  my $add_params = {};
-  $add_params->{"title"} = $title if ($title);
-  $self->{"label_information"} = $error;
+  $self->{title} = $title if ($title);
 
   $self->header();
-  print($self->parse_html_template("generic/information", $add_params));
+  print $self->parse_html_template("generic/information", $add_params);
 
   die("Information: $error\n");
 }
@@ -614,7 +841,9 @@ sub redirect {
 
   if ($self->{callback}) {
 
-    ($script, $argv) = split(/\?/, $self->{callback});
+    ($script, $argv) = split(/\?/, $self->{callback}, 2);
+    $script =~ s|.*/||;
+    $script =~ s|[^a-zA-Z0-9_\.]||g;
     exec("perl", "$script", $argv);
 
   } else {
@@ -645,18 +874,23 @@ sub format_amount {
   if ($amount eq "") {
     $amount = 0;
   }
-  my $neg = ($amount =~ s/-//);
-
+  
+  # Hey watch out! The amount can be an exponential term like 1.13686837721616e-13
+  
+  my $neg = ($amount =~ s/^-//);
+  my $exp = ($amount =~ m/[e]/) ? 1 : 0;
+  
   if (defined($places) && ($places ne '')) {
-    if ($places < 0) {
-      $amount *= 1;
-      $places *= -1;
-
-      my ($actual_places) = ($amount =~ /\.(\d+)/);
-      $actual_places = length($actual_places);
-      $places = $actual_places > $places ? $actual_places : $places;
+    if (not $exp) {
+      if ($places < 0) {
+        $amount *= 1;
+        $places *= -1;
+
+        my ($actual_places) = ($amount =~ /\.(\d+)/);
+        $actual_places = length($actual_places);
+        $places = $actual_places > $places ? $actual_places : $places;
+      }
     }
-
     $amount = $self->round_amount($amount, $places);
   }
 
@@ -678,7 +912,89 @@ sub format_amount {
   $main::lxdebug->leave_sub(2);
   return $amount;
 }
+
+sub format_amount_units {
+  $main::lxdebug->enter_sub();
+
+  my $self             = shift;
+  my %params           = @_;
+
+  Common::check_params(\%params, qw(amount part_unit));
+
+  my $myconfig         = \%main::myconfig;
+  my $amount           = $params{amount};
+  my $places           = $params{places};
+  my $part_unit_name   = $params{part_unit};
+  my $amount_unit_name = $params{amount_unit};
+  my $conv_units       = $params{conv_units};
+  my $max_places       = $params{max_places};
+
+  AM->retrieve_all_units();
+  my $all_units        = $main::all_units;
+
+  if (('' eq ref $conv_units) && ($conv_units =~ /convertible/)) {
+    $conv_units = AM->convertible_units($all_units, $part_unit_name, $conv_units eq 'convertible_not_smaller');
+  }
+
+  if (!scalar @{ $conv_units }) {
+    my $result = $self->format_amount($myconfig, $amount, $places, undef, $max_places) . " " . $part_unit_name;
+    $main::lxdebug->leave_sub();
+    return $result;
+  }
+
+  my $part_unit  = $all_units->{$part_unit_name};
+  my $conv_unit  = ($amount_unit_name && ($amount_unit_name ne $part_unit_name)) ? $all_units->{$amount_unit_name} : $part_unit;
+
+  $amount       *= $conv_unit->{factor};
+
+  my @values;
+
+  foreach my $unit (@$conv_units) {
+    my $last = $unit->{name} eq $part_unit->{name};
+    if (!$last) {
+      $num     = int($amount / $unit->{factor});
+      $amount -= $num * $unit->{factor};
+    }
+
+    if ($last ? $amount : $num) {
+      push @values, { "unit"   => $unit->{name},
+                      "amount" => $last ? $amount / $unit->{factor} : $num,
+                      "places" => $last ? $places : 0 };
+    }
+
+    last if $last;
+  }
+
+  if (!@values) {
+    push @values, { "unit"   => $part_unit_name,
+                    "amount" => 0,
+                    "places" => 0 };
+  }
+
+  my $result = join " ", map { $self->format_amount($myconfig, $_->{amount}, $_->{places}, undef, $max_places), $_->{unit} } @values;
+
+  $main::lxdebug->leave_sub();
+
+  return $result;
+}
+
+sub format_string {
+  $main::lxdebug->enter_sub(2);
+
+  my $self  = shift;
+  my $input = shift;
+
+  $input =~ s/(^|[^\#]) \#  (\d+)  /$1$_[$2 - 1]/gx;
+  $input =~ s/(^|[^\#]) \#\{(\d+)\}/$1$_[$2 - 1]/gx;
+  $input =~ s/\#\#/\#/g;
+
+  $main::lxdebug->leave_sub(2);
+
+  return $input;
+}
+
 #
+
 sub parse_amount {
   $main::lxdebug->enter_sub(2);
 
@@ -726,7 +1042,9 @@ sub parse_template {
   $main::lxdebug->enter_sub();
 
   my ($self, $myconfig, $userspath) = @_;
-  my $template;
+  my ($template, $out);
+
+  local (*IN, *OUT);
 
   $self->{"cwd"} = getcwd();
   $self->{"tmpdir"} = $self->{cwd} . "/${userspath}";
@@ -760,16 +1078,29 @@ sub parse_template {
   map({ $self->{"employee_${_}"} = $myconfig->{$_}; }
       qw(email tel fax name signature company address businessnumber
          co_ustid taxnumber duns));
-  map({ $self->{"employee_${_}"} =~ s/\\n/\n/g; }
-      qw(company address signature));
-  map({ $self->{$_} =~ s/\\n/\n/g; } qw(company address signature));
+
+  map({ $self->{"${_}"} = $myconfig->{$_}; }
+      qw(co_ustid));
+              
 
   $self->{copies} = 1 if (($self->{copies} *= 1) <= 0);
 
   # OUT is used for the media, screen, printer, email
   # for postscript we store a copy in a temporary file
   my $fileid = time;
-  $self->{tmpfile} = "$userspath/${fileid}.$self->{IN}" if ( $self->{tmpfile} eq '' );
+  my $prepend_userspath;
+
+  if (!$self->{tmpfile}) {
+    $self->{tmpfile}   = "${fileid}.$self->{IN}";
+    $prepend_userspath = 1;
+  }
+
+  $prepend_userspath = 1 if substr($self->{tmpfile}, 0, length $userspath) eq $userspath;
+
+  $self->{tmpfile} =~ s|.*/||;
+  $self->{tmpfile} =~ s/[^a-zA-Z0-9\._\ \-]//g;
+  $self->{tmpfile} = "$userspath/$self->{tmpfile}" if $prepend_userspath;
+
   if ($template->uses_temp_file() || $self->{media} eq 'email') {
     $out = $self->{OUT};
     $self->{OUT} = ">$self->{tmpfile}";
@@ -793,23 +1124,23 @@ sub parse_template {
 
     if ($self->{media} eq 'email') {
 
-      use SL::Mailer;
-
       my $mail = new Mailer;
 
       map { $mail->{$_} = $self->{$_} }
-        qw(cc bcc subject message version format charset);
+        qw(cc bcc subject message version format);
+      $mail->{charset} = $main::dbcharset ? $main::dbcharset : Common::DEFAULT_CHARSET;
       $mail->{to} = $self->{EMAIL_RECIPIENT} ? $self->{EMAIL_RECIPIENT} : $self->{email};
       $mail->{from}   = qq|"$myconfig->{name}" <$myconfig->{email}>|;
       $mail->{fileid} = "$fileid.";
-      $myconfig->{signature} =~ s/\\r\\n/\\n/g;
+      $myconfig->{signature} =~ s/\r//g;
 
       # if we send html or plain text inline
       if (($self->{format} eq 'html') && ($self->{sendmode} eq 'inline')) {
         $mail->{contenttype} = "text/html";
 
-        $mail->{message}       =~ s/\r\n/<br>\n/g;
-        $myconfig->{signature} =~ s/\\n/<br>\n/g;
+        $mail->{message}       =~ s/\r//g;
+        $mail->{message}       =~ s/\n/<br>\n/g;
+        $myconfig->{signature} =~ s/\n/<br>\n/g;
         $mail->{message} .= "<br>\n-- <br>\n$myconfig->{signature}\n<br>";
 
         open(IN, $self->{tmpfile})
@@ -829,13 +1160,12 @@ sub parse_template {
                  $self->{"attachment_filename"} : $self->{"tmpfile"} });
         }
 
-        $mail->{message}       =~ s/\r\n/\n/g;
-        $myconfig->{signature} =~ s/\\n/\n/g;
-        $mail->{message} .= "\n-- \n$myconfig->{signature}";
+        $mail->{message}  =~ s/\r//g;
+        $mail->{message} .=  "\n-- \n$myconfig->{signature}";
 
       }
 
-      my $err = $mail->send($out);
+      my $err = $mail->send();
       $self->error($self->cleanup . "$err") if ($err);
 
     } else {
@@ -856,7 +1186,10 @@ sub parse_template {
           open(OUT, $self->{OUT})
             or $self->error($self->cleanup . "$self->{OUT} : $!");
         } else {
-          $self->{attachment_filename} = $self->{tmpfile} if ($self->{attachment_filename} eq '');
+          $self->{attachment_filename} = ($self->{attachment_filename}) 
+                                       ? $self->{attachment_filename}
+                                       : $self->generate_attachment_filename();
+
           # launch application
           print qq|Content-Type: | . $template->get_mime_type() . qq|
 Content-Disposition: attachment; filename="$self->{attachment_filename}"
@@ -888,6 +1221,85 @@ Content-Length: $numbytes
   $main::lxdebug->leave_sub();
 }
 
+sub get_formname_translation {
+  my ($self, $formname) = @_;
+
+  $formname ||= $self->{formname};
+
+  my %formname_translations = (
+    bin_list                => $main::locale->text('Bin List'),
+    credit_note             => $main::locale->text('Credit Note'),
+    invoice                 => $main::locale->text('Invoice'),
+    packing_list            => $main::locale->text('Packing List'),
+    pick_list               => $main::locale->text('Pick List'),
+    proforma                => $main::locale->text('Proforma Invoice'),
+    purchase_order          => $main::locale->text('Purchase Order'),
+    request_quotation       => $main::locale->text('RFQ'),
+    sales_order             => $main::locale->text('Confirmation'),
+    sales_quotation         => $main::locale->text('Quotation'),
+    storno_invoice          => $main::locale->text('Storno Invoice'),
+    storno_packing_list     => $main::locale->text('Storno Packing List'),
+    sales_delivery_order    => $main::locale->text('Delivery Order'),
+    purchase_delivery_order => $main::locale->text('Delivery Order'),
+  );
+
+  return $formname_translations{$formname}
+}
+
+sub get_number_prefix_for_type {
+  my ($self) = @_;
+
+  my $prefix =
+      (first { $self->{type} eq $_ } qw(invoice credit_note)) ? 'inv'
+    : ($self->{type} =~ /_quotation$/)                        ? 'quo'
+    : ($self->{type} =~ /_delivery_order$/)                   ? 'do'
+    :                                                           'ord';
+
+  return $prefix;
+}
+
+sub get_extension_for_format {
+  my ($self)    = @_;
+
+  my $extension = $self->{format} =~ /pdf/i          ? ".pdf"
+                : $self->{format} =~ /postscript/i   ? ".ps"
+                : $self->{format} =~ /opendocument/i ? ".odt"
+                : $self->{format} =~ /html/i         ? ".html"
+                :                                      "";
+
+  return $extension;
+}
+
+sub generate_attachment_filename {
+  my ($self) = @_;
+
+  my $attachment_filename = $main::locale->unquote_special_chars('HTML', $self->get_formname_translation());
+  my $prefix              = $self->get_number_prefix_for_type();
+
+  if ($attachment_filename && $self->{"${prefix}number"}) {
+    $attachment_filename .=  "_" . $self->{"${prefix}number"} . $self->get_extension_for_format();
+    $attachment_filename  =  $main::locale->quote_special_chars('filenames', $attachment_filename);
+    $attachment_filename  =~ s|[\s/\\]+|_|g;
+  } else {
+    $attachment_filename = "";
+  }
+
+  return $attachment_filename;
+}
+
+sub generate_email_subject {
+  my ($self) = @_;
+
+  my $subject = $main::locale->unquote_special_chars('HTML', $self->get_formname_translation());
+  my $prefix  = $self->get_number_prefix_for_type();
+
+  if ($subject && $self->{"${prefix}number"}) {
+    $subject .= " " . $self->{"${prefix}number"}
+  }
+
+  return $subject;
+}
+
 sub cleanup {
   $main::lxdebug->enter_sub();
 
@@ -977,21 +1389,33 @@ sub dbconnect_noauto {
   $main::lxdebug->enter_sub();
 
   my ($self, $myconfig) = @_;
-
+  
   # connect to database
   $dbh =
     DBI->connect($myconfig->{dbconnect}, $myconfig->{dbuser},
                  $myconfig->{dbpasswd}, { AutoCommit => 0 })
     or $self->dberror;
 
-  # set db options
-  if ($myconfig->{dboptions}) {
-    $dbh->do($myconfig->{dboptions}) || $self->dberror($myconfig->{dboptions});
-  }
+  # set db options
+  if ($myconfig->{dboptions}) {
+    $dbh->do($myconfig->{dboptions}) || $self->dberror($myconfig->{dboptions});
+  }
+
+  $main::lxdebug->leave_sub();
+
+  return $dbh;
+}
+
+sub get_standard_dbh {
+  $main::lxdebug->enter_sub(2);
+
+  my ($self, $myconfig) = @_;
+
+  $standard_dbh ||= $self->dbconnect_noauto($myconfig);
 
-  $main::lxdebug->leave_sub();
+  $main::lxdebug->leave_sub(2);
 
-  return $dbh;
+  return $standard_dbh;
 }
 
 sub update_balance {
@@ -1021,18 +1445,38 @@ sub update_exchangerate {
   $main::lxdebug->enter_sub();
 
   my ($self, $dbh, $curr, $transdate, $buy, $sell) = @_;
-
+  my ($query);
   # some sanity check for currency
   if ($curr eq '') {
     $main::lxdebug->leave_sub();
     return;
+  }  
+  $query = qq|SELECT curr FROM defaults|;
+
+  my ($currency) = selectrow_query($self, $dbh, $query);
+  my ($defaultcurrency) = split m/:/, $currency;
+
+
+  if ($curr eq $defaultcurrency) {
+    $main::lxdebug->leave_sub();
+    return;
   }
 
-  my $query = qq|SELECT e.curr FROM exchangerate e
+  $query = qq|SELECT e.curr FROM exchangerate e
                  WHERE e.curr = ? AND e.transdate = ?
                  FOR UPDATE|;
   my $sth = prepare_execute_query($self, $dbh, $query, $curr, $transdate);
 
+  if ($buy == 0) {
+    $buy = "";
+  }
+  if ($sell == 0) {
+    $sell = "";
+  }
+
+  $buy = conv_i($buy, "NULL");
+  $sell = conv_i($sell, "NULL");
+
   my $set;
   if ($buy != 0 && $sell != 0) {
     $set = "buy = $buy, sell = $sell";
@@ -1047,6 +1491,7 @@ sub update_exchangerate {
                 SET $set
                 WHERE curr = ?
                 AND transdate = ?|;
+    
   } else {
     $query = qq|INSERT INTO exchangerate (curr, buy, sell, transdate)
                 VALUES (?, $buy, $sell, ?)|;
@@ -1064,12 +1509,15 @@ sub save_exchangerate {
 
   my $dbh = $self->dbconnect($myconfig);
 
-  my ($buy, $sell) = (0, 0);
+  my ($buy, $sell);
+
   $buy  = $rate if $fld eq 'buy';
   $sell = $rate if $fld eq 'sell';
 
+
   $self->update_exchangerate($dbh, $currency, $transdate, $buy, $sell);
 
+
   $dbh->disconnect;
 
   $main::lxdebug->leave_sub();
@@ -1079,19 +1527,28 @@ sub get_exchangerate {
   $main::lxdebug->enter_sub();
 
   my ($self, $dbh, $curr, $transdate, $fld) = @_;
+  my ($query);
 
   unless ($transdate) {
     $main::lxdebug->leave_sub();
     return 1;
   }
 
-  my $query = qq|SELECT e.$fld FROM exchangerate e
+  $query = qq|SELECT curr FROM defaults|;
+
+  my ($currency) = selectrow_query($self, $dbh, $query);
+  my ($defaultcurrency) = split m/:/, $currency;
+
+  if ($currency eq $defaultcurrency) {
+    $main::lxdebug->leave_sub();
+    return 1;
+  }
+
+  $query = qq|SELECT e.$fld FROM exchangerate e
                  WHERE e.curr = ? AND e.transdate = ?|;
   my ($exchangerate) = selectrow_query($self, $dbh, $query, $curr, $transdate);
 
-  if (!$exchangerate) {
-    $exchangerate = 1;
-  }
+
 
   $main::lxdebug->leave_sub();
 
@@ -1108,102 +1565,142 @@ sub check_exchangerate {
     return "";
   }
 
-  my $dbh = $self->dbconnect($myconfig);
+  my ($defaultcurrency) = $self->get_default_currency($myconfig);
+
+  if ($currency eq $defaultcurrency) {
+    $main::lxdebug->leave_sub();
+    return 1;
+  }
 
+  my $dbh   = $self->get_standard_dbh($myconfig);
   my $query = qq|SELECT e.$fld FROM exchangerate e
                  WHERE e.curr = ? AND e.transdate = ?|;
+
   my ($exchangerate) = selectrow_query($self, $dbh, $query, $currency, $transdate);
-  $dbh->disconnect;
+
+  $exchangerate = 1 if ($exchangerate eq "");
 
   $main::lxdebug->leave_sub();
 
   return $exchangerate;
 }
 
+sub get_default_currency {
+  $main::lxdebug->enter_sub();
+
+  my ($self, $myconfig) = @_;
+  my $dbh = $self->get_standard_dbh($myconfig);
+
+  my $query = qq|SELECT curr FROM defaults|;
+
+  my ($curr)            = selectrow_query($self, $dbh, $query);
+  my ($defaultcurrency) = split m/:/, $curr;
+
+  $main::lxdebug->leave_sub();
+
+  return $defaultcurrency;
+}
+
+
 sub set_payment_options {
   $main::lxdebug->enter_sub();
 
   my ($self, $myconfig, $transdate) = @_;
 
-  if ($self->{payment_id}) {
+  return $main::lxdebug->leave_sub() unless ($self->{payment_id});
 
-    my $dbh = $self->dbconnect($myconfig);
+  my $dbh = $self->get_standard_dbh($myconfig);
 
-    my $query =
-      qq|SELECT p.terms_netto, p.terms_skonto, p.percent_skonto, p.description_long | .
-      qq|FROM payment_terms p | .
-      qq|WHERE p.id = ?|;
+  my $query =
+    qq|SELECT p.terms_netto, p.terms_skonto, p.percent_skonto, p.description_long | .
+    qq|FROM payment_terms p | .
+    qq|WHERE p.id = ?|;
 
-    ($self->{terms_netto}, $self->{terms_skonto}, $self->{percent_skonto},
-     $self->{payment_terms}) =
-       selectrow_query($self, $dbh, $query, $self->{payment_id});
+  ($self->{terms_netto}, $self->{terms_skonto}, $self->{percent_skonto},
+   $self->{payment_terms}) =
+     selectrow_query($self, $dbh, $query, $self->{payment_id});
 
-    if ($transdate eq "") {
-      if ($self->{invdate}) {
-        $transdate = $self->{invdate};
-      } else {
-        $transdate = $self->{transdate};
-      }
+  if ($transdate eq "") {
+    if ($self->{invdate}) {
+      $transdate = $self->{invdate};
+    } else {
+      $transdate = $self->{transdate};
     }
+  }
+
+  $query =
+    qq|SELECT ?::date + ?::integer AS netto_date, ?::date + ?::integer AS skonto_date | .
+    qq|FROM payment_terms|;
+  ($self->{netto_date}, $self->{skonto_date}) =
+    selectrow_query($self, $dbh, $query, $transdate, $self->{terms_netto}, $transdate, $self->{terms_skonto});
+
+  my ($invtotal, $total);
+  my (%amounts, %formatted_amounts);
+
+  if ($self->{type} =~ /_order$/) {
+    $amounts{invtotal} = $self->{ordtotal};
+    $amounts{total}    = $self->{ordtotal};
+
+  } elsif ($self->{type} =~ /_quotation$/) {
+    $amounts{invtotal} = $self->{quototal};
+    $amounts{total}    = $self->{quototal};
+
+  } else {
+    $amounts{invtotal} = $self->{invtotal};
+    $amounts{total}    = $self->{total};
+  }
+
+  map { $amounts{$_} = $self->parse_amount($myconfig, $amounts{$_}) } keys %amounts;
+
+  $amounts{skonto_amount}      = $amounts{invtotal} * $self->{percent_skonto};
+  $amounts{invtotal_wo_skonto} = $amounts{invtotal} * (1 - $self->{percent_skonto});
+  $amounts{total_wo_skonto}    = $amounts{total}    * (1 - $self->{percent_skonto});
 
+  foreach (keys %amounts) {
+    $amounts{$_}           = $self->round_amount($amounts{$_}, 2);
+    $formatted_amounts{$_} = $self->format_amount($myconfig, $amounts{$_}, 2);
+  }
+
+  if ($self->{"language_id"}) {
     $query =
-      qq|SELECT ?::date + ?::integer AS netto_date, ?::date + ?::integer AS skonto_date | .
-      qq|FROM payment_terms|;
-    ($self->{netto_date}, $self->{skonto_date}) =
-      selectrow_query($self, $dbh, $query, $transdate, $self->{terms_netto}, $transdate, $self->{terms_skonto});
-
-    my $total = ($self->{invtotal}) ? $self->{invtotal} : $self->{ordtotal};
-    my $skonto_amount = $self->parse_amount($myconfig, $total) *
-      $self->{percent_skonto};
-
-    $self->{skonto_amount} =
-      $self->format_amount($myconfig, $skonto_amount, 2);
-
-    if ($self->{"language_id"}) {
-      $query =
-        qq|SELECT t.description_long, l.output_numberformat, l.output_dateformat, l.output_longdates | .
-        qq|FROM translation_payment_terms t | .
-        qq|LEFT JOIN language l ON t.language_id = l.id | .
-        qq|WHERE (t.language_id = ?) AND (t.payment_terms_id = ?)|;
-      my ($description_long, $output_numberformat, $output_dateformat,
-        $output_longdates) =
-        selectrow_query($self, $dbh, $query,
-                        $self->{"language_id"}, $self->{"payment_id"});
-
-      $self->{payment_terms} = $description_long if ($description_long);
-
-      if ($output_dateformat) {
-        foreach my $key (qw(netto_date skonto_date)) {
-          $self->{$key} =
-            $main::locale->reformat_date($myconfig, $self->{$key},
-                                         $output_dateformat,
-                                         $output_longdates);
-        }
+      qq|SELECT t.description_long, l.output_numberformat, l.output_dateformat, l.output_longdates | .
+      qq|FROM translation_payment_terms t | .
+      qq|LEFT JOIN language l ON t.language_id = l.id | .
+      qq|WHERE (t.language_id = ?) AND (t.payment_terms_id = ?)|;
+    my ($description_long, $output_numberformat, $output_dateformat,
+      $output_longdates) =
+      selectrow_query($self, $dbh, $query,
+                      $self->{"language_id"}, $self->{"payment_id"});
+
+    $self->{payment_terms} = $description_long if ($description_long);
+
+    if ($output_dateformat) {
+      foreach my $key (qw(netto_date skonto_date)) {
+        $self->{$key} =
+          $main::locale->reformat_date($myconfig, $self->{$key},
+                                       $output_dateformat,
+                                       $output_longdates);
       }
+    }
 
-      if ($output_numberformat &&
-          ($output_numberformat ne $myconfig->{"numberformat"})) {
-        my $saved_numberformat = $myconfig->{"numberformat"};
-        $myconfig->{"numberformat"} = $output_numberformat;
-        $self->{skonto_amount} =
-          $self->format_amount($myconfig, $skonto_amount, 2);
-        $myconfig->{"numberformat"} = $saved_numberformat;
-      }
+    if ($output_numberformat &&
+        ($output_numberformat ne $myconfig->{"numberformat"})) {
+      my $saved_numberformat = $myconfig->{"numberformat"};
+      $myconfig->{"numberformat"} = $output_numberformat;
+      map { $formatted_amounts{$_} = $self->format_amount($myconfig, $amounts{$_}) } keys %amounts;
+      $myconfig->{"numberformat"} = $saved_numberformat;
     }
+  }
 
-    $self->{payment_terms} =~ s/<%netto_date%>/$self->{netto_date}/g;
-    $self->{payment_terms} =~ s/<%skonto_date%>/$self->{skonto_date}/g;
-    $self->{payment_terms} =~ s/<%skonto_amount%>/$self->{skonto_amount}/g;
-    $self->{payment_terms} =~ s/<%total%>/$self->{total}/g;
-    $self->{payment_terms} =~ s/<%invtotal%>/$self->{invtotal}/g;
-    $self->{payment_terms} =~ s/<%currency%>/$self->{currency}/g;
-    $self->{payment_terms} =~ s/<%terms_netto%>/$self->{terms_netto}/g;
-    $self->{payment_terms} =~ s/<%account_number%>/$self->{account_number}/g;
-    $self->{payment_terms} =~ s/<%bank%>/$self->{bank}/g;
-    $self->{payment_terms} =~ s/<%bank_code%>/$self->{bank_code}/g;
+  $self->{payment_terms} =~ s/<%netto_date%>/$self->{netto_date}/g;
+  $self->{payment_terms} =~ s/<%skonto_date%>/$self->{skonto_date}/g;
+  $self->{payment_terms} =~ s/<%currency%>/$self->{currency}/g;
+  $self->{payment_terms} =~ s/<%terms_netto%>/$self->{terms_netto}/g;
+  $self->{payment_terms} =~ s/<%account_number%>/$self->{account_number}/g;
+  $self->{payment_terms} =~ s/<%bank%>/$self->{bank}/g;
+  $self->{payment_terms} =~ s/<%bank_code%>/$self->{bank_code}/g;
 
-    $dbh->disconnect;
-  }
+  map { $self->{payment_terms} =~ s/<%${_}%>/$formatted_amounts{$_}/g; } keys %formatted_amounts;
 
   $main::lxdebug->leave_sub();
 
@@ -1217,10 +1714,9 @@ sub get_template_language {
   my $template_code = "";
 
   if ($self->{language_id}) {
-    my $dbh = $self->dbconnect($myconfig);
+    my $dbh = $self->get_standard_dbh($myconfig);
     my $query = qq|SELECT template_code FROM language WHERE id = ?|;
     ($template_code) = selectrow_query($self, $dbh, $query, $self->{language_id});
-    $dbh->disconnect;
   }
 
   $main::lxdebug->leave_sub();
@@ -1236,10 +1732,9 @@ sub get_printer_code {
   my $template_code = "";
 
   if ($self->{printer_id}) {
-    my $dbh = $self->dbconnect($myconfig);
+    my $dbh = $self->get_standard_dbh($myconfig);
     my $query = qq|SELECT template_code, printer_command FROM printers WHERE id = ?|;
     ($template_code, $self->{printer_command}) = selectrow_query($self, $dbh, $query, $self->{printer_id});
-    $dbh->disconnect;
   }
 
   $main::lxdebug->leave_sub();
@@ -1255,11 +1750,10 @@ sub get_shipto {
   my $template_code = "";
 
   if ($self->{shipto_id}) {
-    my $dbh = $self->dbconnect($myconfig);
+    my $dbh = $self->get_standard_dbh($myconfig);
     my $query = qq|SELECT * FROM shipto WHERE shipto_id = ?|;
     my $ref = selectfirst_hashref_query($self, $dbh, $query, $self->{shipto_id});
     map({ $self->{$_} = $ref->{$_} } keys(%$ref));
-    $dbh->disconnect;
   }
 
   $main::lxdebug->leave_sub();
@@ -1272,6 +1766,7 @@ sub add_shipto {
 
   my $shipto;
   my @values;
+
   foreach my $item (qw(name department_1 department_2 street zipcode city country
                        contact phone fax email)) {
     if ($self->{"shipto$item"}) {
@@ -1279,6 +1774,7 @@ sub add_shipto {
     }
     push(@values, $self->{"shipto${item}"});
   }
+
   if ($shipto) {
     if ($self->{shipto_id}) {
       my $query = qq|UPDATE shipto set
@@ -1307,8 +1803,10 @@ sub add_shipto {
                        shiptocontact = ? AND
                        shiptophone = ? AND
                        shiptofax = ? AND
-                       shiptoemail = ?|;
-      my $insert_check = selectfirst_hashref_query($self, $dbh, $query, @values);
+                       shiptoemail = ? AND
+                       module = ? AND 
+                       trans_id = ?|;
+      my $insert_check = selectfirst_hashref_query($self, $dbh, $query, @values, $module, $id);
       if(!$insert_check){
         $query =
           qq|INSERT INTO shipto (trans_id, shiptoname, shiptodepartment_1, shiptodepartment_2,
@@ -1316,7 +1814,7 @@ sub add_shipto {
                                  shiptocontact, shiptophone, shiptofax, shiptoemail, module)
              VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)|;
         do_query($self, $dbh, $query, $id, @values, $module);
-     }
+      }
     }
   }
 
@@ -1329,8 +1827,8 @@ sub get_employee {
   my ($self, $dbh) = @_;
 
   my $query = qq|SELECT id, name FROM employee WHERE login = ?|;
-  ($self->{employee_id}, $self->{employee}) = selectrow_query($self, $dbh, $query, $self->{login});
-  $self->{employee_id} *= 1;
+  ($self->{"employee_id"}, $self->{"employee"}) = selectrow_query($self, $dbh, $query, $self->{login});
+  $self->{"employee_id"} *= 1;
 
   $main::lxdebug->leave_sub();
 }
@@ -1342,7 +1840,7 @@ sub get_salesman {
 
   $main::lxdebug->leave_sub() and return unless $salesman_id;
 
-  my $dbh = $self->dbconnect($myconfig);
+  my $dbh = $self->get_standard_dbh($myconfig);
 
   my ($login) =
     selectrow_query($self, $dbh, qq|SELECT login FROM employee WHERE id = ?|,
@@ -1357,12 +1855,8 @@ sub get_salesman {
 
     $self->{salesman_name} = $login
       if ($self->{salesman_name} eq "");
-
-    map({ $self->{"salesman_$_"} =~ s/\\n/\n/g; } qw(address company));
   }
 
-  $dbh->disconnect();
-
   $main::lxdebug->leave_sub();
 }
 
@@ -1371,10 +1865,9 @@ sub get_duedate {
 
   my ($self, $myconfig) = @_;
 
-  my $dbh = $self->dbconnect($myconfig);
+  my $dbh = $self->get_standard_dbh($myconfig);
   my $query = qq|SELECT current_date + terms_netto FROM payment_terms WHERE id = ?|;
   ($self->{duedate}) = selectrow_query($self, $dbh, $query, $self->{payment_id});
-  $dbh->disconnect();
 
   $main::lxdebug->leave_sub();
 }
@@ -1455,10 +1948,7 @@ sub _get_shipto {
   $key = "all_shipto" unless ($key);
 
   # get shipping addresses
-  my $query =
-    qq|SELECT shipto_id, shiptoname, shiptodepartment_1 | .
-    qq|FROM shipto | .
-    qq|WHERE trans_id = ?|;
+  my $query = qq|SELECT * FROM shipto WHERE trans_id = ?|;
 
   $self->{$key} = selectall_hashref_query($self, $dbh, $query, $vc_id);
 
@@ -1490,7 +1980,7 @@ sub _get_charts {
   my $transdate = quote_db_date($params->{transdate});
 
   my $query =
-    qq|SELECT c.accno, c.description, c.link, tk.taxkey_id, tk.tax_id | .
+    qq|SELECT c.id, c.accno, c.description, c.link, tk.taxkey_id, tk.tax_id | .
     qq|FROM chart c | .
     qq|LEFT JOIN taxkeys tk ON | .
     qq|(tk.id = (SELECT id FROM taxkeys | .
@@ -1517,14 +2007,27 @@ sub _get_taxcharts {
   $main::lxdebug->leave_sub();
 }
 
-sub _get_employees {
+sub _get_taxzones {
   $main::lxdebug->enter_sub();
 
   my ($self, $dbh, $key) = @_;
 
-  $key = "all_employees" unless ($key);
-  $self->{$key} =
-    selectall_hashref_query($self, $dbh, qq|SELECT * FROM employee|);
+  $key = "all_taxzones" unless ($key);
+
+  my $query = qq|SELECT * FROM tax_zones ORDER BY id|;
+
+  $self->{$key} = selectall_hashref_query($self, $dbh, $query);
+
+  $main::lxdebug->leave_sub();
+}
+
+sub _get_employees {
+  $main::lxdebug->enter_sub();
+
+  my ($self, $dbh, $default_key, $key) = @_;
+
+  $key = $default_key unless ($key);
+  $self->{$key} = selectall_hashref_query($self, $dbh, qq|SELECT * FROM employee ORDER BY lower(name)|);
 
   $main::lxdebug->leave_sub();
 }
@@ -1555,13 +2058,184 @@ sub _get_languages {
   $main::lxdebug->leave_sub();
 }
 
+sub _get_dunning_configs {
+  $main::lxdebug->enter_sub();
+
+  my ($self, $dbh, $key) = @_;
+
+  $key = "all_dunning_configs" unless ($key);
+
+  my $query = qq|SELECT * FROM dunning_config ORDER BY dunning_level|;
+
+  $self->{$key} = selectall_hashref_query($self, $dbh, $query);
+
+  $main::lxdebug->leave_sub();
+}
+
+sub _get_currencies {
+$main::lxdebug->enter_sub();
+
+  my ($self, $dbh, $key) = @_;
+
+  $key = "all_currencies" unless ($key);
+
+  my $query = qq|SELECT curr AS currency FROM defaults|;
+  $self->{$key} = [split(/\:/ , selectfirst_hashref_query($self, $dbh, $query)->{currency})];
+
+  $main::lxdebug->leave_sub();
+}
+
+sub _get_payments {
+$main::lxdebug->enter_sub();
+
+  my ($self, $dbh, $key) = @_;
+
+  $key = "all_payments" unless ($key);
+
+  my $query = qq|SELECT * FROM payment_terms ORDER BY id|;
+  $self->{$key} = selectall_hashref_query($self, $dbh, $query);
+
+  $main::lxdebug->leave_sub();
+}
+
+sub _get_customers {
+  $main::lxdebug->enter_sub();
+
+  my ($self, $dbh, $key, $limit) = @_;
+
+  $key = "all_customers" unless ($key);
+  $limit_clause = "LIMIT $limit" if $limit;
+
+  my $query = qq|SELECT * FROM customer WHERE NOT obsolete ORDER BY name $limit_clause|;
+
+  $self->{$key} = selectall_hashref_query($self, $dbh, $query);
+
+  $main::lxdebug->leave_sub();
+}
+
+sub _get_vendors {
+  $main::lxdebug->enter_sub();
+
+  my ($self, $dbh, $key) = @_;
+
+  $key = "all_vendors" unless ($key);
+
+  my $query = qq|SELECT * FROM vendor WHERE NOT obsolete ORDER BY name|;
+
+  $self->{$key} = selectall_hashref_query($self, $dbh, $query);
+
+  $main::lxdebug->leave_sub();
+}
+
+sub _get_departments {
+  $main::lxdebug->enter_sub();
+
+  my ($self, $dbh, $key) = @_;
+
+  $key = "all_departments" unless ($key);
+
+  my $query = qq|SELECT * FROM department ORDER BY description|;
+
+  $self->{$key} = selectall_hashref_query($self, $dbh, $query);
+
+  $main::lxdebug->leave_sub();
+}
+
+sub _get_warehouses {
+  $main::lxdebug->enter_sub();
+
+  my ($self, $dbh, $param) = @_;
+
+  my ($key, $bins_key, $q_access, @values);
+
+  if ('' eq ref $param) {
+    $key = $param;
+  } else {
+    $key      = $param->{key};
+    $bins_key = $param->{bins};
+
+    if ($param->{access}) {
+      $q_access =
+        qq| AND EXISTS (
+              SELECT wa.employee_id
+              FROM warehouse_access wa
+              WHERE (wa.employee_id  = (SELECT id FROM employee WHERE login = ?))
+                AND (wa.warehouse_id = w.id)
+                AND (wa.access IN ('ro', 'rw')))|;
+      push @values, $param->{access};
+    }
+
+    if ($param->{no_personal}) {
+      $q_access .= qq| AND (w.personal_warehouse_of IS NULL)|;
+
+    } elsif ($param->{personal}) {
+      $q_access .= qq| AND (w.personal_warehouse_of = ?)|;
+      push @values, conv_i($param->{personal});
+    }
+  }
+
+  my $query = qq|SELECT w.* FROM warehouse w
+                 WHERE (NOT w.invalid) AND
+                   ((SELECT COUNT(b.*) FROM bin b WHERE b.warehouse_id = w.id) > 0)
+                   $q_access
+                 ORDER BY w.sortkey|;
+
+  $self->{$key} = selectall_hashref_query($self, $dbh, $query, @values);
+
+  if ($bins_key) {
+    $query = qq|SELECT id, description FROM bin WHERE warehouse_id = ?|;
+    my $sth = prepare_query($self, $dbh, $query);
+
+    foreach my $warehouse (@{ $self->{$key} }) {
+      do_statement($self, $sth, $query, $warehouse->{id});
+      $warehouse->{$bins_key} = [];
+
+      while (my $ref = $sth->fetchrow_hashref()) {
+        push @{ $warehouse->{$bins_key} }, $ref;
+      }
+    }
+    $sth->finish();
+  }
+
+  $main::lxdebug->leave_sub();
+}
+
+sub _get_simple {
+  $main::lxdebug->enter_sub();
+
+  my ($self, $dbh, $table, $key, $sortkey) = @_;
+
+  my $query  = qq|SELECT * FROM $table|;
+  $query    .= qq| ORDER BY $sortkey| if ($sortkey);
+
+  $self->{$key} = selectall_hashref_query($self, $dbh, $query);
+
+  $main::lxdebug->leave_sub();
+}
+
+sub _get_groups {
+  $main::lxdebug->enter_sub();
+
+  my ($self, $dbh, $key) = @_;
+
+  $key ||= "all_groups";
+
+  my $groups = $main::auth->read_groups();
+
+  $self->{$key} = selectall_hashref_query($self, $dbh, $query);
+
+  $main::lxdebug->leave_sub();
+}
+
 sub get_lists {
   $main::lxdebug->enter_sub();
 
   my $self = shift;
   my %params = @_;
 
-  my $dbh = $self->dbconnect(\%main::myconfig);
+  my $dbh = $self->get_standard_dbh(\%main::myconfig);
   my ($sth, $query, $ref);
 
   my $vc = $self->{"vc"} eq "customer" ? "customer" : "vendor";
@@ -1597,15 +2271,65 @@ sub get_lists {
     $self->_get_taxcharts($dbh, $params{"taxcharts"});
   }
 
+  if ($params{"taxzones"}) {
+    $self->_get_taxzones($dbh, $params{"taxzones"});
+  }
+
   if ($params{"employees"}) {
-    $self->_get_employees($dbh, $params{"employees"});
+    $self->_get_employees($dbh, "all_employees", $params{"employees"});
+  }
+  
+  if ($params{"salesmen"}) {
+    $self->_get_employees($dbh, "all_salesmen", $params{"salesmen"});
   }
 
   if ($params{"business_types"}) {
     $self->_get_business_types($dbh, $params{"business_types"});
   }
 
-  $dbh->disconnect();
+  if ($params{"dunning_configs"}) {
+    $self->_get_dunning_configs($dbh, $params{"dunning_configs"});
+  }
+  
+  if($params{"currencies"}) {
+    $self->_get_currencies($dbh, $params{"currencies"});
+  }
+  
+  if($params{"customers"}) {
+    if (ref $params{"customers"} eq 'HASH') {
+      $self->_get_customers($dbh, $params{"customers"}{key}, $params{"customers"}{limit});
+    } else {
+      $self->_get_customers($dbh, $params{"customers"});
+    }
+  }
+  
+  if($params{"vendors"}) {
+    if (ref $params{"vendors"} eq 'HASH') {
+      $self->_get_vendors($dbh, $params{"vendors"}{key}, $params{"vendors"}{limit});
+    } else {
+      $self->_get_vendors($dbh, $params{"vendors"});
+    }
+  }
+  
+  if($params{"payments"}) {
+    $self->_get_payments($dbh, $params{"payments"});
+  }
+
+  if($params{"departments"}) {
+    $self->_get_departments($dbh, $params{"departments"});
+  }
+
+  if ($params{price_factors}) {
+    $self->_get_simple($dbh, 'price_factors', $params{price_factors}, 'sortkey');
+  }
+
+  if ($params{warehouses}) {
+    $self->_get_warehouses($dbh, $params{warehouses});
+  }
+
+  if ($params{groups}) {
+    $self->_get_groups($dbh, $params{groups});
+  }
 
   $main::lxdebug->leave_sub();
 }
@@ -1617,7 +2341,7 @@ sub get_name {
   my ($self, $myconfig, $table) = @_;
 
   # connect to database
-  my $dbh = $self->dbconnect($myconfig);
+  my $dbh = $self->get_standard_dbh($myconfig);
 
   $table = $table eq "customer" ? "customer" : "vendor";
   my $arap = $self->{arap} eq "ar" ? "ar" : "ap";
@@ -1666,7 +2390,7 @@ sub all_vc {
   my ($self, $myconfig, $table, $module) = @_;
 
   my $ref;
-  my $dbh = $self->dbconnect($myconfig);
+  my $dbh = $self->get_standard_dbh($myconfig);
 
   $table = $table eq "customer" ? "customer" : "vendor";
 
@@ -1736,8 +2460,6 @@ sub all_vc {
 
   $self->{payment_terms} = selectall_hashref_query($self, $dbh, $query);
 
-  $dbh->disconnect;
-
   $main::lxdebug->leave_sub();
 }
 
@@ -1746,7 +2468,7 @@ sub language_payment {
 
   my ($self, $myconfig) = @_;
 
-  my $dbh = $self->dbconnect($myconfig);
+  my $dbh = $self->get_standard_dbh($myconfig);
   # get languages
   my $query = qq|SELECT id, description
                  FROM language
@@ -1774,7 +2496,6 @@ sub language_payment {
 
   $self->{BUCHUNGSGRUPPEN} = selectall_hashref_query($self, $dbh, $query);
 
-  $dbh->disconnect;
   $main::lxdebug->leave_sub();
 }
 
@@ -1784,7 +2505,7 @@ sub all_departments {
 
   my ($self, $myconfig, $table) = @_;
 
-  my $dbh = $self->dbconnect($myconfig);
+  my $dbh = $self->get_standard_dbh($myconfig);
   my $where;
 
   if ($table eq 'customer') {
@@ -1799,15 +2520,13 @@ sub all_departments {
 
   delete($self->{all_departments}) unless (@{ $self->{all_departments} });
 
-  $dbh->disconnect;
-
   $main::lxdebug->leave_sub();
 }
 
 sub create_links {
   $main::lxdebug->enter_sub();
 
-  my ($self, $module, $myconfig, $table) = @_;
+  my ($self, $module, $myconfig, $table, $provided_dbh) = @_;
 
   my ($fld, $arap);
   if ($table eq "customer") {
@@ -1824,7 +2543,7 @@ sub create_links {
   # get last customers or vendors
   my ($query, $sth, $ref);
 
-  my $dbh = $self->dbconnect($myconfig);
+  my $dbh = $provided_dbh ? $provided_dbh : $self->get_standard_dbh($myconfig);
   my %xkeyref = ();
 
   if (!$self->{id}) {
@@ -1849,7 +2568,7 @@ sub create_links {
     while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
 
       foreach my $key (split(/:/, $ref->{link})) {
-        if ($key =~ /$module/) {
+        if ($key =~ /\Q$module\E/) {
 
           # cross reference for keys
           $xkeyref{ $ref->{accno} } = $key;
@@ -1870,10 +2589,6 @@ sub create_links {
   $query = qq|SELECT id, taxkey, taxdescription FROM tax|;
   $self->{TAXKEY} = selectall_hashref_query($self, $dbh, $query);
 
-  # get tax zones
-  $query = qq|SELECT id, description FROM tax_zones|;
-  $self->{TAXZONE} = selectall_hashref_query($self, $dbh, $query);
-
   if (($module eq "AP") || ($module eq "AR")) {
     # get tax rates and description
     $query = qq|SELECT * FROM tax|;
@@ -1907,14 +2622,13 @@ sub create_links {
     }
 
     # now get the account numbers
-     $query = qq|SELECT c.accno, c.description, c.link, c.taxkey_id, tk.tax_id
-                 FROM chart c, taxkeys tk
-                 WHERE c.link LIKE ? 
-                   AND (    tk.chart_id = c.id OR     c.link LIKE '%_tax%') 
-                   AND (NOT tk.chart_id = c.id OR NOT c.link LIKE '%_tax%')
-                   AND (tk.id = (SELECT id FROM taxkeys WHERE taxkeys.chart_id = c.id AND startdate <= $transdate ORDER BY startdate DESC LIMIT 1)
-                     OR c.link LIKE '%_tax%')
-                 ORDER BY c.accno|;
+    $query = qq|SELECT c.accno, c.description, c.link, c.taxkey_id, tk.tax_id
+                FROM chart c
+                LEFT JOIN taxkeys tk ON (tk.chart_id = c.id)
+                WHERE c.link LIKE ?
+                  AND (tk.id = (SELECT id FROM taxkeys WHERE taxkeys.chart_id = c.id AND startdate <= $transdate ORDER BY startdate DESC LIMIT 1)
+                    OR c.link LIKE '%_tax%' OR c.taxkey_id IS NULL)
+                ORDER BY c.accno|;
 
     $sth = $dbh->prepare($query);
     do_statement($self, $sth, $query, "%$module%");
@@ -1923,7 +2637,7 @@ sub create_links {
     while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
 
       foreach my $key (split(/:/, $ref->{link})) {
-        if ($key =~ /$module/) {
+        if ($key =~ /\Q$module\E/) {
 
           # cross reference for keys
           $xkeyref{ $ref->{accno} } = $key;
@@ -2023,8 +2737,6 @@ sub create_links {
 
   }
 
-  $dbh->disconnect;
-
   $main::lxdebug->leave_sub();
 }
 
@@ -2072,7 +2784,7 @@ sub current_date {
 
   my ($self, $myconfig, $thisdate, $days) = @_;
 
-  my $dbh = $self->dbconnect($myconfig);
+  my $dbh = $self->get_standard_dbh($myconfig);
   my $query;
 
   $days *= 1;
@@ -2087,8 +2799,6 @@ sub current_date {
 
   ($thisdate) = selectrow_query($self, $dbh, $query);
 
-  $dbh->disconnect;
-
   $main::lxdebug->leave_sub();
 
   return $thisdate;
@@ -2117,8 +2827,7 @@ sub redo_rows {
 
   my @ndx = ();
 
-  map { push @ndx, { num => $new->[$_ - 1]->{runningnumber}, ndx => $_ } }
-    (1 .. $count);
+  map { push @ndx, { num => $new->[$_ - 1]->{runningnumber}, ndx => $_ } } 1 .. $count;
 
   my $i = 0;
 
@@ -2159,8 +2868,8 @@ sub update_status {
   }
   $sth->finish();
 
-  my $printed = ($self->{printed} =~ /$self->{formname}/) ? "1" : "0";
-  my $emailed = ($self->{emailed} =~ /$self->{formname}/) ? "1" : "0";
+  my $printed = ($self->{printed} =~ /\Q$self->{formname}\E/) ? "1" : "0";
+  my $emailed = ($self->{emailed} =~ /\Q$self->{formname}\E/) ? "1" : "0";
 
   my %queued = split / /, $self->{queued};
   my @values;
@@ -2204,7 +2913,7 @@ sub save_status {
   my $formnames  = $self->{printed};
   my $emailforms = $self->{emailed};
 
-  my $query = qq|DELETE FROM status
+  $query = qq|DELETE FROM status
                  WHERE (formname = ?) AND (trans_id = ?)|;
   do_query($self, $dbh, $query, $self->{formname}, $self->{id});
 
@@ -2215,15 +2924,15 @@ sub save_status {
     my %queued = split / /, $self->{queued};
 
     foreach my $formname (keys %queued) {
-      $printed = ($self->{printed} =~ /$self->{formname}/) ? "1" : "0";
-      $emailed = ($self->{emailed} =~ /$self->{formname}/) ? "1" : "0";
+      $printed = ($self->{printed} =~ /\Q$self->{formname}\E/) ? "1" : "0";
+      $emailed = ($self->{emailed} =~ /\Q$self->{formname}\E/) ? "1" : "0";
 
       $query = qq|INSERT INTO status (trans_id, printed, emailed, spoolfile, formname)
                   VALUES (?, ?, ?, ?, ?)|;
       do_query($self, $dbh, $query, $self->{id}, $printed, $emailed, $queued{$formname}, $formname);
 
-      $formnames  =~ s/$self->{formname}//;
-      $emailforms =~ s/$self->{formname}//;
+      $formnames  =~ s/\Q$self->{formname}\E//;
+      $emailforms =~ s/\Q$self->{formname}\E//;
 
     }
   }
@@ -2237,8 +2946,8 @@ sub save_status {
   map { $status{$_}{emailed} = 1 } split / +/, $emailforms;
 
   foreach my $formname (keys %status) {
-    $printed = ($formnames  =~ /$self->{formname}/) ? "1" : "0";
-    $emailed = ($emailforms =~ /$self->{formname}/) ? "1" : "0";
+    $printed = ($formnames  =~ /\Q$self->{formname}\E/) ? "1" : "0";
+    $emailed = ($emailforms =~ /\Q$self->{formname}\E/) ? "1" : "0";
 
     $query = qq|INSERT INTO status (trans_id, printed, emailed, formname)
                 VALUES (?, ?, ?, ?)|;
@@ -2261,6 +2970,7 @@ sub save_status {
 # $main::locale->text('PRINTED')
 # $main::locale->text('MAILED')
 # $main::locale->text('SCREENED')
+# $main::locale->text('CANCELED')
 # $main::locale->text('invoice')
 # $main::locale->text('proforma')
 # $main::locale->text('sales_order')
@@ -2282,10 +2992,10 @@ sub save_history {
   }
 
   my $query =
-    qq|INSERT INTO history_erp (trans_id, employee_id, addition, what_done) | .
-    qq|VALUES (?, ?, ?, ?)|;
-  my @values = (conv_i($self->{id}), conv_i($self->{employee_id}),
-                $self->{addition}, $self->{what_done});
+   qq|INSERT INTO history_erp (trans_id, employee_id, addition, what_done, snumbers) | .
+   qq|VALUES (?, (SELECT id FROM employee WHERE login = ?), ?, ?, ?)|;
+  my @values = (conv_i($self->{id}), $self->{login},
+                $self->{addition}, $self->{what_done}, "$self->{snumbers}");
   do_query($self, $dbh, $query, @values);
 
   $main::lxdebug->leave_sub();
@@ -2294,30 +3004,31 @@ sub save_history {
 sub get_history {
   $main::lxdebug->enter_sub();
 
-  my $self = shift();
-  my $dbh = shift();
-  my $trans_id = shift();
-  my $restriction = shift();
+  my ($self, $dbh, $trans_id, $restriction, $order) = @_;
+  my ($orderBy, $desc) = split(/\-\-/, $order);
+  $order = " ORDER BY " . ($order eq "" ? " h.itime " : ($desc == 1 ? $orderBy . " DESC " : $orderBy . " "));
   my @tempArray;
   my $i = 0;
   if ($trans_id ne "") {
     my $query =
-      qq|SELECT h.employee_id, h.itime::timestamp(0) AS itime, h.addition, h.what_done, emp.name | .
+      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 | .
       qq|FROM history_erp h | .
       qq|LEFT JOIN employee emp ON (emp.id = h.employee_id) | .
-      qq|WHERE trans_id = ? |
-      . $restriction;
-
+      qq|WHERE trans_id = | . $trans_id
+      . $restriction . qq| |
+      . $order;
+      
     my $sth = $dbh->prepare($query) || $self->dberror($query);
 
-    $sth->execute($trans_id) || $self->dberror("$query ($trans_id)");
+    $sth->execute() || $self->dberror("$query");
 
     while(my $hash_ref = $sth->fetchrow_hashref()) {
       $hash_ref->{addition} = $main::locale->text($hash_ref->{addition});
       $hash_ref->{what_done} = $main::locale->text($hash_ref->{what_done});
+      $hash_ref->{snumbers} =~ s/^.+_(.*)$/$1/g;
       $tempArray[$i++] = $hash_ref;
     }
-    $main::lxdebug->leave_sub() and return \@tempArray
+    $main::lxdebug->leave_sub() and return \@tempArray 
       if ($i > 0 && $tempArray[0] ne "");
   }
   $main::lxdebug->leave_sub();
@@ -2342,10 +3053,13 @@ sub update_defaults {
   my ($var) = $sth->fetchrow_array;
   $sth->finish;
 
-  if ($var =~ /^(.*?)(\d+)$/) {
-    $var = "$1" . ($2 + 1);
+  if ($var =~ m/\d+$/) {
+    my $new_var  = (substr $var, $-[0]) * 1 + 1;
+    my $len_diff = length($var) - $-[0] - length($new_var);
+    $var         = substr($var, 0, $-[0]) . ($len_diff > 0 ? '0' x $len_diff : '') . $new_var;
+
   } else {
-    $var++;
+    $var = $var . '1';
   }
 
   $query = qq|UPDATE defaults SET $fld = ?|;
@@ -2377,13 +3091,15 @@ sub update_business {
        WHERE id = ? FOR UPDATE|;
   my ($var) = selectrow_query($self, $dbh, $query, $business_id);
 
-  if ($var ne "") {
-    if ($var =~ /^(.*?)(\d+)$/) {
-      $var = "$1" . ($2 + 1);
-    } else {
-      $var++;
-    }
+  if ($var =~ m/\d+$/) {
+    my $new_var  = (substr $var, $-[0]) * 1 + 1;
+    my $len_diff = length($var) - $-[0] - length($new_var);
+    $var         = substr($var, 0, $-[0]) . ($len_diff > 0 ? '0' x $len_diff : '') . $new_var;
+
+  } else {
+    $var = $var . '1';
   }
+
   $query = qq|UPDATE business
               SET customernumberinit = ?
               WHERE id = ?|;
@@ -2404,7 +3120,7 @@ sub get_partsgroup {
 
   my ($self, $myconfig, $p) = @_;
 
-  my $dbh = $self->dbconnect($myconfig);
+  my $dbh = $self->get_standard_dbh($myconfig);
 
   my $query = qq|SELECT DISTINCT pg.id, pg.partsgroup
                  FROM partsgroup pg
@@ -2443,7 +3159,6 @@ sub get_partsgroup {
 
   $self->{all_partsgroup} = selectall_hashref_query($self, $dbh, $query, @values);
 
-  $dbh->disconnect;
   $main::lxdebug->leave_sub();
 }
 
@@ -2452,7 +3167,7 @@ sub get_pricegroup {
 
   my ($self, $myconfig, $p) = @_;
 
-  my $dbh = $self->dbconnect($myconfig);
+  my $dbh = $self->get_standard_dbh($myconfig);
 
   my $query = qq|SELECT p.id, p.pricegroup
                  FROM pricegroup p|;
@@ -2466,8 +3181,6 @@ sub get_pricegroup {
 
   $self->{all_pricegroup} = selectall_hashref_query($self, $dbh, $query);
 
-  $dbh->disconnect;
-
   $main::lxdebug->leave_sub();
 }
 
@@ -2480,11 +3193,7 @@ sub all_years {
 
   my ($self, $myconfig, $dbh) = @_;
 
-  my $disconnect = 0;
-  if (! $dbh) {
-    $dbh = $self->dbconnect($myconfig);
-    $disconnect = 1;
-  }
+  $dbh ||= $self->get_standard_dbh($myconfig);
 
   # get years
   my $query = qq|SELECT (SELECT MIN(transdate) FROM acc_trans),
@@ -2509,12 +3218,9 @@ sub all_years {
     push @all_years, $enddate--;
   }
 
-  $dbh->disconnect if $disconnect;
-
   return @all_years;
 
   $main::lxdebug->leave_sub();
 }
 
-
 1;