Bug - 5511: Added new system preference: SessionRestrictionByIP
[koha.git] / C4 / Context.pm
blob54b59b592189a83bd17d19902333be3bf977b8ab
1 package C4::Context;
2 # Copyright 2002 Katipo Communications
4 # This file is part of Koha.
6 # Koha is free software; you can redistribute it and/or modify it under the
7 # terms of the GNU General Public License as published by the Free Software
8 # Foundation; either version 2 of the License, or (at your option) any later
9 # version.
11 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
12 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
13 # A PARTICULAR PURPOSE. See the GNU General Public License for more details.
15 # You should have received a copy of the GNU General Public License along
16 # with Koha; if not, write to the Free Software Foundation, Inc.,
17 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
19 use strict;
20 use warnings;
21 use vars qw($VERSION $AUTOLOAD $context @context_stack $servers $memcached $ismemcached);
22 BEGIN {
23 if ($ENV{'HTTP_USER_AGENT'}) {
24 require CGI::Carp;
25 # FIXME for future reference, CGI::Carp doc says
26 # "Note that fatalsToBrowser does not work with mod_perl version 2.0 and higher."
27 import CGI::Carp qw(fatalsToBrowser);
28 sub handle_errors {
29 my $msg = shift;
30 my $debug_level;
31 eval {C4::Context->dbh();};
32 if ($@){
33 $debug_level = 1;
35 else {
36 $debug_level = C4::Context->preference("DebugLevel");
39 print q(<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
40 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
41 <html lang="en" xml:lang="en" xmlns="http://www.w3.org/1999/xhtml">
42 <head><title>Koha Error</title></head>
43 <body>
45 if ($debug_level eq "2"){
46 # debug 2 , print extra info too.
47 my %versions = get_versions();
49 # a little example table with various version info";
50 print "
51 <h1>Koha error</h1>
52 <p>The following fatal error has occurred:</p>
53 <pre><code>$msg</code></pre>
54 <table>
55 <tr><th>Apache</th><td> $versions{apacheVersion}</td></tr>
56 <tr><th>Koha</th><td> $versions{kohaVersion}</td></tr>
57 <tr><th>Koha DB</th><td> $versions{kohaDbVersion}</td></tr>
58 <tr><th>MySQL</th><td> $versions{mysqlVersion}</td></tr>
59 <tr><th>OS</th><td> $versions{osVersion}</td></tr>
60 <tr><th>Perl</th><td> $versions{perlVersion}</td></tr>
61 </table>";
63 } elsif ($debug_level eq "1"){
64 print "
65 <h1>Koha error</h1>
66 <p>The following fatal error has occurred:</p>
67 <pre><code>$msg</code></pre>";
68 } else {
69 print "<p>production mode - trapped fatal error</p>";
71 print "</body></html>";
73 #CGI::Carp::set_message(\&handle_errors);
74 ## give a stack backtrace if KOHA_BACKTRACES is set
75 ## can't rely on DebugLevel for this, as we're not yet connected
76 if ($ENV{KOHA_BACKTRACES}) {
77 $main::SIG{__DIE__} = \&CGI::Carp::confess;
79 } # else there is no browser to send fatals to!
81 # Check if there are memcached servers set
82 $servers = $ENV{'MEMCACHED_SERVERS'};
83 if ($servers) {
84 # Load required libraries and create the memcached object
85 require Cache::Memcached;
86 $memcached = Cache::Memcached->new({
87 servers => [ $servers ],
88 debug => 0,
89 compress_threshold => 10_000,
90 expire_time => 600,
91 namespace => $ENV{'MEMCACHED_NAMESPACE'} || 'koha'
92 });
93 # Verify memcached available (set a variable and test the output)
94 $ismemcached = $memcached->set('ismemcached','1');
97 $VERSION = '3.07.00.049';
100 use DBI;
101 use Encode;
102 use ZOOM;
103 use XML::Simple;
104 use C4::Boolean;
105 use C4::Debug;
106 use POSIX ();
107 use DateTime::TimeZone;
108 use Module::Load::Conditional qw(can_load);
109 use Carp;
111 =head1 NAME
113 C4::Context - Maintain and manipulate the context of a Koha script
115 =head1 SYNOPSIS
117 use C4::Context;
119 use C4::Context("/path/to/koha-conf.xml");
121 $config_value = C4::Context->config("config_variable");
123 $koha_preference = C4::Context->preference("preference");
125 $db_handle = C4::Context->dbh;
127 $Zconn = C4::Context->Zconn;
129 $stopwordhash = C4::Context->stopwords;
131 =head1 DESCRIPTION
133 When a Koha script runs, it makes use of a certain number of things:
134 configuration settings in F</etc/koha/koha-conf.xml>, a connection to the Koha
135 databases, and so forth. These things make up the I<context> in which
136 the script runs.
138 This module takes care of setting up the context for a script:
139 figuring out which configuration file to load, and loading it, opening
140 a connection to the right database, and so forth.
142 Most scripts will only use one context. They can simply have
144 use C4::Context;
146 at the top.
148 Other scripts may need to use several contexts. For instance, if a
149 library has two databases, one for a certain collection, and the other
150 for everything else, it might be necessary for a script to use two
151 different contexts to search both databases. Such scripts should use
152 the C<&set_context> and C<&restore_context> functions, below.
154 By default, C4::Context reads the configuration from
155 F</etc/koha/koha-conf.xml>. This may be overridden by setting the C<$KOHA_CONF>
156 environment variable to the pathname of a configuration file to use.
158 =head1 METHODS
160 =cut
163 # In addition to what is said in the POD above, a Context object is a
164 # reference-to-hash with the following fields:
166 # config
167 # A reference-to-hash whose keys and values are the
168 # configuration variables and values specified in the config
169 # file (/etc/koha/koha-conf.xml).
170 # dbh
171 # A handle to the appropriate database for this context.
172 # dbh_stack
173 # Used by &set_dbh and &restore_dbh to hold other database
174 # handles for this context.
175 # Zconn
176 # A connection object for the Zebra server
178 # Koha's main configuration file koha-conf.xml
179 # is searched for according to this priority list:
181 # 1. Path supplied via use C4::Context '/path/to/koha-conf.xml'
182 # 2. Path supplied in KOHA_CONF environment variable.
183 # 3. Path supplied in INSTALLED_CONFIG_FNAME, as long
184 # as value has changed from its default of
185 # '__KOHA_CONF_DIR__/koha-conf.xml', as happens
186 # when Koha is installed in 'standard' or 'single'
187 # mode.
188 # 4. Path supplied in CONFIG_FNAME.
190 # The first entry that refers to a readable file is used.
192 use constant CONFIG_FNAME => "/etc/koha/koha-conf.xml";
193 # Default config file, if none is specified
195 my $INSTALLED_CONFIG_FNAME = '__KOHA_CONF_DIR__/koha-conf.xml';
196 # path to config file set by installer
197 # __KOHA_CONF_DIR__ is set by rewrite-confg.PL
198 # when Koha is installed in 'standard' or 'single'
199 # mode. If Koha was installed in 'dev' mode,
200 # __KOHA_CONF_DIR__ is *not* rewritten; instead
201 # developers should set the KOHA_CONF environment variable
203 $context = undef; # Initially, no context is set
204 @context_stack = (); # Initially, no saved contexts
207 =head2 KOHAVERSION
209 returns the kohaversion stored in kohaversion.pl file
211 =cut
213 sub KOHAVERSION {
214 my $cgidir = C4::Context->intranetdir;
216 # Apparently the GIT code does not run out of a CGI-BIN subdirectory
217 # but distribution code does? (Stan, 1jan08)
218 if(-d $cgidir . "/cgi-bin"){
219 my $cgidir .= "/cgi-bin";
222 do $cgidir."/kohaversion.pl" || die "NO $cgidir/kohaversion.pl";
223 return kohaversion();
226 =head2 final_linear_version
228 Returns the version number of the final update to run in updatedatabase.pl.
229 This number is equal to the version in kohaversion.pl
231 =cut
233 sub final_linear_version {
234 return KOHAVERSION;
237 =head2 read_config_file
239 Reads the specified Koha config file.
241 Returns an object containing the configuration variables. The object's
242 structure is a bit complex to the uninitiated ... take a look at the
243 koha-conf.xml file as well as the XML::Simple documentation for details. Or,
244 here are a few examples that may give you what you need:
246 The simple elements nested within the <config> element:
248 my $pass = $koha->{'config'}->{'pass'};
250 The <listen> elements:
252 my $listen = $koha->{'listen'}->{'biblioserver'}->{'content'};
254 The elements nested within the <server> element:
256 my $ccl2rpn = $koha->{'server'}->{'biblioserver'}->{'cql2rpn'};
258 Returns undef in case of error.
260 =cut
262 sub read_config_file { # Pass argument naming config file to read
263 my $koha = XMLin(shift, keyattr => ['id'], forcearray => ['listen', 'server', 'serverinfo'], suppressempty => '');
265 if ($ismemcached) {
266 $memcached->set('kohaconf',$koha);
269 return $koha; # Return value: ref-to-hash holding the configuration
272 =head2 ismemcached
274 Returns the value of the $ismemcached variable (0/1)
276 =cut
278 sub ismemcached {
279 return $ismemcached;
282 =head2 memcached
284 If $ismemcached is true, returns the $memcache variable.
285 Returns undef otherwise
287 =cut
289 sub memcached {
290 if ($ismemcached) {
291 return $memcached;
292 } else {
293 return;
297 =head2 db_scheme2dbi
299 my $dbd_driver_name = C4::Context::db_schema2dbi($scheme);
301 This routines translates a database type to part of the name
302 of the appropriate DBD driver to use when establishing a new
303 database connection. It recognizes 'mysql' and 'Pg'; if any
304 other scheme is supplied it defaults to 'mysql'.
306 =cut
308 sub db_scheme2dbi {
309 my $scheme = shift // '';
310 return $scheme eq 'Pg' ? $scheme : 'mysql';
313 sub import {
314 # Create the default context ($C4::Context::Context)
315 # the first time the module is called
316 # (a config file can be optionaly passed)
318 # default context allready exists?
319 return if $context;
321 # no ? so load it!
322 my ($pkg,$config_file) = @_ ;
323 my $new_ctx = __PACKAGE__->new($config_file);
324 return unless $new_ctx;
326 # if successfully loaded, use it by default
327 $new_ctx->set_context;
331 =head2 new
333 $context = new C4::Context;
334 $context = new C4::Context("/path/to/koha-conf.xml");
336 Allocates a new context. Initializes the context from the specified
337 file, which defaults to either the file given by the C<$KOHA_CONF>
338 environment variable, or F</etc/koha/koha-conf.xml>.
340 It saves the koha-conf.xml values in the declared memcached server(s)
341 if currently available and uses those values until them expire and
342 re-reads them.
344 C<&new> does not set this context as the new default context; for
345 that, use C<&set_context>.
347 =cut
350 # Revision History:
351 # 2004-08-10 A. Tarallo: Added check if the conf file is not empty
352 sub new {
353 my $class = shift;
354 my $conf_fname = shift; # Config file to load
355 my $self = {};
357 # check that the specified config file exists and is not empty
358 undef $conf_fname unless
359 (defined $conf_fname && -s $conf_fname);
360 # Figure out a good config file to load if none was specified.
361 if (!defined($conf_fname))
363 # If the $KOHA_CONF environment variable is set, use
364 # that. Otherwise, use the built-in default.
365 if (exists $ENV{"KOHA_CONF"} and $ENV{'KOHA_CONF'} and -s $ENV{"KOHA_CONF"}) {
366 $conf_fname = $ENV{"KOHA_CONF"};
367 } elsif ($INSTALLED_CONFIG_FNAME !~ /__KOHA_CONF_DIR/ and -s $INSTALLED_CONFIG_FNAME) {
368 # NOTE: be careful -- don't change __KOHA_CONF_DIR in the above
369 # regex to anything else -- don't want installer to rewrite it
370 $conf_fname = $INSTALLED_CONFIG_FNAME;
371 } elsif (-s CONFIG_FNAME) {
372 $conf_fname = CONFIG_FNAME;
373 } else {
374 warn "unable to locate Koha configuration file koha-conf.xml";
375 return;
379 if ($ismemcached) {
380 # retreive from memcached
381 $self = $memcached->get('kohaconf');
382 if (not defined $self) {
383 # not in memcached yet
384 $self = read_config_file($conf_fname);
386 } else {
387 # non-memcached env, read from file
388 $self = read_config_file($conf_fname);
391 $self->{"config_file"} = $conf_fname;
392 warn "read_config_file($conf_fname) returned undef" if !defined($self->{"config"});
393 return if !defined($self->{"config"});
395 $self->{"dbh"} = undef; # Database handle
396 $self->{"Zconn"} = undef; # Zebra Connections
397 $self->{"stopwords"} = undef; # stopwords list
398 $self->{"marcfromkohafield"} = undef; # the hash with relations between koha table fields and MARC field/subfield
399 $self->{"userenv"} = undef; # User env
400 $self->{"activeuser"} = undef; # current active user
401 $self->{"shelves"} = undef;
402 $self->{tz} = undef; # local timezone object
404 bless $self, $class;
405 $self->{db_driver} = db_scheme2dbi($self->config('db_scheme')); # cache database driver
406 return $self;
409 =head2 set_context
411 $context = new C4::Context;
412 $context->set_context();
414 set_context C4::Context $context;
417 restore_context C4::Context;
419 In some cases, it might be necessary for a script to use multiple
420 contexts. C<&set_context> saves the current context on a stack, then
421 sets the context to C<$context>, which will be used in future
422 operations. To restore the previous context, use C<&restore_context>.
424 =cut
427 sub set_context
429 my $self = shift;
430 my $new_context; # The context to set
432 # Figure out whether this is a class or instance method call.
434 # We're going to make the assumption that control got here
435 # through valid means, i.e., that the caller used an instance
436 # or class method call, and that control got here through the
437 # usual inheritance mechanisms. The caller can, of course,
438 # break this assumption by playing silly buggers, but that's
439 # harder to do than doing it properly, and harder to check
440 # for.
441 if (ref($self) eq "")
443 # Class method. The new context is the next argument.
444 $new_context = shift;
445 } else {
446 # Instance method. The new context is $self.
447 $new_context = $self;
450 # Save the old context, if any, on the stack
451 push @context_stack, $context if defined($context);
453 # Set the new context
454 $context = $new_context;
457 =head2 restore_context
459 &restore_context;
461 Restores the context set by C<&set_context>.
463 =cut
466 sub restore_context
468 my $self = shift;
470 if ($#context_stack < 0)
472 # Stack underflow.
473 die "Context stack underflow";
476 # Pop the old context and set it.
477 $context = pop @context_stack;
479 # FIXME - Should this return something, like maybe the context
480 # that was current when this was called?
483 =head2 config
485 $value = C4::Context->config("config_variable");
487 $value = C4::Context->config_variable;
489 Returns the value of a variable specified in the configuration file
490 from which the current context was created.
492 The second form is more compact, but of course may conflict with
493 method names. If there is a configuration variable called "new", then
494 C<C4::Config-E<gt>new> will not return it.
496 =cut
498 sub _common_config {
499 my $var = shift;
500 my $term = shift;
501 return if !defined($context->{$term});
502 # Presumably $self->{$term} might be
503 # undefined if the config file given to &new
504 # didn't exist, and the caller didn't bother
505 # to check the return value.
507 # Return the value of the requested config variable
508 return $context->{$term}->{$var};
511 sub config {
512 return _common_config($_[1],'config');
514 sub zebraconfig {
515 return _common_config($_[1],'server');
517 sub ModZebrations {
518 return _common_config($_[1],'serverinfo');
521 =head2 preference
523 $sys_preference = C4::Context->preference('some_variable');
525 Looks up the value of the given system preference in the
526 systempreferences table of the Koha database, and returns it. If the
527 variable is not set or does not exist, undef is returned.
529 In case of an error, this may return 0.
531 Note: It is impossible to tell the difference between system
532 preferences which do not exist, and those whose values are set to NULL
533 with this method.
535 =cut
537 # FIXME: running this under mod_perl will require a means of
538 # flushing the caching mechanism.
540 my %sysprefs;
541 my $use_syspref_cache = 1;
543 sub preference {
544 my $self = shift;
545 my $var = shift; # The system preference to return
547 if ($use_syspref_cache && exists $sysprefs{lc $var}) {
548 return $sysprefs{lc $var};
551 my $dbh = C4::Context->dbh or return 0;
553 my $value;
554 if ( defined $ENV{"OVERRIDE_SYSPREF_$var"} ) {
555 $value = $ENV{"OVERRIDE_SYSPREF_$var"};
556 } else {
557 # Look up systempreferences.variable==$var
558 my $sql = q{
559 SELECT value
560 FROM systempreferences
561 WHERE variable = ?
562 LIMIT 1
564 $value = $dbh->selectrow_array( $sql, {}, lc $var );
567 $sysprefs{lc $var} = $value;
568 return $value;
571 sub boolean_preference {
572 my $self = shift;
573 my $var = shift; # The system preference to return
574 my $it = preference($self, $var);
575 return defined($it)? C4::Boolean::true_p($it): undef;
578 =head2 enable_syspref_cache
580 C4::Context->enable_syspref_cache();
582 Enable the in-memory syspref cache used by C4::Context. This is the
583 default behavior.
585 =cut
587 sub enable_syspref_cache {
588 my ($self) = @_;
589 $use_syspref_cache = 1;
592 =head2 disable_syspref_cache
594 C4::Context->disable_syspref_cache();
596 Disable the in-memory syspref cache used by C4::Context. This should be
597 used with Plack and other persistent environments.
599 =cut
601 sub disable_syspref_cache {
602 my ($self) = @_;
603 $use_syspref_cache = 0;
604 $self->clear_syspref_cache();
607 =head2 clear_syspref_cache
609 C4::Context->clear_syspref_cache();
611 cleans the internal cache of sysprefs. Please call this method if
612 you update the systempreferences table. Otherwise, your new changes
613 will not be seen by this process.
615 =cut
617 sub clear_syspref_cache {
618 %sysprefs = ();
621 =head2 set_preference
623 C4::Context->set_preference( $variable, $value );
625 This updates a preference's value both in the systempreferences table and in
626 the sysprefs cache.
628 =cut
630 sub set_preference {
631 my $self = shift;
632 my $var = lc(shift);
633 my $value = shift;
635 my $dbh = C4::Context->dbh or return 0;
637 my $type = $dbh->selectrow_array( "SELECT type FROM systempreferences WHERE variable = ?", {}, $var );
639 $value = 0 if ( $type && $type eq 'YesNo' && $value eq '' );
641 my $sth = $dbh->prepare( "
642 INSERT INTO systempreferences
643 ( variable, value )
644 VALUES( ?, ? )
645 ON DUPLICATE KEY UPDATE value = VALUES(value)
646 " );
648 if($sth->execute( $var, $value )) {
649 $sysprefs{$var} = $value;
651 $sth->finish;
654 # AUTOLOAD
655 # This implements C4::Config->foo, and simply returns
656 # C4::Context->config("foo"), as described in the documentation for
657 # &config, above.
659 # FIXME - Perhaps this should be extended to check &config first, and
660 # then &preference if that fails. OTOH, AUTOLOAD could lead to crappy
661 # code, so it'd probably be best to delete it altogether so as not to
662 # encourage people to use it.
663 sub AUTOLOAD
665 my $self = shift;
667 $AUTOLOAD =~ s/.*:://; # Chop off the package name,
668 # leaving only the function name.
669 return $self->config($AUTOLOAD);
672 =head2 Zconn
674 $Zconn = C4::Context->Zconn
676 Returns a connection to the Zebra database
678 C<$self>
680 C<$server> one of the servers defined in the koha-conf.xml file
682 C<$async> whether this is a asynchronous connection
684 =cut
686 sub Zconn {
687 my ($self, $server, $async ) = @_;
688 my $cache_key = join ('::', (map { $_ // '' } ($server, $async )));
689 if ( (!defined($ENV{GATEWAY_INTERFACE})) && defined($context->{"Zconn"}->{$cache_key}) && (0 == $context->{"Zconn"}->{$cache_key}->errcode()) ) {
690 # if we are running the script from the commandline, lets try to use the caching
691 return $context->{"Zconn"}->{$cache_key};
693 $context->{"Zconn"}->{$cache_key}->destroy() if defined($context->{"Zconn"}->{$cache_key}); #destroy old connection before making a new one
694 $context->{"Zconn"}->{$cache_key} = &_new_Zconn( $server, $async );
695 return $context->{"Zconn"}->{$cache_key};
698 =head2 _new_Zconn
700 $context->{"Zconn"} = &_new_Zconn($server,$async);
702 Internal function. Creates a new database connection from the data given in the current context and returns it.
704 C<$server> one of the servers defined in the koha-conf.xml file
706 C<$async> whether this is a asynchronous connection
708 C<$auth> whether this connection has rw access (1) or just r access (0 or NULL)
710 =cut
712 sub _new_Zconn {
713 my ( $server, $async ) = @_;
715 my $tried=0; # first attempt
716 my $Zconn; # connection object
717 my $elementSetName;
718 my $index_mode;
719 my $syntax;
721 $server //= "biblioserver";
723 if ( $server eq 'biblioserver' ) {
724 $index_mode = $context->{'config'}->{'zebra_bib_index_mode'} // 'dom';
725 } elsif ( $server eq 'authorityserver' ) {
726 $index_mode = $context->{'config'}->{'zebra_auth_index_mode'} // 'dom';
729 if ( $index_mode eq 'grs1' ) {
730 $elementSetName = 'F';
731 $syntax = ( $context->preference("marcflavour") eq 'UNIMARC' )
732 ? 'unimarc'
733 : 'usmarc';
735 } else { # $index_mode eq 'dom'
736 $syntax = 'xml';
737 $elementSetName = 'marcxml';
740 my $host = $context->{'listen'}->{$server}->{'content'};
741 my $user = $context->{"serverinfo"}->{$server}->{"user"};
742 my $password = $context->{"serverinfo"}->{$server}->{"password"};
743 eval {
744 # set options
745 my $o = new ZOOM::Options();
746 $o->option(user => $user) if $user && $password;
747 $o->option(password => $password) if $user && $password;
748 $o->option(async => 1) if $async;
749 $o->option(cqlfile=> $context->{"server"}->{$server}->{"cql2rpn"});
750 $o->option(cclfile=> $context->{"serverinfo"}->{$server}->{"ccl2rpn"});
751 $o->option(preferredRecordSyntax => $syntax);
752 $o->option(elementSetName => $elementSetName) if $elementSetName;
753 $o->option(databaseName => $context->{"config"}->{$server}||"biblios");
755 # create a new connection object
756 $Zconn= create ZOOM::Connection($o);
758 # forge to server
759 $Zconn->connect($host, 0);
761 # check for errors and warn
762 if ($Zconn->errcode() !=0) {
763 warn "something wrong with the connection: ". $Zconn->errmsg();
766 return $Zconn;
769 # _new_dbh
770 # Internal helper function (not a method!). This creates a new
771 # database connection from the data given in the current context, and
772 # returns it.
773 sub _new_dbh
776 ## $context
777 ## correct name for db_scheme
778 my $db_driver = $context->{db_driver};
780 my $db_name = $context->config("database");
781 my $db_host = $context->config("hostname");
782 my $db_port = $context->config("port") || '';
783 my $db_user = $context->config("user");
784 my $db_passwd = $context->config("pass");
785 # MJR added or die here, as we can't work without dbh
786 my $dbh = DBI->connect("DBI:$db_driver:dbname=$db_name;host=$db_host;port=$db_port",
787 $db_user, $db_passwd, {'RaiseError' => $ENV{DEBUG}?1:0 }) or die $DBI::errstr;
789 # Check for the existence of a systempreference table; if we don't have this, we don't
790 # have a valid database and should not set RaiseError in order to allow the installer
791 # to run; installer will not run otherwise since we raise all db errors
793 eval {
794 local $dbh->{PrintError} = 0;
795 local $dbh->{RaiseError} = 1;
796 $dbh->do(qq{SELECT * FROM systempreferences WHERE 1 = 0 });
799 if ($@) {
800 $dbh->{RaiseError} = 0;
803 if ( $db_driver eq 'mysql' ) {
804 $dbh->{mysql_auto_reconnect} = 1;
807 my $tz = $ENV{TZ};
808 if ( $db_driver eq 'mysql' ) {
809 # Koha 3.0 is utf-8, so force utf8 communication between mySQL and koha, whatever the mysql default config.
810 # this is better than modifying my.cnf (and forcing all communications to be in utf8)
811 $dbh->{'mysql_enable_utf8'}=1; #enable
812 $dbh->do("set NAMES 'utf8'");
813 ($tz) and $dbh->do(qq(SET time_zone = "$tz"));
815 elsif ( $db_driver eq 'Pg' ) {
816 $dbh->do( "set client_encoding = 'UTF8';" );
817 ($tz) and $dbh->do(qq(SET TIME ZONE = "$tz"));
819 return $dbh;
822 =head2 dbh
824 $dbh = C4::Context->dbh;
826 Returns a database handle connected to the Koha database for the
827 current context. If no connection has yet been made, this method
828 creates one, and connects to the database.
830 This database handle is cached for future use: if you call
831 C<C4::Context-E<gt>dbh> twice, you will get the same handle both
832 times. If you need a second database handle, use C<&new_dbh> and
833 possibly C<&set_dbh>.
835 =cut
838 sub dbh
840 my $self = shift;
841 my $params = shift;
842 my $sth;
844 unless ( $params->{new} ) {
845 if ( defined($context->{db_driver}) && $context->{db_driver} eq 'mysql' && $context->{"dbh"} ) {
846 return $context->{"dbh"};
847 } elsif ( defined($context->{"dbh"}) && $context->{"dbh"}->ping() ) {
848 return $context->{"dbh"};
852 # No database handle or it died . Create one.
853 $context->{"dbh"} = &_new_dbh();
855 return $context->{"dbh"};
858 =head2 new_dbh
860 $dbh = C4::Context->new_dbh;
862 Creates a new connection to the Koha database for the current context,
863 and returns the database handle (a C<DBI::db> object).
865 The handle is not saved anywhere: this method is strictly a
866 convenience function; the point is that it knows which database to
867 connect to so that the caller doesn't have to know.
869 =cut
872 sub new_dbh
874 my $self = shift;
876 return &_new_dbh();
879 =head2 set_dbh
881 $my_dbh = C4::Connect->new_dbh;
882 C4::Connect->set_dbh($my_dbh);
884 C4::Connect->restore_dbh;
886 C<&set_dbh> and C<&restore_dbh> work in a manner analogous to
887 C<&set_context> and C<&restore_context>.
889 C<&set_dbh> saves the current database handle on a stack, then sets
890 the current database handle to C<$my_dbh>.
892 C<$my_dbh> is assumed to be a good database handle.
894 =cut
897 sub set_dbh
899 my $self = shift;
900 my $new_dbh = shift;
902 # Save the current database handle on the handle stack.
903 # We assume that $new_dbh is all good: if the caller wants to
904 # screw himself by passing an invalid handle, that's fine by
905 # us.
906 push @{$context->{"dbh_stack"}}, $context->{"dbh"};
907 $context->{"dbh"} = $new_dbh;
910 =head2 restore_dbh
912 C4::Context->restore_dbh;
914 Restores the database handle saved by an earlier call to
915 C<C4::Context-E<gt>set_dbh>.
917 =cut
920 sub restore_dbh
922 my $self = shift;
924 if ($#{$context->{"dbh_stack"}} < 0)
926 # Stack underflow
927 die "DBH stack underflow";
930 # Pop the old database handle and set it.
931 $context->{"dbh"} = pop @{$context->{"dbh_stack"}};
933 # FIXME - If it is determined that restore_context should
934 # return something, then this function should, too.
937 =head2 queryparser
939 $queryparser = C4::Context->queryparser
941 Returns a handle to an initialized Koha::QueryParser::Driver::PQF object.
943 =cut
945 sub queryparser {
946 my $self = shift;
947 unless (defined $context->{"queryparser"}) {
948 $context->{"queryparser"} = &_new_queryparser();
951 return
952 defined( $context->{"queryparser"} )
953 ? $context->{"queryparser"}->new
954 : undef;
957 =head2 _new_queryparser
959 Internal helper function to create a new QueryParser object. QueryParser
960 is loaded dynamically so as to keep the lack of the QueryParser library from
961 getting in anyone's way.
963 =cut
965 sub _new_queryparser {
966 my $qpmodules = {
967 'OpenILS::QueryParser' => undef,
968 'Koha::QueryParser::Driver::PQF' => undef
970 if ( can_load( 'modules' => $qpmodules ) ) {
971 my $QParser = Koha::QueryParser::Driver::PQF->new();
972 my $config_file = $context->config('queryparser_config');
973 $config_file ||= '/etc/koha/searchengine/queryparser.yaml';
974 if ( $QParser->load_config($config_file) ) {
975 # Set 'keyword' as the default search class
976 $QParser->default_search_class('keyword');
977 # TODO: allow indexes to be configured in the database
978 return $QParser;
981 return;
984 =head2 marcfromkohafield
986 $dbh = C4::Context->marcfromkohafield;
988 Returns a hash with marcfromkohafield.
990 This hash is cached for future use: if you call
991 C<C4::Context-E<gt>marcfromkohafield> twice, you will get the same hash without real DB access
993 =cut
996 sub marcfromkohafield
998 my $retval = {};
1000 # If the hash already exists, return it.
1001 return $context->{"marcfromkohafield"} if defined($context->{"marcfromkohafield"});
1003 # No hash. Create one.
1004 $context->{"marcfromkohafield"} = &_new_marcfromkohafield();
1006 return $context->{"marcfromkohafield"};
1009 # _new_marcfromkohafield
1010 # Internal helper function (not a method!). This creates a new
1011 # hash with stopwords
1012 sub _new_marcfromkohafield
1014 my $dbh = C4::Context->dbh;
1015 my $marcfromkohafield;
1016 my $sth = $dbh->prepare("select frameworkcode,kohafield,tagfield,tagsubfield from marc_subfield_structure where kohafield > ''");
1017 $sth->execute;
1018 while (my ($frameworkcode,$kohafield,$tagfield,$tagsubfield) = $sth->fetchrow) {
1019 my $retval = {};
1020 $marcfromkohafield->{$frameworkcode}->{$kohafield} = [$tagfield,$tagsubfield];
1022 return $marcfromkohafield;
1025 =head2 stopwords
1027 $dbh = C4::Context->stopwords;
1029 Returns a hash with stopwords.
1031 This hash is cached for future use: if you call
1032 C<C4::Context-E<gt>stopwords> twice, you will get the same hash without real DB access
1034 =cut
1037 sub stopwords
1039 my $retval = {};
1041 # If the hash already exists, return it.
1042 return $context->{"stopwords"} if defined($context->{"stopwords"});
1044 # No hash. Create one.
1045 $context->{"stopwords"} = &_new_stopwords();
1047 return $context->{"stopwords"};
1050 # _new_stopwords
1051 # Internal helper function (not a method!). This creates a new
1052 # hash with stopwords
1053 sub _new_stopwords
1055 my $dbh = C4::Context->dbh;
1056 my $stopwordlist;
1057 my $sth = $dbh->prepare("select word from stopwords");
1058 $sth->execute;
1059 while (my $stopword = $sth->fetchrow_array) {
1060 $stopwordlist->{$stopword} = uc($stopword);
1062 $stopwordlist->{A} = "A" unless $stopwordlist;
1063 return $stopwordlist;
1066 =head2 userenv
1068 C4::Context->userenv;
1070 Retrieves a hash for user environment variables.
1072 This hash shall be cached for future use: if you call
1073 C<C4::Context-E<gt>userenv> twice, you will get the same hash without real DB access
1075 =cut
1078 sub userenv {
1079 my $var = $context->{"activeuser"};
1080 if (defined $var and defined $context->{"userenv"}->{$var}) {
1081 return $context->{"userenv"}->{$var};
1082 } else {
1083 return;
1087 =head2 set_userenv
1089 C4::Context->set_userenv($usernum, $userid, $usercnum, $userfirstname,
1090 $usersurname, $userbranch, $userflags, $emailaddress, $branchprinter,
1091 $persona);
1093 Establish a hash of user environment variables.
1095 set_userenv is called in Auth.pm
1097 =cut
1100 sub set_userenv {
1101 my ($usernum, $userid, $usercnum, $userfirstname, $usersurname, $userbranch, $branchname, $userflags, $emailaddress, $branchprinter, $persona, $shibboleth)=
1102 map { Encode::is_utf8( $_ ) ? $_ : Encode::decode('UTF-8', $_) } # CGI::Session doesn't handle utf-8, so we decode it here
1104 my $var=$context->{"activeuser"} || '';
1105 my $cell = {
1106 "number" => $usernum,
1107 "id" => $userid,
1108 "cardnumber" => $usercnum,
1109 "firstname" => $userfirstname,
1110 "surname" => $usersurname,
1111 #possibly a law problem
1112 "branch" => $userbranch,
1113 "branchname" => $branchname,
1114 "flags" => $userflags,
1115 "emailaddress" => $emailaddress,
1116 "branchprinter" => $branchprinter,
1117 "persona" => $persona,
1118 "shibboleth" => $shibboleth,
1120 $context->{userenv}->{$var} = $cell;
1121 return $cell;
1124 sub set_shelves_userenv {
1125 my ($type, $shelves) = @_ or return;
1126 my $activeuser = $context->{activeuser} or return;
1127 $context->{userenv}->{$activeuser}->{barshelves} = $shelves if $type eq 'bar';
1128 $context->{userenv}->{$activeuser}->{pubshelves} = $shelves if $type eq 'pub';
1129 $context->{userenv}->{$activeuser}->{totshelves} = $shelves if $type eq 'tot';
1132 sub get_shelves_userenv {
1133 my $active;
1134 unless ($active = $context->{userenv}->{$context->{activeuser}}) {
1135 $debug and warn "get_shelves_userenv cannot retrieve context->{userenv}->{context->{activeuser}}";
1136 return;
1138 my $totshelves = $active->{totshelves} or undef;
1139 my $pubshelves = $active->{pubshelves} or undef;
1140 my $barshelves = $active->{barshelves} or undef;
1141 return ($totshelves, $pubshelves, $barshelves);
1144 =head2 _new_userenv
1146 C4::Context->_new_userenv($session); # FIXME: This calling style is wrong for what looks like an _internal function
1148 Builds a hash for user environment variables.
1150 This hash shall be cached for future use: if you call
1151 C<C4::Context-E<gt>userenv> twice, you will get the same hash without real DB access
1153 _new_userenv is called in Auth.pm
1155 =cut
1158 sub _new_userenv
1160 shift; # Useless except it compensates for bad calling style
1161 my ($sessionID)= @_;
1162 $context->{"activeuser"}=$sessionID;
1165 =head2 _unset_userenv
1167 C4::Context->_unset_userenv;
1169 Destroys the hash for activeuser user environment variables.
1171 =cut
1175 sub _unset_userenv
1177 my ($sessionID)= @_;
1178 undef $context->{"activeuser"} if ($context->{"activeuser"} eq $sessionID);
1182 =head2 get_versions
1184 C4::Context->get_versions
1186 Gets various version info, for core Koha packages, Currently called from carp handle_errors() sub, to send to browser if 'DebugLevel' syspref is set to '2'.
1188 =cut
1192 # A little example sub to show more debugging info for CGI::Carp
1193 sub get_versions {
1194 my %versions;
1195 $versions{kohaVersion} = KOHAVERSION();
1196 $versions{kohaDbVersion} = C4::Context->preference('version');
1197 $versions{osVersion} = join(" ", POSIX::uname());
1198 $versions{perlVersion} = $];
1200 no warnings qw(exec); # suppress warnings if unable to find a program in $PATH
1201 $versions{mysqlVersion} = `mysql -V`;
1202 $versions{apacheVersion} = `httpd -v`;
1203 $versions{apacheVersion} = `httpd2 -v` unless $versions{apacheVersion} ;
1204 $versions{apacheVersion} = `apache2 -v` unless $versions{apacheVersion} ;
1205 $versions{apacheVersion} = `/usr/sbin/apache2 -v` unless $versions{apacheVersion} ;
1207 return %versions;
1211 =head2 tz
1213 C4::Context->tz
1215 Returns a DateTime::TimeZone object for the system timezone
1217 =cut
1219 sub tz {
1220 my $self = shift;
1221 if (!defined $context->{tz}) {
1222 $context->{tz} = DateTime::TimeZone->new(name => 'local');
1224 return $context->{tz};
1228 =head2 IsSuperLibrarian
1230 C4::Context->IsSuperlibrarian();
1232 =cut
1234 sub IsSuperLibrarian {
1235 my $userenv = C4::Context->userenv;
1237 unless ( $userenv and exists $userenv->{flags} ) {
1238 # If we reach this without a user environment,
1239 # assume that we're running from a command-line script,
1240 # and act as a superlibrarian.
1241 carp("C4::Context->userenv not defined!");
1242 return 1;
1245 return ($userenv->{flags}//0) % 2;
1248 =head2 interface
1250 Sets the current interface for later retrieval in any Perl module
1252 C4::Context->interface('opac');
1253 C4::Context->interface('intranet');
1254 my $interface = C4::Context->interface;
1256 =cut
1258 sub interface {
1259 my ($class, $interface) = @_;
1261 if (defined $interface) {
1262 $interface = lc $interface;
1263 if ($interface eq 'opac' || $interface eq 'intranet') {
1264 $context->{interface} = $interface;
1265 } else {
1266 warn "invalid interface : '$interface'";
1270 return $context->{interface} // 'opac';
1274 __END__
1276 =head1 ENVIRONMENT
1278 =head2 C<KOHA_CONF>
1280 Specifies the configuration file to read.
1282 =head1 SEE ALSO
1284 XML::Simple
1286 =head1 AUTHORS
1288 Andrew Arensburger <arensb at ooblick dot com>
1290 Joshua Ferraro <jmf at liblime dot com>