summaryrefslogtreecommitdiff
path: root/LedgerSMB.pm
blob: 37652d5b17436e7ad10f496c5b16daa34ce62259 (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->{VERSION} = $VERSION;
  101. $self->merge($params);
  102. $self->{action} =~ s/\W/_/g;
  103. $self->{action} = lc $self->{action};
  104. if ( $self->{path} eq "bin/lynx" ) {
  105. $self->{menubar} = 1;
  106. #menubar will be deprecated, replaced with below
  107. $self->{lynx} = 1;
  108. $self->{path} = "bin/lynx";
  109. }
  110. else {
  111. $self->{path} = "bin/mozilla";
  112. }
  113. if ( ( $self->{script} =~ m#(..|\\|/)# ) ) {
  114. $self->error("Access Denied");
  115. }
  116. if (!$self->{login}){
  117. #this is an ugly hack we need to rethink.
  118. return $self;
  119. }
  120. $self->{_user} = LedgerSMB::User->fetch_config($self->{login});
  121. my $locale = LedgerSMB::Locale->get_handle($self->{_user}->{countrycode})
  122. or $self->error(__FILE__.':'.__LINE__.": Locale not loaded: $!\n");
  123. if ( !${LedgerSMB::Sysconfig::GLOBALDBH} ) {
  124. $locale->text("No GlobalDBH Configured or Could not Connect");
  125. }
  126. $self->{_locale} = $locale;
  127. $self->{stylesheet} = $self->{_user}->{stylesheet};
  128. if ( $self->{password} ) {
  129. if (
  130. !Session::password_check(
  131. $self, $self->{login}, $self->{password}
  132. )
  133. )
  134. {
  135. if ($self->is_run_mode('cgi', 'mod_perl')) {
  136. $self->_get_password();
  137. }
  138. else {
  139. $self->error( __FILE__ . ':' . __LINE__ . ': '
  140. . $locale->text('Access Denied!') );
  141. }
  142. exit;
  143. }
  144. else {
  145. Session::session_create($self);
  146. }
  147. }
  148. else {
  149. if ($self->is_run_mode('cgi', 'mod_perl')) {
  150. my %cookie;
  151. $ENV{HTTP_COOKIE} =~ s/;\s*/;/g;
  152. my @cookies = split /;/, $ENV{HTTP_COOKIE};
  153. foreach (@cookies) {
  154. my ( $name, $value ) = split /=/, $_, 2;
  155. $cookie{$name} = $value;
  156. }
  157. #check for valid session
  158. if ( !Session::session_check( $cookie{"LedgerSMB"}, $self) ) {
  159. $self->_get_password(1);
  160. exit;
  161. }
  162. }
  163. else {
  164. exit;
  165. }
  166. }
  167. $self->{stylesheet} = $self->{_user}->{stylesheet};
  168. $self->_db_init;
  169. $self;
  170. }
  171. sub _get_password {
  172. my ($self) = shift @_;
  173. $self->{sessionexpired} = shift @_;
  174. $self->{hidden} = [];
  175. for (keys %$self){
  176. next if $_ =~ /(^script$|^endsession$|^password$)/;
  177. my $attr = {};
  178. $attr->{name} = $_;
  179. $attr->{value} = $self->{$_};
  180. push @{$self->{hidden}}, $attr;
  181. }
  182. my $template = LedgerSMB::Template->new(
  183. user =>$self->{_user},
  184. locale => $self->{_locale},
  185. path => 'UI',
  186. template => 'get_password',
  187. format => 'HTML'
  188. );
  189. $template->render($self);
  190. $template->output('http');
  191. exit;
  192. }
  193. sub debug {
  194. my $self = shift @_;
  195. my $args = shift @_;
  196. my $file;
  197. if (scalar keys %$args){
  198. $file = $args->{'file'};
  199. }
  200. my $d = Data::Dumper->new( [$self] );
  201. $d->Sortkeys(1);
  202. if ($file) {
  203. open( FH, '>', "$file" ) or die $!;
  204. print FH $d->Dump();
  205. close(FH);
  206. }
  207. else {
  208. print "\n";
  209. print $d->Dump();
  210. }
  211. }
  212. sub escape {
  213. my $self = shift;
  214. my %args = @_;
  215. my $str = $args{string};
  216. my $regex = qr/([^a-zA-Z0-9_.-])/;
  217. $str =~ s/$regex/sprintf("%%%02x", ord($1))/ge;
  218. $str;
  219. }
  220. sub is_blank {
  221. my $self = shift @_;
  222. my %args = @_;
  223. my $name = $args{name};
  224. if (not defined $name){
  225. # TODO: Raise error
  226. }
  227. my $rc;
  228. if ( $self->{$name} =~ /^\s*$/ ) {
  229. $rc = 1;
  230. }
  231. else {
  232. $rc = 0;
  233. }
  234. $rc;
  235. }
  236. sub is_run_mode {
  237. my $self = shift @_;
  238. my $mode = lc shift @_;
  239. my $rc = 0;
  240. if ( $mode eq 'cgi' && $ENV{GATEWAY_INTERFACE} ) {
  241. $rc = 1;
  242. }
  243. elsif ( $mode eq 'cli' && !( $ENV{GATEWAY_INTERFACE} || $ENV{MOD_PERL} ) ) {
  244. $rc = 1;
  245. }
  246. elsif ( $mode eq 'mod_perl' && $ENV{MOD_PERL} ) {
  247. $rc = 1;
  248. }
  249. $rc;
  250. }
  251. sub num_text_rows {
  252. my $self = shift @_;
  253. my %args = @_;
  254. my $string = $args{string};
  255. my $cols = $args{cols};
  256. my $maxrows = $args{max};
  257. my $rows = 0;
  258. for ( split /\n/, $string ) {
  259. my $line = $_;
  260. while ( length($line) > $cols ) {
  261. my $fragment = substr( $line, 0, $cols + 1 );
  262. $fragment =~ s/^(.*)\W.*$/$1/;
  263. $line =~ s/$fragment//;
  264. if ( $line eq $fragment ) { # No word breaks!
  265. $line = "";
  266. }
  267. ++$rows;
  268. }
  269. ++$rows;
  270. }
  271. if ( !defined $maxrows ) {
  272. $maxrows = $rows;
  273. }
  274. return ( $rows > $maxrows ) ? $maxrows : $rows;
  275. }
  276. sub redirect {
  277. my $self = shift @_;
  278. my %args = @_;
  279. my $msg = $args{msg};
  280. if ( $self->{callback} || !$msg ) {
  281. main::redirect();
  282. exit;
  283. }
  284. else {
  285. $self->info($msg);
  286. }
  287. }
  288. # TODO: Either we should have an amount class with formats and such attached
  289. # Or maybe we should move this into the user class...
  290. sub format_amount {
  291. # Based on SQL-Ledger's Form::format_amount
  292. my $self = shift @_;
  293. my %args = @_;
  294. my $myconfig = $args{user};
  295. my $amount = $args{amount};
  296. my $places = $args{precision};
  297. my $dash = $args{neg_format};
  298. my $negative;
  299. if ($amount) {
  300. $amount = $self->parse_amount( 'user' => $myconfig, 'amount' => $amount );
  301. $negative = ( $amount < 0 );
  302. $amount =~ s/-//;
  303. }
  304. if ( $places =~ /\d+/ ) {
  305. #$places = 4 if $places == 2;
  306. $amount = $self->round_amount( $amount, $places );
  307. }
  308. # is the amount negative
  309. # Parse $myconfig->{numberformat}
  310. my ( $ts, $ds ) = ( $1, $2 );
  311. if ($amount) {
  312. if ( $myconfig->{numberformat} ) {
  313. my ( $whole, $dec ) = split /\./, "$amount";
  314. $amount = join '', reverse split //, $whole;
  315. if ($places) {
  316. $dec .= "0" x $places;
  317. $dec = substr( $dec, 0, $places );
  318. }
  319. if ( $myconfig->{numberformat} eq '1,000.00' ) {
  320. $amount =~ s/\d{3,}?/$&,/g;
  321. $amount =~ s/,$//;
  322. $amount = join '', reverse split //, $amount;
  323. $amount .= "\.$dec" if ( $dec ne "" );
  324. }
  325. elsif ( $myconfig->{numberformat} eq '1 000.00' ) {
  326. $amount =~ s/\d{3,}?/$& /g;
  327. $amount =~ s/\s$//;
  328. $amount = join '', reverse split //, $amount;
  329. $amount .= "\.$dec" if ( $dec ne "" );
  330. }
  331. elsif ( $myconfig->{numberformat} eq "1'000.00" ) {
  332. $amount =~ s/\d{3,}?/$&'/g;
  333. $amount =~ s/'$//;
  334. $amount = join '', reverse split //, $amount;
  335. $amount .= "\.$dec" if ( $dec ne "" );
  336. }
  337. elsif ( $myconfig->{numberformat} eq '1.000,00' ) {
  338. $amount =~ s/\d{3,}?/$&./g;
  339. $amount =~ s/\.$//;
  340. $amount = join '', reverse split //, $amount;
  341. $amount .= ",$dec" if ( $dec ne "" );
  342. }
  343. elsif ( $myconfig->{numberformat} eq '1000,00' ) {
  344. $amount = "$whole";
  345. $amount .= ",$dec" if ( $dec ne "" );
  346. }
  347. elsif ( $myconfig->{numberformat} eq '1000.00' ) {
  348. $amount = "$whole";
  349. $amount .= ".$dec" if ( $dec ne "" );
  350. }
  351. if ( $dash =~ /-/ ) {
  352. $amount = ($negative) ? "($amount)" : "$amount";
  353. }
  354. elsif ( $dash =~ /DRCR/ ) {
  355. $amount = ($negative) ? "$amount DR" : "$amount CR";
  356. }
  357. else {
  358. $amount = ($negative) ? "-$amount" : "$amount";
  359. }
  360. }
  361. }
  362. else {
  363. if ( $dash eq "0" && $places ) {
  364. if ( $myconfig->{numberformat} =~ /0,00$/ ) {
  365. $amount = "0" . "," . "0" x $places;
  366. }
  367. else {
  368. $amount = "0" . "." . "0" x $places;
  369. }
  370. }
  371. else {
  372. $amount = ( $dash ne "" ) ? "$dash" : "";
  373. }
  374. }
  375. $amount;
  376. }
  377. # This should probably go to the User object too.
  378. sub parse_amount {
  379. my $self = shift @_;
  380. my %args = @_;
  381. my $myconfig = $args{user};
  382. my $amount = $args{amount};
  383. if ( $amount eq '' or ! defined $amount) {
  384. return 0;
  385. }
  386. if ( UNIVERSAL::isa( $amount, 'Math::BigFloat' ) )
  387. { # Amount may not be an object
  388. return $amount;
  389. }
  390. my $numberformat = $myconfig->{numberformat};
  391. if ( ( $numberformat eq '1.000,00' )
  392. || ( $numberformat eq '1000,00' ) )
  393. {
  394. $amount =~ s/\.//g;
  395. $amount =~ s/,/./;
  396. }
  397. elsif ( $numberformat eq '1 000.00' ) {
  398. $amount =~ s/\s//g;
  399. }
  400. elsif ( $numberformat eq "1'000.00" ) {
  401. $amount =~ s/'//g;
  402. }
  403. $amount =~ s/,//g;
  404. if ( $amount =~ s/\((\d*\.?\d*)\)/$1/ ) {
  405. $amount = $1 * -1;
  406. }
  407. elsif ( $amount =~ s/(\d*\.?\d*)\s?DR/$1/ ) {
  408. $amount = $1 * -1;
  409. }
  410. $amount =~ s/\s?CR//;
  411. $amount = new Math::BigFloat($amount);
  412. return ( $amount * 1 );
  413. }
  414. sub round_amount {
  415. my ( $self, $amount, $places ) = @_;
  416. # These rounding rules follow from the previous implementation.
  417. # They should be changed to allow different rules for different accounts.
  418. if ($amount >= 0) {
  419. Math::BigFloat->round_mode('+inf');
  420. }
  421. else {
  422. Math::BigFloat->round_mode('-inf');
  423. }
  424. if ($places >= 0) {
  425. $amount = Math::BigFloat->new($amount)->ffround( -$places );
  426. }
  427. else {
  428. $amount = Math::BigFloat->new($amount)->ffround( -( $places - 1 ) );
  429. }
  430. $amount->precision(undef);
  431. return $amount;
  432. }
  433. sub call_procedure {
  434. my $self = shift @_;
  435. my %args = @_;
  436. my $procname = $args{procname};
  437. my @call_args;
  438. @call_args = @{ $args{args} } if defined $args{args};
  439. my $order_by = $args{order_by};
  440. my $argstr = "";
  441. my @results;
  442. for ( 1 .. scalar @call_args ) {
  443. $argstr .= "?, ";
  444. }
  445. $argstr =~ s/\, $//;
  446. my $query = "SELECT * FROM $procname()";
  447. if ($order_by){
  448. $query .= " ORDER BY $order_by";
  449. }
  450. $query =~ s/\(\)/($argstr)/;
  451. my $sth = $self->{dbh}->prepare($query);
  452. if (scalar @call_args){
  453. $sth->execute(@call_args);
  454. } else {
  455. $sth->execute();
  456. }
  457. my @types = @{$sth->{TYPE}};
  458. my @names = @{$sth->{NAME_lc}};
  459. while ( my $ref = $sth->fetchrow_hashref('NAME_lc') ) {
  460. for (0 .. $#names){
  461. if ($types[$_] == 3){
  462. $ref->{$names[$_]} = Math::BigFloat->new($ref->{$names[$_]});
  463. }
  464. }
  465. push @results, $ref;
  466. }
  467. @results;
  468. }
  469. # Keeping this here due to common requirements
  470. sub is_allowed_role {
  471. my $self = shift @_;
  472. my %args = @_;
  473. my @roles = @{$args{allowed_roles}};
  474. for my $role (@roles){
  475. if (scalar(grep /^$role$/, $self->{_roles})){
  476. return 1;
  477. }
  478. }
  479. return 1; # TODO change to 0 when the role system is implmented
  480. }
  481. # This should probably be moved to User too...
  482. sub date_to_number {
  483. #based on SQL-Ledger's Form::datetonum
  484. my $self = shift @_;
  485. my %args = @_;
  486. my $myconfig = $args{user};
  487. my $date = $args{date};
  488. my ( $yy, $mm, $dd );
  489. if ( $date && $date =~ /\D/ ) {
  490. if ( $myconfig->{dateformat} =~ /^yy/ ) {
  491. ( $yy, $mm, $dd ) = split /\D/, $date;
  492. }
  493. elsif ( $myconfig->{dateformat} =~ /^mm/ ) {
  494. ( $mm, $dd, $yy ) = split /\D/, $date;
  495. }
  496. elsif ( $myconfig->{dateformat} =~ /^dd/ ) {
  497. ( $dd, $mm, $yy ) = split /\D/, $date;
  498. }
  499. $dd *= 1;
  500. $mm *= 1;
  501. $yy += 2000 if length $yy == 2;
  502. $dd = substr( "0$dd", -2 );
  503. $mm = substr( "0$mm", -2 );
  504. $date = "$yy$mm$dd";
  505. }
  506. $date;
  507. }
  508. # To be replaced with a generic interface to an Error class
  509. sub error {
  510. my ( $self, $msg ) = @_;
  511. if ( $ENV{GATEWAY_INTERFACE} ) {
  512. $self->{msg} = $msg;
  513. $self->{format} = "html";
  514. delete $self->{pre};
  515. print qq|Content-Type: text/html; charset=utf-8\n\n|;
  516. print "<head></head>";
  517. print
  518. qq|<body><h2 class="error">Error!</h2> <p><b>$self->{msg}</b></body>|;
  519. exit;
  520. }
  521. else {
  522. if ( $ENV{error_function} ) {
  523. &{ $ENV{error_function} }($msg);
  524. }
  525. die "Error: $msg\n";
  526. }
  527. }
  528. # Database routines used throughout
  529. sub _db_init {
  530. my $self = shift @_;
  531. my %args = @_;
  532. my $myconfig = $self->{_user};
  533. my $dbh = DBI->connect(
  534. $myconfig->{dbconnect}, $myconfig->{dbuser},
  535. $myconfig->{dbpasswd}, { AutoCommit => 0 }
  536. ) or $self->dberror;
  537. $dbh->{pg_server_prepare} = 0;
  538. $dbh->{pg_enable_utf8} = 1;
  539. if ( $myconfig->{dboptions} ) {
  540. $dbh->do( $myconfig->{dboptions} );
  541. }
  542. $self->{dbh} = $dbh;
  543. my $query = "SELECT t.extends,
  544. coalesce (t.table_name, 'custom_' || extends)
  545. || ':' || f.field_name as field_def
  546. FROM custom_table_catalog t
  547. JOIN custom_field_catalog f USING (table_id)";
  548. my $sth = $self->{dbh}->prepare($query);
  549. $sth->execute;
  550. my $ref;
  551. while ( $ref = $sth->fetchrow_hashref('NAME_lc') ) {
  552. push @{ $self->{custom_db_fields}{ $ref->{extends} } },
  553. $ref->{field_def};
  554. }
  555. }
  556. sub redo_rows {
  557. my $self = shift @_;
  558. my %args = @_;
  559. my @flds = @{ $args{fields} };
  560. my $count = $args{count};
  561. my $index = ( $args{index} ) ? $args{index} : 'runningnumber';
  562. my @rows;
  563. my $i; # incriment counter use only
  564. for $i ( 1 .. $count ) {
  565. my $temphash = { _inc => $i };
  566. for my $fld (@flds) {
  567. $temphash->{$fld} = $self->{ "$fld" . "_$i" };
  568. }
  569. push @rows, $temphash;
  570. }
  571. $i = 1;
  572. for my $row ( sort { $a->{index} <=> $b->{index} } @rows ) {
  573. for my $fld (@flds) {
  574. $self->{ "$fld" . "_$i" } = $row->{$fld};
  575. }
  576. ++$i;
  577. }
  578. }
  579. sub merge {
  580. my ( $self, $src ) = @_;
  581. for my $arg ( $self, $src ) {
  582. shift;
  583. }
  584. my %args = @_;
  585. my @keys;
  586. if (defined $args{keys}){
  587. @keys = @{ $args{keys} };
  588. }
  589. my $index = $args{index};
  590. if ( !scalar @keys ) {
  591. @keys = keys %{$src};
  592. }
  593. for my $arg ( @keys ) {
  594. my $dst_arg;
  595. if ($index) {
  596. $dst_arg = $arg . "_$index";
  597. }
  598. else {
  599. $dst_arg = $arg;
  600. }
  601. $self->{$dst_arg} = $src->{$arg};
  602. }
  603. }
  604. 1;