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
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.
21 use vars
qw($VERSION $AUTOLOAD $context @context_stack $servers $memcached $ismemcached);
23 if ($ENV{'HTTP_USER_AGENT'}) {
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);
31 eval {C4
::Context
->dbh();};
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
>
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";
52 <p>The following fatal error has occurred:</p>
53 <pre><code>$msg</code></pre>
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>
63 } elsif ($debug_level eq "1"){
66 <p>The following fatal error has occurred:</p>
67 <pre><code>$msg</code></pre>";
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'};
84 # Load required libraries and create the memcached object
85 require Cache
::Memcached
;
86 $memcached = Cache
::Memcached
->new({
87 servers
=> [ $servers ],
89 compress_threshold
=> 10_000
,
91 namespace
=> $ENV{'MEMCACHED_NAMESPACE'} || 'koha'
93 # Verify memcached available (set a variable and test the output)
94 $ismemcached = $memcached->set('ismemcached','1');
97 $VERSION = '3.07.00.049';
107 use DateTime
::TimeZone
;
108 use Module
::Load
::Conditional
qw(can_load);
113 C4::Context - Maintain and manipulate the context of a Koha script
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;
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
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
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.
163 # In addition to what is said in the POD above, a Context object is a
164 # reference-to-hash with the following fields:
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).
171 # A handle to the appropriate database for this context.
173 # Used by &set_dbh and &restore_dbh to hold other database
174 # handles for this context.
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'
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
209 returns the kohaversion stored in kohaversion.pl file
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
233 sub final_linear_version
{
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.
262 sub read_config_file
{ # Pass argument naming config file to read
263 my $koha = XMLin
(shift, keyattr
=> ['id'], forcearray
=> ['listen', 'server', 'serverinfo'], suppressempty
=> '');
266 $memcached->set('kohaconf',$koha);
269 return $koha; # Return value: ref-to-hash holding the configuration
274 Returns the value of the $ismemcached variable (0/1)
284 If $ismemcached is true, returns the $memcache variable.
285 Returns undef otherwise
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'.
309 my $scheme = shift // '';
310 return $scheme eq 'Pg' ?
$scheme : 'mysql';
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?
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;
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
344 C<&new> does not set this context as the new default context; for
345 that, use C<&set_context>.
351 # 2004-08-10 A. Tarallo: Added check if the conf file is not empty
354 my $conf_fname = shift; # Config file to load
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
;
374 warn "unable to locate Koha configuration file koha-conf.xml";
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);
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
405 $self->{db_driver
} = db_scheme2dbi
($self->config('db_scheme')); # cache database driver
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>.
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
441 if (ref($self) eq "")
443 # Class method. The new context is the next argument.
444 $new_context = shift;
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
461 Restores the context set by C<&set_context>.
470 if ($#context_stack < 0)
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?
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.
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};
512 return _common_config
($_[1],'config');
515 return _common_config
($_[1],'server');
518 return _common_config
($_[1],'serverinfo');
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
537 # FIXME: running this under mod_perl will require a means of
538 # flushing the caching mechanism.
541 my $use_syspref_cache = 1;
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;
554 if ( defined $ENV{"OVERRIDE_SYSPREF_$var"} ) {
555 $value = $ENV{"OVERRIDE_SYSPREF_$var"};
557 # Look up systempreferences.variable==$var
560 FROM systempreferences
564 $value = $dbh->selectrow_array( $sql, {}, lc $var );
567 $sysprefs{lc $var} = $value;
571 sub boolean_preference
{
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
587 sub enable_syspref_cache
{
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.
601 sub disable_syspref_cache
{
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.
617 sub clear_syspref_cache
{
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
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
645 ON DUPLICATE KEY UPDATE value = VALUES(value)
648 if($sth->execute( $var, $value )) {
649 $sysprefs{$var} = $value;
655 # This implements C4::Config->foo, and simply returns
656 # C4::Context->config("foo"), as described in the documentation for
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.
667 $AUTOLOAD =~ s/.*:://; # Chop off the package name,
668 # leaving only the function name.
669 return $self->config($AUTOLOAD);
674 $Zconn = C4::Context->Zconn
676 Returns a connection to the Zebra database
680 C<$server> one of the servers defined in the koha-conf.xml file
682 C<$async> whether this is a asynchronous connection
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};
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)
713 my ( $server, $async ) = @_;
715 my $tried=0; # first attempt
716 my $Zconn; # connection object
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' )
735 } else { # $index_mode eq 'dom'
737 $elementSetName = 'marcxml';
740 my $host = $context->{'listen'}->{$server}->{'content'};
741 my $user = $context->{"serverinfo"}->{$server}->{"user"};
742 my $password = $context->{"serverinfo"}->{$server}->{"password"};
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);
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();
770 # Internal helper function (not a method!). This creates a new
771 # database connection from the data given in the current context, and
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
794 local $dbh->{PrintError
} = 0;
795 local $dbh->{RaiseError
} = 1;
796 $dbh->do(qq{SELECT
* FROM systempreferences WHERE
1 = 0 });
800 $dbh->{RaiseError
} = 0;
803 if ( $db_driver eq 'mysql' ) {
804 $dbh->{mysql_auto_reconnect
} = 1;
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"));
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>.
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"};
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.
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.
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
906 push @
{$context->{"dbh_stack"}}, $context->{"dbh"};
907 $context->{"dbh"} = $new_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>.
924 if ($#{$context->{"dbh_stack"}} < 0)
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.
939 $queryparser = C4::Context->queryparser
941 Returns a handle to an initialized Koha::QueryParser::Driver::PQF object.
947 unless (defined $context->{"queryparser"}) {
948 $context->{"queryparser"} = &_new_queryparser
();
952 defined( $context->{"queryparser"} )
953 ?
$context->{"queryparser"}->new
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.
965 sub _new_queryparser
{
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
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
996 sub marcfromkohafield
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 > ''");
1018 while (my ($frameworkcode,$kohafield,$tagfield,$tagsubfield) = $sth->fetchrow) {
1020 $marcfromkohafield->{$frameworkcode}->{$kohafield} = [$tagfield,$tagsubfield];
1022 return $marcfromkohafield;
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
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"};
1051 # Internal helper function (not a method!). This creates a new
1052 # hash with stopwords
1055 my $dbh = C4
::Context
->dbh;
1057 my $sth = $dbh->prepare("select word from stopwords");
1059 while (my $stopword = $sth->fetchrow_array) {
1060 $stopwordlist->{$stopword} = uc($stopword);
1062 $stopwordlist->{A
} = "A" unless $stopwordlist;
1063 return $stopwordlist;
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
1079 my $var = $context->{"activeuser"};
1080 if (defined $var and defined $context->{"userenv"}->{$var}) {
1081 return $context->{"userenv"}->{$var};
1089 C4::Context->set_userenv($usernum, $userid, $usercnum, $userfirstname,
1090 $usersurname, $userbranch, $userflags, $emailaddress, $branchprinter,
1093 Establish a hash of user environment variables.
1095 set_userenv is called in Auth.pm
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"} || '';
1106 "number" => $usernum,
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;
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
{
1134 unless ($active = $context->{userenv
}->{$context->{activeuser
}}) {
1135 $debug and warn "get_shelves_userenv cannot retrieve context->{userenv}->{context->{activeuser}}";
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);
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
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.
1177 my ($sessionID)= @_;
1178 undef $context->{"activeuser"} if ($context->{"activeuser"} eq $sessionID);
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'.
1192 # A little example sub to show more debugging info for CGI::Carp
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
} ;
1215 Returns a DateTime::TimeZone object for the system timezone
1221 if (!defined $context->{tz
}) {
1222 $context->{tz
} = DateTime
::TimeZone
->new(name
=> 'local');
1224 return $context->{tz
};
1228 =head2 IsSuperLibrarian
1230 C4::Context->IsSuperlibrarian();
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!");
1245 return ($userenv->{flags
}//0) % 2;
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;
1259 my ($class, $interface) = @_;
1261 if (defined $interface) {
1262 $interface = lc $interface;
1263 if ($interface eq 'opac' || $interface eq 'intranet') {
1264 $context->{interface
} = $interface;
1266 warn "invalid interface : '$interface'";
1270 return $context->{interface
} // 'opac';
1280 Specifies the configuration file to read.
1288 Andrew Arensburger <arensb at ooblick dot com>
1290 Joshua Ferraro <jmf at liblime dot com>