summaryrefslogtreecommitdiff
path: root/LedgerSMB.pm
blob: 3a06bacf380dd11cc26d8ce9fbf35ab93241f74c (plain)
  1. =head1 NAME
  2. LedgerSMB The Base class for many LedgerSMB objects, including DBObject.
  3. =head1 SYOPSIS
  4. This module creates a basic request handler with utility functions available
  5. in database objects (LedgerSMB::DBObject)
  6. =head1 METHODS
  7. =item new ()
  8. This method creates a new base request instance.
  9. =item date_to_number (user => $LedgerSMB::User, date => $string);
  10. This function takes the date in the format provided and returns a numeric
  11. string in YYMMDD format. This may be moved to User in the future.
  12. =item debug (file => $path);
  13. This dumps the current object to the file if that is defined and otherwise to
  14. standard output.
  15. =item escape (string => $string);
  16. This function returns the current string escaped using %hexhex notation.
  17. =item unescape (string => $string);
  18. This function returns the $string encoded using %hexhex using ordinary notation.
  19. =item format_amount (user => $LedgerSMB::User::hash, amount => $string, precision => $integer, neg_format => (-|DRCR));
  20. The function takes a monetary amount and formats it according to the user
  21. preferences, the negative format (- or DR/CR). Note that it may move to
  22. LedgerSMB::User at some point in the future.
  23. =item parse_amount (user => $LedgerSMB::User::hash, amount => $variable);
  24. If $amount is a Bigfloat, it is returned as is. If it is a string, it is
  25. parsed according to the user preferences stored in the LedgerSMB::User object.
  26. =item format_fields (fields => \@array);
  27. This function converts fields to their appropriate representation in
  28. HTML/SGML/XML or LaTeX.
  29. =item is_blank (name => $string)
  30. This function returns true if $self->{$string} only consists of whitespace
  31. characters or is an empty string.
  32. =item is_run_mode ('(cli|cgi|mod_perl)')
  33. This function returns 1 if the run mode is what is specified. Otherwise
  34. returns 0.
  35. =item num_text_rows (string => $string, cols => $number, max => $number);
  36. This function determines the likely number of rows needed to hold text in a
  37. textbox. It returns either that number or max, which ever is lower.
  38. =item merge ($hashref, keys => @list, index => $number);
  39. This command merges the $hashref into the current object. If keys are
  40. specified, only those keys are used. Otherwise all keys are merged.
  41. If an index is specified, the merged keys are given a form of
  42. "$key" . "_$index", otherwise the key is used on both sides.
  43. =item redirect (msg => $string)
  44. This function redirects to the script and argument set determined by
  45. $self->{callback}, and if this is not set, goes to an info screen and prints
  46. $msg.
  47. =item redo_rows (fields => \@list, count => $integer, [index => $string);
  48. This function is undergoing serious redesign at the moment. If index is
  49. defined, that field is used for ordering the rows. If not, runningnumber is
  50. used. Behavior is not defined when index points to a field containing
  51. non-numbers.
  52. =head1 Copyright (C) 2006, The LedgerSMB core team.
  53. # This work contains copyrighted information from a number of sources all used
  54. # with permission.
  55. #
  56. # This file contains source code included with or based on SQL-Ledger which
  57. # is Copyright Dieter Simader and DWS Systems Inc. 2000-2005 and licensed
  58. # under the GNU General Public License version 2 or, at your option, any later
  59. # version. For a full list including contact information of contributors,
  60. # maintainers, and copyright holders, see the CONTRIBUTORS file.
  61. #
  62. # Original Copyright Notice from SQL-Ledger 2.6.17 (before the fork):
  63. # Copyright (C) 2000
  64. #
  65. # Author: DWS Systems Inc.
  66. # Web: http://www.sql-ledger.org
  67. #
  68. # Contributors: Thomas Bayen <bayen@gmx.de>
  69. # Antti Kaihola <akaihola@siba.fi>
  70. # Moritz Bunkus (tex)
  71. # Jim Rawlings <jim@your-dba.com> (DB2)
  72. #======================================================================
  73. =cut
  74. use CGI;
  75. use Math::BigFloat lib=>'GMP';
  76. use LedgerSMB::Sysconfig;
  77. use Data::Dumper;
  78. use strict;
  79. package LedgerSMB;
  80. sub new {
  81. my $type = shift @_;
  82. my $argstr = shift @_;
  83. my $self = {};
  84. $self->{version} = "1.3.0 Alpha 0 Pre";
  85. $self->{dbversion} = "1.2.0";
  86. bless $self, $type;
  87. my $query = ($argstr) ? new CGI($argstr) : new CGI;
  88. my $params = $query->Vars;
  89. $self->merge($params);
  90. $self->{action} =~ s/\W/_/g;
  91. $self->{action} = lc $self->{action};
  92. if ($self->{path} =~ /lynx/i){
  93. $self->{menubar} = 1;
  94. #menubar will be deprecated, replaced with below
  95. $self->{lynx} = 1;
  96. }
  97. $self;
  98. }
  99. sub debug {
  100. my $self = shift @_;
  101. my %args = @_;
  102. my $file = $args{file};
  103. my $d = Data::Dumper->new([@_]);
  104. $d->Sortkeys(1);
  105. if ($file) {
  106. open(FH, '>', "$file") or die $!;
  107. print FH $d->Dump();
  108. close(FH);
  109. } else {
  110. print "\n";
  111. print $d->Dump();
  112. }
  113. }
  114. sub escape {
  115. my ($self) = @_;
  116. my %args = @_;
  117. my $str = $args{string};
  118. my $regex = qr/([^a-zA-Z0-9_.-])/;
  119. $str =~ s/$regex/sprintf("%%%02x", ord($1))/ge;
  120. $str;
  121. }
  122. sub is_blank {
  123. my $self = shift @_;
  124. my %args = @_;
  125. my $name = $args{name};
  126. my $rc;
  127. if ($self->{$name} =~ /^\s*$/){
  128. $rc = 1;
  129. } else {
  130. $rc = 0;
  131. }
  132. $rc;
  133. }
  134. sub is_run_mode {
  135. my $self = shift @_;
  136. my $mode = lc shift @_;
  137. my $rc = 0;
  138. if ($mode eq 'cgi' && $ENV{GATEWAY_INTERFACE}){
  139. $rc = 1;
  140. }
  141. elsif ($mode eq 'cli' && ! ($ENV{GATEWAY_INTERFACE} || $ENV{MOD_PERL})){
  142. $rc = 1;
  143. } elsif ($mode eq 'mod_perl' && $ENV{MOD_PERL}){
  144. $rc = 1;
  145. }
  146. $rc;
  147. }
  148. sub num_text_rows {
  149. my $self = shift @_;
  150. my %args = @_;
  151. my $string = $args{string};
  152. my $cols = $args{cols};
  153. my $maxrows = $args{max};
  154. my $rows = 0;
  155. for (split /\n/, $string) {
  156. my $line = $_;
  157. while (length($line) > $cols){
  158. my $fragment = substr($line, 0, $cols + 1);
  159. my $fragment = s/^(.*)\S*$/$1/;
  160. $line = s/$fragment//;
  161. if ($line eq $fragment){ # No word breaks!
  162. $line = "";
  163. }
  164. ++$rows;
  165. }
  166. ++$rows;
  167. }
  168. if (! defined $maxrows){
  169. $maxrows = $rows;
  170. }
  171. return ($rows > $maxrows) ? $maxrows : $rows;
  172. }
  173. sub redirect {
  174. my $self = shift @_;
  175. my %args = @_;
  176. my $msg = $args{msg};
  177. if ($self->{callback} || !$msg) {
  178. main::redirect();
  179. } else {
  180. $self->info($msg);
  181. }
  182. }
  183. sub format_fields {
  184. # Based on SQL-Ledger's Form::format_string
  185. # We should look at moving this into LedgerSMB::Template.
  186. # And cleaning it up...... Chris
  187. my $self = shift @_;
  188. my %args = @_;
  189. my @fields = @{$args{fields}};
  190. my $format = $self->{format};
  191. if ($self->{format} =~ /(postscript|pdf)/) {
  192. $format = 'tex';
  193. }
  194. my %replace = (
  195. 'order' => {
  196. html => [ '<', '>', '\n', '\r' ],
  197. txt => [ '\n', '\r' ],
  198. tex => [ quotemeta('\\'), '&', '\n','\r',
  199. '\$', '%', '_', '#',
  200. quotemeta('^'), '{', '}', '<', '>', '£'
  201. ] },
  202. html => { '<' => '&lt;', '>' => '&gt;','\n' => '<br />',
  203. '\r' => '<br />' },
  204. txt => { '\n' => "\n", '\r' => "\r" },
  205. tex => {'&' => '\&', '$' => '\$', '%' => '\%', '_' => '\_',
  206. '#' => '\#', quotemeta('^') => '\^\\', '{' => '\{',
  207. '}' => '\}', '<' => '$<$', '>' => '$>$',
  208. '\n' => '\newline ', '\r' => '\newline ',
  209. '£' => '\pounds ', quotemeta('\\') => '/'}
  210. );
  211. my $key;
  212. foreach $key (@{ $replace{order}{$format} }) {
  213. for (@fields) { $self->{$_} =~ s/$key/$replace{$format}{$key}/g }
  214. }
  215. }
  216. # TODO: Either we should have an amount class with formats and such attached
  217. # Or maybe we should move this into the user class...
  218. sub format_amount {
  219. # Based on SQL-Ledger's Form::format_amount
  220. my $self = shift @_;
  221. my %args = @_;
  222. my $myconfig = $args{user};
  223. my $amount = $args{amount};
  224. my $places = $args{precision};
  225. my $dash = $args{neg_format};
  226. my $negative ;
  227. if ($amount){
  228. $amount = $self->parse_amount($myconfig, $amount);
  229. $negative = ($amount < 0);
  230. $amount =~ s/-//;
  231. }
  232. if ($places =~ /\d+/) {
  233. #$places = 4 if $places == 2;
  234. $amount = $self->round_amount($amount, $places);
  235. }
  236. # is the amount negative
  237. # Parse $myconfig->{numberformat}
  238. my ($ts, $ds) = ($1, $2);
  239. if ($amount) {
  240. if ($myconfig->{numberformat}) {
  241. my ($whole, $dec) = split /\./, "$amount";
  242. $amount = join '', reverse split //, $whole;
  243. if ($places) {
  244. $dec .= "0" x $places;
  245. $dec = substr($dec, 0, $places);
  246. }
  247. if ($myconfig->{numberformat} eq '1,000.00') {
  248. $amount =~ s/\d{3,}?/$&,/g;
  249. $amount =~ s/,$//;
  250. $amount = join '', reverse split //, $amount;
  251. $amount .= "\.$dec" if ($dec ne "");
  252. }
  253. if ($myconfig->{numberformat} eq '1 000.00') {
  254. $amount =~ s/\d{3,}?/$& /g;
  255. $amount =~ s/\s$//;
  256. $amount = join '', reverse split //, $amount;
  257. $amount .= "\.$dec" if ($dec ne "");
  258. }
  259. if ($myconfig->{numberformat} eq "1'000.00") {
  260. $amount =~ s/\d{3,}?/$&'/g;
  261. $amount =~ s/'$//;
  262. $amount = join '', reverse split //, $amount;
  263. $amount .= "\.$dec" if ($dec ne "");
  264. }
  265. if ($myconfig->{numberformat} eq '1.000,00') {
  266. $amount =~ s/\d{3,}?/$&./g;
  267. $amount =~ s/\.$//;
  268. $amount = join '', reverse split //, $amount;
  269. $amount .= ",$dec" if ($dec ne "");
  270. }
  271. if ($myconfig->{numberformat} eq '1000,00') {
  272. $amount = "$whole";
  273. $amount .= ",$dec" if ($dec ne "");
  274. }
  275. if ($myconfig->{numberformat} eq '1000.00') {
  276. $amount = "$whole";
  277. $amount .= ".$dec" if ($dec ne "");
  278. }
  279. if ($dash =~ /-/) {
  280. $amount = ($negative) ? "($amount)" : "$amount";
  281. } elsif ($dash =~ /DRCR/) {
  282. $amount = ($negative) ? "$amount DR" : "$amount CR";
  283. } else {
  284. $amount = ($negative) ? "-$amount" : "$amount";
  285. }
  286. }
  287. } else {
  288. if ($dash eq "0" && $places) {
  289. if ($myconfig->{numberformat} eq '1.000,00') {
  290. $amount = "0".","."0" x $places;
  291. } else {
  292. $amount = "0"."."."0" x $places;
  293. }
  294. } else {
  295. $amount = ($dash ne "") ? "$dash" : "";
  296. }
  297. }
  298. $amount;
  299. }
  300. # This should probably go to the User object too.
  301. sub parse_amount {
  302. my $self = shift @_;
  303. my %args = @_;
  304. my $myconfig = $args{user};
  305. my $amount = $args{amount};
  306. if ($amount eq '' or $amount == undef){
  307. return 0;
  308. }
  309. if (UNIVERSAL::isa($amount, 'Math::BigFloat')){ # Amount may not be an object
  310. return $amount;
  311. }
  312. my $numberformat = $myconfig->{numberformat};
  313. if (($numberformat eq '1.000,00') ||
  314. ($numberformat eq '1000,00')) {
  315. $amount =~ s/\.//g;
  316. $amount =~ s/,/./;
  317. }
  318. if ($numberformat eq '1 000.00'){
  319. $amount =~ s/\s//g;
  320. }
  321. if ($numberformat eq "1'000.00") {
  322. $amount =~ s/'//g;
  323. }
  324. $amount =~ s/,//g;
  325. if ($amount =~ s/\((\d*\.?\d*)\)/$1/){
  326. $amount = $1 * -1;
  327. }
  328. if ($amount =~ s/(\d*\.?\d*)\s?DR/$1/){
  329. $amount = $1 * -1;
  330. }
  331. $amount =~ s/\s?CR//;
  332. $amount = new Math::BigFloat($amount);
  333. return ($amount * 1);
  334. }
  335. sub round_amount {
  336. my ($self, $amount, $places) = @_;
  337. # These rounding rules follow from the previous implementation.
  338. # They should be changed to allow different rules for different accounts.
  339. Math::BigFloat->round_mode('+inf') if $amount >= 0;
  340. Math::BigFloat->round_mode('-inf') if $amount < 0;
  341. $amount = Math::BigFloat->new($amount)->ffround(-$places) if $places >= 0;
  342. $amount = Math::BigFloat->new($amount)->ffround(-($places-1)) if $places < 0;
  343. return $amount;
  344. }
  345. sub call_procedure {
  346. my $self = shift @_;
  347. my %args = @_;
  348. my $procname = $args{procname};
  349. my @args = @{$args{args}};
  350. my $argstr = "";
  351. my @results;
  352. for (1 .. scalar @args){
  353. $argstr .= "?, ";
  354. }
  355. $argstr =~ s/\, $//;
  356. my $query = "SELECT * FROM $procname()";
  357. $query =~ s/\(\)/($argstr)/;
  358. my $sth = $self->{dbh}->prepare($query);
  359. $sth->execute(@args);
  360. while (my $ref = $sth->fetchrow_hashref('NAME_lc')){
  361. push @results, $ref;
  362. }
  363. @results;
  364. }
  365. # This should probably be moved to User too...
  366. sub date_to_number {
  367. #based on SQL-Ledger's Form::datetonum
  368. my $self = shift @_;
  369. my %args = @_;
  370. my $myconfig = $args{user};
  371. my $date = $args{date};
  372. my ($yy, $mm, $dd);
  373. if ($date && $date =~ /\D/) {
  374. if ($myconfig->{dateformat} =~ /^yy/) {
  375. ($yy, $mm, $dd) = split /\D/, $date;
  376. }
  377. if ($myconfig->{dateformat} =~ /^mm/) {
  378. ($mm, $dd, $yy) = split /\D/, $date;
  379. }
  380. if ($myconfig->{dateformat} =~ /^dd/) {
  381. ($dd, $mm, $yy) = split /\D/, $date;
  382. }
  383. $dd *= 1;
  384. $mm *= 1;
  385. $yy += 2000 if length $yy == 2;
  386. $dd = substr("0$dd", -2);
  387. $mm = substr("0$mm", -2);
  388. $date = "$yy$mm$dd";
  389. }
  390. $date;
  391. }
  392. # Database routines used throughout
  393. sub db_init {
  394. my $self = shift @_;
  395. my %args = @_;
  396. my $myconfig = $args{user};
  397. my $dbh = DBI->connect($myconfig->{dbconnect}, $myconfig->{dbuser},
  398. $myconfig->{dbpasswd}, {AutoCommit => 0}) or $self->dberror;
  399. if ($myconfig->{dboptions}) {
  400. $dbh->do($myconfig->{dboptions});
  401. }
  402. my $query =
  403. "SELECT t.extends,
  404. coalesce (t.table_name, 'custom_' || extends)
  405. || ':' || f.field_name as field_def
  406. FROM custom_table_catalog t
  407. JOIN custom_field_catalog f USING (table_id)";
  408. my $sth = $self->{dbh}->prepare($query);
  409. $sth->execute;
  410. my $ref;
  411. while ($ref = $sth->fetchrow_hashref('NAME_lc')){
  412. push @{$self->{custom_db_fields}{$ref->{extends}}},
  413. $ref->{field_def};
  414. }
  415. }
  416. sub redo_rows {
  417. my $self = shift @_;
  418. my %args = @_;
  419. my @flds = @{$args{fields}};
  420. my $count = $args{count};
  421. my $index = ($args{index}) ? $args{index} : 'runningnumber';
  422. my @rows;
  423. my $i; # incriment counter use only
  424. for $i (1 .. $count){
  425. my $temphash = {_inc => $i};
  426. for my $fld (@flds){
  427. $temphash->{$fld} = $self->{"$fld"."_$i"}
  428. }
  429. push @rows, $temphash;
  430. }
  431. $i = 1;
  432. for my $row (sort {$a->{index} <=> $b->{index}} @rows){
  433. for my $fld (@flds){
  434. $self->{"$fld"."_$i"} = $row->{$fld};
  435. }
  436. ++$i;
  437. }
  438. }
  439. sub merge {
  440. my ($self, $src) = @_;
  441. for my $arg ($self, $src){
  442. shift;
  443. }
  444. my %args = @_;
  445. my @keys = @{$args{keys}};
  446. my $index = $args{index};
  447. if (! scalar @keys){
  448. @keys = keys %{$src};
  449. }
  450. for my $arg (keys %$src){
  451. my $dst_arg;
  452. if ($index){
  453. $dst_arg = $arg . "_$index";
  454. } else {
  455. $dst_arg = $arg;
  456. }
  457. $self->{$dst_arg} = $src->{$arg};
  458. }
  459. }
  460. 1;