3 # Copyright 2002 Katipo Communications
5 # This file is part of Koha.
7 # Koha is free software; you can redistribute it and/or modify it
8 # under the terms of the GNU General Public License as published by
9 # the Free Software Foundation; either version 3 of the License, or
10 # (at your option) any later version.
12 # Koha is distributed in the hope that it will be useful, but
13 # WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 # GNU General Public License for more details.
17 # You should have received a copy of the GNU General Public License
18 # along with Koha; if not, see <http://www.gnu.org/licenses>.
22 use vars qw($AUTOLOAD $context @context_stack);
24 if ( $ENV{'HTTP_USER_AGENT'} ) { # Only hit when plack is not enabled
26 # Redefine multi_param if cgi version is < 4.08
27 # Remove the "CGI::param called in list context" warning in this case
28 require CGI; # Can't check version without the require.
29 if ( !defined($CGI::VERSION) || $CGI::VERSION < 4.08 ) {
30 no warnings 'redefine';
31 *CGI::multi_param = \&CGI::param;
32 use warnings 'redefine';
33 $CGI::LIST_CONTEXT_WARN = 0;
39 use DateTime::TimeZone;
47 use Koha::Config::SysPref;
48 use Koha::Config::SysPrefs;
54 C4::Context - Maintain and manipulate the context of a Koha script
60 use C4::Context("/path/to/koha-conf.xml");
62 $config_value = C4::Context->config("config_variable");
64 $koha_preference = C4::Context->preference("preference");
66 $db_handle = C4::Context->dbh;
68 $Zconn = C4::Context->Zconn;
72 When a Koha script runs, it makes use of a certain number of things:
73 configuration settings in F</etc/koha/koha-conf.xml>, a connection to the Koha
74 databases, and so forth. These things make up the I<context> in which
77 This module takes care of setting up the context for a script:
78 figuring out which configuration file to load, and loading it, opening
79 a connection to the right database, and so forth.
81 Most scripts will only use one context. They can simply have
87 Other scripts may need to use several contexts. For instance, if a
88 library has two databases, one for a certain collection, and the other
89 for everything else, it might be necessary for a script to use two
90 different contexts to search both databases. Such scripts should use
91 the C<&set_context> and C<&restore_context> functions, below.
93 By default, C4::Context reads the configuration from
94 F</etc/koha/koha-conf.xml>. This may be overridden by setting the C<$KOHA_CONF>
95 environment variable to the pathname of a configuration file to use.
102 # In addition to what is said in the POD above, a Context object is a
103 # reference-to-hash with the following fields:
106 # A reference-to-hash whose keys and values are the
107 # configuration variables and values specified in the config
108 # file (/etc/koha/koha-conf.xml).
110 # A handle to the appropriate database for this context.
112 # Used by &set_dbh and &restore_dbh to hold other database
113 # handles for this context.
115 # A connection object for the Zebra server
117 $context = undef; # Initially, no context is set
118 @context_stack = (); # Initially, no saved contexts
121 # Create the default context ($C4::Context::Context)
122 # the first time the module is called
123 # (a config file can be optionaly passed)
125 # default context already exists?
129 my ($pkg,$config_file) = @_ ;
130 my $new_ctx = __PACKAGE__->new($config_file);
131 return unless $new_ctx;
133 # if successfully loaded, use it by default
134 $new_ctx->set_context;
140 $context = C4::Context->new;
141 $context = C4::Context->new("/path/to/koha-conf.xml");
143 Allocates a new context. Initializes the context from the specified
144 file, which defaults to either the file given by the C<$KOHA_CONF>
145 environment variable, or F</etc/koha/koha-conf.xml>.
147 It saves the koha-conf.xml values in the declared memcached server(s)
148 if currently available and uses those values until them expire and
151 C<&new> does not set this context as the new default context; for
152 that, use C<&set_context>.
158 # 2004-08-10 A. Tarallo: Added check if the conf file is not empty
161 my $conf_fname = shift; # Config file to load
163 # check that the specified config file exists and is not empty
164 undef $conf_fname unless
165 (defined $conf_fname && -s $conf_fname);
166 # Figure out a good config file to load if none was specified.
167 unless ( defined $conf_fname ) {
168 $conf_fname = Koha::Config->guess_koha_conf;
169 unless ( $conf_fname ) {
170 warn "unable to locate Koha configuration file koha-conf.xml";
176 $self->{config} = Koha::Config->get_instance($conf_fname);
177 unless ( defined $self->{config} ) {
178 warn "The config file ($conf_fname) has not been parsed correctly";
182 $self->{"Zconn"} = undef; # Zebra Connections
183 $self->{"userenv"} = undef; # User env
184 $self->{"activeuser"} = undef; # current active user
185 $self->{"shelves"} = undef;
186 $self->{tz} = undef; # local timezone object
194 $context = new C4::Context;
195 $context->set_context();
197 set_context C4::Context $context;
200 restore_context C4::Context;
202 In some cases, it might be necessary for a script to use multiple
203 contexts. C<&set_context> saves the current context on a stack, then
204 sets the context to C<$context>, which will be used in future
205 operations. To restore the previous context, use C<&restore_context>.
213 my $new_context; # The context to set
215 # Figure out whether this is a class or instance method call.
217 # We're going to make the assumption that control got here
218 # through valid means, i.e., that the caller used an instance
219 # or class method call, and that control got here through the
220 # usual inheritance mechanisms. The caller can, of course,
221 # break this assumption by playing silly buggers, but that's
222 # harder to do than doing it properly, and harder to check
224 if (ref($self) eq "")
226 # Class method. The new context is the next argument.
227 $new_context = shift;
229 # Instance method. The new context is $self.
230 $new_context = $self;
233 # Save the old context, if any, on the stack
234 push @context_stack, $context if defined($context);
236 # Set the new context
237 $context = $new_context;
240 =head2 restore_context
244 Restores the context set by C<&set_context>.
253 if ($#context_stack < 0)
256 die "Context stack underflow";
259 # Pop the old context and set it.
260 $context = pop @context_stack;
262 # FIXME - Should this return something, like maybe the context
263 # that was current when this was called?
268 $value = C4::Context->config("config_variable");
270 Returns the value of a variable specified in the configuration file
271 from which the current context was created.
276 my ($var, $term) = @_;
278 return unless defined $context and defined $context->{config};
280 return $context->{config}->get($var, $term);
284 return _common_config($_[1],'config');
287 return _common_config($_[1],'server');
292 $sys_preference = C4::Context->preference('some_variable');
294 Looks up the value of the given system preference in the
295 systempreferences table of the Koha database, and returns it. If the
296 variable is not set or does not exist, undef is returned.
298 In case of an error, this may return 0.
300 Note: It is impossible to tell the difference between system
301 preferences which do not exist, and those whose values are set to NULL
306 my $use_syspref_cache = 1;
309 my $var = shift; # The system preference to return
311 return Encode::decode_utf8($ENV{"OVERRIDE_SYSPREF_$var"})
312 if defined $ENV{"OVERRIDE_SYSPREF_$var"};
316 if ($use_syspref_cache) {
317 my $syspref_cache = Koha::Caches->get_instance('syspref');
318 my $cached_var = $syspref_cache->get_from_cache("syspref_$var");
319 return $cached_var if defined $cached_var;
323 eval { $syspref = Koha::Config::SysPrefs->find( lc $var ) };
324 my $value = $syspref ? $syspref->value() : undef;
326 if ( $use_syspref_cache ) {
327 my $syspref_cache = Koha::Caches->get_instance('syspref');
328 $syspref_cache->set_in_cache("syspref_$var", $value);
333 =head2 yaml_preference
335 Retrieves the required system preference value, and converts it
336 from YAML into a Perl data structure. It throws an exception if
337 the value cannot be properly decoded as YAML.
341 sub yaml_preference {
342 my ( $self, $preference ) = @_;
344 my $yaml = eval { YAML::XS::Load( Encode::encode_utf8( $self->preference( $preference ) ) ); };
346 warn "Unable to parse $preference syspref : $@";
353 =head2 enable_syspref_cache
355 C4::Context->enable_syspref_cache();
357 Enable the in-memory syspref cache used by C4::Context. This is the
362 sub enable_syspref_cache {
364 $use_syspref_cache = 1;
365 # We need to clear the cache to have it up-to-date
366 $self->clear_syspref_cache();
369 =head2 disable_syspref_cache
371 C4::Context->disable_syspref_cache();
373 Disable the in-memory syspref cache used by C4::Context. This should be
374 used with Plack and other persistent environments.
378 sub disable_syspref_cache {
380 $use_syspref_cache = 0;
381 $self->clear_syspref_cache();
384 =head2 clear_syspref_cache
386 C4::Context->clear_syspref_cache();
388 cleans the internal cache of sysprefs. Please call this method if
389 you update the systempreferences table. Otherwise, your new changes
390 will not be seen by this process.
394 sub clear_syspref_cache {
395 return unless $use_syspref_cache;
396 my $syspref_cache = Koha::Caches->get_instance('syspref');
397 $syspref_cache->flush_all;
400 =head2 set_preference
402 C4::Context->set_preference( $variable, $value, [ $explanation, $type, $options ] );
404 This updates a preference's value both in the systempreferences table and in
405 the sysprefs cache. If the optional parameters are provided, then the query
406 becomes a create. It won't update the parameters (except value) for an existing
412 my ( $self, $variable, $value, $explanation, $type, $options ) = @_;
414 my $variable_case = $variable;
415 $variable = lc $variable;
417 my $syspref = Koha::Config::SysPrefs->find($variable);
420 : $syspref ? $syspref->type
423 $value = 0 if ( $type && $type eq 'YesNo' && $value eq '' );
425 # force explicit protocol on OPACBaseURL
426 if ( $variable eq 'opacbaseurl' && $value && substr( $value, 0, 4 ) !~ /http/ ) {
427 $value = 'http://' . $value;
432 { ( defined $value ? ( value => $value ) : () ),
433 ( $explanation ? ( explanation => $explanation ) : () ),
434 ( $type ? ( type => $type ) : () ),
435 ( $options ? ( options => $options ) : () ),
439 $syspref = Koha::Config::SysPref->new(
440 { variable => $variable_case,
442 explanation => $explanation || undef,
444 options => $options || undef,
449 if ( $use_syspref_cache ) {
450 my $syspref_cache = Koha::Caches->get_instance('syspref');
451 $syspref_cache->set_in_cache( "syspref_$variable", $value );
457 =head2 delete_preference
459 C4::Context->delete_preference( $variable );
461 This deletes a system preference from the database. Returns a true value on
462 success. Failure means there was an issue with the database, not that there
463 was no syspref of the name.
467 sub delete_preference {
468 my ( $self, $var ) = @_;
470 if ( Koha::Config::SysPrefs->find( $var )->delete ) {
471 if ( $use_syspref_cache ) {
472 my $syspref_cache = Koha::Caches->get_instance('syspref');
473 $syspref_cache->clear_from_cache("syspref_$var");
483 $Zconn = C4::Context->Zconn
485 Returns a connection to the Zebra database
489 C<$server> one of the servers defined in the koha-conf.xml file
491 C<$async> whether this is a asynchronous connection
496 my ($self, $server, $async ) = @_;
497 my $cache_key = join ('::', (map { $_ // '' } ($server, $async )));
498 if ( (!defined($ENV{GATEWAY_INTERFACE})) && defined($context->{"Zconn"}->{$cache_key}) && (0 == $context->{"Zconn"}->{$cache_key}->errcode()) ) {
499 # if we are running the script from the commandline, lets try to use the caching
500 return $context->{"Zconn"}->{$cache_key};
502 $context->{"Zconn"}->{$cache_key}->destroy() if defined($context->{"Zconn"}->{$cache_key}); #destroy old connection before making a new one
503 $context->{"Zconn"}->{$cache_key} = &_new_Zconn( $server, $async );
504 return $context->{"Zconn"}->{$cache_key};
509 $context->{"Zconn"} = &_new_Zconn($server,$async);
511 Internal function. Creates a new database connection from the data given in the current context and returns it.
513 C<$server> one of the servers defined in the koha-conf.xml file
515 C<$async> whether this is a asynchronous connection
517 C<$auth> whether this connection has rw access (1) or just r access (0 or NULL)
522 my ( $server, $async ) = @_;
524 my $tried=0; # first attempt
525 my $Zconn; # connection object
529 $server //= "biblioserver";
532 $elementSetName = 'marcxml';
534 my $host = _common_config($server, 'listen')->{content};
535 my $serverinfo = _common_config($server, 'serverinfo');
536 my $user = $serverinfo->{user};
537 my $password = $serverinfo->{password};
540 my $o = ZOOM::Options->new();
541 $o->option(user => $user) if $user && $password;
542 $o->option(password => $password) if $user && $password;
543 $o->option(async => 1) if $async;
544 $o->option(cqlfile=> _common_config($server, 'server')->{cql2rpn});
545 $o->option(cclfile=> $serverinfo->{ccl2rpn});
546 $o->option(preferredRecordSyntax => $syntax);
547 $o->option(elementSetName => $elementSetName) if $elementSetName;
548 $o->option(databaseName => _common_config($server, 'config') || 'biblios');
550 # create a new connection object
551 $Zconn= create ZOOM::Connection($o);
554 $Zconn->connect($host, 0);
556 # check for errors and warn
557 if ($Zconn->errcode() !=0) {
558 warn "something wrong with the connection: ". $Zconn->errmsg();
565 # Internal helper function (not a method!). This creates a new
566 # database connection from the data given in the current context, and
571 Koha::Database->schema({ new => 1 })->storage->dbh;
576 $dbh = C4::Context->dbh;
578 Returns a database handle connected to the Koha database for the
579 current context. If no connection has yet been made, this method
580 creates one, and connects to the database.
582 This database handle is cached for future use: if you call
583 C<C4::Context-E<gt>dbh> twice, you will get the same handle both
584 times. If you need a second database handle, use C<&new_dbh> and
585 possibly C<&set_dbh>.
595 unless ( $params->{new} ) {
596 return Koha::Database->schema->storage->dbh;
599 return Koha::Database->schema({ new => 1 })->storage->dbh;
604 $dbh = C4::Context->new_dbh;
606 Creates a new connection to the Koha database for the current context,
607 and returns the database handle (a C<DBI::db> object).
609 The handle is not saved anywhere: this method is strictly a
610 convenience function; the point is that it knows which database to
611 connect to so that the caller doesn't have to know.
620 return &dbh({ new => 1 });
625 $my_dbh = C4::Connect->new_dbh;
626 C4::Connect->set_dbh($my_dbh);
628 C4::Connect->restore_dbh;
630 C<&set_dbh> and C<&restore_dbh> work in a manner analogous to
631 C<&set_context> and C<&restore_context>.
633 C<&set_dbh> saves the current database handle on a stack, then sets
634 the current database handle to C<$my_dbh>.
636 C<$my_dbh> is assumed to be a good database handle.
646 # Save the current database handle on the handle stack.
647 # We assume that $new_dbh is all good: if the caller wants to
648 # screw himself by passing an invalid handle, that's fine by
650 push @{$context->{"dbh_stack"}}, $context->{"dbh"};
651 $context->{"dbh"} = $new_dbh;
656 C4::Context->restore_dbh;
658 Restores the database handle saved by an earlier call to
659 C<C4::Context-E<gt>set_dbh>.
668 if ($#{$context->{"dbh_stack"}} < 0)
671 die "DBH stack underflow";
674 # Pop the old database handle and set it.
675 $context->{"dbh"} = pop @{$context->{"dbh_stack"}};
677 # FIXME - If it is determined that restore_context should
678 # return something, then this function should, too.
683 C4::Context->userenv;
685 Retrieves a hash for user environment variables.
687 This hash shall be cached for future use: if you call
688 C<C4::Context-E<gt>userenv> twice, you will get the same hash without real DB access
694 my $var = $context->{"activeuser"};
695 if (defined $var and defined $context->{"userenv"}->{$var}) {
696 return $context->{"userenv"}->{$var};
704 C4::Context->set_userenv($usernum, $userid, $usercnum,
705 $userfirstname, $usersurname,
706 $userbranch, $branchname, $userflags,
707 $emailaddress, $shibboleth
708 $desk_id, $desk_name,
709 $register_id, $register_name);
711 Establish a hash of user environment variables.
713 set_userenv is called in Auth.pm
721 $usernum, $userid, $usercnum, $userfirstname,
722 $usersurname, $userbranch, $branchname, $userflags,
723 $emailaddress, $shibboleth, $desk_id, $desk_name,
724 $register_id, $register_name
727 my $var=$context->{"activeuser"} || '';
729 "number" => $usernum,
731 "cardnumber" => $usercnum,
732 "firstname" => $userfirstname,
733 "surname" => $usersurname,
735 #possibly a law problem
736 "branch" => $userbranch,
737 "branchname" => $branchname,
738 "flags" => $userflags,
739 "emailaddress" => $emailaddress,
740 "shibboleth" => $shibboleth,
741 "desk_id" => $desk_id,
742 "desk_name" => $desk_name,
743 "register_id" => $register_id,
744 "register_name" => $register_name
746 $context->{userenv}->{$var} = $cell;
752 C4::Context->_new_userenv($session); # FIXME: This calling style is wrong for what looks like an _internal function
754 Builds a hash for user environment variables.
756 This hash shall be cached for future use: if you call
757 C<C4::Context-E<gt>userenv> twice, you will get the same hash without real DB access
759 _new_userenv is called in Auth.pm
766 shift; # Useless except it compensates for bad calling style
768 $context->{"activeuser"}=$sessionID;
771 =head2 _unset_userenv
773 C4::Context->_unset_userenv;
775 Destroys the hash for activeuser user environment variables.
784 undef $context->{"activeuser"} if ($context->{"activeuser"} eq $sessionID);
790 C4::Context->get_versions
792 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'.
798 # A little example sub to show more debugging info for CGI::Carp
801 $versions{kohaVersion} = Koha::version();
802 $versions{kohaDbVersion} = C4::Context->preference('version');
803 $versions{osVersion} = join(" ", POSIX::uname());
804 $versions{perlVersion} = $];
806 no warnings qw(exec); # suppress warnings if unable to find a program in $PATH
807 $versions{mysqlVersion} = `mysql -V`;
808 $versions{apacheVersion} = (`apache2ctl -v`)[0];
809 $versions{apacheVersion} = `httpd -v` unless $versions{apacheVersion} ;
810 $versions{apacheVersion} = `httpd2 -v` unless $versions{apacheVersion} ;
811 $versions{apacheVersion} = `apache2 -v` unless $versions{apacheVersion} ;
812 $versions{apacheVersion} = `/usr/sbin/apache2 -v` unless $versions{apacheVersion} ;
821 Returns a DateTime::TimeZone object for the system timezone
827 if (!defined $context->{tz}) {
828 my $timezone = $context->{config}->timezone;
829 $context->{tz} = DateTime::TimeZone->new(name => $timezone);
831 return $context->{tz};
835 =head2 IsSuperLibrarian
837 C4::Context->IsSuperLibrarian();
841 sub IsSuperLibrarian {
842 my $userenv = C4::Context->userenv;
844 unless ( $userenv and exists $userenv->{flags} ) {
845 # If we reach this without a user environment,
846 # assume that we're running from a command-line script,
847 # and act as a superlibrarian.
848 carp("C4::Context->userenv not defined!");
852 return ($userenv->{flags}//0) % 2;
857 Sets the current interface for later retrieval in any Perl module
859 C4::Context->interface('opac');
860 C4::Context->interface('intranet');
861 my $interface = C4::Context->interface;
866 my ($class, $interface) = @_;
868 if (defined $interface) {
869 $interface = lc $interface;
870 if ( $interface eq 'api'
871 || $interface eq 'opac'
872 || $interface eq 'intranet'
873 || $interface eq 'sip'
874 || $interface eq 'cron'
875 || $interface eq 'commandline' )
877 $context->{interface} = $interface;
879 warn "invalid interface : '$interface'";
883 return $context->{interface} // 'opac';
886 # always returns a string for OK comparison via "eq" or "ne"
888 C4::Context->userenv or return '';
889 return C4::Context->userenv->{branch} || '';
892 =head2 only_my_library
894 my $test = C4::Context->only_my_library;
896 Returns true if you enabled IndependentBranches and the current user
897 does not have superlibrarian permissions.
901 sub only_my_library {
903 C4::Context->preference('IndependentBranches')
904 && C4::Context->userenv
905 && !C4::Context->IsSuperLibrarian()
906 && C4::Context->userenv->{branch};
909 =head3 temporary_directory
911 Returns root directory for temporary storage
915 sub temporary_directory {
917 return C4::Context->config('tmp_path') || File::Spec->tmpdir;
920 =head3 set_remote_address
922 set_remote_address should be called at the beginning of every script
923 that is *not* running under plack in order to the REMOTE_ADDR environment
924 variable to be set correctly.
928 sub set_remote_address {
929 if ( C4::Context->config('koha_trusted_proxies') ) {
931 my $header = CGI->http('HTTP_X_FORWARDED_FOR');
934 require Koha::Middleware::RealIP;
935 $ENV{REMOTE_ADDR} = Koha::Middleware::RealIP::get_real_ip( $ENV{REMOTE_ADDR}, $header );
942 https_enabled should be called when checking if a HTTPS connection
945 Note that this depends on a HTTPS environmental variable being defined
946 by the web server. This function may not return the expected result,
947 if your web server or reverse proxies are not setting the correct
948 X-Forwarded-Proto headers and HTTPS environmental variable.
950 Note too that the HTTPS value can vary from web server to web server.
951 We are relying on the convention of the value being "on" or "ON" here.
956 my $https_enabled = 0;
957 my $env_https = $ENV{HTTPS};
959 if ($env_https =~ /^ON$/i){
963 return $https_enabled;
970 if ( $context->needs_install ) { ... }
972 This method returns a boolean representing the install status of the Koha instance.
978 return ($self->preference('Version')) ? 0 : 1;
987 Specifies the configuration file to read.
991 Andrew Arensburger <arensb at ooblick dot com>
993 Joshua Ferraro <jmf at liblime dot com>