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