Merge branch 'master' of git@lx-office.linet-services.de:lx-office-erp
[kivitendo-erp.git] / SL / Form.pm
index 6ad6a92..6e7145f 100644 (file)
@@ -42,21 +42,29 @@ use Data::Dumper;
 use CGI;
 use CGI::Ajax;
 use Cwd;
+use Encode;
+use File::Copy;
 use IO::File;
 use SL::Auth;
 use SL::Auth::DB;
 use SL::Auth::LDAP;
 use SL::AM;
 use SL::Common;
+use SL::CVar;
+use SL::DB;
 use SL::DBUtils;
+use SL::DO;
+use SL::IC;
+use SL::IS;
 use SL::Mailer;
 use SL::Menu;
+use SL::OE;
 use SL::Template;
 use SL::User;
 use Template;
 use URI;
 use List::Util qw(first max min sum);
-use List::MoreUtils qw(any);
+use List::MoreUtils qw(all any apply);
 
 use strict;
 
@@ -254,7 +262,7 @@ sub new {
     $self->_request_to_hash($content);
   }
 
-  my $db_charset   = $main::dbcharset;
+  my $db_charset   = $::lx_office_conf{system}->{dbcharset};
   $db_charset    ||= Common::DEFAULT_CHARSET;
 
   my $encoding     = $self->{INPUT_ENCODING} || $db_charset;
