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