1 # Copyright 2002 Katipo Communications
3 # This file is part of Koha.
5 # Koha is free software; you can redistribute it and/or modify it under the
6 # terms of the GNU General Public License as published by the Free Software
7 # Foundation; either version 2 of the License, or (at your option) any later
10 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
11 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
12 # A PARTICULAR PURPOSE. See the GNU General Public License for more details.
14 # You should have received a copy of the GNU General Public License along with
15 # Koha; if not, write to the Free Software Foundation, Inc., 59 Temple Place,
16 # Suite 330, Boston, MA 02111-1307 USA
20 # 2004-08-11 A. Tarallo: Added the function db_escheme2dbi, tested my bugfixes,
21 # further details about them in the code.
22 # 2004-11-23 A. Tarallo, E. Silva: Bugfixes for running in a mod_perl environment.
23 # Clean up of previous bugfixes, better documentation of what was done.
30 use vars qw($VERSION $AUTOLOAD),
34 $VERSION = do { my @v = '$Revision$' =~ /\d+/g;
35 shift(@v) . "." . join("_", map {sprintf "%03d", $_ } @v); };
39 C4::Context - Maintain and manipulate the context of a Koha script
45 use C4::Context("/path/to/koha.conf");
47 $config_value = C4::Context->config("config_variable");
48 $db_handle = C4::Context->dbh;
49 $stopwordhash = C4::Context->stopwords;
53 When a Koha script runs, it makes use of a certain number of things:
54 configuration settings in F</etc/koha.conf>, a connection to the Koha
55 database, and so forth. These things make up the I<context> in which
58 This module takes care of setting up the context for a script:
59 figuring out which configuration file to load, and loading it, opening
60 a connection to the right database, and so forth.
62 Most scripts will only use one context. They can simply have
68 Other scripts may need to use several contexts. For instance, if a
69 library has two databases, one for a certain collection, and the other
70 for everything else, it might be necessary for a script to use two
71 different contexts to search both databases. Such scripts should use
72 the C<&set_context> and C<&restore_context> functions, below.
74 By default, C4::Context reads the configuration from
75 F</etc/koha.conf>. This may be overridden by setting the C<$KOHA_CONF>
76 environment variable to the pathname of a configuration file to use.
84 # In addition to what is said in the POD above, a Context object is a
85 # reference-to-hash with the following fields:
88 # A reference-to-hash whose keys and values are the
89 # configuration variables and values specified in the config
90 # file (/etc/koha.conf).
92 # A handle to the appropriate database for this context.
94 # Used by &set_dbh and &restore_dbh to hold other database
95 # handles for this context.
97 use constant CONFIG_FNAME => "/etc/koha.conf";
98 # Default config file, if none is specified
100 $context = undef; # Initially, no context is set
101 @context_stack = (); # Initially, no saved contexts
104 # Reads the specified Koha config file. Returns a reference-to-hash
105 # whose keys are the configuration variables, and whose values are the
106 # configuration values (duh).
107 # Returns undef in case of error.
110 # 2004-08-10 A. Tarallo: Added code that checks if a variable is already
111 # assigned and prints a message, otherwise create a new entry in the hash to
113 # Also added code that complaints if finds a line that isn't a variable
114 # assignmet and skips the line.
115 # Added a quick hack that makes the translation between the db_schema
116 # and the DBI driver for that schema.
120 my $fname = shift; # Config file to read
121 my $retval = {}; # Return value: ref-to-hash holding the
124 open (CONF, $fname) or return undef;
128 my $var; # Variable name
129 my $value; # Variable value
132 s/#.*//; # Strip comments
133 next if /^\s*$/; # Ignore blank lines
135 # Look for a line of the form
137 if (!/^\s*(\w+)\s*=\s*(.*?)\s*$/)
140 "$_ isn't a variable assignment, skipping it";
144 # Found a variable assignment
145 if ( exists $retval->{$1} )
147 print STDERR "$var was already defined, ignoring\n";
149 # Quick hack for allowing databases name in full text
150 if ( $1 eq "db_scheme" )
152 $value = db_scheme2dbi($2);
156 $retval->{$1} = $value;
165 # Translates the full text name of a database into de appropiate dbi name
172 # FIXME - Should have other databases.
173 if (/mysql/i) { return("mysql"); }
174 if (/Postgres|Pg|PostgresSQL/) { return("Pg"); }
175 if (/oracle/i) { return("Oracle"); }
177 return undef; # Just in case
183 my $conf_fname = shift; # Config file name
186 # Create a new context from the given config file name, if
187 # any, then set it as the current context.
188 $context = new C4::Context($conf_fname);
189 return undef if !defined($context);
190 $context->set_context;
195 $context = new C4::Context;
196 $context = new C4::Context("/path/to/koha.conf");
198 Allocates a new context. Initializes the context from the specified
199 file, which defaults to either the file given by the C<$KOHA_CONF>
200 environment variable, or F</etc/koha.conf>.
202 C<&new> does not set this context as the new default context; for
203 that, use C<&set_context>.
208 # 2004-08-10 A. Tarallo: Added check if the conf file is not empty
212 my $conf_fname = shift; # Config file to load
215 # check that the specified config file exists and is not empty
216 undef $conf_fname unless
217 (defined $conf_fname && -e $conf_fname && -s $conf_fname);
218 # Figure out a good config file to load if none was specified.
219 if (!defined($conf_fname))
221 # If the $KOHA_CONF environment variable is set, use
222 # that. Otherwise, use the built-in default.
223 $conf_fname = $ENV{"KOHA_CONF"} || CONFIG_FNAME;
225 $self->{"config_file"} = $conf_fname;
227 # Load the desired config file.
228 $self->{"config"} = &read_config_file($conf_fname);
229 warn "read_config_file($conf_fname) returned undef" if !defined($self->{"config"});
230 return undef if !defined($self->{"config"});
232 $self->{"dbh"} = undef; # Database handle
233 $self->{"stopwords"} = undef; # stopwords list
234 $self->{"marcfromkohafield"} = undef; # the hash with relations between koha table fields and MARC field/subfield
235 $self->{"userenv"} = undef; # User env
236 $self->{"activeuser"} = undef; # current active user
244 $context = new C4::Context;
245 $context->set_context();
247 set_context C4::Context $context;
250 restore_context C4::Context;
252 In some cases, it might be necessary for a script to use multiple
253 contexts. C<&set_context> saves the current context on a stack, then
254 sets the context to C<$context>, which will be used in future
255 operations. To restore the previous context, use C<&restore_context>.
262 my $new_context; # The context to set
264 # Figure out whether this is a class or instance method call.
266 # We're going to make the assumption that control got here
267 # through valid means, i.e., that the caller used an instance
268 # or class method call, and that control got here through the
269 # usual inheritance mechanisms. The caller can, of course,
270 # break this assumption by playing silly buggers, but that's
271 # harder to do than doing it properly, and harder to check
273 if (ref($self) eq "")
275 # Class method. The new context is the next argument.
276 $new_context = shift;
278 # Instance method. The new context is $self.
279 $new_context = $self;
282 # Save the old context, if any, on the stack
283 push @context_stack, $context if defined($context);
285 # Set the new context
286 $context = $new_context;
289 =item restore_context
293 Restores the context set by C<&set_context>.
301 if ($#context_stack < 0)
304 die "Context stack underflow";
307 # Pop the old context and set it.
308 $context = pop @context_stack;
310 # FIXME - Should this return something, like maybe the context
311 # that was current when this was called?
316 $value = C4::Context->config("config_variable");
318 $value = C4::Context->config_variable;
320 Returns the value of a variable specified in the configuration file
321 from which the current context was created.
323 The second form is more compact, but of course may conflict with
324 method names. If there is a configuration variable called "new", then
325 C<C4::Config-E<gt>new> will not return it.
332 my $var = shift; # The config variable to return
334 return undef if !defined($context->{"config"});
335 # Presumably $self->{config} might be
336 # undefined if the config file given to &new
337 # didn't exist, and the caller didn't bother
338 # to check the return value.
340 # Return the value of the requested config variable
341 return $context->{"config"}{$var};
346 $sys_preference = C4::Context->preference("some_variable");
348 Looks up the value of the given system preference in the
349 systempreferences table of the Koha database, and returns it. If the
350 variable is not set, or in case of error, returns the undefined value.
354 # FIXME - The preferences aren't likely to change over the lifetime of
355 # the script (and things might break if they did change), so perhaps
356 # this function should cache the results it finds.
360 my $var = shift; # The system preference to return
361 my $retval; # Return value
362 my $dbh = C4::Context->dbh; # Database handle
363 my $sth; # Database query handle
365 # Look up systempreferences.variable==$var
366 $retval = $dbh->selectrow_array(<<EOT);
368 FROM systempreferences
369 WHERE variable='$var'
375 sub boolean_preference ($) {
377 my $var = shift; # The system preference to return
378 my $it = preference($self, $var);
379 return defined($it)? C4::Boolean::true_p($it): undef;
383 # This implements C4::Config->foo, and simply returns
384 # C4::Context->config("foo"), as described in the documentation for
387 # FIXME - Perhaps this should be extended to check &config first, and
388 # then &preference if that fails. OTOH, AUTOLOAD could lead to crappy
389 # code, so it'd probably be best to delete it altogether so as not to
390 # encourage people to use it.
395 $AUTOLOAD =~ s/.*:://; # Chop off the package name,
396 # leaving only the function name.
397 return $self->config($AUTOLOAD);
401 # Internal helper function (not a method!). This creates a new
402 # database connection from the data given in the current context, and
406 my $db_driver = $context->{"config"}{"db_scheme"} || "mysql";
407 my $db_name = $context->{"config"}{"database"};
408 my $db_host = $context->{"config"}{"hostname"};
409 my $db_user = $context->{"config"}{"user"};
410 my $db_passwd = $context->{"config"}{"pass"};
411 return DBI->connect("DBI:$db_driver:$db_name:$db_host",
412 $db_user, $db_passwd);
417 $dbh = C4::Context->dbh;
419 Returns a database handle connected to the Koha database for the
420 current context. If no connection has yet been made, this method
421 creates one, and connects to the database.
423 This database handle is cached for future use: if you call
424 C<C4::Context-E<gt>dbh> twice, you will get the same handle both
425 times. If you need a second database handle, use C<&new_dbh> and
426 possibly C<&set_dbh>.
435 if (defined($context->{"dbh"})) {
436 $sth=$context->{"dbh"}->prepare("select 1");
437 return $context->{"dbh"} if (defined($sth->execute));
440 # No database handle or it died . Create one.
441 $context->{"dbh"} = &_new_dbh();
443 return $context->{"dbh"};
448 $dbh = C4::Context->new_dbh;
450 Creates a new connection to the Koha database for the current context,
451 and returns the database handle (a C<DBI::db> object).
453 The handle is not saved anywhere: this method is strictly a
454 convenience function; the point is that it knows which database to
455 connect to so that the caller doesn't have to know.
468 $my_dbh = C4::Connect->new_dbh;
469 C4::Connect->set_dbh($my_dbh);
471 C4::Connect->restore_dbh;
473 C<&set_dbh> and C<&restore_dbh> work in a manner analogous to
474 C<&set_context> and C<&restore_context>.
476 C<&set_dbh> saves the current database handle on a stack, then sets
477 the current database handle to C<$my_dbh>.
479 C<$my_dbh> is assumed to be a good database handle.
488 # Save the current database handle on the handle stack.
489 # We assume that $new_dbh is all good: if the caller wants to
490 # screw himself by passing an invalid handle, that's fine by
492 push @{$context->{"dbh_stack"}}, $context->{"dbh"};
493 $context->{"dbh"} = $new_dbh;
498 C4::Context->restore_dbh;
500 Restores the database handle saved by an earlier call to
501 C<C4::Context-E<gt>set_dbh>.
509 if ($#{$context->{"dbh_stack"}} < 0)
512 die "DBH stack underflow";
515 # Pop the old database handle and set it.
516 $context->{"dbh"} = pop @{$context->{"dbh_stack"}};
518 # FIXME - If it is determined that restore_context should
519 # return something, then this function should, too.
522 =item marcfromkohafield
524 $dbh = C4::Context->marcfromkohafield;
526 Returns a hash with marcfromkohafield.
528 This hash is cached for future use: if you call
529 C<C4::Context-E<gt>marcfromkohafield> twice, you will get the same hash without real DB access
533 sub marcfromkohafield
537 # If the hash already exists, return it.
538 return $context->{"marcfromkohafield"} if defined($context->{"marcfromkohafield"});
540 # No hash. Create one.
541 $context->{"marcfromkohafield"} = &_new_marcfromkohafield();
543 return $context->{"marcfromkohafield"};
546 # _new_marcfromkohafield
547 # Internal helper function (not a method!). This creates a new
548 # hash with stopwords
549 sub _new_marcfromkohafield
551 my $dbh = C4::Context->dbh;
552 my $marcfromkohafield;
553 my $sth = $dbh->prepare("select frameworkcode,kohafield,tagfield,tagsubfield from marc_subfield_structure where kohafield > ''");
555 while (my ($frameworkcode,$kohafield,$tagfield,$tagsubfield) = $sth->fetchrow) {
557 $marcfromkohafield->{$frameworkcode}->{$kohafield} = [$tagfield,$tagsubfield];
559 return $marcfromkohafield;
564 $dbh = C4::Context->stopwords;
566 Returns a hash with stopwords.
568 This hash is cached for future use: if you call
569 C<C4::Context-E<gt>stopwords> twice, you will get the same hash without real DB access
577 # If the hash already exists, return it.
578 return $context->{"stopwords"} if defined($context->{"stopwords"});
580 # No hash. Create one.
581 $context->{"stopwords"} = &_new_stopwords();
583 return $context->{"stopwords"};
587 # Internal helper function (not a method!). This creates a new
588 # hash with stopwords
591 my $dbh = C4::Context->dbh;
593 my $sth = $dbh->prepare("select word from stopwords");
595 while (my $stopword = $sth->fetchrow_array) {
597 $stopwordlist->{$stopword} = uc($stopword);
599 $stopwordlist->{A} = "A" unless $stopwordlist;
600 return $stopwordlist;
605 %userenv = C4::Context->userenv;
607 Returns a hash with userenvironment variables.
609 This hash is cached for future use: if you call
610 C<C4::Context-E<gt>userenv> twice, you will get the same hash without real DB access
612 Returns Null if userenv is not set.
613 userenv is set in _new_userenv, called in Auth.pm
620 C4::Context->userenv;
622 Builds a hash for user environment variables.
624 This hash shall be cached for future use: if you call
625 C<C4::Context-E<gt>userenv> twice, you will get the same hash without real DB access
627 set_userenv is called in Auth.pm
633 my $var = $context->{"activeuser"};
634 return $context->{"userenv"}->{$var} if (defined $context->{"userenv"}->{$var});
639 C4::Context->set_userenv;
641 Builds a hash for user environment variables.
643 This hash shall be cached for future use: if you call
644 C<C4::Context-E<gt>userenv> twice, you will get the same hash without real DB access
646 set_userenv is called in Auth.pm
651 my ($usernum, $userid, $usercnum, $userfirstname, $usersurname, $userbranch, $userflags)= @_;
652 my $var=$context->{"activeuser"};
654 "number" => $usernum,
656 "cardnumber" => $usercnum,
657 "firstname" => $userfirstname,
658 "surname" => $usersurname,
659 "branch" => $userbranch,
660 "flags" => $userflags
662 $context->{userenv}->{$var} = $cell;
668 C4::Context->_new_userenv($session);
670 Builds a hash for user environment variables.
672 This hash shall be cached for future use: if you call
673 C<C4::Context-E<gt>userenv> twice, you will get the same hash without real DB access
675 _new_userenv is called in Auth.pm
683 $context->{"activeuser"}=$sessionID;
688 C4::Context->_unset_userenv;
690 Destroys the hash for activeuser user environment variables.
698 # undef $context->{$sessionID};
699 undef $context->{"activeuser"} if ($context->{"activeuser"} eq $sessionID);
700 # $context->{"activeuser"}--;
715 Specifies the configuration file to read.
725 Andrew Arensburger <arensb at ooblick dot com>