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