@@ -262,10 +270,11 @@ sub new {
 
   _recode_recursively(SL::Iconv->new($encoding, $db_charset), $self);
 
-  $self->{action}  =  lc $self->{action};
-  $self->{action}  =~ s/( |-|,|\#)/_/g;
-
-  $self->{version} =  "2.6.1";
+  #$self->{version} =  "2.6.1";                 # Old hardcoded but secure style
+  open VERSION_FILE, "VERSION";                 # New but flexible code reads version from VERSION-file
+  $self->{version} =  <VERSION_FILE>;
+  close VERSION_FILE;
+  $self->{version}  =~ s/[^0-9A-Za-z\.\_\-]//g; # only allow numbers, letters, points, underscores and dashes. Prevents injecting of malicious code.
 
   $main::lxdebug->leave_sub();
 
@@ -375,7 +384,8 @@ sub escape {
 
   my ($self, $str) = @_;
 
-  $str =~ s/([^a-zA-Z0-9_.-])/sprintf("%%%02x", ord($1))/ge;
+  $str =  Encode::encode('utf-8-strict', $str) if $::locale->is_utf8;
+  $str =~ s/([^a-zA-Z0-9_.:-])/sprintf("%%%02x", ord($1))/ge;
 
   $main::lxdebug->leave_sub(2);
 
@@ -391,6 +401,7 @@ sub unescape {
   $str =~ s/\\$//;
 
   $str =~ s/%([0-9a-fA-Z]{2})/pack("c",hex($1))/eg;
+  $str =  Encode::decode('utf-8-strict', $str) if $::locale->is_utf8;
 
   $main::lxdebug->leave_sub(2);
 
@@ -438,13 +449,23 @@ sub hide_form {
   $main::lxdebug->leave_sub();
 }
 
+sub throw_on_error {
+  my ($self, $code) = @_;
+  local $self->{__ERROR_HANDLER} = sub { die({ error => $_[0] }) };
+  $code->();
+}
+
 sub error {
   $main::lxdebug->enter_sub();
 
   $main::lxdebug->show_backtrace();
 
   my ($self, $msg) = @_;
-  if ($ENV{HTTP_USER_AGENT}) {
+
+  if ($self->{__ERROR_HANDLER}) {
+    $self->{__ERROR_HANDLER}->($msg);
+
+  } elsif ($ENV{HTTP_USER_AGENT}) {
     $msg =~ s/\n/<br>/g;
     $self->show_generic_error($msg);
 
@@ -466,13 +487,22 @@ sub info {
 
     if (!$self->{header}) {
       $self->header;
-      print qq|
-      <body>|;
+      print qq|<body>|;
     }
 
     print qq|
+    <p class="message_ok"><b>$msg</b></p>
 
-    <p><b>$msg</b>
+    <script type="text/javascript">
+    <!--
+    // If JavaScript is enabled, the whole thing will be reloaded.
+    // The reason is: When one changes his menu setup (HTML / XUL / CSS ...)
+    // it now loads the correct code into the browser instead of do nothing.
+    setTimeout("top.frames.location.href='login.pl'",500);
+    //-->
+    </script>
+
+</body>
     |;
 
   } else {
@@ -579,20 +609,21 @@ sub create_http_response {
     pop @segments;
     $uri->path_segments(@segments);
 
-    my $session_cookie_value   = $main::auth->get_session_id();
-    $session_cookie_value    ||= 'NO_SESSION';
+    my $session_cookie_value = $main::auth->get_session_id();
 
-    $session_cookie = $cgi->cookie('-name'   => $main::auth->get_session_cookie_name(),
-                                   '-value'  => $session_cookie_value,
-                                   '-path'   => $uri->path,
-                                   '-secure' => $ENV{HTTPS});
+    if ($session_cookie_value) {
+      $session_cookie = $cgi->cookie('-name'   => $main::auth->get_session_cookie_name(),
+                                     '-value'  => $session_cookie_value,
+                                     '-path'   => $uri->path,
+                                     '-secure' => $ENV{HTTPS});
+    }
   }
 
   my %cgi_params = ('-type' => $params{content_type});
   $cgi_params{'-charset'} = $params{charset} if ($params{charset});
+  $cgi_params{'-cookie'}  = $session_cookie  if ($session_cookie);
 
-  my $output = $cgi->header('-cookie' => $session_cookie,
-                            %cgi_params);
+  my $output = $cgi->header(%cgi_params);
 
   $main::lxdebug->leave_sub();
 
@@ -601,107 +632,71 @@ sub create_http_response {
 
 
 sub header {
-  $main::lxdebug->enter_sub();
+  $::lxdebug->enter_sub;
 
-  # extra code ist currently only used by menuv3 and menuv4 to set their css.
+  # extra code is currently only used by menuv3 and menuv4 to set their css.
   # it is strongly deprecated, and will be changed in a future version.
   my ($self, $extra_code) = @_;
-
-  if ($self->{header}) {
-    $main::lxdebug->leave_sub();
-    return;
-  }
-
-  my ($stylesheet, $favicon, $pagelayout);
-
-  if ($ENV{HTTP_USER_AGENT}) {
-    my $doctype;
-
-    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};
-
-    if ($self->{favicon} && (-f "$self->{favicon}")) {
-      $favicon =
-        qq|<LINK REL="shortcut icon" HREF="$self->{favicon}" TYPE="image/x-icon">
-  |;
-    }
-
-    my $db_charset = $main::dbcharset ? $main::dbcharset : Common::DEFAULT_CHARSET;
-
-    if ($self->{landscape}) {
-      $pagelayout = qq|<style type="text/css">
-                        \@page { size:landscape; }
-                        </style>|;
-    }
-
-    my $fokus = qq|
+  my $db_charset = $::lx_office_conf{system}->{dbcharset} || Common::DEFAULT_CHARSET;
+  my @header;
+
+  $::lxdebug->leave_sub and return if !$ENV{HTTP_USER_AGENT} || $self->{header}++;
+
+  $self->{favicon} ||= "favicon.ico";
+  $self->{titlebar}  = "$self->{title} - $self->{titlebar}" if $self->{title};
+
+  # build includes
+  if ($self->{refresh_url} || $self->{refresh_time}) {
+    my $refresh_time = $self->{refresh_time} || 3;
+    my $refresh_url  = $self->{refresh_url}  || $ENV{REFERER};
+    push @header, "<meta http-equiv='refresh' content='$refresh_time;$refresh_url'>";
+  }
+
+  push @header, "<link rel='stylesheet' href='css/$_' type='text/css' title='Lx-Office stylesheet'>"
+    for grep { -f "css/$_" } apply { s|.*/|| } $self->{stylesheet}, $self->{stylesheets};
+
+  push @header, "<style type='text/css'>\@page { size:landscape; }</style>" if $self->{landscape};
+  push @header, "<link rel='shortcut icon' href='$self->{favicon}' type='image/x-icon'>" if -f $self->{favicon};
+  push @header, '<script type="text/javascript" src="js/jquery.js"></script>',
+                '<script type="text/javascript" src="js/common.js"></script>',
+                '<style type="text/css">@import url(js/jscalendar/calendar-win2k-1.css);</style>',
+                '<script type="text/javascript" src="js/jscalendar/calendar.js"></script>',
+                '<script type="text/javascript" src="js/jscalendar/lang/calendar-de.js"></script>',
+                '<script type="text/javascript" src="js/jscalendar/calendar-setup.js"></script>',
+                '<script type="text/javascript" src="js/part_selection.js"></script>';
+  push @header, $self->{javascript} if $self->{javascript};
+  push @header, map { $_->show_javascript } @{ $self->{AJAX} || [] };
+  push @header, "<script type='text/javascript'>function fokus(){ document.$self->{fokus}.focus(); }</script>" if $self->{fokus};
+  push @header, sprintf "<script type='text/javascript'>top.document.title='%s';</script>",
+    join ' - ', grep $_, $self->{title}, $self->{login}, $::myconfig{dbname}, $self->{version} if $self->{title};
+
+  # if there is a title, we put some JavaScript in to the page, wich writes a
+  # meaningful title-tag for our frameset.
+  my $title_hack = '';
+  if ($self->{title}) {
+    $title_hack = qq|
     <script type="text/javascript">
     <!--
-      function fokus() {
-        document.$self->{fokus}.focus();
-      }
+      // Write a meaningful title-tag for our frameset.
+      top.document.title="| . $self->{"title"} . qq| - | . $self->{"login"} . qq| - | . $::myconfig{dbname} . qq| - V| . $self->{"version"} . qq|";
     //-->
-    </script>
-    | if $self->{"fokus"};
-
-    #Set Calendar
-    my $jsscript = "";
-    if ($self->{jsscript} == 1) {
-
-      $jsscript = qq|
-        <script type="text/javascript" src="js/jquery.js"></script>
-        <script type="text/javascript" src="js/common.js"></script>
-        <style type="text/css">\@import url(js/jscalendar/calendar-win2k-1.css);</style>
-        <script type="text/javascript" src="js/jscalendar/calendar.js"></script>
-        <script type="text/javascript" src="js/jscalendar/lang/calendar-de.js"></script>
-        <script type="text/javascript" src="js/jscalendar/calendar-setup.js"></script>
-        $self->{javascript}
-       |;
-    }
-
-    $self->{titlebar} =
-      ($self->{title})
-      ? "$self->{title} - $self->{titlebar}"
-      : $self->{titlebar};
-    my $ajax = "";
-    for my $item (@ { $self->{AJAX} || [] }) {
-      $ajax .= $item->show_javascript();
-    }
+    </script>|;
+  }
 
-    print $self->create_http_response('content_type' => 'text/html',
-                                      'charset'      => $db_charset,);
-    print qq|${doctype}<html>
-<head>
-  <META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=${db_charset}">
+  # output
+  print $self->create_http_response(content_type => 'text/html', charset => $db_charset);
+  print "<!DOCTYPE HTML PUBLIC '-//W3C//DTD HTML 4.01//EN' 'http://www.w3.org/TR/html4/strict.dtd'>\n"
+    if  $ENV{'HTTP_USER_AGENT'} =~ m/MSIE\s+\d/; # Other browsers may choke on menu scripts with DOCTYPE.
+  print <<EOT;
+<html>
+ <head>
+  <meta http-equiv="Content-Type" content="text/html; charset=$db_charset">
   <title>$self->{titlebar}</title>
-  $stylesheet
-  $pagelayout
-  $favicon
-  $jsscript
-  $ajax
-
-  $fokus
-
+EOT
+  print "  $_\n" for @header;
+  print <<EOT;
   <link rel="stylesheet" href="css/jquery.autocomplete.css" type="text/css" />
-
   <meta name="robots" content="noindex,nofollow" />
-  <script type="text/javascript" src="js/highlight_input.js"></script>
-
   <link rel="stylesheet" type="text/css" href="css/tabcontent.css" />
   <script type="text/javascript" src="js/tabcontent.js">
 
@@ -712,15 +707,13 @@ sub header {
    ***********************************************/
 
   </script>
-
   $extra_code
-</head>
+  $title_hack
+ </head>
 
-|;
-  }
-  $self->{header} = 1;
+EOT
 
-  $main::lxdebug->leave_sub();
+  $::lxdebug->leave_sub;
 }
 
 sub ajax_response_header {
@@ -728,7 +721,7 @@ sub ajax_response_header {
 
   my ($self) = @_;
 
-  my $db_charset = $main::dbcharset ? $main::dbcharset : Common::DEFAULT_CHARSET;
+  my $db_charset = $::lx_office_conf{system}->{dbcharset} || Common::DEFAULT_CHARSET;
   my $cgi        = $main::cgi || CGI->new('');
   my $output     = $cgi->header('-charset' => $db_charset);
 
@@ -769,7 +762,7 @@ sub _prepare_html_template {
   my $language;
 
   if (!%::myconfig || !$::myconfig{"countrycode"}) {
-    $language = $main::language;
+    $language = $::lx_office_conf{system}->{language};
   } else {
     $language = $main::myconfig{"countrycode"};
   }
@@ -786,9 +779,8 @@ sub _prepare_html_template {
     $file = "templates/webpages/${file}.html";
 
   } else {
-    my $info = "Web page template '${file}' not found.\n" .
-      "Please re-run 'locales.pl' in 'locale/${language}'.";
-    print(qq|<pre>$info</pre>|);
+    my $info = "Web page template '${file}' not found.\n";
+    print qq|<pre>$info</pre>|;
     ::end_of_request();
   }
 
@@ -802,22 +794,25 @@ sub _prepare_html_template {
   }
 
   if (%main::myconfig) {
-    map({ $additional_params->{"myconfig_${_}"} = $main::myconfig{$_}; } keys(%main::myconfig));
-    my $jsc_dateformat = $main::myconfig{"dateformat"};
-    $jsc_dateformat =~ s/d+/\%d/gi;
-    $jsc_dateformat =~ s/m+/\%m/gi;
-    $jsc_dateformat =~ s/y+/\%Y/gi;
-    $additional_params->{"myconfig_jsc_dateformat"} = $jsc_dateformat;
+    $::myconfig{jsc_dateformat} = apply {
+      s/d+/\%d/gi;
+      s/m+/\%m/gi;
+      s/y+/\%Y/gi;
+    } $::myconfig{"dateformat"};
     $additional_params->{"myconfig"} ||= \%::myconfig;
+    map { $additional_params->{"myconfig_${_}"} = $main::myconfig{$_}; } keys %::myconfig;
   }
 
-  $additional_params->{"conf_dbcharset"}              = $main::dbcharset;
-  $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;
-  $additional_params->{"conf_vertreter"}              = $main::vertreter;
-  $additional_params->{"conf_show_best_before"}       = $main::show_best_before;
+  $additional_params->{"conf_dbcharset"}              = $::lx_office_conf{system}->{dbcharset};
+  $additional_params->{"conf_webdav"}                 = $::lx_office_conf{system}->{webdav};
+  $additional_params->{"conf_lizenzen"}               = $::lx_office_conf{system}->{lizenzen};
+  $additional_params->{"conf_latex_templates"}        = $::lx_office_conf{print_templates}->{latex};
+  $additional_params->{"conf_opendocument_templates"} = $::lx_office_conf{print_templates}->{opendocument};
+  $additional_params->{"conf_vertreter"}              = $::lx_office_conf{system}->{vertreter};
+  $additional_params->{"conf_show_best_before"}       = $::lx_office_conf{system}->{show_best_before};
+  $additional_params->{"conf_parts_image_css"}        = $::lx_office_conf{features}->{parts_image_css};
+  $additional_params->{"conf_parts_listing_images"}   = $::lx_office_conf{features}->{parts_listing_images};
+  $additional_params->{"conf_parts_show_image"}       = $::lx_office_conf{features}->{parts_show_image};
 
   if (%main::debug_options) {
     map { $additional_params->{'DEBUG_' . uc($_)} = $main::debug_options{$_} } keys %main::debug_options;
@@ -867,7 +862,7 @@ sub init_template {
      'PLUGIN_BASE'  => 'SL::Template::Plugin',
      'INCLUDE_PATH' => '.:templates/webpages',
      'COMPILE_EXT'  => '.tcc',
-     'COMPILE_DIR'  => $::userspath . '/templates-cache',
+     'COMPILE_DIR'  => $::lx_office_conf{paths}->{userspath} . '/templates-cache',
   })) || die;
 }
 
@@ -882,6 +877,12 @@ sub show_generic_error {
 
   my ($self, $error, %params) = @_;
 
+  if ($self->{__ERROR_HANDLER}) {
+    $self->{__ERROR_HANDLER}->($error);
+    $main::lxdebug->leave_sub();
+    return;
+  }
+
   my $add_params = {
     'title_error' => $params{title},
     'label_error' => $error,
@@ -1191,11 +1192,13 @@ sub round_amount {
 sub parse_template {
   $main::lxdebug->enter_sub();
 
-  my ($self, $myconfig, $userspath) = @_;
+  my ($self, $myconfig) = @_;
   my $out;
 
   local (*IN, *OUT);
 
+  my $userspath = $::lx_office_conf{paths}->{userspath};
+
   $self->{"cwd"} = getcwd();
   $self->{"tmpdir"} = $self->{cwd} . "/${userspath}";
 
@@ -1220,7 +1223,7 @@ sub parse_template {
     $ext_for_format = 'xml';
 
   } elsif ( $self->{"format"} =~ /elster(?:winston|taxbird)/i ) {
-    $template_type = 'xml';
+    $template_type = 'XML';
 
   } elsif ( $self->{"format"} =~ /excel/i ) {
     $template_type  = 'Excel';
@@ -1250,6 +1253,7 @@ sub parse_template {
   }
 
   map { $self->{"${_}"} = $myconfig->{$_}; } qw(co_ustid);
+  map { $self->{"myconfig_${_}"} = $myconfig->{$_} } grep { $_ ne 'dbpasswd' } keys %{ $myconfig };
 
   $self->{copies} = 1 if (($self->{copies} *= 1) <= 0);
 
@@ -1291,6 +1295,16 @@ sub parse_template {
     $self->error("$self->{IN} : " . $template->get_error());
   }
 
+  if ($self->{media} eq 'file') {
+    copy(join('/', $self->{cwd}, $userspath, $self->{tmpfile}), $out =~ m|^/| ? $out : join('/', $self->{cwd}, $out)) if $template->uses_temp_file;
+    $self->cleanup;
+    chdir("$self->{cwd}");
+
+    $::lxdebug->leave_sub();
+
+    return;
+  }
+
   if ($template->uses_temp_file() || $self->{media} eq 'email') {
 
     if ($self->{media} eq 'email') {
@@ -1299,7 +1313,7 @@ sub parse_template {
 
       map { $mail->{$_} = $self->{$_} }
         qw(cc bcc subject message version format);
-      $mail->{charset} = $main::dbcharset ? $main::dbcharset : Common::DEFAULT_CHARSET;
+      $mail->{charset} = $::lx_office_conf{system}->{dbcharset} || Common::DEFAULT_CHARSET;
       $mail->{to} = $self->{EMAIL_RECIPIENT} ? $self->{EMAIL_RECIPIENT} : $self->{email};
       $mail->{from}   = qq|"$myconfig->{name}" <$myconfig->{email}>|;
       $mail->{fileid} = "$fileid.";
@@ -1346,6 +1360,7 @@ sub parse_template {
       my $numbytes = (-s $self->{tmpfile});
       open(IN, $self->{tmpfile})
         or $self->error($self->cleanup . "$self->{tmpfile} : $!");
+      binmode IN;
 
       $self->{copies} = 1 unless $self->{media} eq 'printer';
 
@@ -1396,7 +1411,6 @@ sub get_formname_translation {
     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'),
@@ -1404,7 +1418,6 @@ sub get_formname_translation {
     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'),
     dunning                 => $main::locale->text('Dunning'),
@@ -1496,7 +1509,7 @@ sub cleanup {
     close(FH);
   }
 
-  if ($self->{tmpfile} && ! $::keep_temp_files) {
+  if ($self->{tmpfile} && !($::lx_office_conf{debug} && $::lx_office_conf{debug}->{keep_temp_files})) {
     $self->{tmpfile} =~ s|.*/||g;
     # strip extension
     $self->{tmpfile} =~ s/\.\w+$//g;
@@ -1547,15 +1560,21 @@ sub datetonum {
 
 # Database routines used throughout
 
+sub _dbconnect_options {
+  my $self    = shift;
+  my $options = { pg_enable_utf8 => $::locale->is_utf8,
+                  @_ };
+
+  return $options;
+}
+
 sub dbconnect {
   $main::lxdebug->enter_sub(2);
 
   my ($self, $myconfig) = @_;
 
   # connect to database
-  my $dbh =
-    DBI->connect($myconfig->{dbconnect},
-                 $myconfig->{dbuser}, $myconfig->{dbpasswd})
+  my $dbh = DBI->connect($myconfig->{dbconnect}, $myconfig->{dbuser}, $myconfig->{dbpasswd}, $self->_dbconnect_options)
     or $self->dberror;
 
   # set db options
@@ -1574,9 +1593,7 @@ sub dbconnect_noauto {
   my ($self, $myconfig) = @_;
 
   # connect to database
-  my $dbh =
-    DBI->connect($myconfig->{dbconnect}, $myconfig->{dbuser},
-                 $myconfig->{dbpasswd}, { AutoCommit => 0 })
+  my $dbh = DBI->connect($myconfig->{dbconnect}, $myconfig->{dbuser}, $myconfig->{dbpasswd}, $self->_dbconnect_options(AutoCommit => 0))
     or $self->dberror;
 
   # set db options
@@ -1988,7 +2005,7 @@ sub add_shipto {
   my @values;
 
   foreach my $item (qw(name department_1 department_2 street zipcode city country
-                       contact phone fax email)) {
+                       contact cp_gender phone fax email)) {
     if ($self->{"shipto$item"}) {
       $shipto = 1 if ($self->{$item} ne $self->{"shipto$item"});
     }
@@ -2006,6 +2023,7 @@ sub add_shipto {
                        shiptocity = ?,
                        shiptocountry = ?,
                        shiptocontact = ?,
+                       shiptocp_gender = ?,
                        shiptophone = ?,
                        shiptofax = ?,
                        shiptoemail = ?
@@ -2021,6 +2039,7 @@ sub add_shipto {
                        shiptocity = ? AND
                        shiptocountry = ? AND
                        shiptocontact = ? AND
+                       shiptocp_gender = ? AND
                        shiptophone = ? AND
                        shiptofax = ? AND
                        shiptoemail = ? AND
@@ -2031,8 +2050,8 @@ sub add_shipto {
         $query =
           qq|INSERT INTO shipto (trans_id, shiptoname, shiptodepartment_1, shiptodepartment_2,
                                  shiptostreet, shiptozipcode, shiptocity, shiptocountry,
-                                 shiptocontact, shiptophone, shiptofax, shiptoemail, module)
-             VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)|;
+                                 shiptocontact, shiptocp_gender, shiptophone, shiptofax, shiptoemail, module)
+             VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)|;
         do_query($self, $dbh, $query, $id, @values, $module);
       }
     }
@@ -3241,7 +3260,6 @@ sub save_status {
 # $main::locale->text('invoice')
 # $main::locale->text('proforma')
 # $main::locale->text('sales_order')
-# $main::locale->text('packing_list')
 # $main::locale->text('pick_list')
 # $main::locale->text('purchase_order')
 # $main::locale->text('bin_list')
@@ -3515,6 +3533,163 @@ sub restore_vars {
   $main::lxdebug->leave_sub();
 }
 
+sub prepare_for_printing {
+  my ($self) = @_;
+
+  $self->{templates} ||= $::myconfig{templates};
+  $self->{formname}  ||= $self->{type};
+  $self->{media}     ||= 'email';
+
+  die "'media' other than 'email', 'file', 'printer' is not supported yet" unless $self->{media} =~ m/^(?:email|file|printer)$/;
+
+  # set shipto from billto unless set
+  my $has_shipto = any { $self->{"shipto$_"} } qw(name street zipcode city country contact);
+  if (!$has_shipto && ($self->{type} =~ m/^(?:purchase_order|request_quotation)$/)) {
+    $self->{shiptoname}   = $::myconfig{company};
+    $self->{shiptostreet} = $::myconfig{address};
+  }
+
+  my $language = $self->{language} ? '_' . $self->{language} : '';
+
+  my ($language_tc, $output_numberformat, $output_dateformat, $output_longdates);
+  if ($self->{language_id}) {
+    ($language_tc, $output_numberformat, $output_dateformat, $output_longdates) = AM->get_language_details(\%::myconfig, $self, $self->{language_id});
+  } else {
+    $output_dateformat   = $::myconfig{dateformat};
+    $output_numberformat = $::myconfig{numberformat};
+    $output_longdates    = 1;
+  }
+
+  # Retrieve accounts for tax calculation.
+  IC->retrieve_accounts(\%::myconfig, $self, map { $_ => $self->{"id_$_"} } 1 .. $self->{rowcount});
+
+  if ($self->{type} =~ /_delivery_order$/) {
+    DO->order_details();
+  } elsif ($self->{type} =~ /sales_order|sales_quotation|request_quotation|purchase_order/) {
+    OE->order_details(\%::myconfig, $self);
+  } else {
+    IS->invoice_details(\%::myconfig, $self, $::locale);
+  }
+
+  # Chose extension & set source file name
+  my $extension = 'html';
+  if ($self->{format} eq 'postscript') {
+    $self->{postscript}   = 1;
+    $extension            = 'tex';
+  } elsif ($self->{"format"} =~ /pdf/) {
+    $self->{pdf}          = 1;
+    $extension            = $self->{'format'} =~ m/opendocument/i ? 'odt' : 'tex';
+  } elsif ($self->{"format"} =~ /opendocument/) {
+    $self->{opendocument} = 1;
+    $extension            = 'odt';
+  } elsif ($self->{"format"} =~ /excel/) {
+    $self->{excel}        = 1;
+    $extension            = 'xls';
+  }
+
+  my $printer_code    = '_' . $self->{printer_code} if $self->{printer_code};
+  my $email_extension = '_email' if -f "$self->{templates}/$self->{formname}_email${language}${printer_code}.${extension}";
+  $self->{IN}         = "$self->{formname}${email_extension}${language}${printer_code}.${extension}";
+
+  # Format dates.
+  $self->format_dates($output_dateformat, $output_longdates,
+                      qw(invdate orddate quodate pldate duedate reqdate transdate shippingdate deliverydate validitydate paymentdate datepaid
+                         transdate_oe deliverydate_oe employee_startdate employee_enddate),
+                      grep({ /^(?:datepaid|transdate_oe|reqdate|deliverydate|deliverydate_oe|transdate)_\d+$/ } keys(%{$self})));
+
+  $self->reformat_numbers($output_numberformat, 2,
+                          qw(invtotal ordtotal quototal subtotal linetotal listprice sellprice netprice discount tax taxbase total paid),
+                          grep({ /^(?:linetotal|listprice|sellprice|netprice|taxbase|discount|paid|subtotal|total|tax)_\d+$/ } keys(%{$self})));
+
+  $self->reformat_numbers($output_numberformat, undef, qw(qty price_factor), grep({ /^qty_\d+$/} keys(%{$self})));
+
+  my ($cvar_date_fields, $cvar_number_fields) = CVar->get_field_format_list('module' => 'CT', 'prefix' => 'vc_');
+
+  if (scalar @{ $cvar_date_fields }) {
+    $self->format_dates($output_dateformat, $output_longdates, @{ $cvar_date_fields });
+  }
+
+  while (my ($precision, $field_list) = each %{ $cvar_number_fields }) {
+    $self->reformat_numbers($output_numberformat, $precision, @{ $field_list });
+  }
+
+  return $self;
+}
+
+sub format_dates {
+  my ($self, $dateformat, $longformat, @indices) = @_;
+
+  $dateformat ||= $::myconfig{dateformat};
+
+  foreach my $idx (@indices) {
+    if ($self->{TEMPLATE_ARRAYS} && (ref($self->{TEMPLATE_ARRAYS}->{$idx}) eq "ARRAY")) {
+      for (my $i = 0; $i < scalar(@{ $self->{TEMPLATE_ARRAYS}->{$idx} }); $i++) {
+        $self->{TEMPLATE_ARRAYS}->{$idx}->[$i] = $::locale->reformat_date(\%::myconfig, $self->{TEMPLATE_ARRAYS}->{$idx}->[$i], $dateformat, $longformat);
+      }
+    }
+
+    next unless defined $self->{$idx};
+
+    if (!ref($self->{$idx})) {
+      $self->{$idx} = $::locale->reformat_date(\%::myconfig, $self->{$idx}, $dateformat, $longformat);
+
+    } elsif (ref($self->{$idx}) eq "ARRAY") {
+      for (my $i = 0; $i < scalar(@{ $self->{$idx} }); $i++) {
+        $self->{$idx}->[$i] = $::locale->reformat_date(\%::myconfig, $self->{$idx}->[$i], $dateformat, $longformat);
+      }
+    }
+  }
+}
+
+sub reformat_numbers {
+  my ($self, $numberformat, $places, @indices) = @_;
+
+  return if !$numberformat || ($numberformat eq $::myconfig{numberformat});
+
+  foreach my $idx (@indices) {
+    if ($self->{TEMPLATE_ARRAYS} && (ref($self->{TEMPLATE_ARRAYS}->{$idx}) eq "ARRAY")) {
+      for (my $i = 0; $i < scalar(@{ $self->{TEMPLATE_ARRAYS}->{$idx} }); $i++) {
+        $self->{TEMPLATE_ARRAYS}->{$idx}->[$i] = $self->parse_amount(\%::myconfig, $self->{TEMPLATE_ARRAYS}->{$idx}->[$i]);
+      }
+    }
+
+    next unless defined $self->{$idx};
+
+    if (!ref($self->{$idx})) {
+      $self->{$idx} = $self->parse_amount(\%::myconfig, $self->{$idx});
+
+    } elsif (ref($self->{$idx}) eq "ARRAY") {
+      for (my $i = 0; $i < scalar(@{ $self->{$idx} }); $i++) {
+        $self->{$idx}->[$i] = $self->parse_amount(\%::myconfig, $self->{$idx}->[$i]);
+      }
+    }
+  }
+
+  my $saved_numberformat    = $::myconfig{numberformat};
+  $::myconfig{numberformat} = $numberformat;
+
+  foreach my $idx (@indices) {
+    if ($self->{TEMPLATE_ARRAYS} && (ref($self->{TEMPLATE_ARRAYS}->{$idx}) eq "ARRAY")) {
+      for (my $i = 0; $i < scalar(@{ $self->{TEMPLATE_ARRAYS}->{$idx} }); $i++) {
+        $self->{TEMPLATE_ARRAYS}->{$idx}->[$i] = $self->format_amount(\%::myconfig, $self->{TEMPLATE_ARRAYS}->{$idx}->[$i], $places);
+      }
+    }
+
+    next unless defined $self->{$idx};
+
+    if (!ref($self->{$idx})) {
+      $self->{$idx} = $self->format_amount(\%::myconfig, $self->{$idx}, $places);
+
+    } elsif (ref($self->{$idx}) eq "ARRAY") {
+      for (my $i = 0; $i < scalar(@{ $self->{$idx} }); $i++) {
+        $self->{$idx}->[$i] = $self->format_amount(\%::myconfig, $self->{$idx}->[$i], $places);
+      }
+    }
+  }
+
+  $::myconfig{numberformat} = $saved_numberformat;
+}
+
 1;
 
 __END__
@@ -3534,9 +3709,7 @@ Points of interest for a beginner are:
 
 =head1 SPECIAL FUNCTIONS
 
-=over 4
-
-=item _store_value()
+=head2 C<_store_value()>
 
 parses a complex var name, and stores it in the form.
 
@@ -3591,7 +3764,7 @@ supported key structures are:
 
   filter.status[]  => $form->{status}->[ val1, val2, ... ]
 
-=item update_business PARAMS
+=head2 C<update_business> PARAMS
 
 PARAMS (not named):
  \%config,     - config hashref
@@ -3603,7 +3776,7 @@ handles business (thats customer/vendor types) sequences.
 special behaviour for empty strings in customerinitnumber field:
 will in this case not increase the value, and return undef.
 
-=item redirect_header $url
+=head2 C<redirect_header> $url
 
 Generates a HTTP redirection header for the new C<$url>. Constructs an
 absolute URL including scheme, host name and port. If C<$url> is a
@@ -3617,6 +3790,45 @@ Examples:
   print $::form->redirect_header('oe.pl?action=edit&id=1234');
   print $::form->redirect_header('http://www.lx-office.org/');
 
+=head2 C<header>
+
+Generates a general purpose http/html header and includes most of the scripts
+ans stylesheets needed.
+
+Only one header will be generated. If the method was already called in this
+request it will not output anything and return undef. Also if no
+HTTP_USER_AGENT is found, no header is generated.
+
+Although header does not accept parameters itself, it will honor special
+hashkeys of its Form instance:
+
+=over 4
+
+=item refresh_time
+
+=item refresh_url
+
+If one of these is set, a http-equiv refresh is generated. Missing parameters
+default to 3 seconds and the refering url.
+
+=item stylesheet
+
+=item stylesheets
+
+If these are arrayrefs the contents will be inlined into the header.
+
+=item landscape
+
+If true, a css snippet will be generated that sets the page in landscape mode.
+
+=item favicon
+
+Used to override the default favicon.
+
+=item title
+
+A html page title will be generated from this
+
 =back
 
 =cut