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