eb.
summaryrefslogtreecommitdiff
path: root/LedgerSMB/Form.pm
blob: e873622de20e0f7320838dba6ee17d0f86be8b37 (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. package Form;
  38. sub new {
  39. my $type = shift;
  40. my $argstr = shift;
  41. read(STDIN, $_, $ENV{CONTENT_LENGTH});
  42. if ($argstr){
  43. $_ = $argstr;
  44. }
  45. elsif ($ENV{QUERY_STRING}) {
  46. $_ = $ENV{QUERY_STRING};
  47. }
  48. elsif ($ARGV[0]) {
  49. $_ = $ARGV[0];
  50. }
  51. my $self = {};
  52. %$self = split /[&=]/;
  53. for (keys %$self) { $self->{$_} = unescape("", $self->{$_}) }
  54. if (substr($self->{action}, 0, 1) !~ /( |\.)/) {
  55. $self->{action} = lc $self->{action};
  56. $self->{action} =~ s/( |-|,|\#|\/|\.$)/_/g;
  57. $self->{nextsub} = lc $self->{nextsub};
  58. $self->{nextsub} =~ s/( |-|,|\#|\/|\.$)/_/g;
  59. }
  60. $self->{menubar} = 1 if $self->{path} =~ /lynx/i;
  61. #menubar will be deprecated, replaced with below
  62. $self->{lynx} = 1 if $self->{path} =~ /lynx/i;
  63. $self->{version} = "1.2.0 Release Candidate 4";
  64. $self->{dbversion} = "1.2.0";
  65. bless $self, $type;
  66. if ($form->{path} ne 'bin/lynx'){ $form->{path} = 'bin/mozilla';}
  67. if (($self->{script} =~ m#(..|\\|/)#)){
  68. $self->error("Access Denied");
  69. }
  70. if (($self->{action} =~ /:/) || ($self->{nextsub} =~ /:/)){
  71. $self->error("Access Denied");
  72. }
  73. $self;
  74. }
  75. sub debug {
  76. my ($self, $file) = @_;
  77. if ($file) {
  78. open(FH, '>', "$file") or die $!;
  79. for (sort keys %$self) { print FH "$_ = $self->{$_}\n" }
  80. close(FH);
  81. } else {
  82. print "\n";
  83. for (sort keys %$self) { print "$_ = $self->{$_}\n" }
  84. }
  85. }
  86. sub encode_all {
  87. # TODO;
  88. }
  89. sub decode_all {
  90. # TODO
  91. }
  92. sub escape {
  93. my ($self, $str, $beenthere) = @_;
  94. # for Apache 2 we escape strings twice
  95. if (($ENV{SERVER_SIGNATURE} =~ /Apache\/2\.(\d+)\.(\d+)/) && !$beenthere) {
  96. $str = $self->escape($str, 1) if $1 == 0 && $2 < 44;
  97. }
  98. $str =~ s/([^a-zA-Z0-9_.-])/sprintf("%%%02x", ord($1))/ge;
  99. $str;
  100. }
  101. sub unescape {
  102. my ($self, $str) = @_;
  103. $str =~ tr/+/ /;
  104. $str =~ s/\\$//;
  105. $str =~ s/%([0-9a-fA-Z]{2})/pack("c",hex($1))/eg;
  106. $str =~ s/\r?\n/\n/g;
  107. $str;
  108. }
  109. sub quote {
  110. my ($self, $str) = @_;
  111. if ($str && ! ref($str)) {
  112. $str =~ s/"/&quot;/g;
  113. }
  114. $str;
  115. }
  116. sub unquote {
  117. my ($self, $str) = @_;
  118. if ($str && ! ref($str)) {
  119. $str =~ s/&quot;/"/g;
  120. }
  121. $str;
  122. }
  123. sub hide_form {
  124. my $self = shift;
  125. if (@_) {
  126. for (@_) {
  127. print qq|<input type="hidden" name="$_" value="|.$self->quote($self->{$_}).qq|" />\n|
  128. }
  129. } else {
  130. delete $self->{header};
  131. for (sort keys %$self) {
  132. print qq|<input type="hidden" name="$_" value="|.$self->quote($self->{$_}).qq|" />\n|
  133. }
  134. }
  135. }
  136. sub error {
  137. my ($self, $msg) = @_;
  138. if ($ENV{GATEWAY_INTERFACE}) {
  139. $self->{msg} = $msg;
  140. $self->{format} = "html";
  141. $self->format_string('msg');
  142. delete $self->{pre};
  143. if (!$self->{header}) {
  144. $self->header;
  145. }
  146. print qq|<body><h2 class="error">Error!</h2> <p><b>$self->{msg}</b></body>|;
  147. exit;
  148. } else {
  149. if ($ENV{error_function}) {
  150. &{ $ENV{error_function} }($msg);
  151. } else {
  152. die "Error: $msg\n";
  153. }
  154. }
  155. }
  156. sub info {
  157. my ($self, $msg) = @_;
  158. if ($ENV{GATEWAY_INTERFACE}) {
  159. $msg =~ s/\n/<br>/g;
  160. delete $self->{pre};
  161. if (!$self->{header}) {
  162. $self->header;
  163. print qq| <body>|;
  164. $self->{header} = 1;
  165. }
  166. print "<b>$msg</b>";
  167. } else {
  168. if ($ENV{info_function}) {
  169. &{ $ENV{info_function} }($msg);
  170. } else {
  171. print "$msg\n";
  172. }
  173. }
  174. }
  175. sub numtextrows {
  176. my ($self, $str, $cols, $maxrows) = @_;
  177. my $rows = 0;
  178. for (split /\n/, $str) {
  179. $rows += int (((length) - 2)/$cols) + 1
  180. }
  181. $maxrows = $rows unless defined $maxrows;
  182. return ($rows > $maxrows) ? $maxrows : $rows;
  183. }
  184. sub dberror {
  185. my ($self, $msg) = @_;
  186. $self->error("$msg\n".$DBI::errstr);
  187. }
  188. sub isblank {
  189. my ($self, $name, $msg) = @_;
  190. $self->error($msg) if $self->{$name} =~ /^\s*$/;
  191. }
  192. sub header {
  193. my ($self, $init, $headeradd) = @_;
  194. return if $self->{header};
  195. my ($stylesheet, $favicon, $charset);
  196. if ($ENV{GATEWAY_INTERFACE}) {
  197. if ($self->{stylesheet} && (-f "css/$self->{stylesheet}")) {
  198. $stylesheet = qq|<link rel="stylesheet" href="css/$self->{stylesheet}" type="text/css" title="LedgerSMB stylesheet" />\n|;
  199. }
  200. if ($self->{charset}) {
  201. $charset = qq|<meta http-equiv="content-type" content="text/html; charset=$self->{charset}" />\n|;
  202. }
  203. $self->{titlebar} = ($self->{title}) ? "$self->{title} - $self->{titlebar}" : $self->{titlebar};
  204. print qq|Content-Type: text/html\n\n
  205. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  206. "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  207. <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
  208. <head>
  209. <title>$self->{titlebar}</title>
  210. <meta http-equiv="Pragma" content="no-cache" />
  211. <meta http-equiv="Expires" content="-1" />
  212. <link rel="shortcut icon" href="favicon.ico" type="image/x-icon" />
  213. $stylesheet
  214. $charset
  215. <meta name="robots" content="noindex,nofollow" />
  216. $headeradd
  217. </head>
  218. $self->{pre} \n|;
  219. }
  220. $self->{header} = 1;
  221. }
  222. sub redirect {
  223. my ($self, $msg) = @_;
  224. use List::Util qw(first);
  225. if ($self->{callback} || !$msg){
  226. main::redirect();
  227. } else {
  228. $self->info($msg);
  229. }
  230. }
  231. sub sort_columns {
  232. my ($self, @columns) = @_;
  233. if ($self->{sort}) {
  234. if (@columns) {
  235. @columns = grep !/^$self->{sort}$/, @columns;
  236. splice @columns, 0, 0, $self->{sort};
  237. }
  238. }
  239. @columns;
  240. }
  241. sub sort_order {
  242. my ($self, $columns, $ordinal) = @_;
  243. # setup direction
  244. if ($self->{direction}) {
  245. if ($self->{sort} eq $self->{oldsort}) {
  246. if ($self->{direction} eq 'ASC') {
  247. $self->{direction} = "DESC";
  248. } else {
  249. $self->{direction} = "ASC";
  250. }
  251. }
  252. } else {
  253. $self->{direction} = "ASC";
  254. }
  255. $self->{oldsort} = $self->{sort};
  256. my @a = $self->sort_columns(@{$columns});
  257. if (%$ordinal) {
  258. $a[0] = ($ordinal->{$a[$_]}) ? "$ordinal->{$a[0]} $self->{direction}" : "$a[0] $self->{direction}";
  259. for (1 .. $#a) {
  260. $a[$_] = $ordinal->{$a[$_]} if $ordinal->{$a[$_]}
  261. }
  262. } else {
  263. $a[0] .= " $self->{direction}";
  264. }
  265. $sortorder = join ',', @a;
  266. $sortorder;
  267. }
  268. sub format_amount {
  269. my ($self, $myconfig, $amount, $places, $dash) = @_;
  270. my $negative ;
  271. if ($amount){
  272. $amount = $self->parse_amount($myconfig, $amount);
  273. $negative = ($amount < 0);
  274. $amount =~ s/-//;
  275. }
  276. if ($places =~ /\d+/) {
  277. #$places = 4 if $places == 2;
  278. $amount = $self->round_amount($amount, $places);
  279. }
  280. # is the amount negative
  281. # Parse $myconfig->{numberformat}
  282. my ($ts, $ds) = ($1, $2);
  283. if ($amount) {
  284. if ($myconfig->{numberformat}) {
  285. my ($whole, $dec) = split /\./, "$amount";
  286. $amount = join '', reverse split //, $whole;
  287. if ($places) {
  288. $dec .= "0" x $places;
  289. $dec = substr($dec, 0, $places);
  290. }
  291. if ($myconfig->{numberformat} eq '1,000.00') {
  292. $amount =~ s/\d{3,}?/$&,/g;
  293. $amount =~ s/,$//;
  294. $amount = join '', reverse split //, $amount;
  295. $amount .= "\.$dec" if ($dec ne "");
  296. }
  297. if ($myconfig->{numberformat} eq '1 000.00') {
  298. $amount =~ s/\d{3,}?/$& /g;
  299. $amount =~ s/\s$//;
  300. $amount = join '', reverse split //, $amount;
  301. $amount .= "\.$dec" if ($dec ne "");
  302. }
  303. if ($myconfig->{numberformat} eq "1'000.00") {
  304. $amount =~ s/\d{3,}?/$&'/g;
  305. $amount =~ s/'$//;
  306. $amount = join '', reverse split //, $amount;
  307. $amount .= "\.$dec" if ($dec ne "");
  308. }
  309. if ($myconfig->{numberformat} eq '1.000,00') {
  310. $amount =~ s/\d{3,}?/$&./g;
  311. $amount =~ s/\.$//;
  312. $amount = join '', reverse split //, $amount;
  313. $amount .= ",$dec" if ($dec ne "");
  314. }
  315. if ($myconfig->{numberformat} eq '1000,00') {
  316. $amount = "$whole";
  317. $amount .= ",$dec" if ($dec ne "");
  318. }
  319. if ($myconfig->{numberformat} eq '1000.00') {
  320. $amount = "$whole";
  321. $amount .= ".$dec" if ($dec ne "");
  322. }
  323. if ($dash =~ /-/) {
  324. $amount = ($negative) ? "($amount)" : "$amount";
  325. } elsif ($dash =~ /DRCR/) {
  326. $amount = ($negative) ? "$amount DR" : "$amount CR";
  327. } else {
  328. $amount = ($negative) ? "-$amount" : "$amount";
  329. }
  330. }
  331. } else {
  332. if ($dash eq "0" && $places) {
  333. if ($myconfig->{numberformat} eq '1.000,00') {
  334. $amount = "0".","."0" x $places;
  335. } else {
  336. $amount = "0"."."."0" x $places;
  337. }
  338. } else {
  339. $amount = ($dash ne "") ? "$dash" : "";
  340. }
  341. }
  342. $amount;
  343. }
  344. sub parse_amount {
  345. my ($self, $myconfig, $amount) = @_;
  346. if (($amount eq '') or ($amount eq undef)) {
  347. $amount = 0;
  348. }
  349. if (UNIVERSAL::isa($amount, 'Math::BigFloat')){ # Amount may not be an object
  350. return $amount;
  351. }
  352. my $numberformat = $myconfig->{numberformat};
  353. if (($numberformat eq '1.000,00') ||
  354. ($numberformat eq '1000,00')) {
  355. $amount =~ s/\.//g;
  356. $amount =~ s/,/./;
  357. }
  358. if ($numberformat eq '1 000.00'){
  359. $amount =~ s/\s//g;
  360. }
  361. if ($numberformat eq "1'000.00") {
  362. $amount =~ s/'//g;
  363. }
  364. $amount =~ s/,//g;
  365. if ($amount =~ s/\((\d*\.?\d*)\)/$1/){
  366. $amount = $1 * -1;
  367. }
  368. if ($amount =~ s/(\d*\.?\d*)\s?DR/$1/){
  369. $amount = $1 * -1;
  370. }
  371. $amount =~ s/\s?CR//;
  372. $amount = new Math::BigFloat($amount);
  373. return ($amount * 1);
  374. }
  375. sub round_amount {
  376. my ($self, $amount, $places) = @_;
  377. # These rounding rules follow from the previous implementation.
  378. # They should be changed to allow different rules for different accounts.
  379. Math::BigFloat->round_mode('+inf') if $amount >= 0;
  380. Math::BigFloat->round_mode('-inf') if $amount < 0;
  381. $amount = Math::BigFloat->new($amount)->ffround(-$places) if $places >= 0;
  382. $amount = Math::BigFloat->new($amount)->ffround(-($places-1)) if $places < 0;
  383. return $amount;
  384. }
  385. sub callproc {
  386. my $procname = shift @_;
  387. my $argstr = "";
  388. my @results;
  389. for (1 .. $#_){
  390. $argstr .= "?, ";
  391. }
  392. $argstr =~ s/\, $//;
  393. $query = "SELECT $procname";
  394. $query =~ s/\(\)/$argstr/;
  395. my $sth = $self->{dbh}->prepare($query);
  396. while (my $ref = $sth->fetchrow_hashref(NAME_lc)){
  397. push @results, $ref;
  398. }
  399. @results;
  400. }
  401. sub get_my_emp_num {
  402. my ($self, $myconfig, $form) = @_;
  403. %myconfig = %{$myconfig};
  404. my $dbh = $form->{dbh};
  405. # we got a connection, check the version
  406. my $query = qq|
  407. SELECT employeenumber FROM employee
  408. WHERE login = ?|;
  409. my $sth = $dbh->prepare($query);
  410. $sth->execute($form->{login}) || $form->dberror($query);
  411. $sth->execute;
  412. my ($id) = $sth->fetchrow_array;
  413. $sth->finish;
  414. $form->{'emp_num'} = $id;
  415. }
  416. sub parse_template {
  417. my ($self, $myconfig) = @_;
  418. my ($chars_per_line, $lines_on_first_page, $lines_on_second_page) = (0, 0, 0);
  419. my ($current_page, $current_line) = (1, 1);
  420. my $pagebreak = "";
  421. my $sum = 0;
  422. my $subdir = "";
  423. my $err = "";
  424. my %include = ();
  425. my $ok;
  426. if ($self->{language_code}) {
  427. if ($self->{language_code} =~ /(\.\.|\/|\*)/){
  428. $self->error("Invalid Language Code");
  429. }
  430. if (-f "$self->{templates}/$self->{language_code}/$self->{IN}") {
  431. open(IN, '<', "$self->{templates}/$self->{language_code}/$self->{IN}") or $self->error("$self->{IN} : $!");
  432. } else {
  433. open(IN, '<', "$self->{templates}/$self->{IN}") or $self->error("$self->{IN} : $!");
  434. }
  435. } else {
  436. open(IN, "$self->{templates}/$self->{IN}") or $self->error("$self->{IN} : $!");
  437. }
  438. @_ = <IN>;
  439. close(IN);
  440. $self->{copies} = 1 if (($self->{copies} *= 1) <= 0);
  441. # OUT is used for the media, screen, printer, email
  442. # for postscript we store a copy in a temporary file
  443. my $fileid = time;
  444. my $tmpfile = $self->{IN};
  445. $tmpfile =~ s/\./_$self->{fileid}./ if $self->{fileid};
  446. $self->{tmpfile} = "${LedgerSMB::Sysconfig::userspath}/${fileid}_${tmpfile}";
  447. my $temphash;
  448. if ($self->{format} =~ /(postscript|pdf)/ || $self->{media} eq 'email') {
  449. $temphash{out} = $self->{OUT};
  450. $self->{OUT} = "$self->{tmpfile}";
  451. $temphash{printmode} = $self->{printmode};
  452. $self->{printmode} = '>';
  453. }
  454. if ($self->{OUT}) {
  455. open(OUT, $self->{printmode}, "$self->{OUT}") or $self->error("$self->{OUT} : $!");
  456. } else {
  457. open(OUT, ">-") or $self->error("STDOUT : $!");
  458. $self->header;
  459. }
  460. # first we generate a tmpfile
  461. # read file and replace <?lsmb variable ?>
  462. while ($_ = shift) {
  463. $par = "";
  464. $var = $_;
  465. # detect pagebreak block and its parameters
  466. if (/<\?lsmb pagebreak ([0-9]+) ([0-9]+) ([0-9]+) \?>/) {
  467. $chars_per_line = $1;
  468. $lines_on_first_page = $2;
  469. $lines_on_second_page = $3;
  470. while ($_ = shift) {
  471. last if (/<\?lsmb end pagebreak \?>/);
  472. $pagebreak .= $_;
  473. }
  474. }
  475. if (/<\?lsmb foreach /) {
  476. # this one we need for the count
  477. chomp $var;
  478. $var =~ s/.*?<\?lsmb foreach (.+?) \?>/$1/;
  479. while ($_ = shift) {
  480. last if (/<\?lsmb end $var \?>/);
  481. # store line in $par
  482. $par .= $_;
  483. }
  484. # display contents of $self->{number}[] array
  485. for $i (0 .. $#{ $self->{$var} }) {
  486. if ($var =~ /^(part|service)$/) {
  487. next if $self->{$var}[$i] eq 'NULL';
  488. }
  489. # Try to detect whether a manual page break is necessary
  490. # but only if there was a <?lsmb pagebreak ... ?> block before
  491. if ($var eq 'number' || $var eq 'part' || $var eq 'service') {
  492. if ($chars_per_line && defined $self->{$var}) {
  493. my $line;
  494. my $lines = 0;
  495. my @d = qw(description);
  496. push @d, "itemnotes" if $self->{countitemnotes};
  497. foreach my $item (@d) {
  498. if ($self->{$item}[$i]) {
  499. foreach $line (split /\r?\n/, $self->{$item}[$i]) {
  500. $lines++;
  501. $lines += int(length($line) / $chars_per_line);
  502. }
  503. }
  504. }
  505. my $lpp;
  506. if ($current_page == 1) {
  507. $lpp = $lines_on_first_page;
  508. } else {
  509. $lpp = $lines_on_second_page;
  510. }
  511. # Yes we need a manual page break
  512. if (($current_line + $lines) > $lpp) {
  513. my $pb = $pagebreak;
  514. # replace the special variables <?lsmb sumcarriedforward ?>
  515. # and <?lsmb lastpage ?>
  516. my $psum = $self->format_amount($myconfig, $sum, 2);
  517. $pb =~ s/<\?lsmb sumcarriedforward \?>/$psum/g;
  518. $pb =~ s/<\?lsmb lastpage \?>/$current_page/g;
  519. # only "normal" variables are supported here
  520. # (no <?lsmb if, no <?lsmb foreach, no <?lsmb include)
  521. $pb =~ s/<\?lsmb (.+?) \?>/$self->{$1}/g;
  522. # page break block is ready to rock
  523. print(OUT $pb);
  524. $current_page++;
  525. $current_line = 1;
  526. $lines = 0;
  527. }
  528. $current_line += $lines;
  529. }
  530. $sum += $self->parse_amount($myconfig, $self->{linetotal}[$i]);
  531. }
  532. # don't parse par, we need it for each line
  533. print OUT $self->format_line($par, $i);
  534. }
  535. next;
  536. }
  537. # if not comes before if!
  538. if (/<\?lsmb if not /) {
  539. # check if it is not set and display
  540. chop;
  541. s/.*?<\?lsmb if not (.+?) \?>/$1/;
  542. if (! $self->{$_}) {
  543. while ($_ = shift) {
  544. last if (/<\?lsmb end /);
  545. # store line in $par
  546. $par .= $_;
  547. }
  548. $_ = $par;
  549. } else {
  550. while ($_ = shift) {
  551. last if (/<\?lsmb end /);
  552. }
  553. next;
  554. }
  555. }
  556. if (/<\?lsmb if /) {
  557. # check if it is set and display
  558. chop;
  559. s/.*?<\?lsmb if (.+?) \?>/$1/;
  560. # commenting this out for security reasons. If needed,
  561. # please uncomment. Functionality below will be in 1.3
  562. # Chris Travers
  563. #if (/\s/) {
  564. # @args = split;
  565. # if ($args[1] !~ /^(==|eq|>|gt|>|lt|>=|ge|le|<=|ne|!=)$/){
  566. # $self->error("Unknown/forbidden operator");
  567. # }
  568. # $ok = eval "$self->{$args[0]} $args[1] $args[2]";
  569. #} else {
  570. $ok = $self->{$_};
  571. #}
  572. if ($ok) {
  573. while ($_ = shift) {
  574. last if (/<\?lsmb end /);
  575. # store line in $par
  576. $par .= $_;
  577. }
  578. $_ = $par;
  579. } else {
  580. while ($_ = shift) {
  581. last if (/<\?lsmb end /);
  582. }
  583. next;
  584. }
  585. }
  586. # check for <?lsmb include filename ?>
  587. if (/<\?lsmb include /) {
  588. # get the filename
  589. chomp $var;
  590. $var =~ s/.*?<\?lsmb include (.+?) \?>/$1/;
  591. # remove / .. for security reasons
  592. $var =~ s/(\/|\.\.)//g;
  593. # assume loop after 10 includes of the same file
  594. next if ($include{$var} > 10);
  595. unless (open(INC, '<', "$self->{templates}/$self->{language_code}/$var")) {
  596. $err = $!;
  597. $self->cleanup;
  598. $self->error("$self->{templates}/$self->{language_code}/$var : $err");
  599. }
  600. unshift(@_, <INC>);
  601. close(INC);
  602. $include{$var}++;
  603. next;
  604. }
  605. print OUT $self->format_line($_);
  606. }
  607. close(OUT);
  608. delete $self->{countitemnotes};
  609. # Convert the tex file to postscript
  610. if ($self->{format} =~ /(postscript|pdf)/) {
  611. use Cwd;
  612. $self->{cwd} = cwd();
  613. $self->{tmpdir} = "$self->{cwd}/${LedgerSMB::Sysconfig::userspath}";
  614. $self->{tmpdir} = "${LedgerSMB::Sysconfig::userspath}" if
  615. ${LedgerSMB::Sysconfig::userspath} =~ /^\//;
  616. unless (chdir("${LedgerSMB::Sysconfig::userspath}")) {
  617. $err = $!;
  618. $self->cleanup;
  619. $self->error("chdir : $err");
  620. }
  621. $self->{tmpfile} =~ s/${LedgerSMB::Sysconfig::userspath}\///g;
  622. $self->{errfile} = $self->{tmpfile};
  623. $self->{errfile} =~ s/tex$/err/;
  624. my $r = 1;
  625. if ($self->{format} eq 'postscript') {
  626. system("latex --interaction=nonstopmode $self->{tmpfile} > $self->{errfile}");
  627. while ($self->rerun_latex) {
  628. system("latex --interaction=nonstopmode $self->{tmpfile} > $self->{errfile}");
  629. last if ++$r > 4;
  630. }
  631. $self->{tmpfile} =~ s/tex$/dvi/;
  632. $self->error($self->cleanup) if ! (-f $self->{tmpfile});
  633. system("dvips $self->{tmpfile} -o -q");
  634. $self->error($self->cleanup."dvips : $!") if ($?);
  635. $self->{tmpfile} =~ s/dvi$/ps/;
  636. }
  637. if ($self->{format} eq 'pdf') {
  638. system("pdflatex --interaction=nonstopmode $self->{tmpfile} > $self->{errfile}");
  639. while ($self->rerun_latex) {
  640. system("pdflatex --interaction=nonstopmode $self->{tmpfile} > $self->{errfile}");
  641. last if ++$r > 4;
  642. }
  643. $self->{tmpfile} =~ s/tex$/pdf/;
  644. $self->error($self->cleanup) if ! (-f $self->{tmpfile});
  645. }
  646. }
  647. if ($self->{format} =~ /(postscript|pdf)/ || $self->{media} eq 'email') {
  648. if ($self->{media} eq 'email') {
  649. use LedgerSMB::Mailer;
  650. my $mail = new Mailer;
  651. for (qw(cc bcc subject message version format charset)) {
  652. $mail->{$_} = $self->{$_}
  653. }
  654. $mail->{to} = qq|$self->{email}|;
  655. $mail->{from} = qq|"$myconfig->{name}" <$myconfig->{email}>|;
  656. $mail->{notify} = $self->{notify};
  657. $mail->{fileid} = "$fileid.";
  658. # if we send html or plain text inline
  659. if (($self->{format} =~ /(html|txt)/) &&
  660. ($self->{sendmode} eq 'inline')) {
  661. my $br = "";
  662. $br = "<br>" if $self->{format} eq 'html';
  663. $mail->{contenttype} = "text/$self->{format}";
  664. $mail->{message} =~ s/\r?\n/$br\n/g;
  665. $myconfig->{signature} =~ s/\\n/$br\n/g;
  666. $mail->{message} .= "$br\n-- $br\n$myconfig->{signature}\n$br" if $myconfig->{signature};
  667. unless (open(IN, '<', $self->{tmpfile})) {
  668. $err = $!;
  669. $self->cleanup;
  670. $self->error("$self->{tmpfile} : $err");
  671. }
  672. while (<IN>) {
  673. $mail->{message} .= $_;
  674. }
  675. close(IN);
  676. } else {
  677. @{ $mail->{attachments} } = ($self->{tmpfile});
  678. $myconfig->{signature} =~ s/\\n/\n/g;
  679. $mail->{message} .= "\n-- \n$myconfig->{signature}" if $myconfig->{signature};
  680. }
  681. if ($err = $mail->send) {
  682. $self->cleanup;
  683. $self->error($err);
  684. }
  685. } else {
  686. $self->{OUT} = $temphash{out};
  687. $self->{printmode} = $temphash{printmode} if $temphash{printmode};
  688. unless (open(IN, '<', $self->{tmpfile})) {
  689. $err = $!;
  690. $self->cleanup;
  691. $self->error("$self->{tmpfile} : $err");
  692. }
  693. binmode(IN);
  694. $self->{copies} = 1 if $self->{media} =~ /(screen|email|queue)/;
  695. chdir("$self->{cwd}");
  696. for my $i (1 .. $self->{copies}) {
  697. if ($self->{OUT}) {
  698. unless (open(OUT, $self->{printmode}, $self->{OUT})) {
  699. $err = $!;
  700. $self->cleanup;
  701. $self->error("$self->{OUT} : $err");
  702. }
  703. } else {
  704. # launch application
  705. print qq|Content-Type: application/$self->{format}\n|.
  706. qq|Content-Disposition: attachment; filename="$self->{tmpfile}"\n\n|;
  707. unless (open(OUT, ">-")) {
  708. $err = $!;
  709. $self->cleanup;
  710. $self->error("STDOUT : $err");
  711. }
  712. }
  713. binmode(OUT);
  714. while (<IN>) {
  715. print OUT $_;
  716. }
  717. close(OUT);
  718. seek IN, 0, 0;
  719. }
  720. close(IN);
  721. }
  722. $self->cleanup;
  723. }
  724. }
  725. sub format_line {
  726. my $self = shift;
  727. $_ = shift;
  728. my $i = shift;
  729. my $str;
  730. my $newstr;
  731. my $pos;
  732. my $l;
  733. my $lf;
  734. my $line;
  735. my $var = "";
  736. my %a;
  737. my $offset;
  738. my $pad;
  739. my $item;
  740. while (/<\?lsmb (.+?) \?>/) {
  741. %a = ();
  742. foreach $item (split / /, $1) {
  743. my ($key, $value) = split /=/, $item;
  744. if ($value ne "") {
  745. $a{$key} = $value;
  746. } else {
  747. $var = $item;
  748. }
  749. }
  750. $str = (defined $i) ? $self->{$var}[$i] : $self->{$var};
  751. $newstr = $str;
  752. $self->{countitemnotes} = 1 if $var eq 'itemnotes';
  753. $var = $1;
  754. if ($var =~ /^if\s+not\s+/) {
  755. if ($str) {
  756. $var =~ s/if\s+not\s+//;
  757. s/<\?lsmb if\s+not\s+$var \?>.*?(<\?lsmb end\s+$var \?>|$)//s;
  758. } else {
  759. s/<\?lsmb $var \?>//;
  760. }
  761. next;
  762. }
  763. if ($var =~ /^if\s+/) {
  764. if ($str) {
  765. s/<\?lsmb $var \?>//;
  766. } else {
  767. $var =~ s/if\s+//;
  768. s/<\?lsmb if\s+$var \?>.*?(<\?lsmb end\s+$var \?>|$)//s;
  769. }
  770. next;
  771. }
  772. if ($var =~ /^end\s+/) {
  773. s/<\?lsmb $var \?>//;
  774. next;
  775. }
  776. if ($a{align} || $a{width} || $a{offset}) {
  777. $newstr = "";
  778. $offset = 0;
  779. $lf = "";
  780. foreach $str (split /\n/, $str) {
  781. $line = $str;
  782. $l = length $str;
  783. do {
  784. if (($pos = length $str) > $a{width}) {
  785. if (($pos = rindex $str, " ", $a{width}) > 0) {
  786. $line = substr($str, 0, $pos);
  787. }
  788. $pos = length $str if $pos == -1;
  789. }
  790. $l = length $line;
  791. # pad left, right or center
  792. $l = ($a{width} - $l);
  793. $pad = " " x $l;
  794. if ($a{align} =~ /right/i) {
  795. $line = " " x $offset . $pad . $line;
  796. }
  797. if ($a{align} =~ /left/i) {
  798. $line = " " x $offset . $line . $pad;
  799. }
  800. if ($a{align} =~ /center/i) {
  801. $pad = " " x ($l/2);
  802. $line = " " x $offset . $pad . $line;
  803. $pad = " " x ($l/2);
  804. $line .= $pad;
  805. }
  806. $newstr .= "$lf$line";
  807. $str = substr($str, $pos + 1);
  808. $line = $str;
  809. $lf = "\n";
  810. $offset = $a{offset};
  811. } while ($str);
  812. }
  813. }
  814. s/<\?lsmb (.+?) \?>/$newstr/;
  815. }
  816. $_;
  817. }
  818. sub cleanup {
  819. my $self = shift;
  820. chdir("$self->{tmpdir}");
  821. my @err = ();
  822. if (-f "$self->{errfile}") {
  823. open(FH, '<', "$self->{errfile}");
  824. @err = <FH>;
  825. close(FH);
  826. }
  827. if ($self->{tmpfile}) {
  828. # strip extension
  829. $self->{tmpfile} =~ s/\.\w+$//g;
  830. my $tmpfile = $self->{tmpfile};
  831. unlink(<$tmpfile.*>);
  832. }
  833. chdir("$self->{cwd}");
  834. "@err";
  835. }
  836. sub rerun_latex {
  837. my $self = shift;
  838. my $a = 0;
  839. if (-f "$self->{errfile}") {
  840. open(FH, '<', "$self->{errfile}");
  841. $a = grep /(longtable Warning:|Warning:.*?LastPage)/, <FH>;
  842. close(FH);
  843. }
  844. $a;
  845. }
  846. sub format_string {
  847. my ($self, @fields) = @_;
  848. my $format = $self->{format};
  849. if ($self->{format} =~ /(postscript|pdf)/) {
  850. $format = 'tex';
  851. }
  852. my %replace = (
  853. 'order' => {
  854. html => [ '<', '>', '\n', '\r' ],
  855. txt => [ '\n', '\r' ],
  856. tex => [ quotemeta('\\'), '&', '\n','\r',
  857. '\$', '%', '_', '#',
  858. quotemeta('^'), '{', '}', '<', '>', '£'
  859. ] },
  860. html => { '<' => '&lt;', '>' => '&gt;','\n' => '<br />',
  861. '\r' => '<br />' },
  862. txt => { '\n' => "\n", '\r' => "\r" },
  863. tex => {'&' => '\&', '$' => '\$', '%' => '\%', '_' => '\_',
  864. '#' => '\#', quotemeta('^') => '\^\\', '{' => '\{',
  865. '}' => '\}', '<' => '$<$', '>' => '$>$',
  866. '\n' => '\newline ', '\r' => '\newline ',
  867. '£' => '\pounds ', quotemeta('\\') => '/'}
  868. );
  869. my $key;
  870. foreach $key (@{ $replace{order}{$format} }) {
  871. for (@fields) { $self->{$_} =~ s/$key/$replace{$format}{$key}/g }
  872. }
  873. }
  874. sub datetonum {
  875. my ($self, $myconfig, $date, $picture) = @_;
  876. if ($date && $date =~ /\D/) {
  877. if ($myconfig->{dateformat} =~ /^yy/) {
  878. ($yy, $mm, $dd) = split /\D/, $date;
  879. }
  880. if ($myconfig->{dateformat} =~ /^mm/) {
  881. ($mm, $dd, $yy) = split /\D/, $date;
  882. }
  883. if ($myconfig->{dateformat} =~ /^dd/) {
  884. ($dd, $mm, $yy) = split /\D/, $date;
  885. }
  886. $dd *= 1;
  887. $mm *= 1;
  888. $yy += 2000 if length $yy == 2;
  889. $dd = substr("0$dd", -2);
  890. $mm = substr("0$mm", -2);
  891. $date = "$yy$mm$dd";
  892. }
  893. $date;
  894. }
  895. sub add_date {
  896. my ($self, $myconfig, $date, $repeat, $unit) = @_;
  897. use Time::Local;
  898. my $diff = 0;
  899. my $spc = $myconfig->{dateformat};
  900. $spc =~ s/\w//g;
  901. $spc = substr($spc, 0, 1);
  902. if ($date) {
  903. if ($date =~ /\D/) {
  904. if ($myconfig->{dateformat} =~ /^yy/) {
  905. ($yy, $mm, $dd) = split /\D/, $date;
  906. }
  907. if ($myconfig->{dateformat} =~ /^mm/) {
  908. ($mm, $dd, $yy) = split /\D/, $date;
  909. }
  910. if ($myconfig->{dateformat} =~ /^dd/) {
  911. ($dd, $mm, $yy) = split /\D/, $date;
  912. }
  913. } else {
  914. # ISO
  915. ($yy, $mm, $dd) =~ /(....)(..)(..)/;
  916. }
  917. if ($unit eq 'days') {
  918. $diff = $repeat * 86400;
  919. }
  920. if ($unit eq 'weeks') {
  921. $diff = $repeat * 604800;
  922. }
  923. if ($unit eq 'months') {
  924. $diff = $mm + $repeat;
  925. my $whole = int($diff / 12);
  926. $yy += $whole;
  927. $mm = ($diff % 12) + 1;
  928. $diff = 0;
  929. }
  930. if ($unit eq 'years') {
  931. $yy++;
  932. }
  933. $mm--;
  934. @t = localtime(timelocal(0,0,0,$dd,$mm,$yy) + $diff);
  935. $t[4]++;
  936. $mm = substr("0$t[4]",-2);
  937. $dd = substr("0$t[3]",-2);
  938. $yy = $t[5] + 1900;
  939. if ($date =~ /\D/) {
  940. if ($myconfig->{dateformat} =~ /^yy/) {
  941. $date = "$yy$spc$mm$spc$dd";
  942. }
  943. if ($myconfig->{dateformat} =~ /^mm/) {
  944. $date = "$mm$spc$dd$spc$yy";
  945. }
  946. if ($myconfig->{dateformat} =~ /^dd/) {
  947. $date = "$dd$spc$mm$spc$yy";
  948. }
  949. } else {
  950. $date = "$yy$mm$dd";
  951. }
  952. }
  953. $date;
  954. }
  955. sub print_button {
  956. my ($self, $button, $name) = @_;
  957. print 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|;
  958. }
  959. # Database routines used throughout
  960. sub db_init {
  961. my ($self, $myconfig) = @_;
  962. $self->{dbh} = $self->dbconnect_noauto($myconfig) || $self->dberror();
  963. my $query =
  964. "SELECT t.extends,
  965. coalesce (t.table_name, 'custom_' || extends)
  966. || ':' || f.field_name as field_def
  967. FROM custom_table_catalog t
  968. JOIN custom_field_catalog f USING (table_id)";
  969. my $sth = $self->{dbh}->prepare($query);
  970. $sth->execute;
  971. my $ref;
  972. while ($ref = $sth->fetchrow_hashref(NAME_lc)){
  973. push @{$self->{custom_db_fields}{$ref->{extends}}},
  974. $ref->{field_def};
  975. }
  976. }
  977. sub run_custom_queries {
  978. my ($self, $tablename, $query_type, $linenum) = @_;
  979. my $dbh = $self->{dbh};
  980. if ($query_type !~ /^(select|insert|update)$/i){
  981. $self->error($locale->text(
  982. "Passed incorrect query type to run_custom_queries."
  983. ));
  984. }
  985. my @rc;
  986. my %temphash;
  987. my @templist;
  988. my @elements;
  989. my $query;
  990. my $ins_values;
  991. if ($linenum){
  992. $linenum = "_$linenum";
  993. }
  994. $query_type = uc($query_type);
  995. for (@{$self->{custom_db_fields}{$tablename}}){
  996. @elements = split (/:/, $_);
  997. push @{$temphash{$elements[0]}}, $elements[1];
  998. }
  999. for (keys %temphash){
  1000. my @data;
  1001. my $ins_values;
  1002. $query = "$query_type ";
  1003. if ($query_type eq 'UPDATE'){
  1004. $query = "DELETE FROM $_ WHERE row_id = ?";
  1005. my $sth = $dbh->prepare($query);
  1006. $sth->execute->($self->{"id"."$linenum"})
  1007. || $self->dberror($query);
  1008. } elsif ($query_type eq 'INSERT'){
  1009. $query .= " INTO $_ (";
  1010. }
  1011. my $first = 1;
  1012. for (@{$temphash{$_}}){
  1013. $query .= "$_";
  1014. if ($query_type eq 'UPDATE'){
  1015. $query .= '= ?';
  1016. }
  1017. $ins_values .= "?, ";
  1018. $query .= ", ";
  1019. $first = 0;
  1020. if ($query_type eq 'UPDATE' or $query_type eq 'INSERT'){
  1021. push @data, $self->{"$_$linenum"};
  1022. }
  1023. }
  1024. if ($query_type ne 'INSERT'){
  1025. $query =~ s/, $//;
  1026. }
  1027. if ($query_type eq 'SELECT'){
  1028. $query .= " FROM $_";
  1029. }
  1030. if ($query_type eq 'SELECT' or $query_type eq 'UPDATE'){
  1031. $query .= " WHERE row_id = ?";
  1032. }
  1033. if ($query_type eq 'INSERT'){
  1034. $query .= " row_id) VALUES ($ins_values ?)";
  1035. }
  1036. if ($query_type eq 'SELECT'){
  1037. push @rc, [ $query ];
  1038. } else {
  1039. unshift (@data, $query);
  1040. push @rc, [ @data ];
  1041. }
  1042. }
  1043. if ($query_type eq 'INSERT'){
  1044. for (@rc){
  1045. $query = shift (@{$_});
  1046. $sth = $dbh->prepare($query)
  1047. || $self->db_error($query);
  1048. $sth->execute(@{$_}, $self->{id})
  1049. || $self->dberror($query);;
  1050. $sth->finish;
  1051. $did_insert = 1;
  1052. }
  1053. } elsif ($query_type eq 'UPDATE'){
  1054. @rc = $self->run_custom_queries(
  1055. $tablename, 'INSERT', $linenum);
  1056. } elsif ($query_type eq 'SELECT'){
  1057. for (@rc){
  1058. $query = shift @{$_};
  1059. $sth = $self->{dbh}->prepare($query);
  1060. $sth->execute($self->{id});
  1061. $ref = $sth->fetchrow_hashref(NAME_lc);
  1062. for (keys %{$ref}){
  1063. $self->{$_} = $ref->{$_};
  1064. }
  1065. }
  1066. }
  1067. @rc;
  1068. }
  1069. sub dbconnect {
  1070. my ($self, $myconfig) = @_;
  1071. # connect to database
  1072. my $dbh = DBI->connect($myconfig->{dbconnect}, $myconfig->{dbuser}, $myconfig->{dbpasswd}) or $self->dberror;
  1073. # set db options
  1074. if ($myconfig->{dboptions}) {
  1075. $dbh->do($myconfig->{dboptions}) || $self->dberror($myconfig->{dboptions});
  1076. }
  1077. $dbh;
  1078. }
  1079. sub dbconnect_noauto {
  1080. my ($self, $myconfig) = @_;
  1081. # connect to database
  1082. $dbh = DBI->connect($myconfig->{dbconnect}, $myconfig->{dbuser}, $myconfig->{dbpasswd}, {AutoCommit => 0}) or $self->dberror;
  1083. # set db options
  1084. if ($myconfig->{dboptions}) {
  1085. $dbh->do($myconfig->{dboptions});
  1086. }
  1087. $dbh;
  1088. }
  1089. sub dbquote {
  1090. my ($self, $var) = @_;
  1091. if ($var eq ''){
  1092. $_ = "NULL";
  1093. } else {
  1094. $_ = $self->{dbh}->quote($var);
  1095. }
  1096. $_;
  1097. }
  1098. sub update_balance {
  1099. # This is a dangerous private function. All apps calling it must
  1100. # be careful to avoid SQL injection issues
  1101. my ($self, $dbh, $table, $field, $where, $value) = @_;
  1102. # if we have a value, go do it
  1103. if ($value) {
  1104. # retrieve balance from table
  1105. my $query = "SELECT $field FROM $table WHERE $where FOR UPDATE";
  1106. my ($balance) = $dbh->selectrow_array($query);
  1107. $balance += $value;
  1108. # update balance
  1109. $query = "UPDATE $table SET $field = $balance WHERE $where";
  1110. $dbh->do($query) || $self->dberror($query);
  1111. }
  1112. }
  1113. sub update_exchangerate {
  1114. my ($self, $dbh, $curr, $transdate, $buy, $sell) = @_;
  1115. # some sanity check for currency