C4::Context - Maintain and manipulate the context of a Koha script


  use C4::Context;

  use C4::Context("/path/to/koha-conf.xml");

  $config_value = C4::Context->config("config_variable");

  $koha_preference = C4::Context->preference("preference");

  $db_handle = C4::Context->dbh;

  $Zconn = C4::Context->Zconn;


When a Koha script runs, it makes use of a certain number of things: configuration settings in /etc/koha/koha-conf.xml, a connection to the Koha databases, and so forth. These things make up the context in which the script runs.

This module takes care of setting up the context for a script: figuring out which configuration file to load, and loading it, opening a connection to the right database, and so forth.

Most scripts will only use one context. They can simply have

  use C4::Context;

at the top.

Other scripts may need to use several contexts. For instance, if a library has two databases, one for a certain collection, and the other for everything else, it might be necessary for a script to use two different contexts to search both databases. Such scripts should use the &set_context and &restore_context functions, below.

By default, C4::Context reads the configuration from /etc/koha/koha-conf.xml. This may be overridden by setting the $KOHA_CONF environment variable to the pathname of a configuration file to use.



    my $dbd_driver_name = C4::Context::db_schema2dbi($scheme);

This routines translates a database type to part of the name of the appropriate DBD driver to use when establishing a new database connection. It recognizes 'mysql' and 'Pg'; if any other scheme is supplied it defaults to 'mysql'.


  $context = new C4::Context;
  $context = new C4::Context("/path/to/koha-conf.xml");

Allocates a new context. Initializes the context from the specified file, which defaults to either the file given by the $KOHA_CONF environment variable, or /etc/koha/koha-conf.xml.

It saves the koha-conf.xml values in the declared memcached server(s) if currently available and uses those values until them expire and re-reads them.

&new does not set this context as the new default context; for that, use &set_context.


  $context = new C4::Context;
  set_context C4::Context $context;

  restore_context C4::Context;

In some cases, it might be necessary for a script to use multiple contexts. &set_context saves the current context on a stack, then sets the context to $context, which will be used in future operations. To restore the previous context, use &restore_context.



Restores the context set by &set_context.


  $value = C4::Context->config("config_variable");

  $value = C4::Context->config_variable;

Returns the value of a variable specified in the configuration file from which the current context was created.

The second form is more compact, but of course may conflict with method names. If there is a configuration variable called "new", then C4::Config->new will not return it.


  $sys_preference = C4::Context->preference('some_variable');

Looks up the value of the given system preference in the systempreferences table of the Koha database, and returns it. If the variable is not set or does not exist, undef is returned.

In case of an error, this may return 0.

Note: It is impossible to tell the difference between system preferences which do not exist, and those whose values are set to NULL with this method.



Enable the in-memory syspref cache used by C4::Context. This is the default behavior.



Disable the in-memory syspref cache used by C4::Context. This should be used with Plack and other persistent environments.



cleans the internal cache of sysprefs. Please call this method if you update the systempreferences table. Otherwise, your new changes will not be seen by this process.


  C4::Context->set_preference( $variable, $value, [ $explanation, $type, $options ] );

This updates a preference's value both in the systempreferences table and in the sysprefs cache. If the optional parameters are provided, then the query becomes a create. It won't update the parameters (except value) for an existing preference.


    C4::Context->delete_preference( $variable );

This deletes a system preference from the database. Returns a true value on success. Failure means there was an issue with the database, not that there was no syspref of the name.


  $Zconn = C4::Context->Zconn

Returns a connection to the Zebra database


$server one of the servers defined in the koha-conf.xml file

$async whether this is a asynchronous connection


$context->{"Zconn"} = &_new_Zconn($server,$async);

Internal function. Creates a new database connection from the data given in the current context and returns it.

$server one of the servers defined in the koha-conf.xml file

$async whether this is a asynchronous connection

$auth whether this connection has rw access (1) or just r access (0 or NULL)


  $dbh = C4::Context->dbh;

Returns a database handle connected to the Koha database for the current context. If no connection has yet been made, this method creates one, and connects to the database.

This database handle is cached for future use: if you call C4::Context->dbh twice, you will get the same handle both times. If you need a second database handle, use &new_dbh and possibly &set_dbh.


  $dbh = C4::Context->new_dbh;

Creates a new connection to the Koha database for the current context, and returns the database handle (a DBI::db object).

The handle is not saved anywhere: this method is strictly a convenience function; the point is that it knows which database to connect to so that the caller doesn't have to know.


  $my_dbh = C4::Connect->new_dbh;

&set_dbh and &restore_dbh work in a manner analogous to &set_context and &restore_context.

&set_dbh saves the current database handle on a stack, then sets the current database handle to $my_dbh.

$my_dbh is assumed to be a good database handle.



Restores the database handle saved by an earlier call to C4::Context->set_dbh.


  $queryparser = C4::Context->queryparser

Returns a handle to an initialized Koha::QueryParser::Driver::PQF object.


Internal helper function to create a new QueryParser object. QueryParser is loaded dynamically so as to keep the lack of the QueryParser library from getting in anyone's way.



Retrieves a hash for user environment variables.

This hash shall be cached for future use: if you call C4::Context->userenv twice, you will get the same hash without real DB access


  C4::Context->set_userenv($usernum, $userid, $usercnum,
                           $userfirstname, $usersurname,
                           $userbranch, $branchname, $userflags,
                           $emailaddress, $branchprinter, $shibboleth);

Establish a hash of user environment variables.

set_userenv is called in Auth.pm


  C4::Context->_new_userenv($session);  # FIXME: This calling style is wrong for what looks like an _internal function

Builds a hash for user environment variables.

This hash shall be cached for future use: if you call C4::Context->userenv twice, you will get the same hash without real DB access

_new_userenv is called in Auth.pm



Destroys the hash for activeuser user environment variables.



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'.



  Returns a DateTime::TimeZone object for the system timezone




Sets the current interface for later retrieval in any Perl module

    my $interface = C4::Context->interface;


    my $test = C4::Context->only_my_library;

    Returns true if you enabled IndependentBranches and the current user
    does not have superlibrarian permissions.



Specifies the configuration file to read.




Andrew Arensburger <arensb at ooblick dot com>

Joshua Ferraro <jmf at liblime dot com>