1 #====================================================================
 
   4 # Based on SQL-Ledger Version 2.1.9
 
   5 # Web http://www.lx-office.org
 
   7 #=====================================================================
 
   8 # SQL-Ledger Accounting
 
   9 # Copyright (C) 1998-2002
 
  11 #  Author: Dieter Simader
 
  12 #   Email: dsimader@sql-ledger.org
 
  13 #     Web: http://www.sql-ledger.org
 
  15 # Contributors: Thomas Bayen <bayen@gmx.de>
 
  16 #               Antti Kaihola <akaihola@siba.fi>
 
  17 #               Moritz Bunkus (tex code)
 
  19 # This program is free software; you can redistribute it and/or modify
 
  20 # it under the terms of the GNU General Public License as published by
 
  21 # the Free Software Foundation; either version 2 of the License, or
 
  22 # (at your option) any later version.
 
  24 # This program is distributed in the hope that it will be useful,
 
  25 # but WITHOUT ANY WARRANTY; without even the implied warranty of
 
  26 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
  27 # GNU General Public License for more details.
 
  28 # You should have received a copy of the GNU General Public License
 
  29 # along with this program; if not, write to the Free Software
 
  30 # Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 
  31 #======================================================================
 
  32 # Utilities for parsing forms
 
  33 # and supporting routines for linking account numbers
 
  34 # used in AR, AP and IS, IR modules
 
  36 #======================================================================
 
  44   $main::lxdebug->enter_sub(2);
 
  48   my @pairs = split(/&/, $input);
 
  51     my ($name, $value) = split(/=/, $_, 2);
 
  52     $in{$name} = unescape(undef, $value);
 
  55   $main::lxdebug->leave_sub(2);
 
  60 sub _request_to_hash {
 
  61   $main::lxdebug->enter_sub(2);
 
  64   my ($i,        $loc,  $key,    $val);
 
  65   my (%ATTACH,   $f,    $header, $header_body, $len, $buf);
 
  66   my ($boundary, @list, $size,   $body, $x, $blah, $name);
 
  68   if ($ENV{'CONTENT_TYPE'}
 
  69       && ($ENV{'CONTENT_TYPE'} =~ /multipart\/form-data; boundary=(.+)$/)) {
 
  70     $boundary = quotemeta('--' . $1);
 
  71     @list     = split(/$boundary/, $input);
 
  73     # For some reason there are always 2 extra, that are empty
 
  76     for ($x = 1; $x <= $size; $x++) {
 
  77       $header_body = $list[$x];
 
  78       $header_body =~ /\r\n\r\n|\n\n/;
 
  80       # Here we split the header and body
 
  85       # Now we try to get the file name
 
  87       $name =~ /name=\"(.+)\"/;
 
  88       ($name, $blah) = split(/\"/, $1);
 
  90       # If the form name is not attach, then we need to parse this like
 
  92       if ($name ne "attach") {
 
  93         $body =~ s/%([0-9a-fA-Z]{2})/pack("c",hex($1))/eg;
 
  94         $ATTACH{$name} = $body;
 
  96         # Otherwise it is an attachment and we need to finish it up
 
  97       } elsif ($name eq "attach") {
 
  98         $header =~ /filename=\"(.+)\"/;
 
  99         $ATTACH{'FILE_NAME'} = $1;
 
 100         $ATTACH{'FILE_NAME'} =~ s/\"//g;
 
 101         $ATTACH{'FILE_NAME'} =~ s/\s//g;
 
 102         $ATTACH{'FILE_CONTENT'} = $body;
 
 104         for ($i = $x; $list[$i]; $i++) {
 
 105           $list[$i] =~ s/^.+name=$//;
 
 106           $list[$i] =~ /\"(\w+)\"/;
 
 112     $main::lxdebug->leave_sub(2);
 
 116     $main::lxdebug->leave_sub(2);
 
 117     return _input_to_hash($input);
 
 122   $main::lxdebug->enter_sub();
 
 128   read(STDIN, $_, $ENV{CONTENT_LENGTH});
 
 130   if ($ENV{QUERY_STRING}) {
 
 131     $_ = $ENV{QUERY_STRING};
 
 138   my %parameters = _request_to_hash($_);
 
 139   map({ $self->{$_} = $parameters{$_}; } keys(%parameters));
 
 141   $self->{menubar} = 1 if $self->{path} =~ /lynx/i;
 
 143   $self->{action} = lc $self->{action};
 
 144   $self->{action} =~ s/( |-|,|#)/_/g;
 
 146   $self->{version}   = "2.3.0";
 
 148   $main::lxdebug->leave_sub();
 
 154   $main::lxdebug->enter_sub();
 
 160   map { print "$_ = $self->{$_}\n" } (sort keys %{$self});
 
 162   $main::lxdebug->leave_sub();
 
 166   $main::lxdebug->enter_sub(2);
 
 168   my ($self, $str, $beenthere) = @_;
 
 170   # for Apache 2 we escape strings twice
 
 171   #if (($ENV{SERVER_SOFTWARE} =~ /Apache\/2/) && !$beenthere) {
 
 172   #  $str = $self->escape($str, 1);
 
 175   $str =~ s/([^a-zA-Z0-9_.-])/sprintf("%%%02x", ord($1))/ge;
 
 177   $main::lxdebug->leave_sub(2);
 
 183   $main::lxdebug->enter_sub(2);
 
 185   my ($self, $str) = @_;
 
 190   $str =~ s/%([0-9a-fA-Z]{2})/pack("c",hex($1))/eg;
 
 192   $main::lxdebug->leave_sub(2);
 
 198   my ($self, $str) = @_;
 
 200   if ($str && !ref($str)) {
 
 201     $str =~ s/\"/"/g;
 
 209   my ($self, $str) = @_;
 
 211   if ($str && !ref($str)) {
 
 212     $str =~ s/"/\"/g;
 
 224       print qq|<input type=hidden name="$_" value="|
 
 225         . $self->quote($self->{$_})
 
 229     delete $self->{header};
 
 230     for (sort keys %$self) {
 
 231       print qq|<input type=hidden name="$_" value="|
 
 232         . $self->quote($self->{$_})
 
 240   $main::lxdebug->enter_sub();
 
 242   my ($self, $msg) = @_;
 
 244   if ($ENV{HTTP_USER_AGENT}) {
 
 246     $self->show_generic_error($msg);
 
 250     if ($self->{error_function}) {
 
 251       &{ $self->{error_function} }($msg);
 
 257   $main::lxdebug->leave_sub();
 
 261   $main::lxdebug->enter_sub();
 
 263   my ($self, $msg) = @_;
 
 265   if ($ENV{HTTP_USER_AGENT}) {
 
 268     if (!$self->{header}) {
 
 281     if ($self->{info_function}) {
 
 282       &{ $self->{info_function} }($msg);
 
 288   $main::lxdebug->leave_sub();
 
 292   $main::lxdebug->enter_sub();
 
 294   my ($self, $str, $cols, $maxrows) = @_;
 
 298   map { $rows += int(((length) - 2) / $cols) + 1 } split /\r/, $str;
 
 300   $maxrows = $rows unless defined $maxrows;
 
 302   $main::lxdebug->leave_sub();
 
 304   return ($rows > $maxrows) ? $maxrows : $rows;
 
 308   $main::lxdebug->enter_sub();
 
 310   my ($self, $msg) = @_;
 
 312   $self->error("$msg\n" . $DBI::errstr);
 
 314   $main::lxdebug->leave_sub();
 
 318   $main::lxdebug->enter_sub();
 
 320   my ($self, $name, $msg) = @_;
 
 322   if ($self->{$name} =~ /^\s*$/) {
 
 325   $main::lxdebug->leave_sub();
 
 329   $main::lxdebug->enter_sub();
 
 333   if ($self->{header}) {
 
 334     $main::lxdebug->leave_sub();
 
 338   my ($stylesheet, $favicon, $charset);
 
 340   if ($ENV{HTTP_USER_AGENT}) {
 
 342     if ($self->{stylesheet} && (-f "css/$self->{stylesheet}")) {
 
 344         qq|<LINK REL="stylesheet" HREF="css/$self->{stylesheet}" TYPE="text/css" TITLE="Lx-Office stylesheet">
 
 348     if ($self->{favicon} && (-f "$self->{favicon}")) {
 
 350         qq|<LINK REL="shortcut icon" HREF="$self->{favicon}" TYPE="image/x-icon">
 
 354     if ($self->{charset}) {
 
 356         qq|<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=$self->{charset}">
 
 359     if ($self->{landscape}) {
 
 360       $pagelayout = qq|<style type="text/css">
 
 361                         \@page { size:landscape; }
 
 364     if ($self->{fokus}) {
 
 365       $fokus = qq|<script type="text/javascript">
 
 367 function fokus(){document.$self->{fokus}.focus();}
 
 374     if ($self->{jsscript} == 1) {
 
 377         <style type="text/css">\@import url(js/jscalendar/calendar-win2k-1.css);</style>
 
 378         <script type="text/javascript" src="js/jscalendar/calendar.js"></script>
 
 379         <script type="text/javascript" src="js/jscalendar/lang/calendar-de.js"></script>
 
 380         <script type="text/javascript" src="js/jscalendar/calendar-setup.js"></script>
 
 387       ? "$self->{title} - $self->{titlebar}"
 
 390     print qq|Content-Type: text/html
 
 394   <title>$self->{titlebar}</title>
 
 407   $main::lxdebug->leave_sub();
 
 410 sub parse_html_template {
 
 411   $main::lxdebug->enter_sub();
 
 413   my ($self, $file, $additional_params) = @_;
 
 416   if (!defined($main::myconfig) || !defined($main::myconfig{"countrycode"})) {
 
 417     $language = $main::language;
 
 419     $language = $main::myconfig{"countrycode"};
 
 422   if (-f "templates/webpages/${file}_${language}.html") {
 
 423     if ((-f ".developer") &&
 
 424         (-f "templates/webpages/${file}_master.html") &&
 
 425         ((stat("templates/webpages/${file}_master.html"))[9] >
 
 426          (stat("templates/webpages/${file}_${language}.html"))[9])) {
 
 427       my $info = "Developper information: templates/webpages/${file}_master.html is newer than the localized version.\n" .
 
 428         "Please re-run 'locales.pl' in 'locale/${language}'.";
 
 429       print(qq|<pre>$info</pre>|);
 
 433     $file = "templates/webpages/${file}_${language}.html";
 
 434   } elsif (-f "templates/webpages/${file}.html") {
 
 435     $file = "templates/webpages/${file}.html";
 
 437     my $info = "Web page template '${file}' not found.\n" .
 
 438       "Please re-run 'locales.pl' in 'locale/${language}'.";
 
 439     print(qq|<pre>$info</pre>|);
 
 443   my $template = HTML::Template->new("filename" => $file,
 
 444                                      "die_on_bad_params" => 0,
 
 446                                      "case_sensitive" => 1,
 
 447                                      "loop_context_vars" => 1,
 
 450   $additional_params = {} unless ($additional_params);
 
 451   if ($self->{"DEBUG"}) {
 
 452     $additional_params->{"DEBUG"} = $self->{"DEBUG"};
 
 455   if ($additional_params->{"DEBUG"}) {
 
 456     $additional_params->{"DEBUG"} =
 
 457       "<br><em>DEBUG INFORMATION:</em><pre>" . $additional_params->{"DEBUG"} . "</pre>";
 
 460   if (%main::myconfig) {
 
 461     map({ $additional_params->{"myconfig_${_}"} = $main::myconfig{$_}; } keys(%main::myconfig));
 
 462     my $jsc_dateformat = $main::myconfig{"dateformat"};
 
 463     $jsc_dateformat =~ s/d+/\%d/gi;
 
 464     $jsc_dateformat =~ s/m+/\%m/gi;
 
 465     $jsc_dateformat =~ s/y+/\%Y/gi;
 
 466     $additional_params->{"myconfig_jsc_dateformat"} = $jsc_dateformat;
 
 469   $additional_params->{"conf_jscalendar"} = $main::jscalendar;
 
 470   $additional_params->{"conf_lizenzen"} = $main::lizenzen;
 
 471   $additional_params->{"conf_latex_templates"} = $main::latex;
 
 472   $additional_params->{"conf_opendocument_templates"} = $main::opendocument_templates;
 
 475   if (-f $self->{"login"} . "_menu.ini") {
 
 476     $menu = Menu->new($self->{"login"} . "_menu.ini");
 
 478     $menu = Menu->new("menu.ini");
 
 480   $menu->generate_acl("", $additional_params);
 
 482   my @additional_param_names = keys(%{$additional_params});
 
 484   foreach my $key ($template->param()) {
 
 485     if (grep(/^${key}$/, @additional_param_names)) {
 
 486       $template->param($key => $additional_params->{$key});
 
 488       $template->param($key => $self->{$key});
 
 492   my $output = $template->output();
 
 494   $main::lxdebug->leave_sub();
 
 499 sub show_generic_error {
 
 500   my ($self, $error, $title) = @_;
 
 503   $add_params->{"title"} = $title if ($title);
 
 504   $self->{"label_error"} = $error;
 
 507   print($self->parse_html_template("generic/error", $add_params));
 
 509   die("Error: $error\n");
 
 512 sub show_generic_information {
 
 513   my ($self, $error, $title) = @_;
 
 516   $add_params->{"title"} = $title if ($title);
 
 517   $self->{"label_information"} = $error;
 
 520   print($self->parse_html_template("generic/information", $add_params));
 
 522   die("Information: $error\n");
 
 525 # write Trigger JavaScript-Code ($qty = quantity of Triggers)
 
 526 # changed it to accept an arbitrary number of triggers - sschoeling
 
 528   $main::lxdebug->enter_sub();
 
 531   my $myconfig = shift;
 
 534   # set dateform for jsscript
 
 536   $ifFormat = "%d.%m.%Y";
 
 537   if ($myconfig->{dateformat} eq "dd.mm.yy") {
 
 538     $ifFormat = "%d.%m.%Y";
 
 540     if ($myconfig->{dateformat} eq "dd-mm-yy") {
 
 541       $ifFormat = "%d-%m-%Y";
 
 543       if ($myconfig->{dateformat} eq "dd/mm/yy") {
 
 544         $ifFormat = "%d/%m/%Y";
 
 546         if ($myconfig->{dateformat} eq "mm/dd/yy") {
 
 547           $ifFormat = "%m/%d/%Y";
 
 549           if ($myconfig->{dateformat} eq "mm-dd-yy") {
 
 550             $ifFormat = "%m-%d-%Y";
 
 552             if ($myconfig->{dateformat} eq "yyyy-mm-dd") {
 
 553               $ifFormat = "%Y-%m-%d";
 
 565       inputField : "| . (shift) . qq|",
 
 566       ifFormat :"$ifFormat",
 
 567       align : "| .  (shift) . qq|", 
 
 568       button : "| . (shift) . qq|"
 
 574        <script type="text/javascript">
 
 575        <!--| . join("", @triggers) . qq|//-->
 
 579   $main::lxdebug->leave_sub();
 
 582 }    #end sub write_trigger
 
 585   $main::lxdebug->enter_sub();
 
 587   my ($self, $msg) = @_;
 
 589   if ($self->{callback}) {
 
 591     ($script, $argv) = split(/\?/, $self->{callback});
 
 592     exec("perl", "$script", $argv);
 
 600   $main::lxdebug->leave_sub();
 
 603 # sort of columns removed - empty sub
 
 605   $main::lxdebug->enter_sub();
 
 607   my ($self, @columns) = @_;
 
 609   $main::lxdebug->leave_sub();
 
 615   $main::lxdebug->enter_sub(2);
 
 617   my ($self, $myconfig, $amount, $places, $dash) = @_;
 
 618   my $neg = ($amount =~ s/-//);
 
 620   $amount = $self->round_amount($amount, $places) if ($places =~ /\d/);
 
 622   my @d = map { s/\d//g; reverse split // } my $tmp = $myconfig->{numberformat}; # get delim chars
 
 623   my @p = split /\./, $amount ; # split amount at decimal point
 
 625   $p[0] =~ s/\B(?=(...)*$)/$d[1]/g if $d[1]; # add 1,000 delimiters
 
 628   $amount .= $d[0].$p[1].(0 x ($places - length $p[1])) if ($places || $p[1] ne '');
 
 631     ($dash =~ /-/)    ? ($neg ? "($amount)"  : "$amount" )    :
 
 632     ($dash =~ /DRCR/) ? ($neg ? "$amount DR" : "$amount CR" ) :
 
 633                         ($neg ? "-$amount"   : "$amount" )    ;
 
 636   $main::lxdebug->leave_sub(2);
 
 641   $main::lxdebug->enter_sub(2);
 
 643   my ($self, $myconfig, $amount) = @_;
 
 645   if ($myconfig->{in_numberformat} == 1) {
 
 646     # Extra input number format 1000.00 or 1000,00
 
 648     $amount = scalar reverse $amount;
 
 649     $amount =~ s/\./DOT/;
 
 651     $amount =~ s/DOT/\./;
 
 652     $amount = scalar reverse $amount;
 
 653     $main::lxdebug->leave_sub(2);
 
 654     return ($amount * 1);
 
 657   if (   ($myconfig->{numberformat} eq '1.000,00')
 
 658       || ($myconfig->{numberformat} eq '1000,00')) {
 
 663   if ($myconfig->{numberformat} eq "1'000.00") {
 
 669   $main::lxdebug->leave_sub(2);
 
 671   return ($amount * 1);
 
 675   $main::lxdebug->enter_sub(2);
 
 677   my ($self, $amount, $places) = @_;
 
 680   # Rounding like "Kaufmannsrunden"
 
 681   # Descr. http://de.wikipedia.org/wiki/Rundung
 
 683   # http://www.perl.com/doc/FAQs/FAQ/oldfaq-html/Q4.13.html
 
 686   $amount = $amount * (10**($places));
 
 687   $round_amount = int($amount + .5 * ($amount <=> 0)) / (10**($places));
 
 689   $main::lxdebug->leave_sub(2);
 
 691   return $round_amount;
 
 696   $main::lxdebug->enter_sub();
 
 698   my ($self, $myconfig, $userspath) = @_;
 
 701   # Some variables used for page breaks
 
 702   my ($chars_per_line, $lines_on_first_page, $lines_on_second_page) =
 
 704   my ($current_page, $current_line, $current_row) = (1, 1, 0);
 
 709   # The old fixed notation of <%variable%> is changed to a new dynamic one.
 
 710   my ${pre} = '<%'; # Variable Prefix, must be regex save!
 
 711   my ${suf} = '%>'; # Variable Suffix, must be regex save!
 
 714   # Make sure that all *notes* (intnotes, partnotes_*, notes etc) are converted to markup correctly.
 
 715   $self->format_string(grep(/notes/, keys(%{$self})));
 
 717   # Copy the notes from the invoice/sales order etc. back to the variable "notes" because that is where most templates expect it to be.
 
 718   $self->{"notes"} = $self->{ $self->{"formname"} . "notes" };
 
 720   map({ $self->{"employee_${_}"} = $myconfig->{$_}; }
 
 721       qw(email tel fax name signature company address businessnumber));
 
 723   open(IN, "$self->{templates}/$self->{IN}")
 
 724     or $self->error("$self->{IN} : $!");
 
 729   $self->{copies} = 1 if (($self->{copies} *= 1) <= 0);
 
 731   # OUT is used for the media, screen, printer, email
 
 732   # for postscript we store a copy in a temporary file
 
 734   $self->{tmpfile} = "$userspath/${fileid}.$self->{IN}";
 
 735   if ($self->{format} =~ /(postscript|pdf)/ || $self->{media} eq 'email') {
 
 737     $self->{OUT} = ">$self->{tmpfile}";
 
 741     open(OUT, "$self->{OUT}") or $self->error("$self->{OUT} : $!");
 
 743     open(OUT, ">-") or $self->error("STDOUT : $!");
 
 747   # Do we have to run LaTeX two times? This is needed if
 
 748   # the template contains page references.
 
 751   # first we generate a tmpfile
 
 752   # read file and replace ${pre}variable${suf}
 
 758     # Switch ${pre}analyse${suf} for template checking
 
 759     # If ${pre}analyse${suf} is set in the template, you'll find the 
 
 760     # parsed output in the user Directory for analysing
 
 762     # ${pre}analyse${suf} is a switch (allways off, on if set), not a Variable
 
 763     # Set $form->{analysing}="" for system state: never analyse.
 
 764     # Set $form->{analysing}="1" for system state: ever analyse.
 
 765     $self->{analysing} = "1" if (/${pre}analyse${suf}/ && !defined $self->{analysing});    
 
 767     $two_passes = 1 if (/\\pageref/);
 
 770     # detect pagebreak block and its parameters
 
 771     if (/\s*${pre}pagebreak ([0-9]+) ([0-9]+) ([0-9]+)${suf}/) {
 
 772       $chars_per_line       = $1;
 
 773       $lines_on_first_page  = $2;
 
 774       $lines_on_second_page = $3;
 
 777         last if (/\s*${pre}end pagebreak${suf}/);
 
 784     if (/\s*${pre}foreach /) {
 
 786       # this one we need for the count
 
 788       $var =~ s/\s*${pre}foreach (.+?)${suf}/$1/;
 
 790         last if (/\s*${pre}end /);
 
 796       # display contents of $self->{number}[] array
 
 797       for $i (0 .. $#{ $self->{$var} }) {
 
 800         # Try to detect whether a manual page break is necessary
 
 801         # but only if there was a ${pre}pagebreak ...${suf} block before
 
 803         if ($chars_per_line) {
 
 805             int(length($self->{"description"}[$i]) / $chars_per_line + 0.95);
 
 808           my $_description = $self->{"description"}[$i];
 
 809           while ($_description =~ /\\newline/) {
 
 811             $_description =~ s/\\newline//;
 
 813           $self->{"description"}[$i] =~ s/(\\newline\s?)*$//;
 
 815           if ($current_page == 1) {
 
 816             $lpp = $lines_on_first_page;
 
 818             $lpp = $lines_on_second_page;
 
 821           # Yes we need a manual page break -- or the user has forced one
 
 823              (($current_line + $lines) > $lpp)
 
 824              || ($self->{"_forced_pagebreaks"}
 
 825                && grep(/^${current_row}$/, @{ $self->{"_forced_pagebreaks"} }))
 
 829             # replace the special variables ${pre}sumcarriedforward${suf}
 
 830             # and ${pre}lastpage${suf}
 
 832             my $psum = $self->format_amount($myconfig, $sum, 2);
 
 833             $pb =~ s/${pre}sumcarriedforward${suf}/$psum/g;
 
 834             $pb =~ s/${pre}lastpage${suf}/$current_page/g;
 
 836             # only "normal" variables are supported here
 
 837             # (no ${pre}if, no ${pre}foreach, no ${pre}include)
 
 839             $pb =~ s/${pre}(.+?)${suf}/$self->{$1}/g;
 
 841             # page break block is ready to rock
 
 846           $current_line += $lines;
 
 849         $sum += $self->parse_amount($myconfig, $self->{"linetotal"}[$i]);
 
 853         # don't parse par, we need it for each line
 
 855         s/${pre}(.+?)${suf}/$self->{$1}[$i]/mg;
 
 861     # if not comes before if!
 
 862     if (/\s*${pre}if not /) {
 
 864       # check if it is not set and display
 
 866       s/\s*${pre}if not (.+?)${suf}/$1/;
 
 868       unless ($self->{$_}) {
 
 870           last if (/\s*${pre}end /);
 
 880           last if (/\s*${pre}end /);
 
 886     if (/\s*${pre}if /) {
 
 888       # check if it is set and display
 
 890       s/\s*${pre}if (.+?)${suf}/$1/;
 
 894           last if (/\s*${pre}end /);
 
 904           last if (/\s*${pre}end /);
 
 910     # check for ${pre}include filename${suf}
 
 911     if (/\s*${pre}include /) {
 
 913       # get the directory/filename
 
 915       $var =~ s/\s*${pre}include (.+?)${suf}/$1/;
 
 917       # mangle filename on basedir
 
 918       $var =~ s/^(\/|\.\.)//g;
 
 920       # prevent the infinite loop!
 
 921       next if ($self->{"$var"});
 
 923       open(INC, "$self->{templates}/$var")
 
 924         or $self->error($self->cleanup . "$self->{templates}/$var : $!");
 
 933     s/${pre}(.+?)${suf}/$self->{$1}/g;
 
 934     s/<nobr><\/nobr>/ /g;
 
 941   # Convert the tex file to postscript
 
 942   if ($self->{format} =~ /(postscript|pdf)/) {
 
 945     $self->{cwd}    = cwd();
 
 946     $self->{tmpdir} = "$self->{cwd}/$userspath";
 
 948     chdir("$userspath") or $self->error($self->cleanup . "chdir : $!");
 
 950     $self->{tmpfile} =~ s/$userspath\///g;
 
 952     if ($self->{format} eq 'postscript') {
 
 954         "latex --interaction=nonstopmode $self->{tmpfile} > $self->{tmpfile}.err"
 
 956       $self->error($self->cleanup) if ($?);
 
 959           "latex --interaction=nonstopmode $self->{tmpfile} > $self->{tmpfile}.err"
 
 961         $self->error($self->cleanup) if ($?);
 
 964       $self->{tmpfile} =~ s/tex$/dvi/;
 
 966       system("dvips $self->{tmpfile} -o -q > /dev/null");
 
 967       $self->error($self->cleanup . "dvips : $!") if ($?);
 
 968       $self->{tmpfile} =~ s/dvi$/ps/;
 
 970     if ($self->{format} eq 'pdf') {
 
 972         "pdflatex --interaction=nonstopmode $self->{tmpfile} > $self->{tmpfile}.err"
 
 974       $self->error($self->cleanup) if ($?);
 
 977           "pdflatex --interaction=nonstopmode $self->{tmpfile} > $self->{tmpfile}.err"
 
 979         $self->error($self->cleanup) if ($?);
 
 981       $self->{tmpfile} =~ s/tex$/pdf/;
 
 986   if ($self->{format} =~ /(postscript|pdf)/ || $self->{media} eq 'email') {
 
 988     if ($self->{media} eq 'email') {
 
 992       my $mail = new Mailer;
 
 994       map { $mail->{$_} = $self->{$_} }
 
 995         qw(cc bcc subject message version format charset);
 
 996       $mail->{to}     = qq|$self->{email}|;
 
 997       $mail->{from}   = qq|"$myconfig->{name}" <$myconfig->{email}>|;
 
 998       $mail->{fileid} = "$fileid.";
 
1000       # if we send html or plain text inline
 
1001       if (($self->{format} eq 'html') && ($self->{sendmode} eq 'inline')) {
 
1002         $mail->{contenttype} = "text/html";
 
1004         $mail->{message}       =~ s/\r\n/<br>\n/g;
 
1005         $myconfig->{signature} =~ s/\\n/<br>\n/g;
 
1006         $mail->{message} .= "<br>\n--<br>\n$myconfig->{signature}\n<br>";
 
1008         open(IN, $self->{tmpfile})
 
1009           or $self->error($self->cleanup . "$self->{tmpfile} : $!");
 
1011           $mail->{message} .= $_;
 
1018         @{ $mail->{attachments} } = ($self->{tmpfile});
 
1020         $myconfig->{signature} =~ s/\\n/\r\n/g;
 
1021         $mail->{message} .= "\r\n--\r\n$myconfig->{signature}";
 
1025       my $err = $mail->send($out);
 
1026       $self->error($self->cleanup . "$err") if ($err);
 
1030       $self->{OUT} = $out;
 
1032       my $numbytes = (-s $self->{tmpfile});
 
1033       open(IN, $self->{tmpfile})
 
1034         or $self->error($self->cleanup . "$self->{tmpfile} : $!");
 
1036       $self->{copies} = 1 unless $self->{media} eq 'printer';
 
1038       chdir("$self->{cwd}");
 
1040       for my $i (1 .. $self->{copies}) {
 
1042           open(OUT, $self->{OUT})
 
1043             or $self->error($self->cleanup . "$self->{OUT} : $!");
 
1046           # launch application
 
1047           print qq|Content-Type: application/$self->{format}
 
1048 Content-Disposition: attachment; filename="$self->{tmpfile}"
 
1049 Content-Length: $numbytes
 
1053           open(OUT, ">-") or $self->error($self->cleanup . "$!: STDOUT");
 
1073   chdir("$self->{cwd}");
 
1074   $main::lxdebug->leave_sub();
 
1078   $main::lxdebug->enter_sub();
 
1082   chdir("$self->{tmpdir}");
 
1085   if (-f "$self->{tmpfile}.err") {
 
1086     open(FH, "$self->{tmpfile}.err");
 
1091   if ($self->{analysing} eq "") {
 
1092     if ($self->{tmpfile}) {
 
1095       $self->{tmpfile} =~ s/\.\w+$//g;  
 
1096       my $tmpfile = $self->{tmpfile};
 
1097       unlink(<$tmpfile.*>);
 
1101   chdir("$self->{cwd}");
 
1103   $main::lxdebug->leave_sub();
 
1109   $main::lxdebug->enter_sub();
 
1111   my ($self, @fields) = @_;
 
1114   %unique_fields = map({ $_ => 1 } @fields);
 
1115   @fields        = keys(%unique_fields);
 
1117   foreach my $field (@fields) {
 
1118     next unless ($self->{$field} =~ /\<pagebreak\>/);
 
1119     $self->{$field} =~ s/\<pagebreak\>//g;
 
1120     if ($field =~ /.*_(\d+)$/) {
 
1121       if (!$self->{"_forced_pagebreaks"}) {
 
1122         $self->{"_forced_pagebreaks"} = [];
 
1124       push(@{ $self->{"_forced_pagebreaks"} }, "$1");
 
1128   my $format = $self->{format};
 
1129   if ($self->{format} =~ /(postscript|pdf)/) {
 
1136         '<', '>', quotemeta('\n'), '
 
1140         '&', quotemeta('\n'), '
 
1142         '"', '\$', '%', '_', '#', quotemeta('^'),
 
1143         '{', '}',  '<', '>', '£', "\r", '²'
 
1149       quotemeta('\n') => '<br>',
 
1160       quotemeta('^')  => '\^\\',
 
1165       quotemeta('\n') => '\newline ',
 
1173   foreach my $key (@{ $replace{order}{$format} }) {
 
1174     map { $self->{$_} =~ s/$key/$replace{$format}{$key}/g; } @fields;
 
1177   # Allow some HTML markup to be converted into the output format's
 
1178   # corresponding markup code, e.g. bold or italic.
 
1179   if ('html' eq $format) {
 
1180     my @markup_replace = ('b', 'i', 's', 'u');
 
1182     foreach my $key (@markup_replace) {
 
1183       map({ $self->{$_} =~ s/\<(\/?)${key}\>/<$1${key}>/g } @fields);
 
1186   } elsif ('tex' eq $format) {
 
1187     my %markup_replace = ('b' => 'textbf',
 
1189                           'u' => 'underline');
 
1191     foreach my $field (@fields) {
 
1192       foreach my $key (keys(%markup_replace)) {
 
1193         my $new = $markup_replace{$key};
 
1195           s/\$\<\$${key}\$\>\$(.*?)\$<\$\/${key}\$>\$/\\${new}\{$1\}/gi;
 
1200   $main::lxdebug->leave_sub();
 
1204   $main::lxdebug->enter_sub();
 
1206   my ($self, $date, $myconfig) = @_;
 
1208   if ($date && $date =~ /\D/) {
 
1210     if ($myconfig->{dateformat} =~ /^yy/) {
 
1211       ($yy, $mm, $dd) = split /\D/, $date;
 
1213     if ($myconfig->{dateformat} =~ /^mm/) {
 
1214       ($mm, $dd, $yy) = split /\D/, $date;
 
1216     if ($myconfig->{dateformat} =~ /^dd/) {
 
1217       ($dd, $mm, $yy) = split /\D/, $date;
 
1222     $yy = ($yy < 70) ? $yy + 2000 : $yy;
 
1223     $yy = ($yy >= 70 && $yy <= 99) ? $yy + 1900 : $yy;
 
1225     $dd = "0$dd" if ($dd < 10);
 
1226     $mm = "0$mm" if ($mm < 10);
 
1228     $date = "$yy$mm$dd";
 
1231   $main::lxdebug->leave_sub();
 
1236 # Database routines used throughout
 
1239   $main::lxdebug->enter_sub();
 
1241   my ($self, $myconfig) = @_;
 
1243   # connect to database
 
1245     DBI->connect($myconfig->{dbconnect},
 
1246                  $myconfig->{dbuser}, $myconfig->{dbpasswd})
 
1250   if ($myconfig->{dboptions}) {
 
1251     $dbh->do($myconfig->{dboptions}) || $self->dberror($myconfig->{dboptions});
 
1254   $main::lxdebug->leave_sub();
 
1259 sub dbconnect_noauto {
 
1260   $main::lxdebug->enter_sub();
 
1262   my ($self, $myconfig) = @_;
 
1264   # connect to database
 
1266     DBI->connect($myconfig->{dbconnect}, $myconfig->{dbuser},
 
1267                  $myconfig->{dbpasswd}, { AutoCommit => 0 })
 
1271   if ($myconfig->{dboptions}) {
 
1272     $dbh->do($myconfig->{dboptions}) || $self->dberror($myconfig->{dboptions});
 
1275   $main::lxdebug->leave_sub();
 
1280 sub update_balance {
 
1281   $main::lxdebug->enter_sub();
 
1283   my ($self, $dbh, $table, $field, $where, $value) = @_;
 
1285   # if we have a value, go do it
 
1288     # retrieve balance from table
 
1289     my $query = "SELECT $field FROM $table WHERE $where FOR UPDATE";
 
1290     my $sth   = $dbh->prepare($query);
 
1292     $sth->execute || $self->dberror($query);
 
1293     my ($balance) = $sth->fetchrow_array;
 
1299     $query = "UPDATE $table SET $field = $balance WHERE $where";
 
1300     $dbh->do($query) || $self->dberror($query);
 
1302   $main::lxdebug->leave_sub();
 
1305 sub update_exchangerate {
 
1306   $main::lxdebug->enter_sub();
 
1308   my ($self, $dbh, $curr, $transdate, $buy, $sell) = @_;
 
1310   # some sanity check for currency
 
1312     $main::lxdebug->leave_sub();
 
1316   my $query = qq|SELECT e.curr FROM exchangerate e
 
1317                  WHERE e.curr = '$curr'
 
1318                  AND e.transdate = '$transdate'
 
1320   my $sth = $dbh->prepare($query);
 
1321   $sth->execute || $self->dberror($query);
 
1324   if ($buy != 0 && $sell != 0) {
 
1325     $set = "buy = $buy, sell = $sell";
 
1326   } elsif ($buy != 0) {
 
1327     $set = "buy = $buy";
 
1328   } elsif ($sell != 0) {
 
1329     $set = "sell = $sell";
 
1332   if ($sth->fetchrow_array) {
 
1333     $query = qq|UPDATE exchangerate
 
1335                 WHERE curr = '$curr'
 
1336                 AND transdate = '$transdate'|;
 
1338     $query = qq|INSERT INTO exchangerate (curr, buy, sell, transdate)
 
1339                 VALUES ('$curr', $buy, $sell, '$transdate')|;
 
1342   $dbh->do($query) || $self->dberror($query);
 
1344   $main::lxdebug->leave_sub();
 
1347 sub save_exchangerate {
 
1348   $main::lxdebug->enter_sub();
 
1350   my ($self, $myconfig, $currency, $transdate, $rate, $fld) = @_;
 
1352   my $dbh = $self->dbconnect($myconfig);
 
1354   my ($buy, $sell) = (0, 0);
 
1355   $buy  = $rate if $fld eq 'buy';
 
1356   $sell = $rate if $fld eq 'sell';
 
1358   $self->update_exchangerate($dbh, $currency, $transdate, $buy, $sell);
 
1362   $main::lxdebug->leave_sub();
 
1365 sub get_exchangerate {
 
1366   $main::lxdebug->enter_sub();
 
1368   my ($self, $dbh, $curr, $transdate, $fld) = @_;
 
1370   unless ($transdate) {
 
1371     $main::lxdebug->leave_sub();
 
1375   my $query = qq|SELECT e.$fld FROM exchangerate e
 
1376                  WHERE e.curr = '$curr'
 
1377                  AND e.transdate = '$transdate'|;
 
1378   my $sth = $dbh->prepare($query);
 
1379   $sth->execute || $self->dberror($query);
 
1381   my ($exchangerate) = $sth->fetchrow_array;
 
1384   $main::lxdebug->leave_sub();
 
1386   return $exchangerate;
 
1389 sub check_exchangerate {
 
1390   $main::lxdebug->enter_sub();
 
1392   my ($self, $myconfig, $currency, $transdate, $fld) = @_;
 
1394   unless ($transdate) {
 
1395     $main::lxdebug->leave_sub();
 
1399   my $dbh = $self->dbconnect($myconfig);
 
1401   my $query = qq|SELECT e.$fld FROM exchangerate e
 
1402                  WHERE e.curr = '$currency'
 
1403                  AND e.transdate = '$transdate'|;
 
1404   my $sth = $dbh->prepare($query);
 
1405   $sth->execute || $self->dberror($query);
 
1407   my ($exchangerate) = $sth->fetchrow_array;
 
1411   $main::lxdebug->leave_sub();
 
1413   return $exchangerate;
 
1417   $main::lxdebug->enter_sub();
 
1419   my ($self, $dbh, $id) = @_;
 
1423     qw(name department_1 department_2 street zipcode city country contact phone fax email)
 
1425     if ($self->{"shipto$item"}) {
 
1426       $shipto = 1 if ($self->{$item} ne $self->{"shipto$item"});
 
1428     $self->{"shipto$item"} =~ s/\'/\'\'/g;
 
1433       qq|INSERT INTO shipto (trans_id, shiptoname, shiptodepartment_1, shiptodepartment_2, shiptostreet,
 
1434                    shiptozipcode, shiptocity, shiptocountry, shiptocontact,
 
1435                    shiptophone, shiptofax, shiptoemail) VALUES ($id,
 
1436                    '$self->{shiptoname}', '$self->{shiptodepartment_1}', '$self->{shiptodepartment_2}', '$self->{shiptostreet}',
 
1437                    '$self->{shiptozipcode}', '$self->{shiptocity}',
 
1438                    '$self->{shiptocountry}', '$self->{shiptocontact}',
 
1439                    '$self->{shiptophone}', '$self->{shiptofax}',
 
1440                    '$self->{shiptoemail}')|;
 
1441     $dbh->do($query) || $self->dberror($query);
 
1444   $main::lxdebug->leave_sub();
 
1448   $main::lxdebug->enter_sub();
 
1450   my ($self, $dbh) = @_;
 
1452   my $query = qq|SELECT e.id, e.name FROM employee e
 
1453                  WHERE e.login = '$self->{login}'|;
 
1454   my $sth = $dbh->prepare($query);
 
1455   $sth->execute || $self->dberror($query);
 
1457   ($self->{employee_id}, $self->{employee}) = $sth->fetchrow_array;
 
1458   $self->{employee_id} *= 1;
 
1462   $main::lxdebug->leave_sub();
 
1465 # get other contact for transaction and form - html/tex
 
1467   $main::lxdebug->enter_sub();
 
1469   my ($self, $dbh, $id) = @_;
 
1471   my $query = qq|SELECT c.*
 
1474   $sth = $dbh->prepare($query);
 
1475   $sth->execute || $self->dberror($query);
 
1477   $ref = $sth->fetchrow_hashref(NAME_lc);
 
1479   push @{ $self->{$_} }, $ref;
 
1482   $main::lxdebug->leave_sub();
 
1485 # get contacts for id, if no contact return {"","","","",""}
 
1487   $main::lxdebug->enter_sub();
 
1489   my ($self, $dbh, $id) = @_;
 
1491   my $query = qq|SELECT c.cp_id, c.cp_cv_id, c.cp_name, c.cp_givenname
 
1493               WHERE cp_cv_id=$id|;
 
1494   my $sth = $dbh->prepare($query);
 
1495   $sth->execute || $self->dberror($query);
 
1498   while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
 
1499     push @{ $self->{all_contacts} }, $ref;
 
1504     push @{ $self->{all_contacts} }, { { "", "", "", "", "" } };
 
1507   $main::lxdebug->leave_sub();
 
1510 # this sub gets the id and name from $table
 
1512   $main::lxdebug->enter_sub();
 
1514   my ($self, $myconfig, $table) = @_;
 
1516   # connect to database
 
1517   my $dbh = $self->dbconnect($myconfig);
 
1519   my $name           = $self->like(lc $self->{$table});
 
1520   my $customernumber = $self->like(lc $self->{customernumber});
 
1522   if ($self->{customernumber} ne "") {
 
1523     $query = qq~SELECT c.id, c.name,
 
1524                   c.street || ' ' || c.zipcode || ' ' || c.city || ' ' || c.country AS address
 
1526                   WHERE (lower(c.customernumber) LIKE '$customernumber') AND (not c.obsolete)
 
1529     $query = qq~SELECT c.id, c.name,
 
1530                  c.street || ' ' || c.zipcode || ' ' || c.city || ' ' || c.country AS address
 
1532                  WHERE (lower(c.name) LIKE '$name') AND (not c.obsolete)
 
1536   if ($self->{openinvoices}) {
 
1537     $query = qq~SELECT DISTINCT c.id, c.name,
 
1538                 c.street || ' ' || c.zipcode || ' ' || c.city || ' ' || c.country AS address
 
1539                 FROM $self->{arap} a
 
1540                 JOIN $table c ON (a.${table}_id = c.id)
 
1541                 WHERE NOT a.amount = a.paid
 
1542                 AND lower(c.name) LIKE '$name'
 
1545   my $sth = $dbh->prepare($query);
 
1547   $sth->execute || $self->dberror($query);
 
1550   while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
 
1551     push(@{ $self->{name_list} }, $ref);
 
1557   $main::lxdebug->leave_sub();
 
1562 # the selection sub is used in the AR, AP, IS, IR and OE module
 
1565   $main::lxdebug->enter_sub();
 
1567   my ($self, $myconfig, $table, $module) = @_;
 
1570   my $dbh = $self->dbconnect($myconfig);
 
1572   my $query = qq|SELECT count(*) FROM $table|;
 
1573   my $sth   = $dbh->prepare($query);
 
1574   $sth->execute || $self->dberror($query);
 
1575   my ($count) = $sth->fetchrow_array;
 
1578   # build selection list
 
1579   if ($count < $myconfig->{vclimit}) {
 
1580     $query = qq|SELECT id, name
 
1581                 FROM $table WHERE not obsolete
 
1583     $sth = $dbh->prepare($query);
 
1584     $sth->execute || $self->dberror($query);
 
1586     while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
 
1587       push @{ $self->{"all_$table"} }, $ref;
 
1595   $self->get_employee($dbh);
 
1597   # setup sales contacts
 
1598   $query = qq|SELECT e.id, e.name
 
1601               AND NOT e.id = $self->{employee_id}|;
 
1602   $sth = $dbh->prepare($query);
 
1603   $sth->execute || $self->dberror($query);
 
1605   while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
 
1606     push @{ $self->{all_employees} }, $ref;
 
1611   push @{ $self->{all_employees} },
 
1612     { id   => $self->{employee_id},
 
1613       name => $self->{employee} };
 
1615   # sort the whole thing
 
1616   @{ $self->{all_employees} } =
 
1617     sort { $a->{name} cmp $b->{name} } @{ $self->{all_employees} };
 
1619   if ($module eq 'AR') {
 
1621     # prepare query for departments
 
1622     $query = qq|SELECT d.id, d.description
 
1628     $query = qq|SELECT d.id, d.description
 
1633   $sth = $dbh->prepare($query);
 
1634   $sth->execute || $self->dberror($query);
 
1636   while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
 
1637     push @{ $self->{all_departments} }, $ref;
 
1642   $main::lxdebug->leave_sub();
 
1645 # this is only used for reports
 
1646 sub all_departments {
 
1647   $main::lxdebug->enter_sub();
 
1649   my ($self, $myconfig, $table) = @_;
 
1651   my $dbh   = $self->dbconnect($myconfig);
 
1652   my $where = "1 = 1";
 
1654   if (defined $table) {
 
1655     if ($table eq 'customer') {
 
1656       $where = " d.role = 'P'";
 
1660   my $query = qq|SELECT d.id, d.description
 
1664   my $sth = $dbh->prepare($query);
 
1665   $sth->execute || $self->dberror($query);
 
1667   while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
 
1668     push @{ $self->{all_departments} }, $ref;
 
1674   $main::lxdebug->leave_sub();
 
1678   $main::lxdebug->enter_sub();
 
1680   my ($self, $module, $myconfig, $table) = @_;
 
1682   $self->all_vc($myconfig, $table, $module);
 
1684   # get last customers or vendors
 
1687   my $dbh = $self->dbconnect($myconfig);
 
1691   # now get the account numbers
 
1692   $query = qq|SELECT c.accno, c.description, c.link, c.taxkey_id
 
1694               WHERE c.link LIKE '%$module%'
 
1697   $sth = $dbh->prepare($query);
 
1698   $sth->execute || $self->dberror($query);
 
1700   $self->{accounts} = "";
 
1701   while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
 
1703     foreach my $key (split /:/, $ref->{link}) {
 
1704       if ($key =~ /$module/) {
 
1706         # cross reference for keys
 
1707         $xkeyref{ $ref->{accno} } = $key;
 
1709         push @{ $self->{"${module}_links"}{$key} },
 
1710           { accno       => $ref->{accno},
 
1711             description => $ref->{description},
 
1712             taxkey      => $ref->{taxkey_id} };
 
1714         $self->{accounts} .= "$ref->{accno} " unless $key =~ /tax/;
 
1720   if (($module eq "AP") || ($module eq "AR")) {
 
1722     # get tax rates and description
 
1723     $query = qq| SELECT * FROM tax t|;
 
1724     $sth   = $dbh->prepare($query);
 
1725     $sth->execute || $self->dberror($query);
 
1727     while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
 
1728       push @{ $self->{TAX} }, $ref;
 
1734     my $arap = ($table eq 'customer') ? 'ar' : 'ap';
 
1736     $query = qq|SELECT a.cp_id, a.invnumber, a.transdate,
 
1737                 a.${table}_id, a.datepaid, a.duedate, a.ordnumber,
 
1738                 a.taxincluded, a.curr AS currency, a.notes, a.intnotes,
 
1739                 c.name AS $table, a.department_id, d.description AS department,
 
1740                 a.amount AS oldinvtotal, a.paid AS oldtotalpaid,
 
1741                 a.employee_id, e.name AS employee, a.gldate
 
1743                 JOIN $table c ON (a.${table}_id = c.id)
 
1744                 LEFT JOIN employee e ON (e.id = a.employee_id)
 
1745                 LEFT JOIN department d ON (d.id = a.department_id)
 
1746                 WHERE a.id = $self->{id}|;
 
1747     $sth = $dbh->prepare($query);
 
1748     $sth->execute || $self->dberror($query);
 
1750     $ref = $sth->fetchrow_hashref(NAME_lc);
 
1751     foreach $key (keys %$ref) {
 
1752       $self->{$key} = $ref->{$key};
 
1756     # get amounts from individual entries
 
1757     $query = qq|SELECT c.accno, c.description, a.source, a.amount, a.memo,
 
1758                 a.transdate, a.cleared, a.project_id, p.projectnumber, a.taxkey, t.rate
 
1760                 JOIN chart c ON (c.id = a.chart_id)
 
1761                 LEFT JOIN project p ON (p.id = a.project_id)
 
1762                 LEFT Join tax t ON (a.taxkey = t.taxkey)
 
1763                 WHERE a.trans_id = $self->{id}
 
1764                 AND a.fx_transaction = '0'
 
1765                 ORDER BY a.oid,a.transdate|;
 
1766     $sth = $dbh->prepare($query);
 
1767     $sth->execute || $self->dberror($query);
 
1769     my $fld = ($table eq 'customer') ? 'buy' : 'sell';
 
1771     # get exchangerate for currency
 
1772     $self->{exchangerate} =
 
1773       $self->get_exchangerate($dbh, $self->{currency}, $self->{transdate},
 
1777     # store amounts in {acc_trans}{$key} for multiple accounts
 
1778     while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
 
1779       $ref->{exchangerate} =
 
1780         $self->get_exchangerate($dbh, $self->{currency}, $ref->{transdate},
 
1782       if (!($xkeyref{ $ref->{accno} } =~ /tax/)) {
 
1785       $ref->{index} = $index;
 
1787       push @{ $self->{acc_trans}{ $xkeyref{ $ref->{accno} } } }, $ref;
 
1791     $query = qq|SELECT d.curr AS currencies, d.closedto, d.revtrans,
 
1792                   (SELECT c.accno FROM chart c
 
1793                    WHERE d.fxgain_accno_id = c.id) AS fxgain_accno,
 
1794                   (SELECT c.accno FROM chart c
 
1795                    WHERE d.fxloss_accno_id = c.id) AS fxloss_accno
 
1797     $sth = $dbh->prepare($query);
 
1798     $sth->execute || $self->dberror($query);
 
1800     $ref = $sth->fetchrow_hashref(NAME_lc);
 
1801     map { $self->{$_} = $ref->{$_} } keys %$ref;
 
1807     $query = qq|SELECT current_date AS transdate,
 
1808                 d.curr AS currencies, d.closedto, d.revtrans,
 
1809                   (SELECT c.accno FROM chart c
 
1810                    WHERE d.fxgain_accno_id = c.id) AS fxgain_accno,
 
1811                   (SELECT c.accno FROM chart c
 
1812                    WHERE d.fxloss_accno_id = c.id) AS fxloss_accno
 
1814     $sth = $dbh->prepare($query);
 
1815     $sth->execute || $self->dberror($query);
 
1817     $ref = $sth->fetchrow_hashref(NAME_lc);
 
1818     map { $self->{$_} = $ref->{$_} } keys %$ref;
 
1821     if ($self->{"$self->{vc}_id"}) {
 
1823       # only setup currency
 
1824       ($self->{currency}) = split /:/, $self->{currencies};
 
1828       $self->lastname_used($dbh, $myconfig, $table, $module);
 
1830       my $fld = ($table eq 'customer') ? 'buy' : 'sell';
 
1832       # get exchangerate for currency
 
1833       $self->{exchangerate} =
 
1834         $self->get_exchangerate($dbh, $self->{currency}, $self->{transdate},
 
1843   $main::lxdebug->leave_sub();
 
1847   $main::lxdebug->enter_sub();
 
1849   my ($self, $dbh, $myconfig, $table, $module) = @_;
 
1851   my $arap  = ($table eq 'customer') ? "ar" : "ap";
 
1852   my $where = "1 = 1";
 
1854   if ($self->{type} =~ /_order/) {
 
1856     $where = "quotation = '0'";
 
1858   if ($self->{type} =~ /_quotation/) {
 
1860     $where = "quotation = '1'";
 
1863   my $query = qq|SELECT MAX(id) FROM $arap
 
1865                               AND ${table}_id > 0|;
 
1866   my $sth = $dbh->prepare($query);
 
1867   $sth->execute || $self->dberror($query);
 
1869   my ($trans_id) = $sth->fetchrow_array;
 
1873   $query = qq|SELECT ct.name, a.curr, a.${table}_id,
 
1874               current_date + ct.terms AS duedate, a.department_id,
 
1875               d.description AS department
 
1877               JOIN $table ct ON (a.${table}_id = ct.id)
 
1878               LEFT JOIN department d ON (a.department_id = d.id)
 
1879               WHERE a.id = $trans_id|;
 
1880   $sth = $dbh->prepare($query);
 
1881   $sth->execute || $self->dberror($query);
 
1883   ($self->{$table},  $self->{currency},      $self->{"${table}_id"},
 
1884    $self->{duedate}, $self->{department_id}, $self->{department})
 
1885     = $sth->fetchrow_array;
 
1888   $main::lxdebug->leave_sub();
 
1892   $main::lxdebug->enter_sub();
 
1894   my ($self, $myconfig, $thisdate, $days) = @_;
 
1896   my $dbh = $self->dbconnect($myconfig);
 
1901     my $dateformat = $myconfig->{dateformat};
 
1902     $dateformat .= "yy" if $myconfig->{dateformat} !~ /^y/;
 
1904     $query = qq|SELECT to_date('$thisdate', '$dateformat') + $days AS thisdate
 
1906     $sth = $dbh->prepare($query);
 
1907     $sth->execute || $self->dberror($query);
 
1909     $query = qq|SELECT current_date AS thisdate
 
1911     $sth = $dbh->prepare($query);
 
1912     $sth->execute || $self->dberror($query);
 
1915   ($thisdate) = $sth->fetchrow_array;
 
1920   $main::lxdebug->leave_sub();
 
1926   $main::lxdebug->enter_sub();
 
1928   my ($self, $string) = @_;
 
1930   if ($string !~ /%/) {
 
1931     $string = "%$string%";
 
1934   $string =~ s/\'/\'\'/g;
 
1936   $main::lxdebug->leave_sub();
 
1942   $main::lxdebug->enter_sub();
 
1944   my ($self, $flds, $new, $count, $numrows) = @_;
 
1948   map { push @ndx, { num => $new->[$_ - 1]->{runningnumber}, ndx => $_ } }
 
1954   foreach my $item (sort { $a->{num} <=> $b->{num} } @ndx) {
 
1956     $j = $item->{ndx} - 1;
 
1957     map { $self->{"${_}_$i"} = $new->[$j]->{$_} } @{$flds};
 
1961   for $i ($count + 1 .. $numrows) {
 
1962     map { delete $self->{"${_}_$i"} } @{$flds};
 
1965   $main::lxdebug->leave_sub();
 
1969   $main::lxdebug->enter_sub();
 
1971   my ($self, $myconfig) = @_;
 
1975   my $dbh = $self->dbconnect_noauto($myconfig);
 
1977   my $query = qq|DELETE FROM status
 
1978                  WHERE formname = '$self->{formname}'
 
1980   my $sth = $dbh->prepare($query) || $self->dberror($query);
 
1982   if ($self->{formname} =~ /(check|receipt)/) {
 
1983     for $i (1 .. $self->{rowcount}) {
 
1984       $sth->execute($self->{"id_$i"} * 1) || $self->dberror($query);
 
1988     $sth->execute($self->{id}) || $self->dberror($query);
 
1992   my $printed = ($self->{printed} =~ /$self->{formname}/) ? "1" : "0";
 
1993   my $emailed = ($self->{emailed} =~ /$self->{formname}/) ? "1" : "0";
 
1995   my %queued = split / /, $self->{queued};
 
1997   if ($self->{formname} =~ /(check|receipt)/) {
 
1999     # this is a check or receipt, add one entry for each lineitem
 
2000     my ($accno) = split /--/, $self->{account};
 
2001     $query = qq|INSERT INTO status (trans_id, printed, spoolfile, formname,
 
2002                 chart_id) VALUES (?, '$printed',
 
2003                 '$queued{$self->{formname}}', '$self->{prinform}',
 
2004                 (SELECT c.id FROM chart c WHERE c.accno = '$accno'))|;
 
2005     $sth = $dbh->prepare($query) || $self->dberror($query);
 
2007     for $i (1 .. $self->{rowcount}) {
 
2008       if ($self->{"checked_$i"}) {
 
2009         $sth->execute($self->{"id_$i"}) || $self->dberror($query);
 
2014     $query = qq|INSERT INTO status (trans_id, printed, emailed,
 
2015                 spoolfile, formname)
 
2016                 VALUES ($self->{id}, '$printed', '$emailed',
 
2017                 '$queued{$self->{formname}}', '$self->{formname}')|;
 
2018     $dbh->do($query) || $self->dberror($query);
 
2024   $main::lxdebug->leave_sub();
 
2028   $main::lxdebug->enter_sub();
 
2030   my ($self, $dbh) = @_;
 
2032   my ($query, $printed, $emailed);
 
2034   my $formnames  = $self->{printed};
 
2035   my $emailforms = $self->{emailed};
 
2037   my $query = qq|DELETE FROM status
 
2038                  WHERE formname = '$self->{formname}'
 
2039                  AND trans_id = $self->{id}|;
 
2040   $dbh->do($query) || $self->dberror($query);
 
2042   # this only applies to the forms
 
2043   # checks and receipts are posted when printed or queued
 
2045   if ($self->{queued}) {
 
2046     my %queued = split / /, $self->{queued};
 
2048     foreach my $formname (keys %queued) {
 
2049       $printed = ($self->{printed} =~ /$self->{formname}/) ? "1" : "0";
 
2050       $emailed = ($self->{emailed} =~ /$self->{formname}/) ? "1" : "0";
 
2052       $query = qq|INSERT INTO status (trans_id, printed, emailed,
 
2053                   spoolfile, formname)
 
2054                   VALUES ($self->{id}, '$printed', '$emailed',
 
2055                   '$queued{$formname}', '$formname')|;
 
2056       $dbh->do($query) || $self->dberror($query);
 
2058       $formnames  =~ s/$self->{formname}//;
 
2059       $emailforms =~ s/$self->{formname}//;
 
2064   # save printed, emailed info
 
2065   $formnames  =~ s/^ +//g;
 
2066   $emailforms =~ s/^ +//g;
 
2069   map { $status{$_}{printed} = 1 } split / +/, $formnames;
 
2070   map { $status{$_}{emailed} = 1 } split / +/, $emailforms;
 
2072   foreach my $formname (keys %status) {
 
2073     $printed = ($formnames  =~ /$self->{formname}/) ? "1" : "0";
 
2074     $emailed = ($emailforms =~ /$self->{formname}/) ? "1" : "0";
 
2076     $query = qq|INSERT INTO status (trans_id, printed, emailed, formname)
 
2077                 VALUES ($self->{id}, '$printed', '$emailed', '$formname')|;
 
2078     $dbh->do($query) || $self->dberror($query);
 
2081   $main::lxdebug->leave_sub();
 
2084 sub update_defaults {
 
2085   $main::lxdebug->enter_sub();
 
2087   my ($self, $myconfig, $fld) = @_;
 
2089   my $dbh   = $self->dbconnect_noauto($myconfig);
 
2090   my $query = qq|SELECT $fld FROM defaults FOR UPDATE|;
 
2091   my $sth   = $dbh->prepare($query);
 
2093   $sth->execute || $self->dberror($query);
 
2094   my ($var) = $sth->fetchrow_array;
 
2099   $query = qq|UPDATE defaults
 
2101   $dbh->do($query) || $self->dberror($query);
 
2106   $main::lxdebug->leave_sub();
 
2111 sub update_business {
 
2112   $main::lxdebug->enter_sub();
 
2114   my ($self, $myconfig, $business_id) = @_;
 
2116   my $dbh   = $self->dbconnect_noauto($myconfig);
 
2118     qq|SELECT customernumberinit FROM business  WHERE id=$business_id FOR UPDATE|;
 
2119   my $sth = $dbh->prepare($query);
 
2121   $sth->execute || $self->dberror($query);
 
2122   my ($var) = $sth->fetchrow_array;
 
2127   $query = qq|UPDATE business
 
2128               SET customernumberinit = '$var' WHERE id=$business_id|;
 
2129   $dbh->do($query) || $self->dberror($query);
 
2134   $main::lxdebug->leave_sub();
 
2140   $main::lxdebug->enter_sub();
 
2142   my ($self, $myconfig, $salesman) = @_;
 
2144   my $dbh   = $self->dbconnect($myconfig);
 
2146     qq|SELECT id, name FROM customer  WHERE (customernumber ilike '%$salesman%' OR name ilike '%$salesman%') AND business_id in (SELECT id from business WHERE salesman)|;
 
2147   my $sth = $dbh->prepare($query);
 
2148   $sth->execute || $self->dberror($query);
 
2151   while ($ref = $sth->fetchrow_hashref(NAME_lc)) {
 
2152     push(@{ $self->{salesman_list} }, $ref);
 
2156   $main::lxdebug->leave_sub();
 
2161 sub get_partsgroup {
 
2162   $main::lxdebug->enter_sub();
 
2164   my ($self, $myconfig, $p) = @_;
 
2166   my $dbh = $self->dbconnect($myconfig);
 
2168   my $query = qq|SELECT DISTINCT pg.id, pg.partsgroup
 
2170                  JOIN parts p ON (p.partsgroup_id = pg.id)|;
 
2172   if ($p->{searchitems} eq 'part') {
 
2174                  WHERE p.inventory_accno_id > 0|;
 
2176   if ($p->{searchitems} eq 'service') {
 
2178                  WHERE p.inventory_accno_id IS NULL|;
 
2180   if ($p->{searchitems} eq 'assembly') {
 
2182                  WHERE p.assembly = '1'|;
 
2184   if ($p->{searchitems} eq 'labor') {
 
2186                  WHERE p.inventory_accno_id > 0 AND p.income_accno_id IS NULL|;
 
2190                  ORDER BY partsgroup|;
 
2193     $query = qq|SELECT id, partsgroup FROM partsgroup
 
2194                 ORDER BY partsgroup|;
 
2197   if ($p->{language_code}) {
 
2198     $query = qq|SELECT DISTINCT pg.id, pg.partsgroup,
 
2199                 t.description AS translation
 
2201                 JOIN parts p ON (p.partsgroup_id = pg.id)
 
2202                 LEFT JOIN translation t ON (t.trans_id = pg.id AND t.language_code = '$p->{language_code}')
 
2203                 ORDER BY translation|;
 
2206   my $sth = $dbh->prepare($query);
 
2207   $sth->execute || $self->dberror($query);
 
2209   $self->{all_partsgroup} = ();
 
2210   while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
 
2211     push @{ $self->{all_partsgroup} }, $ref;
 
2215   $main::lxdebug->leave_sub();
 
2218 sub get_pricegroup {
 
2219   $main::lxdebug->enter_sub();
 
2221   my ($self, $myconfig, $p) = @_;
 
2223   my $dbh = $self->dbconnect($myconfig);
 
2225   my $query = qq|SELECT p.id, p.pricegroup
 
2229                  ORDER BY pricegroup|;
 
2232     $query = qq|SELECT id, pricegroup FROM pricegroup
 
2233                 ORDER BY pricegroup|;
 
2236   my $sth = $dbh->prepare($query);
 
2237   $sth->execute || $self->dberror($query);
 
2239   $self->{all_pricegroup} = ();
 
2240   while (my $ref = $sth->fetchrow_hashref(NAME_lc)) {
 
2241     push @{ $self->{all_pricegroup} }, $ref;
 
2246   $main::lxdebug->leave_sub();
 
2250   my ($self, $dbh, $myconfig, $audittrail) = @_;
 
2252   # table, $reference, $formname, $action, $id, $transdate) = @_;
 
2259     $dbh        = $self->dbconnect($myconfig);
 
2263   # if we have an id add audittrail, otherwise get a new timestamp
 
2265   if ($audittrail->{id}) {
 
2267     $query = qq|SELECT audittrail FROM defaults|;
 
2269     if ($dbh->selectrow_array($query)) {
 
2270       my ($null, $employee_id) = $self->get_employee($dbh);
 
2272       if ($self->{audittrail} && !$myconfig) {
 
2273         chop $self->{audittrail};
 
2275         my @a = split /\|/, $self->{audittrail};
 
2279         my @flds = qw(tablename reference formname action transdate);
 
2281         # put into hash and remove dups
 
2283           $key = "$a[2]$a[3]";
 
2285           $newtrail{$key} = { map { $_ => $a[$i++] } @flds };
 
2289         $query = qq|INSERT INTO audittrail (trans_id, tablename, reference,
 
2290                     formname, action, employee_id, transdate)
 
2291                     VALUES ($audittrail->{id}, ?, ?,
 
2292                     ?, ?, $employee_id, ?)|;
 
2293         my $sth = $dbh->prepare($query) || $self->dberror($query);
 
2297             $newtrail{$a}{transdate} cmp $newtrail{$b}{transdate}
 
2301           for (@flds) { $sth->bind_param($i++, $newtrail{$key}{$_}) }
 
2303           $sth->execute || $self->dberror;
 
2308       if ($audittrail->{transdate}) {
 
2309         $query = qq|INSERT INTO audittrail (trans_id, tablename, reference,
 
2310                     formname, action, employee_id, transdate) VALUES (
 
2311                     $audittrail->{id}, '$audittrail->{tablename}', |
 
2312           . $dbh->quote($audittrail->{reference}) . qq|,
 
2313                     '$audittrail->{formname}', '$audittrail->{action}',
 
2314                     $employee_id, '$audittrail->{transdate}')|;
 
2316         $query = qq|INSERT INTO audittrail (trans_id, tablename, reference,
 
2317                     formname, action, employee_id) VALUES ($audittrail->{id},
 
2318                     '$audittrail->{tablename}', |
 
2319           . $dbh->quote($audittrail->{reference}) . qq|,
 
2320                     '$audittrail->{formname}', '$audittrail->{action}',
 
2327     $query = qq|SELECT current_timestamp FROM defaults|;
 
2328     my ($timestamp) = $dbh->selectrow_array($query);
 
2331       "$audittrail->{tablename}|$audittrail->{reference}|$audittrail->{formname}|$audittrail->{action}|$timestamp|";
 
2334   $dbh->disconnect if $disconnect;
 
2343   $main::lxdebug->enter_sub();
 
2345   my ($type, $country, $NLS_file) = @_;
 
2349   if ($country && -d "locale/$country") {
 
2350     $self->{countrycode} = $country;
 
2351     eval { require "locale/$country/$NLS_file"; };
 
2354   $self->{NLS_file} = $NLS_file;
 
2356   push @{ $self->{LONG_MONTH} },
 
2357     ("January",   "February", "March",    "April",
 
2358      "May ",      "June",     "July",     "August",
 
2359      "September", "October",  "November", "December");
 
2360   push @{ $self->{SHORT_MONTH} },
 
2361     (qw(Jan Feb Mar Apr May Jun Jul Aug Sep Oct Nov Dec));
 
2363   $main::lxdebug->leave_sub();
 
2369   my ($self, $text) = @_;
 
2371   return (exists $self{texts}{$text}) ? $self{texts}{$text} : $text;
 
2375   $main::lxdebug->enter_sub();
 
2377   my ($self, $text) = @_;
 
2379   if (exists $self{subs}{$text}) {
 
2380     $text = $self{subs}{$text};
 
2382     if ($self->{countrycode} && $self->{NLS_file}) {
 
2384          "$text not defined in locale/$self->{countrycode}/$self->{NLS_file}");
 
2388   $main::lxdebug->leave_sub();
 
2394   $main::lxdebug->enter_sub();
 
2396   my ($self, $myconfig, $date, $longformat) = @_;
 
2399   my $longmonth = ($longformat) ? 'LONG_MONTH' : 'SHORT_MONTH';
 
2404     $spc = $myconfig->{dateformat};
 
2406     $spc = substr($spc, 1, 1);
 
2408     if ($date =~ /\D/) {
 
2409       if ($myconfig->{dateformat} =~ /^yy/) {
 
2410         ($yy, $mm, $dd) = split /\D/, $date;
 
2412       if ($myconfig->{dateformat} =~ /^mm/) {
 
2413         ($mm, $dd, $yy) = split /\D/, $date;
 
2415       if ($myconfig->{dateformat} =~ /^dd/) {
 
2416         ($dd, $mm, $yy) = split /\D/, $date;
 
2419       $date = substr($date, 2);
 
2420       ($yy, $mm, $dd) = ($date =~ /(..)(..)(..)/);
 
2425     $yy = ($yy < 70) ? $yy + 2000 : $yy;
 
2426     $yy = ($yy >= 70 && $yy <= 99) ? $yy + 1900 : $yy;
 
2428     if ($myconfig->{dateformat} =~ /^dd/) {
 
2429       if (defined $longformat && $longformat == 0) {
 
2431         $dd = "0$dd" if ($dd < 10);
 
2432         $mm = "0$mm" if ($mm < 10);
 
2433         $longdate = "$dd$spc$mm$spc$yy";
 
2436         $longdate .= ($spc eq '.') ? ". " : " ";
 
2437         $longdate .= &text($self, $self->{$longmonth}[$mm]) . " $yy";
 
2439     } elsif ($myconfig->{dateformat} eq "yyyy-mm-dd") {
 
2441       # Use German syntax with the ISO date style "yyyy-mm-dd" because
 
2442       # Lx-Office is mainly used in Germany or German speaking countries.
 
2443       if (defined $longformat && $longformat == 0) {
 
2445         $dd = "0$dd" if ($dd < 10);
 
2446         $mm = "0$mm" if ($mm < 10);
 
2447         $longdate = "$yy-$mm-$dd";
 
2449         $longdate = "$dd. ";
 
2450         $longdate .= &text($self, $self->{$longmonth}[$mm]) . " $yy";
 
2453       if (defined $longformat && $longformat == 0) {
 
2455         $dd = "0$dd" if ($dd < 10);
 
2456         $mm = "0$mm" if ($mm < 10);
 
2457         $longdate = "$mm$spc$dd$spc$yy";
 
2459         $longdate = &text($self, $self->{$longmonth}[$mm]) . " $dd, $yy";
 
2465   $main::lxdebug->leave_sub();
 
2471   $main::lxdebug->enter_sub();
 
2473   my ($self, $myconfig, $date, $longformat) = @_;
 
2476     $main::lxdebug->leave_sub();
 
2481   $spc = $myconfig->{dateformat};
 
2483   $spc = substr($spc, 1, 1);
 
2485   if ($date =~ /\D/) {
 
2486     if ($myconfig->{dateformat} =~ /^yy/) {
 
2487       ($yy, $mm, $dd) = split /\D/, $date;
 
2488     } elsif ($myconfig->{dateformat} =~ /^mm/) {
 
2489       ($mm, $dd, $yy) = split /\D/, $date;
 
2490     } elsif ($myconfig->{dateformat} =~ /^dd/) {
 
2491       ($dd, $mm, $yy) = split /\D/, $date;
 
2494     $date = substr($date, 2);
 
2495     ($yy, $mm, $dd) = ($date =~ /(..)(..)(..)/);
 
2500   $yy = ($yy < 70) ? $yy + 2000 : $yy;
 
2501   $yy = ($yy >= 70 && $yy <= 99) ? $yy + 1900 : $yy;
 
2503   $main::lxdebug->leave_sub();
 
2504   return ($yy, $mm, $dd);