='generator' content='cgit v1.2.3'/>
summaryrefslogtreecommitdiff
path: root/LedgerSMB/Form.pm
blob: 823ece35b48f914fce86bdeb3f0c5c3f44f42075 (plain)
  1. #=====================================================================
  2. # LedgerSMB
  3. # Small Medium Business Accounting software
  4. # http://www.ledgersmb.org/
  5. #
  6. # Copyright (C) 2006
  7. # This work contains copyrighted information from a number of sources all used
  8. # with permission.
  9. #
  10. # This file contains source code included with or based on SQL-Ledger which
  11. # is Copyright Dieter Simader and DWS Systems Inc. 2000-2005 and licensed
  12. # under the GNU General Public License version 2 or, at your option, any later
  13. # version. For a full list including contact information of contributors,
  14. # maintainers, and copyright holders, see the CONTRIBUTORS file.
  15. #
  16. # Original Copyright Notice from SQL-Ledger 2.6.17 (before the fork):
  17. # Copyright (C) 2000
  18. #
  19. # Author: DWS Systems Inc.
  20. # Web: http://www.sql-ledger.org
  21. #
  22. # Contributors: Thomas Bayen <bayen@gmx.de>
  23. # Antti Kaihola <akaihola@siba.fi>
  24. # Moritz Bunkus (tex)
  25. # Jim Rawlings <jim@your-dba.com> (DB2)
  26. #======================================================================
  27. #
  28. # This file has undergone whitespace cleanup.
  29. #
  30. #======================================================================
  31. #
  32. # main package
  33. #
  34. #======================================================================
  35. use Math::BigFloat lib => 'GMP';
  36. use LedgerSMB::Sysconfig;
  37. use List::Util qw(first);
  38. use LedgerSMB::Mailer;
  39. use Time::Local;
  40. use Cwd;
  41. use File::Copy;
  42. use charnames ':full';
  43. use open ':utf8';
  44. package Form;
  45. sub new {
  46. my $type = shift;
  47. my $argstr = shift;
  48. read( STDIN, $_, $ENV{CONTENT_LENGTH} );
  49. if ($argstr) {
  50. $_ = $argstr;
  51. }
  52. elsif ( $ENV{QUERY_STRING} ) {
  53. $_ = $ENV{QUERY_STRING};
  54. }
  55. elsif ( $ARGV[0] ) {
  56. $_ = $ARGV[0];
  57. }
  58. my $self = {};
  59. %$self = split /[&=]/;
  60. for ( keys %$self ) { $self->{$_} = unescape( "", $self->{$_} ) }
  61. if ( substr( $self->{action}, 0, 1 ) !~ /( |\.)/ ) {
  62. $self->{action} = lc $self->{action};
  63. $self->{action} =~ s/( |-|,|\#|\/|\.$)/_/g;
  64. $self->{nextsub} = lc $self->{nextsub};
  65. $self->{nextsub} =~ s/( |-|,|\#|\/|\.$)/_/g;
  66. }
  67. $self->{login} =~ s/[^a-zA-Z0-9._+\@'-]//g;
  68. $self->{menubar} = 1 if $self->{path} =~ /lynx/i;
  69. #menubar will be deprecated, replaced with below
  70. $self->{lynx} = 1 if $self->{path} =~ /lynx/i;
  71. $self->{version} = "SVN Trunk";
  72. $self->{dbversion} = "1.2.0";
  73. bless $self, $type;
  74. if ( $self->{path} ne 'bin/lynx' ) { $self->{path} = 'bin/mozilla'; }
  75. if ( ( $self->{script} )
  76. and not List::Util::first { $_ eq $self->{script} }
  77. @{LedgerSMB::Sysconfig::scripts} )
  78. {
  79. $self->error( 'Access Denied', __line__, __file__ );
  80. }
  81. if ( ( $self->{action} =~ /(:|')/ ) || ( $self->{nextsub} =~ /(:|')/ ) ) {
  82. $self->error( "Access Denied", __line__, __file__ );
  83. }
  84. for ( keys %$self ) { $self->{$_} =~ s/\N{NULL}//g }
  85. $self;
  86. }
  87. sub debug {
  88. my ( $self, $file ) = @_;
  89. if ($file) {
  90. open( FH, '>', "$file" ) or die $!;
  91. for ( sort keys %$self ) { print FH "$_ = $self->{$_}\n" }
  92. close(FH);
  93. }
  94. else {
  95. print "\n";
  96. for ( sort keys %$self ) { print "$_ = $self->{$_}\n" }
  97. }
  98. }
  99. sub encode_all {
  100. # TODO;
  101. }
  102. sub decode_all {
  103. # TODO
  104. }
  105. sub escape {
  106. my ( $self, $str, $beenthere ) = @_;
  107. # for Apache 2 we escape strings twice
  108. if ( ( $ENV{SERVER_SIGNATURE} =~ /Apache\/2\.(\d+)\.(\d+)/ )
  109. && !$beenthere )
  110. {
  111. $str = $self->escape( $str, 1 ) if $1 == 0 && $2 < 44;
  112. }
  113. utf8::encode($str);
  114. $str =~ s/([^a-zA-Z0-9_.-])/sprintf("%%%02x", ord($1))/ge;
  115. $str;
  116. }
  117. sub unescape {
  118. my ( $self, $str ) = @_;
  119. $str =~ tr/+/ /;
  120. $str =~ s/\\$//;
  121. utf8::encode($str) if utf8::is_utf8($str);
  122. $str =~ s/%([0-9a-fA-Z]{2})/pack("c",hex($1))/eg;
  123. utf8::decode($str);
  124. $str =~ s/\r?\n/\n/g;
  125. $str;
  126. }
  127. sub quote {
  128. my ( $self, $str ) = @_;
  129. if ( $str && !ref($str) ) {
  130. $str =~ s/"/&quot;/g;
  131. }
  132. $str;
  133. }
  134. sub unquote {
  135. my ( $self, $str ) = @_;
  136. if ( $str && !ref($str) ) {
  137. $str =~ s/&quot;/"/g;
  138. }
  139. $str;
  140. }
  141. sub hide_form {
  142. my $self = shift;
  143. if (@_) {
  144. for (@_) {
  145. print qq|<input type="hidden" name="$_" value="|
  146. . $self->quote( $self->{$_} )
  147. . qq|" />\n|;
  148. }
  149. }
  150. else {
  151. delete $self->{header};
  152. for ( sort keys %$self ) {
  153. print qq|<input type="hidden" name="$_" value="|
  154. . $self->quote( $self->{$_} )
  155. . qq|" />\n|;
  156. }
  157. }
  158. }
  159. sub error {
  160. my ( $self, $msg ) = @_;
  161. if ( $ENV{GATEWAY_INTERFACE} ) {
  162. $self->{msg} = $msg;
  163. $self->{format} = "html";
  164. $self->format_string('msg');
  165. delete $self->{pre};
  166. if ( !$self->{header} ) {
  167. $self->header;
  168. }
  169. print
  170. qq|<body><h2 class="error">Error!</h2> <p><b>$self->{msg}</b></body>|;
  171. exit;
  172. }
  173. else {
  174. if ( $ENV{error_function} ) {
  175. &{ $ENV{error_function} }($msg);
  176. }
  177. die "Error: $msg\n";
  178. }
  179. }
  180. sub info {
  181. my ( $self, $msg ) = @_;
  182. if ( $ENV{GATEWAY_INTERFACE} ) {
  183. $msg =~ s/\n/<br>/g;
  184. delete $self->{pre};
  185. if ( !$self->{header} ) {
  186. $self->header;
  187. print qq| <body>|;
  188. $self->{header} = 1;
  189. }
  190. print "<b>$msg</b>";
  191. }
  192. else {
  193. if ( $ENV{info_function} ) {
  194. &{ $ENV{info_function} }($msg);
  195. }
  196. else {
  197. print "$msg\n";
  198. }
  199. }
  200. }
  201. sub numtextrows {
  202. my ( $self, $str, $cols, $maxrows ) = @_;
  203. my $rows = 0;
  204. for ( split /\n/, $str ) {
  205. $rows += int( ( (length) - 2 ) / $cols ) + 1;
  206. }
  207. $maxrows = $rows unless defined $maxrows;
  208. return ( $rows > $maxrows ) ? $maxrows : $rows;
  209. }
  210. sub dberror {
  211. my ( $self, $msg ) = @_;
  212. $self->error( "$msg\n" . $DBI::errstr );
  213. }
  214. sub isblank {
  215. my ( $self, $name, $msg ) = @_;
  216. $self->error($msg) if $self->{$name} =~ /^\s*$/;
  217. }
  218. sub header {
  219. my ( $self, $init, $headeradd ) = @_;
  220. return if $self->{header};
  221. my ( $stylesheet, $favicon, $charset );
  222. if ( $ENV{GATEWAY_INTERFACE} ) {
  223. if ( $self->{stylesheet} && ( -f "css/$self->{stylesheet}" ) ) {
  224. $stylesheet =
  225. qq|<link rel="stylesheet" href="css/$self->{stylesheet}" type="text/css" title="LedgerSMB stylesheet" />\n|;
  226. }
  227. $self->{charset} ||= "utf-8";
  228. $charset =
  229. qq|<meta http-equiv="content-type" content="text/html; charset=$self->{charset}" />\n|;
  230. $self->{titlebar} =
  231. ( $self->{title} )
  232. ? "$self->{title} - $self->{titlebar}"
  233. : $self->{titlebar};
  234. print qq|Content-Type: text/html; charset=utf-8\n\n
  235. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  236. "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  237. <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
  238. <head>
  239. <title>$self->{titlebar}</title>
  240. <meta http-equiv="Pragma" content="no-cache" />
  241. <meta http-equiv="Expires" content="-1" />
  242. <link rel="shortcut icon" href="favicon.ico" type="image/x-icon" />
  243. $stylesheet
  244. $charset
  245. <meta name="robots" content="noindex,nofollow" />
  246. $headeradd
  247. </head>
  248. $self->{pre} \n|;
  249. }
  250. $self->{header} = 1;
  251. }
  252. sub redirect {
  253. my ( $self, $msg ) = @_;
  254. if ( $self->{callback} || !$msg ) {
  255. main::redirect();
  256. }
  257. else {
  258. $self->info($msg);
  259. }
  260. }
  261. sub sort_columns {
  262. my ( $self, @columns ) = @_;
  263. if ( $self->{sort} ) {
  264. if (@columns) {
  265. @columns = grep !/^$self->{sort}$/, @columns;
  266. splice @columns, 0, 0, $self->{sort};
  267. }
  268. }
  269. @columns;
  270. }
  271. sub sort_order {
  272. my ( $self, $columns, $ordinal ) = @_;
  273. # setup direction
  274. if ( $self->{direction} ) {
  275. if ( $self->{sort} eq $self->{oldsort} ) {
  276. if ( $self->{direction} eq 'ASC' ) {
  277. $self->{direction} = "DESC";
  278. }
  279. else {
  280. $self->{direction} = "ASC";
  281. }
  282. }
  283. }
  284. else {
  285. $self->{direction} = "ASC";
  286. }
  287. $self->{oldsort} = $self->{sort};
  288. my @a = $self->sort_columns( @{$columns} );
  289. if (%$ordinal) {
  290. $a[0] =
  291. ( $ordinal->{ $a[$_] } )
  292. ? "$ordinal->{$a[0]} $self->{direction}"
  293. : "$a[0] $self->{direction}";
  294. for ( 1 .. $#a ) {
  295. $a[$_] = $ordinal->{ $a[$_] } if $ordinal->{ $a[$_] };
  296. }
  297. }
  298. else {
  299. $a[0] .= " $self->{direction}";
  300. }
  301. $sortorder = join ',', @a;
  302. $sortorder;
  303. }
  304. sub format_amount {
  305. my ( $self, $myconfig, $amount, $places, $dash ) = @_;
  306. my $negative;
  307. if ($amount) {
  308. $amount = $self->parse_amount( $myconfig, $amount );
  309. $negative = ( $amount < 0 );
  310. $amount =~ s/-//;
  311. }
  312. if ( $places =~ /\d+/ ) {
  313. #$places = 4 if $places == 2;
  314. $amount = $self->round_amount( $amount, $places );
  315. }
  316. # is the amount negative
  317. # Parse $myconfig->{numberformat}
  318. my ( $ts, $ds ) = ( $1, $2 );
  319. if ($amount) {
  320. if ( $myconfig->{numberformat} ) {
  321. my ( $whole, $dec ) = split /\./, "$amount";
  322. $amount = join '', reverse split //, $whole;
  323. if ($places) {
  324. $dec .= "0" x $places;
  325. $dec = substr( $dec, 0, $places );
  326. }
  327. if ( $myconfig->{numberformat} eq '1,000.00' ) {
  328. $amount =~ s/\d{3,}?/$&,/g;
  329. $amount =~ s/,$//;
  330. $amount = join '', reverse split //, $amount;
  331. $amount .= "\.$dec" if ( $dec ne "" );
  332. }
  333. elsif ( $myconfig->{numberformat} eq '1 000.00' ) {
  334. $amount =~ s/\d{3,}?/$& /g;
  335. $amount =~ s/\s$//;
  336. $amount = join '', reverse split //, $amount;
  337. $amount .= "\.$dec" if ( $dec ne "" );
  338. }
  339. elsif ( $myconfig->{numberformat} eq "1'000.00" ) {
  340. $amount =~ s/\d{3,}?/$&'/g;
  341. $amount =~ s/'$//;
  342. $amount = join '', reverse split //, $amount;
  343. $amount .= "\.$dec" if ( $dec ne "" );
  344. }
  345. elsif ( $myconfig->{numberformat} eq '1.000,00' ) {
  346. $amount =~ s/\d{3,}?/$&./g;
  347. $amount =~ s/\.$//;
  348. $amount = join '', reverse split //, $amount;
  349. $amount .= ",$dec" if ( $dec ne "" );
  350. }
  351. elsif ( $myconfig->{numberformat} eq '1000,00' ) {
  352. $amount = "$whole";
  353. $amount .= ",$dec" if ( $dec ne "" );
  354. }
  355. elsif ( $myconfig->{numberformat} eq '1000.00' ) {
  356. $amount = "$whole";
  357. $amount .= ".$dec" if ( $dec ne "" );
  358. }
  359. if ( $dash =~ /-/ ) {
  360. $amount = ($negative) ? "($amount)" : "$amount";
  361. }
  362. elsif ( $dash =~ /DRCR/ ) {
  363. $amount = ($negative) ? "$amount DR" : "$amount CR";
  364. }
  365. else {
  366. $amount = ($negative) ? "-$amount" : "$amount";
  367. }
  368. }
  369. }
  370. else {
  371. if ( $dash eq "0" && $places ) {
  372. if ( $myconfig->{numberformat} =~ /0,00$/ ) {
  373. $amount = "0" . "," . "0" x $places;
  374. }
  375. else {
  376. $amount = "0" . "." . "0" x $places;
  377. }
  378. }
  379. else {
  380. $amount = ( $dash ne "" ) ? "$dash" : "";
  381. }
  382. }
  383. $amount;
  384. }
  385. sub parse_amount {
  386. my ( $self, $myconfig, $amount ) = @_;
  387. if ( ( $amount eq '' ) or ( ! defined $amount ) ) {
  388. $amount = 0;
  389. }
  390. if ( UNIVERSAL::isa( $amount, 'Math::BigFloat' ) )
  391. { # Amount may not be an object
  392. return $amount;
  393. }
  394. my $numberformat = $myconfig->{numberformat};
  395. if ( ( $numberformat eq '1.000,00' )
  396. || ( $numberformat eq '1000,00' ) )
  397. {
  398. $amount =~ s/\.//g;
  399. $amount =~ s/,/./;
  400. }
  401. elsif ( $numberformat eq '1 000.00' ) {
  402. $amount =~ s/\s//g;
  403. }
  404. elsif ( $numberformat eq "1'000.00" ) {
  405. $amount =~ s/'//g;
  406. }
  407. $amount =~ s/,//g;
  408. if ( $amount =~ s/\((\d*\.?\d*)\)/$1/ ) {
  409. $amount = $1 * -1;
  410. }
  411. elsif ( $amount =~ s/(\d*\.?\d*)\s?DR/$1/ ) {
  412. $amount = $1 * -1;
  413. }
  414. $amount =~ s/\s?CR//;
  415. $amount =~ /(\d*)\.(\d*)/;
  416. my $decimalplaces = length $1 + length $2;
  417. $amount = new Math::BigFloat($amount);
  418. return ( $amount * 1 );
  419. }
  420. sub round_amount {
  421. my ( $self, $amount, $places ) = @_;
  422. # These rounding rules follow from the previous implementation.
  423. # They should be changed to allow different rules for different accounts.
  424. Math::BigFloat->round_mode('+inf') if $amount >= 0;
  425. Math::BigFloat->round_mode('-inf') if $amount < 0;
  426. $amount = Math::BigFloat->new($amount)->ffround( -$places ) if $places >= 0;
  427. $amount = Math::BigFloat->new($amount)->ffround( -( $places - 1 ) )
  428. if $places < 0;
  429. $amount->precision(undef); #we are assuming whole cents so do not round
  430. #immediately on arithmatic. This is necessary
  431. #because Math::BigFloat is arithmatically
  432. #correct wrt accuracy and precision.
  433. return $amount;
  434. }
  435. sub db_parse_numeric {
  436. my $self = shift;
  437. my %args = @_;
  438. my ($sth, $arrayref, $hashref) = ($args{sth}, $args{arrayref},
  439. $args{hashref});
  440. my @types = @{$sth->{TYPE}};
  441. my @names = @{$sth->{NAME_lc}};
  442. for (0 .. $#names){
  443. if ($types[$_] == 3){
  444. $arrayref[$_] = Math::BigFloat->new($arrayref[$_])
  445. if defined $arrayref;
  446. $hashref->{$names[$_]} = Math::BigFloat->new($hashref->{$names[$_]})
  447. if defined $hashref;
  448. }
  449. }
  450. return ($hashref || $arrayref);
  451. }
  452. sub callproc {
  453. my $procname = shift @_;
  454. my $argstr = "";
  455. my @results;
  456. for ( 1 .. $#_ ) {
  457. $argstr .= "?, ";
  458. }
  459. $argstr =~ s/\, $//;
  460. $query = "SELECT * FROM $procname";
  461. $query =~ s/\(\)/$argstr/;
  462. my $sth = $self->{dbh}->prepare($query);
  463. while ( my $ref = $sth->fetchrow_hashref(NAME_lc) ) {
  464. push @results, $ref;
  465. }
  466. @results;
  467. }
  468. sub get_my_emp_num {
  469. my ( $self, $myconfig, $form ) = @_;
  470. %myconfig = %{$myconfig};
  471. my $dbh = $form->{dbh};
  472. # we got a connection, check the version
  473. my $query = qq|
  474. SELECT employeenumber FROM employee
  475. WHERE login = ?|;
  476. my $sth = $dbh->prepare($query);
  477. $sth->execute( $form->{login} ) || $form->dberror($query);
  478. $sth->execute;
  479. my ($id) = $sth->fetchrow_array;
  480. $sth->finish;
  481. $form->{'emp_num'} = $id;
  482. }
  483. sub parse_template {
  484. my ( $self, $myconfig ) = @_;
  485. my ( $chars_per_line, $lines_on_first_page, $lines_on_second_page ) =
  486. ( 0, 0, 0 );
  487. my ( $current_page, $current_line ) = ( 1, 1 );
  488. print STDERR "Using deprecated Form::parse_template function\n";
  489. my $pagebreak = "";
  490. my $sum = 0;
  491. my $subdir = "";
  492. my $err = "";
  493. my %include = ();
  494. my $ok;
  495. $self->{images} = "${LedgerSMB::Sysconfig::images}/$self->{templates}";
  496. if ( $self->{language_code} ) {
  497. if ( $self->{language_code} =~ /(\.\.|\/|\*)/ ) {
  498. $self->error("Invalid Language Code");
  499. }
  500. if ( -f "$self->{templates}/$self->{language_code}/$self->{IN}" ) {
  501. open( IN, '<',
  502. "$self->{templates}/$self->{language_code}/$self->{IN}" )
  503. or $self->error("$self->{IN} : $!");
  504. }
  505. else {
  506. open( IN, '<', "$self->{templates}/$self->{IN}" )
  507. or $self->error("$self->{IN} : $!");
  508. }
  509. }
  510. else {
  511. open( IN, '<', "$self->{templates}/$self->{IN}" )
  512. or $self->error("$self->{IN} : $!");
  513. }
  514. @_ = <IN>;
  515. close(IN);
  516. $self->{copies} = 1 if ( ( $self->{copies} *= 1 ) <= 0 );
  517. # OUT is used for the media, screen, printer, email
  518. # for postscript we store a copy in a temporary file
  519. my $fileid = time;
  520. my $tmpfile = $self->{IN};
  521. $tmpfile =~ s/\./_$self->{fileid}./ if $self->{fileid};
  522. $self->{tmpfile} = "${LedgerSMB::Sysconfig::tempdir}/${fileid}_${tmpfile}";
  523. my $temphash;
  524. if ( $self->{format} =~ /(postscript|pdf)/ || $self->{media} eq 'email' ) {
  525. $temphash{out} = $self->{OUT};
  526. $self->{OUT} = "$self->{tmpfile}";
  527. File::Copy::copy(
  528. "$self->{templates}/logo.png",
  529. "${LedgerSMB::Sysconfig::tempdir}/"
  530. );
  531. File::Copy::copy(
  532. "$self->{templates}/logo.eps",
  533. "${LedgerSMB::Sysconfig::tempdir}/"
  534. );
  535. $temphash{printmode} = $self->{printmode};
  536. $self->{printmode} = '>';
  537. }
  538. if ( $self->{OUT} ) {
  539. open( OUT, $self->{printmode}, "$self->{OUT}" )
  540. or $self->error("$self->{OUT} : $!");
  541. chmod( 0600, "$self->{OUT}" );
  542. }
  543. else {
  544. open( OUT, ">-" ) or $self->error("STDOUT : $!");
  545. $self->header;
  546. }
  547. # first we generate a tmpfile
  548. # read file and replace <?lsmb variable ?>
  549. while ( $_ = shift ) {
  550. $par = "";
  551. $var = $_;
  552. # detect pagebreak block and its parameters
  553. if (/<\?lsmb pagebreak ([0-9]+) ([0-9]+) ([0-9]+) \?>/) {
  554. $chars_per_line = $1;
  555. $lines_on_first_page = $2;
  556. $lines_on_second_page = $3;
  557. while ( $_ = shift ) {
  558. last if (/<\?lsmb end pagebreak \?>/);
  559. $pagebreak .= $_;
  560. }
  561. }
  562. if (/<\?lsmb foreach /) {
  563. # this one we need for the count
  564. chomp $var;
  565. $var =~ s/.*?<\?lsmb foreach (.+?) \?>/$1/;
  566. while ( $_ = shift ) {
  567. last if (/<\?lsmb end $var \?>/);
  568. # store line in $par
  569. $par .= $_;
  570. }
  571. # display contents of $self->{number}[] array
  572. for $i ( 0 .. $#{ $self->{$var} } ) {
  573. if ( $var =~ /^(part|service)$/ ) {
  574. next if $self->{$var}[$i] eq 'NULL';
  575. }
  576. # Try to detect whether a manual page break is necessary
  577. # but only if there was a <?lsmb pagebreak ... ?> block before
  578. if ( $var eq 'number' || $var eq 'part' || $var eq 'service' ) {
  579. if ( $chars_per_line && defined $self->{$var} ) {
  580. my $line;
  581. my $lines = 0;
  582. my @d = qw(description);
  583. push @d, "itemnotes" if $self->{countitemnotes};
  584. foreach my $item (@d) {
  585. if ( $self->{$item}[$i] ) {
  586. foreach $line ( split /\r?\n/,
  587. $self->{$item}[$i] )
  588. {
  589. $lines++;
  590. $lines +=
  591. int( length($line) / $chars_per_line );
  592. }
  593. }
  594. }
  595. my $lpp;
  596. if ( $current_page == 1 ) {
  597. $lpp = $lines_on_first_page;
  598. }
  599. else {
  600. $lpp = $lines_on_second_page;
  601. }
  602. # Yes we need a manual page break
  603. if ( ( $current_line + $lines ) > $lpp ) {
  604. my $pb = $pagebreak;
  605. # replace the special variables <?lsmb sumcarriedforward ?>
  606. # and <?lsmb lastpage ?>
  607. my $psum =
  608. $self->format_amount( $myconfig, $sum, 2 );
  609. $pb =~ s/<\?lsmb sumcarriedforward \?>/$psum/g;
  610. $pb =~ s/<\?lsmb lastpage \?>/$current_page/g;
  611. # only "normal" variables are supported here
  612. # (no <?lsmb if, no <?lsmb foreach, no <?lsmb include)
  613. $pb =~ s/<\?lsmb (.+?) \?>/$self->{$1}/g;
  614. # page break block is ready to rock
  615. print( OUT $pb );
  616. $current_page++;
  617. $current_line = 1;
  618. $lines = 0;
  619. }
  620. $current_line += $lines;
  621. }
  622. $sum +=
  623. $self->parse_amount( $myconfig, $self->{linetotal}[$i] );
  624. }
  625. # don't parse par, we need it for each line
  626. print OUT $self->format_line( $par, $i );
  627. }
  628. next;
  629. }
  630. # if not comes before if!
  631. if (/<\?lsmb if not /) {
  632. # check if it is not set and display
  633. chop;
  634. s/.*?<\?lsmb if not (.+?) \?>/$1/;
  635. if ( !$self->{$_} ) {
  636. while ( $_ = shift ) {
  637. last if (/<\?lsmb end /);
  638. # store line in $par
  639. $par .= $_;
  640. }
  641. $_ = $par;
  642. }
  643. else {
  644. while ( $_ = shift ) {
  645. last if (/<\?lsmb end /);
  646. }
  647. next;
  648. }
  649. }
  650. if (/<\?lsmb if /) {
  651. # check if it is set and display
  652. chop;
  653. s/.*?<\?lsmb if (.+?) \?>/$1/;
  654. # commenting this out for security reasons. If needed,
  655. # please uncomment. Functionality below will be in 1.3
  656. # Chris Travers
  657. #if (/\s/) {
  658. # @args = split;
  659. # if ($args[1] !~ /^(==|eq|>|gt|>|lt|>=|ge|le|<=|ne|!=)$/){
  660. # $self->error("Unknown/forbidden operator");
  661. # }
  662. # $ok = eval "$self->{$args[0]} $args[1] $args[2]";
  663. #} else {
  664. $ok = $self->{$_};
  665. #}
  666. if ($ok) {
  667. while ( $_ = shift ) {
  668. last if (/<\?lsmb end /);
  669. # store line in $par
  670. $par .= $_;
  671. }
  672. $_ = $par;
  673. }
  674. else {
  675. while ( $_ = shift ) {
  676. last if (/<\?lsmb end /);
  677. }
  678. next;
  679. }
  680. }
  681. # check for <?lsmb include filename ?>
  682. if (/<\?lsmb include /) {
  683. # get the filename
  684. chomp $var;
  685. $var =~ s/.*?<\?lsmb include (.+?) \?>/$1/;
  686. # remove / .. for security reasons
  687. $var =~ s/(\/|\.\.)//g;
  688. # assume loop after 10 includes of the same file
  689. next if ( $include{$var} > 10 );
  690. unless (
  691. open( INC, '<', "$self->{templates}/$self->{language_code}/$var"
  692. )
  693. )
  694. {
  695. $err = $!;
  696. $self->cleanup;
  697. $self->error(
  698. "$self->{templates}/$self->{language_code}/$var : $err");
  699. }
  700. unshift( @_, <INC> );
  701. close(INC);
  702. $include{$var}++;
  703. next;
  704. }
  705. print OUT $self->format_line($_);
  706. }
  707. close(OUT);
  708. delete $self->{countitemnotes};
  709. # Convert the tex file to postscript
  710. if ( $self->{format} =~ /(postscript|pdf)/ ) {
  711. $self->{tmpdir} = "${LedgerSMB::Sysconfig::tempdir}";
  712. unless ( chdir( $self->{tmpdir} ) ) {
  713. $err = $!;
  714. $self->cleanup;
  715. $self->error("chdir : $self->{tmpdir} : $err");
  716. }
  717. $self->{tmpfile} =~ s/$self->{tmpdir}\///g;
  718. $self->{errfile} = $self->{tmpfile};
  719. $self->{errfile} =~ s/tex$/err/;
  720. my $r = 1;
  721. if ( $self->{format} eq 'postscript' ) {
  722. system(
  723. "latex --interaction=nonstopmode $self->{tmpfile} > $self->{errfile}"
  724. );
  725. while ( $self->rerun_latex ) {
  726. system(
  727. "latex --interaction=nonstopmode $self->{tmpfile} > $self->{errfile}"
  728. );
  729. last if ++$r > 4;
  730. }
  731. $self->{tmpfile} =~ s/tex$/dvi/;
  732. $self->error( $self->cleanup ) if !( -f $self->{tmpfile} );
  733. system("dvips $self->{tmpfile} -o -q");
  734. $self->error( $self->cleanup . "dvips : $!" ) if ($?);
  735. $self->{tmpfile} =~ s/dvi$/ps/;
  736. }
  737. if ( $self->{format} eq 'pdf' ) {
  738. system(
  739. "pdflatex --interaction=nonstopmode $self->{tmpfile} > $self->{errfile}"
  740. );
  741. while ( $self->rerun_latex ) {
  742. system(
  743. "pdflatex --interaction=nonstopmode $self->{tmpfile} > $self->{errfile}"
  744. );
  745. last if ++$r > 4;
  746. }
  747. $self->{tmpfile} =~ s/tex$/pdf/;
  748. $self->error( $self->cleanup ) if !( -f $self->{tmpfile} );
  749. }
  750. }
  751. if ( $self->{format} =~ /(postscript|pdf)/ || $self->{media} eq 'email' ) {
  752. if ( $self->{media} eq 'email' ) {
  753. my $mail = new Mailer;
  754. for (qw(cc bcc subject message version format charset)) {
  755. $mail->{$_} = $self->{$_};
  756. }
  757. $mail->{to} = qq|$self->{email}|;
  758. $mail->{from} = qq|"$myconfig->{name}" <$myconfig->{email}>|;
  759. $mail->{notify} = $self->{notify};
  760. $mail->{fileid} = "$fileid.";
  761. # if we send html or plain text inline
  762. if ( ( $self->{format} =~ /(html|txt)/ )
  763. && ( $self->{sendmode} eq 'inline' ) )
  764. {
  765. my $br = "";
  766. $br = "<br>" if $self->{format} eq 'html';
  767. $mail->{contenttype} = "text/$self->{format}";
  768. $mail->{message} =~ s/\r?\n/$br\n/g;
  769. $myconfig->{signature} =~ s/\\n/$br\n/g;
  770. $mail->{message} .= "$br\n-- $br\n$myconfig->{signature}\n$br"
  771. if $myconfig->{signature};
  772. unless ( open( IN, '<', $self->{tmpfile} ) ) {
  773. $err = $!;
  774. $self->cleanup;
  775. $self->error("$self->{tmpfile} : $err");
  776. }
  777. while (<IN>) {
  778. $mail->{message} .= $_;
  779. }
  780. close(IN);
  781. }
  782. else {
  783. @{ $mail->{attachments} } = ( $self->{tmpfile} );
  784. $myconfig->{signature} =~ s/\\n/\n/g;
  785. $mail->{message} .= "\n-- \n$myconfig->{signature}"
  786. if $myconfig->{signature};
  787. }
  788. if ( $err = $mail->send ) {
  789. $self->cleanup;
  790. $self->error($err);
  791. }
  792. }
  793. else {
  794. $self->{OUT} = $temphash{out};
  795. $self->{printmode} = $temphash{printmode} if $temphash{printmode};
  796. unless ( open( IN, '<', $self->{tmpfile} ) ) {
  797. $err = $!;
  798. $self->cleanup;
  799. $self->error("$self->{tmpfile} : $err");
  800. }
  801. binmode(IN);
  802. $self->{copies} = 1 if $self->{media} =~ /(screen|email|queue)/;
  803. chdir("$self->{cwd}");
  804. for my $i ( 1 .. $self->{copies} ) {
  805. if ( $self->{OUT} ) {
  806. unless ( open( OUT, $self->{printmode}, $self->{OUT} ) ) {
  807. $err = $!;
  808. $self->cleanup;
  809. $self->error("$self->{OUT} : $err");
  810. }
  811. chmod( 0600, "$self->{OUT}" );
  812. }
  813. else {
  814. # launch application
  815. print qq|Content-Type: application/$self->{format}\n|
  816. . qq|Content-Disposition: attachment; filename="$self->{tmpfile}"\n\n|;
  817. unless ( open( OUT, ">-" ) ) {
  818. $err = $!;
  819. $self->cleanup;
  820. $self->error("STDOUT : $err");
  821. }
  822. }
  823. binmode(OUT);
  824. while (<IN>) {
  825. print OUT $_;
  826. }
  827. close(OUT);
  828. seek IN, 0, 0;
  829. }
  830. close(IN);
  831. }
  832. $self->cleanup;
  833. }
  834. }
  835. sub format_line {
  836. my $self = shift;
  837. $_ = shift;
  838. my $i = shift;
  839. my $str;
  840. my $newstr;
  841. my $pos;
  842. my $l;
  843. my $lf;
  844. my $line;
  845. my $var = "";
  846. my %a;
  847. my $offset;
  848. my $pad;
  849. my $item;
  850. while (/<\?lsmb (.+?) \?>/) {
  851. %a = ();
  852. foreach $item ( split / /, $1 ) {
  853. my ( $key, $value ) = split /=/, $item;
  854. if ( $value ne "" ) {
  855. $a{$key} = $value;
  856. }
  857. else {
  858. $var = $item;
  859. }
  860. }
  861. $str = ( defined $i ) ? $self->{$var}[$i] : $self->{$var};
  862. $newstr = $str;
  863. $self->{countitemnotes} = 1 if $var eq 'itemnotes';
  864. $var = $1;
  865. if ( $var =~ /^if\s+not\s+/ ) {
  866. if ($str) {
  867. $var =~ s/if\s+not\s+//;
  868. s/<\?lsmb if\s+not\s+$var \?>.*?(<\?lsmb end\s+$var \?>|$)//s;
  869. }
  870. else {
  871. s/<\?lsmb $var \?>//;
  872. }
  873. next;
  874. }
  875. if ( $var =~ /^if\s+/ ) {
  876. if ($str) {
  877. s/<\?lsmb $var \?>//;
  878. }
  879. else {
  880. $var =~ s/if\s+//;
  881. s/<\?lsmb if\s+$var \?>.*?(<\?lsmb end\s+$var \?>|$)//s;
  882. }
  883. next;
  884. }
  885. if ( $var =~ /^end\s+/ ) {
  886. s/<\?lsmb $var \?>//;
  887. next;
  888. }
  889. if ( $a{align} || $a{width} || $a{offset} ) {
  890. $newstr = "";
  891. $offset = 0;
  892. $lf = "";
  893. foreach $str ( split /\n/, $str ) {
  894. $line = $str;
  895. $l = length $str;
  896. do {
  897. if ( ( $pos = length $str ) > $a{width} ) {
  898. if ( ( $pos = rindex $str, " ", $a{width} ) > 0 ) {
  899. $line = substr( $str, 0, $pos );
  900. }
  901. $pos = length $str if $pos == -1;
  902. }
  903. $l = length $line;
  904. # pad left, right or center
  905. $l = ( $a{width} - $l );
  906. $pad = " " x $l;
  907. if ( $a{align} =~ /right/i ) {
  908. $line = " " x $offset . $pad . $line;
  909. }
  910. if ( $a{align} =~ /left/i ) {
  911. $line = " " x $offset . $line . $pad;
  912. }
  913. if ( $a{align} =~ /center/i ) {
  914. $pad = " " x ( $l / 2 );
  915. $line = " " x $offset . $pad . $line;
  916. $pad = " " x ( $l / 2 );
  917. $line .= $pad;
  918. }
  919. $newstr .= "$lf$line";
  920. $str = substr( $str, $pos + 1 );
  921. $line = $str;
  922. $lf = "\n";
  923. $offset = $a{offset};
  924. } while ($str);
  925. }
  926. }
  927. s/<\?lsmb (.+?) \?>/$newstr/;
  928. }
  929. $_;
  930. }
  931. sub cleanup {
  932. my $self = shift;
  933. chdir("$self->{tmpdir}");
  934. my @err = ();
  935. if ( -f "$self->{errfile}" ) {
  936. open( FH, '<', "$self->{errfile}" );
  937. @err = <FH>;
  938. close(FH);
  939. }
  940. if ( $self->{tmpfile} ) {
  941. # strip extension
  942. $self->{tmpfile} =~ s/\.\w+$//g;
  943. my $tmpfile = $self->{tmpfile};
  944. unlink(<$tmpfile.*>);
  945. }
  946. chdir("$self->{cwd}");
  947. "@err";
  948. }
  949. sub rerun_latex {
  950. my $self = shift;
  951. my $a = 0;
  952. if ( -f "$self->{errfile}" ) {
  953. open( FH, '<', "$self->{errfile}" );
  954. $a = grep /(longtable Warning:|Warning:.*?LastPage)/, <FH>;
  955. close(FH);
  956. }
  957. $a;
  958. }
  959. sub format_string {
  960. my ( $self, @fields ) = @_;
  961. my $format = $self->{format};
  962. if ( $self->{format} =~ /(postscript|pdf)/ ) {
  963. $format = 'tex';
  964. }
  965. my %replace = (
  966. 'order' => {
  967. html => [ '<', '>', '\n', '\r' ],
  968. txt => [ '\n', '\r' ],
  969. tex => [
  970. quotemeta('\\'), '&', '\n', '\r',
  971. '\$', '%', '_', '#',
  972. quotemeta('^'), '{', '}', '<',
  973. '>', '£'
  974. ]
  975. },
  976. html => {
  977. '<' => '&lt;',
  978. '>' => '&gt;',
  979. '\n' => '<br />',
  980. '\r' => '<br />'
  981. },
  982. txt => { '\n' => "\n", '\r' => "\r" },
  983. tex => {
  984. '&' => '\&',
  985. '$' => '\$',
  986. '%' => '\%',
  987. '_' => '\_',
  988. '#' => '\#',
  989. quotemeta('^') => '\^\\',
  990. '{' => '\{',
  991. '}' => '\}',
  992. '<' => '$<$',
  993. '>' => '$>$',
  994. '\n' => '\newline ',
  995. '\r' => '\newline ',
  996. '£' => '\pounds ',
  997. quotemeta('\\') => '/'
  998. }
  999. );
  1000. my $key;
  1001. foreach $key ( @{ $replace{order}{$format} } ) {
  1002. for (@fields) { $self->{$_} =~ s/$key/$replace{$format}{$key}/g }
  1003. }
  1004. }
  1005. sub datetonum {
  1006. my ( $self, $myconfig, $date, $picture ) = @_;
  1007. if ( $date && $date =~ /\D/ ) {
  1008. if ( $myconfig->{dateformat} =~ /^yy/ ) {
  1009. ( $yy, $mm, $dd ) = split /\D/, $date;
  1010. }
  1011. elsif ( $myconfig->{dateformat} =~ /^mm/ ) {
  1012. ( $mm, $dd, $yy ) = split /\D/, $date;
  1013. }
  1014. elsif ( $myconfig->{dateformat} =~ /^dd/ ) {
  1015. ( $dd, $mm, $yy ) = split /\D/, $date;
  1016. }
  1017. $dd *= 1;
  1018. $mm *= 1;
  1019. $yy += 2000 if length $yy == 2;
  1020. $dd = substr( "0$dd", -2 );
  1021. $mm = substr( "0$mm", -2 );
  1022. $date = "$yy$mm$dd";
  1023. }
  1024. $date;
  1025. }
  1026. sub add_date {
  1027. my ( $self, $myconfig, $date, $repeat, $unit ) = @_;
  1028. my $diff = 0;
  1029. my $spc = $myconfig->{dateformat};
  1030. my $yy;
  1031. my $mm;
  1032. my $dd;
  1033. $spc =~ s/\w//g;
  1034. $spc = substr( $spc, 0, 1 );
  1035. if ($date) {
  1036. if ( $date =~ /\D/ ) {
  1037. if ( $myconfig->{dateformat} =~ /^yy/ ) {
  1038. ( $yy, $mm, $dd ) = split /\D/, $date;
  1039. }
  1040. elsif ( $myconfig->{dateformat} =~ /^mm/ ) {
  1041. ( $mm, $dd, $yy ) = split /\D/, $date;
  1042. }
  1043. elsif ( $myconfig->{dateformat} =~ /^dd/ ) {
  1044. ( $dd, $mm, $yy ) = split /\D/, $date;
  1045. }
  1046. }
  1047. else {
  1048. # ISO
  1049. ( $yy, $mm, $dd ) = ($date =~ /(....)(..)(..)/);
  1050. }
  1051. if ( $unit eq 'days' ) {
  1052. $diff = $repeat * 86400;
  1053. }
  1054. elsif ( $unit eq 'weeks' ) {
  1055. $diff = $repeat * 604800;
  1056. }
  1057. elsif ( $unit eq 'months' ) {
  1058. $diff = $mm + $repeat;
  1059. my $whole = int( $diff / 12 );
  1060. $yy += $whole;
  1061. $mm = ( $diff % 12 );
  1062. $mm = '12' if $mm == 0;
  1063. $yy-- if $mm == 12;
  1064. $diff = 0;
  1065. }
  1066. elsif ( $unit eq 'years' ) {
  1067. $yy += $repeat;
  1068. }
  1069. $mm--;
  1070. @t = localtime( Time::Local::timelocal( 0, 0, 0, $dd, $mm, $yy ) + $diff );
  1071. $t[4]++;
  1072. $mm = substr( "0$t[4]", -2 );
  1073. $dd = substr( "0$t[3]", -2 );
  1074. $yy = $t[5] + 1900;
  1075. if ( $date =~ /\D/ ) {
  1076. if ( $myconfig->{dateformat} =~ /^yy/ ) {
  1077. $date = "$yy$spc$mm$spc$dd";
  1078. }
  1079. elsif ( $myconfig->{dateformat} =~ /^mm/ ) {
  1080. $date = "$mm$spc$dd$spc$yy";
  1081. }
  1082. elsif ( $myconfig->{dateformat} =~ /^dd/ ) {
  1083. $date = "$dd$spc$mm$spc$yy";
  1084. }
  1085. }
  1086. else {
  1087. $date = "$yy$mm$dd";
  1088. }
  1089. }
  1090. $date;
  1091. }
  1092. sub print_button {
  1093. my ( $self, $button, $name ) = @_;
  1094. print
  1095. qq|<button class="submit" type="submit" name="action" value="$name" accesskey="$button->{$name}{key}" title="$button->{$name}{value} [Alt-$button->{$name}{key}]">$button->{$name}{value}</button>\n|;
  1096. }
  1097. # Database routines used throughout
  1098. sub db_init {
  1099. my ( $self, $myconfig ) = @_;
  1100. $self->{dbh} = $self->dbconnect_noauto($myconfig) || $self->dberror();
  1101. %date_query = (
  1102. 'mm/dd/yy' => 'set DateStyle to \'SQL, US\'',
  1103. 'mm-dd-yy' => 'set DateStyle to \'POSTGRES, US\'',
  1104. 'dd/mm/yy' => 'set DateStyle to \'SQL, EUROPEAN\'',
  1105. 'dd-mm-yy' => 'set DateStyle to \'POSTGRES, EUROPEAN\'',
  1106. 'dd.mm.yy' => 'set DateStyle to \'GERMAN\''
  1107. );
  1108. $self->{dbh}->do( $date_query{ $myconfig->{dateformat} } );
  1109. $self->{db_dateformat} = $myconfig->{dateformat}; #shim
  1110. my $query = "SELECT t.extends,
  1111. coalesce (t.table_name, 'custom_' || extends)
  1112. || ':' || f.field_name as field_def
  1113. FROM custom_table_catalog t
  1114. JOIN custom_field_catalog f USING (table_id)";
  1115. my $sth = $self->{dbh}->prepare($query);
  1116. $sth->execute;
  1117. my $ref;
  1118. while ( $ref = $sth->fetchrow_hashref(NAME_lc) ) {
  1119. push @{ $self->{custom_db_fields}{ $ref->{extends} } },
  1120. $ref->{field_def};
  1121. }
  1122. }
  1123. sub run_custom_queries {
  1124. my ( $self, $tablename, $query_type, $linenum ) = @_;
  1125. my $dbh = $self->{dbh};
  1126. if ( $query_type !~ /^(select|insert|update)$/i ) {
  1127. $self->error(
  1128. $locale->text(
  1129. "Passed incorrect query type to run_custom_queries."
  1130. )
  1131. );
  1132. }
  1133. my @rc;
  1134. my %temphash;
  1135. my @templist;
  1136. my @elements;
  1137. my $query;
  1138. my $ins_values;
  1139. if ($linenum) {
  1140. $linenum = "_$linenum";
  1141. }
  1142. $query_type = uc($query_type);
  1143. for ( @{ $self->{custom_db_fields}{$tablename} } ) {
  1144. @elements = split( /:/, $_ );
  1145. push @{ $temphash{ $elements[0] } }, $elements[1];
  1146. }
  1147. for ( keys %temphash ) {
  1148. my @data;
  1149. my $ins_values;
  1150. $query = "$query_type ";
  1151. if ( $query_type eq 'UPDATE' ) {
  1152. $query = "DELETE FROM $_ WHERE row_id = ?";
  1153. my $sth = $dbh->prepare($query);
  1154. $sth->execute( $self->{ "id" . "$linenum" } )
  1155. || $self->dberror($query);
  1156. }
  1157. elsif ( $query_type eq 'INSERT' ) {
  1158. $query .= " INTO $_ (";
  1159. }
  1160. my $first = 1;
  1161. for ( @{ $temphash{$_} } ) {
  1162. $query .= "$_";
  1163. if ( $query_type eq 'UPDATE' ) {
  1164. $query .= '= ?';
  1165. }
  1166. $ins_values .= "?, ";
  1167. $query .= ", ";
  1168. $first = 0;
  1169. if ( $query_type eq 'UPDATE' or $query_type eq 'INSERT' ) {
  1170. push @data, $self->{"$_$linenum"};
  1171. }
  1172. }
  1173. if ( $query_type ne 'INSERT' ) {
  1174. $query =~ s/, $//;
  1175. }
  1176. if ( $query_type eq 'SELECT' ) {
  1177. $query .= " FROM $_";
  1178. }
  1179. if ( $query_type eq 'SELECT' or $query_type eq 'UPDATE' ) {
  1180. $query .= " WHERE row_id = ?";
  1181. }
  1182. if ( $query_type eq 'INSERT' ) {
  1183. $query .= " row_id) VALUES ($ins_values ?)";
  1184. }
  1185. if ( $query_type eq 'SELECT' ) {
  1186. push @rc, [$query];
  1187. }
  1188. else {
  1189. unshift( @data, $query );
  1190. push @rc, [@data];
  1191. }
  1192. }
  1193. if ( $query_type eq 'INSERT' ) {
  1194. for (@rc) {
  1195. $query = shift( @{$_} );
  1196. $sth = $dbh->prepare($query)
  1197. || $self->db_error($query);
  1198. $sth->execute( @{$_}, $self->{id} )
  1199. || $self->dberror($query);
  1200. $sth->finish;
  1201. $did_insert = 1;
  1202. }
  1203. }
  1204. elsif ( $query_type eq 'UPDATE' ) {
  1205. @rc = $self->run_custom_queries( $tablename, 'INSERT', $linenum );
  1206. }
  1207. elsif ( $query_type eq 'SELECT' ) {
  1208. for (@rc) {
  1209. $query = shift @{$_};
  1210. $sth = $self->{dbh}->prepare($query);
  1211. $sth->execute( $self->{id} );
  1212. $ref = $sth->fetchrow_hashref(NAME_lc);
  1213. for ( keys %{$ref} ) {
  1214. $self->{$_} = $ref->{$_};
  1215. }
  1216. }
  1217. }
  1218. @rc;
  1219. }
  1220. sub dbconnect {
  1221. my ( $self, $myconfig ) = @_;
  1222. # connect to database
  1223. my $dbh = DBI->connect( $myconfig->{dbconnect},
  1224. $myconfig->{dbuser}, $myconfig->{dbpasswd} )
  1225. or $self->dberror;
  1226. $dbh->{pg_enable_utf8} = 1;
  1227. # set db options
  1228. if ( $myconfig->{dboptions} ) {
  1229. $dbh->do( $myconfig->{dboptions} )
  1230. || $self->dberror( $myconfig->{dboptions} );
  1231. }
  1232. $dbh;
  1233. }
  1234. sub dbconnect_noauto {
  1235. my ( $self, $myconfig ) = @_;
  1236. # connect to database
  1237. $dbh = DBI->connect(
  1238. $myconfig->{dbconnect}, $myconfig->{dbuser},
  1239. $myconfig->{dbpasswd}, { AutoCommit => 0 }
  1240. ) or $self->dberror;
  1241. $dbh->{pg_enable_utf8} = 1;
  1242. # set db options
  1243. if ( $myconfig->{dboptions} ) {
  1244. $dbh->do( $myconfig->{dboptions} );
  1245. }
  1246. $dbh;
  1247. }
  1248. sub dbquote {
  1249. my ( $self, $var ) = @_;
  1250. if ( $var eq '' ) {
  1251. $_ = "NULL";
  1252. }
  1253. else {
  1254. $_ = $self->{dbh}->quote($var);
  1255. }
  1256. $_;
  1257. }
  1258. sub update_balance {
  1259. # This is a dangerous private function. All apps calling it must
  1260. # be careful to avoid SQL injection issues
  1261. my ( $self, $dbh, $table, $field, $where, $value ) = @_;
  1262. # if we have a value, go do it
  1263. if ($value) {
  1264. # retrieve balance from table
  1265. my $query = "SELECT $field FROM $table WHERE $where FOR UPDATE";
  1266. my ($balance) = $dbh->selectrow_array($query);
  1267. $balance += $value;
  1268. # update balance
  1269. $query = "UPDATE $table SET $field = $balance WHERE $where";
  1270. $dbh->do($query) || $self->dberror($query);
  1271. }
  1272. }
  1273. sub update_exchangerate {
  1274. my ( $self, $dbh, $curr, $transdate, $buy, $sell ) = @_;
  1275. # some sanity check for currency
  1276. return if ( $curr eq "" );
  1277. my $query = qq|
  1278. SELECT curr
  1279. FROM exchangerate
  1280. WHERE curr = ?
  1281. AND transdate = ?
  1282. FOR UPDATE|;
  1283. my $sth = $self->{dbh}->prepare($query);
  1284. $sth->execute( $curr, $transdate ) || $self->dberror($query);
  1285. my $set;
  1286. my @queryargs;
  1287. if ( $buy && $sell ) {
  1288. $set = "buy = ?, sell = ?";
  1289. @queryargs = ( $buy, $sell );
  1290. }
  1291. elsif ($buy) {
  1292. $set = "buy = ?";
  1293. @queryargs = ($buy);
  1294. }
  1295. elsif ($sell) {
  1296. $set = "sell = ?";
  1297. @queryargs = ($sell);
  1298. }
  1299. if ( !$set ) {
  1300. $self->error("Exchange rate missing!");
  1301. }
  1302. if ( $sth->fetchrow_array ) {
  1303. $query = qq|UPDATE exchangerate
  1304. SET $set
  1305. WHERE curr = ?
  1306. AND transdate = ?|;
  1307. push( @queryargs, $curr, $transdate );
  1308. }
  1309. else {
  1310. $query = qq|
  1311. INSERT INTO exchangerate (
  1312. curr, buy, sell, transdate)
  1313. VALUES (?, ?, ?, ?)|;
  1314. @queryargs = ( $curr, $buy, $sell, $transdate );
  1315. }
  1316. $sth->finish;
  1317. $sth = $self->{dbh}->prepare($query);
  1318. $sth->execute(@queryargs) || $self->dberror($query);
  1319. }
  1320. sub save_exchangerate {
  1321. my ( $self, $myconfig, $currency, $transdate, $rate, $fld ) = @_;
  1322. my ( $buy, $sell ) = ( 0, 0 );
  1323. $buy = $rate if $fld eq 'buy';
  1324. $sell = $rate if $fld eq 'sell';
  1325. $self->update_exchangerate( $self->{dbh}, $currency, $transdate, $buy,
  1326. $sell );
  1327. $dbh->commit;
  1328. }
  1329. sub get_exchangerate {
  1330. my ( $self, $dbh, $curr, $transdate, $fld ) = @_;
  1331. my $exchangerate = 1;
  1332. if ($transdate) {
  1333. my $query = qq|
  1334. SELECT $fld FROM exchangerate
  1335. WHERE curr = ? AND transdate = ?|;
  1336. $sth = $self->{dbh}->prepare($query);
  1337. $sth->execute( $curr, $transdate );
  1338. ($exchangerate) = $sth->fetchrow_array;
  1339. $exchangerate = Math::BigFloat->new($exchangerate);
  1340. }
  1341. $sth->finish;
  1342. $self->{dbh}->commit;
  1343. $exchangerate;
  1344. }
  1345. sub check_exchangerate {
  1346. my ( $self, $myconfig, $currency, $transdate, $fld ) = @_;
  1347. return "" unless $transdate;
  1348. my $query = qq|
  1349. SELECT $fld
  1350. FROM exchangerate
  1351. WHERE curr = ? AND transdate = ?|;
  1352. my $sth = $self->{dbh}->prepare($query);
  1353. $sth->execute( $currenct, $transdate );
  1354. my ($exchangerate) = $sth->fetchrow_array;
  1355. $sth->finish;
  1356. $self->{dbh}->commit;
  1357. $exchangerate;
  1358. }
  1359. sub add_shipto {
  1360. my ( $self, $dbh, $id ) = @_;
  1361. my $shipto;
  1362. foreach my $item (
  1363. qw(name address1 address2 city state
  1364. zipcode country contact phone fax email)
  1365. )
  1366. {
  1367. if ( $self->{"shipto$item"} ne "" ) {
  1368. $shipto = 1 if ( $self->{$item} ne $self->{"shipto$item"} );
  1369. }
  1370. }
  1371. if ($shipto) {
  1372. my $query = qq|
  1373. INSERT INTO shipto
  1374. (trans_id, shiptoname, shiptoaddress1,
  1375. shiptoaddress2, shiptocity, shiptostate,
  1376. shiptozipcode, shiptocountry, shiptocontact,
  1377. shiptophone, shiptofax, shiptoemail)
  1378. VALUES ( ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
  1379. |;
  1380. $sth = $self->{dbh}->prepare($query) || $self->dberror($query);
  1381. $sth->execute(
  1382. $id, $self->{shiptoname},
  1383. $self->{shiptoaddress1}, $self->{shiptoaddress2},
  1384. $self->{shiptocity}, $self->{shiptostate},
  1385. $self->{shiptozipcode}, $self->{shiptocountry},
  1386. $self->{shiptocontact}, $self->{shiptophone},
  1387. $self->{shiptofax}, $self->{shiptoemail}
  1388. ) || $self->dberror($query);
  1389. $sth->finish;
  1390. $self->{dbh}->commit;
  1391. }
  1392. }
  1393. sub get_employee {
  1394. my ( $self, $dbh ) = @_;
  1395. my $login = $self->{login};
  1396. $login =~ s/@.*//;
  1397. my $query = qq|
  1398. SELECT name, id
  1399. FROM entity WHERE id IN (select entity_id
  1400. FROM employee
  1401. WHERE login = ?)|;
  1402. $sth = $self->{dbh}->prepare($query);
  1403. $sth->execute($login);
  1404. my (@a) = $sth->fetchrow_array();
  1405. $a[1] *= 1;
  1406. $sth->finish;
  1407. $self->{dbh}->commit;
  1408. @a;
  1409. }
  1410. # this sub gets the id and name from $table
  1411. sub get_name {
  1412. my ( $self, $myconfig, $table, $transdate ) = @_;
  1413. # connect to database
  1414. my @queryargs;
  1415. my $where;
  1416. if ($transdate) {
  1417. $where = qq|
  1418. AND (startdate IS NULL OR startdate <= ?)
  1419. AND (enddate IS NULL OR enddate >= ?)|;
  1420. @queryargs = ( $transdate, $transdate );
  1421. }
  1422. my $name = $self->like( lc $self->{$table} );
  1423. my $query = qq|
  1424. SELECT * FROM $table
  1425. WHERE (lower(name) LIKE ? OR ${table}number LIKE ?)
  1426. $where
  1427. ORDER BY name|;
  1428. unshift( @queryargs, $name, $name );
  1429. my $sth = $self->{dbh}->prepare($query);
  1430. $sth->execute(@queryargs) || $self->dberror($query);
  1431. my $i = 0;
  1432. @{ $self->{name_list} } = ();
  1433. while ( $ref = $sth->fetchrow_hashref(NAME_lc) ) {
  1434. push( @{ $self->{name_list} }, $ref );
  1435. $i++;
  1436. }
  1437. $sth->finish;
  1438. $self->{dbh}->commit;
  1439. $i;
  1440. }
  1441. sub all_vc {
  1442. my ( $self, $myconfig, $vc, $module, $dbh, $transdate, $job ) = @_;
  1443. my $ref;
  1444. my $disconnect = 0;
  1445. $dbh = $self->{dbh};
  1446. my $sth;
  1447. my $query = qq|SELECT count(*) FROM $vc|;
  1448. my $where;
  1449. my @queryargs = ();
  1450. if ($transdate) {
  1451. $query .= qq| WHERE (startdate IS NULL OR startdate <= ?)
  1452. AND (enddate IS NULL OR enddate >= ?)|;
  1453. @queryargs = ( $transdate, $transdate );
  1454. }
  1455. $sth = $dbh->prepare($query);
  1456. $sth->execute(@queryargs);
  1457. my ($count) = $sth->fetchrow_array;
  1458. $sth->finish;
  1459. @queryargs = ();
  1460. # build selection list
  1461. if ( $count < $myconfig->{vclimit} ) {
  1462. $self->{"${vc}_id"} *= 1;
  1463. $where = "AND $where" if $where;
  1464. $query = qq|SELECT id, name
  1465. FROM entity
  1466. WHERE id IN (select entity_id
  1467. FROM $vc)
  1468. $where
  1469. UNION
  1470. SELECT id,name
  1471. FROM entity
  1472. WHERE id = ?
  1473. ORDER BY name|;
  1474. push( @queryargs, $self->{"${vc}_id"} );
  1475. $sth = $dbh->prepare($query);
  1476. $sth->execute(@queryargs) || $self->dberror($query);
  1477. @{ $self->{"all_$vc"} } = ();
  1478. while ( $ref = $sth->fetchrow_hashref(NAME_lc) ) {
  1479. push @{ $self->{"all_$vc"} }, $ref;
  1480. }
  1481. $sth->finish;
  1482. }
  1483. # get self
  1484. if ( !$self->{employee_id} ) {
  1485. ( $self->{employee}, $self->{employee_id} ) = split /--/,
  1486. $self->{employee};
  1487. ( $self->{employee}, $self->{employee_id} ) = $self->get_employee($dbh)
  1488. unless $self->{employee_id};
  1489. }
  1490. $self->all_employees( $myconfig, $dbh, $transdate, 1 );
  1491. $self->all_departments( $myconfig, $dbh, $vc );
  1492. $self->all_projects( $myconfig, $dbh, $transdate, $job );
  1493. # get language codes
  1494. $query = qq|SELECT *
  1495. FROM language
  1496. ORDER BY 2|;
  1497. $sth = $dbh->prepare($query);
  1498. $sth->execute || $self->dberror($query);
  1499. $self->{all_language} = ();
  1500. while ( $ref = $sth->fetchrow_hashref(NAME_lc) ) {
  1501. push @{ $self->{all_language} }, $ref;
  1502. }
  1503. $sth->finish;
  1504. $self->all_taxaccounts( $myconfig, $dbh, $transdate );
  1505. $self->{dbh}->commit;
  1506. }
  1507. sub all_taxaccounts {
  1508. my ( $self, $myconfig, $dbh2, $transdate ) = @_;
  1509. my $dbh = $self->{dbh};
  1510. my $sth;
  1511. my $query;
  1512. my $where;
  1513. my @queryargs = ();
  1514. if ($transdate) {
  1515. $where = qq| AND (t.validto >= ? OR t.validto IS NULL)|;
  1516. push( @queryargs, $transdate );
  1517. }
  1518. if ( $self->{taxaccounts} ) {
  1519. # rebuild tax rates
  1520. $query = qq|SELECT t.rate, t.taxnumber
  1521. FROM tax t
  1522. JOIN chart c ON (c.id = t.chart_id)
  1523. WHERE c.accno = ?
  1524. $where
  1525. ORDER BY accno, validto|;
  1526. $sth = $dbh->prepare($query) || $self->dberror($query);
  1527. foreach my $accno ( split / /, $self->{taxaccounts} ) {
  1528. $sth->execute( $accno, @queryargs );
  1529. ( $self->{"${accno}_rate"}, $self->{"${accno}_taxnumber"} ) =
  1530. $sth->fetchrow_array;
  1531. $sth->finish;
  1532. }
  1533. }
  1534. $self->{dbh}->commit;
  1535. }
  1536. sub all_employees {
  1537. my ( $self, $myconfig, $dbh2, $transdate, $sales ) = @_;
  1538. my $dbh = $self->{dbh};
  1539. my @whereargs = ();
  1540. # setup employees/sales contacts
  1541. my $query = qq|
  1542. SELECT id, name
  1543. FROM entity
  1544. WHERE id IN (SELECT entity_id FROM employee
  1545. WHERE|;
  1546. if ($transdate) {
  1547. $query .= qq| (startdate IS NULL OR startdate <= ?)
  1548. AND (enddate IS NULL OR enddate >= ?) AND|;
  1549. @whereargs = ( $transdate, $transdate );
  1550. }
  1551. else {
  1552. $query .= qq| enddate IS NULL AND|;
  1553. }
  1554. if ($sales) {
  1555. $query .= qq| sales = '1' AND|;
  1556. }
  1557. $query =~ s/(WHERE|AND)$//;
  1558. $query .= qq|) ORDER BY name|;
  1559. my $sth = $dbh->prepare($query);
  1560. $sth->execute(@whereargs) || $self->dberror($query);
  1561. while ( my $ref = $sth->fetchrow_hashref(NAME_lc) ) {
  1562. push @{ $self->{all_employee} }, $ref;
  1563. }
  1564. $sth->finish;
  1565. $dbh->commit;
  1566. }
  1567. sub all_projects {
  1568. my ( $self, $myconfig, $dbh2, $transdate, $job ) = @_;
  1569. my $dbh = $self->{dbh};
  1570. my @queryargs = ();
  1571. my $where = "1 = 1";
  1572. $where = qq|id NOT IN (SELECT id
  1573. FROM parts
  1574. WHERE project_id > 0)| if !$job;
  1575. my $query = qq|SELECT *
  1576. FROM project
  1577. WHERE $where|;
  1578. if ( $self->{language_code} ) {
  1579. $query = qq|
  1580. SELECT pr.*, t.description AS translation
  1581. FROM project pr
  1582. LEFT JOIN translation t ON (t.trans_id = pr.id)
  1583. WHERE t.language_code = ?|;
  1584. push( @queryargs, $self->{language_code} );
  1585. }
  1586. if ($transdate) {
  1587. $query .= qq| AND (startdate IS NULL OR startdate <= ?)
  1588. AND (enddate IS NULL OR enddate >= ?)|;
  1589. push( @queryargs, $transdate, $transdate );
  1590. }
  1591. $query .= qq| ORDER BY projectnumber|;
  1592. $sth = $dbh->prepare($query);
  1593. $sth->execute(@queryargs) || $self->dberror($query);
  1594. @{ $self->{all_project} } = ();
  1595. while ( $ref = $sth->fetchrow_hashref(NAME_lc) ) {
  1596. push @{ $self->{all_project} }, $ref;
  1597. }
  1598. $sth->finish;
  1599. $dbh->commit;
  1600. }
  1601. sub all_departments {
  1602. my ( $self, $myconfig, $dbh2, $vc ) = @_;
  1603. $dbh = $self->{dbh};
  1604. my $where = "1 = 1";
  1605. if ($vc) {
  1606. if ( $vc eq 'customer' ) {
  1607. $where = " role = 'P'";
  1608. }
  1609. }