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