Bug 16011: $VERSION - remove use vars $VERSION
[koha.git] / C4 / Context.pm
index 7bc7097..34a2926 100644 (file)
@@ -3,23 +3,22 @@ package C4::Context;
 #
 # This file is part of Koha.
 #
-# Koha is free software; you can redistribute it and/or modify it under the
-# terms of the GNU General Public License as published by the Free Software
-# Foundation; either version 2 of the License, or (at your option) any later
-# version.
+# Koha is free software; you can redistribute it and/or modify it
+# under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 3 of the License, or
+# (at your option) any later version.
 #
-# Koha is distributed in the hope that it will be useful, but WITHOUT ANY
-# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
-# A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
+# Koha is distributed in the hope that it will be useful, but
+# WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
 #
-# You should have received a copy of the GNU General Public License along
-# with Koha; if not, write to the Free Software Foundation, Inc.,
-# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+# You should have received a copy of the GNU General Public License
+# along with Koha; if not, see <http://www.gnu.org/licenses>.
 
 use strict;
 use warnings;
-use vars qw($VERSION $AUTOLOAD $context @context_stack $servers $memcached $ismemcached);
-
+use vars qw($AUTOLOAD $context @context_stack $servers $memcached $ismemcached);
 BEGIN {
        if ($ENV{'HTTP_USER_AGENT'})    {
                require CGI::Carp;
@@ -77,6 +76,15 @@ BEGIN {
                if ($ENV{KOHA_BACKTRACES}) {
                        $main::SIG{__DIE__} = \&CGI::Carp::confess;
                }
+
+        # Redefine multi_param if cgi version is < 4.08
+        # Remove the "CGI::param called in list context" warning in this case
+        if (!defined($CGI::VERSION) || $CGI::VERSION < 4.08) {
+            no warnings 'redefine';
+            *CGI::multi_param = \&CGI::param;
+            use warnings 'redefine';
+            $CGI::LIST_CONTEXT_WARN = 0;
+        }
     }          # else there is no browser to send fatals to!
 
     # Check if there are memcached servers set
@@ -98,14 +106,20 @@ BEGIN {
     $VERSION = '3.07.00.049';
 }
 
-use DBI;
+use Encode;
 use ZOOM;
 use XML::Simple;
-use C4::Boolean;
-use C4::Debug;
+use Koha::Cache;
 use POSIX ();
 use DateTime::TimeZone;
 use Module::Load::Conditional qw(can_load);
+use Carp;
+
+use C4::Boolean;
+use C4::Debug;
+use Koha;
+use Koha::Config::SysPref;
+use Koha::Config::SysPrefs;
 
 =head1 NAME
 
@@ -125,8 +139,6 @@ C4::Context - Maintain and manipulate the context of a Koha script
 
   $Zconn = C4::Context->Zconn;
 
-  $stopwordhash = C4::Context->stopwords;
-
 =head1 DESCRIPTION
 
 When a Koha script runs, it makes use of a certain number of things:
@@ -203,36 +215,6 @@ $context = undef;        # Initially, no context is set
 @context_stack = ();        # Initially, no saved contexts
 
 
-=head2 KOHAVERSION
-
-returns the kohaversion stored in kohaversion.pl file
-
-=cut
-
-sub KOHAVERSION {
-    my $cgidir = C4::Context->intranetdir;
-
-    # Apparently the GIT code does not run out of a CGI-BIN subdirectory
-    # but distribution code does?  (Stan, 1jan08)
-    if(-d $cgidir . "/cgi-bin"){
-        my $cgidir .= "/cgi-bin";
-    }
-    
-    do $cgidir."/kohaversion.pl" || die "NO $cgidir/kohaversion.pl";
-    return kohaversion();
-}
-
-=head2 final_linear_version
-
-Returns the version number of the final update to run in updatedatabase.pl.
-This number is equal to the version in kohaversion.pl
-
-=cut
-
-sub final_linear_version {
-    return KOHAVERSION;
-}
-
 =head2 read_config_file
 
 Reads the specified Koha config file. 
@@ -293,20 +275,20 @@ sub memcached {
     }
 }
 
-# db_scheme2dbi
-# Translates the full text name of a database into de appropiate dbi name
-# 
+=head2 db_scheme2dbi
+
+    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'.
+
+=cut
+
 sub db_scheme2dbi {
-    my $name = shift;
-    # for instance, we support only mysql, so don't care checking
-    return "mysql";
-    for ($name) {
-# FIXME - Should have other databases. 
-        if (/mysql/) { return("mysql"); }
-        if (/Postgres|Pg|PostgresSQL/) { return("Pg"); }
-        if (/oracle/) { return("Oracle"); }
-    }
-    return;         # Just in case
+    my $scheme = shift // '';
+    return $scheme eq 'Pg' ? $scheme : 'mysql';
 }
 
 sub import {
@@ -314,7 +296,7 @@ sub import {
     # the first time the module is called
     # (a config file can be optionaly passed)
 
-    # default context allready exists? 
+    # default context already exists?
     return if $context;
 
     # no ? so load it!
@@ -376,7 +358,7 @@ sub new {
     }
     
     if ($ismemcached) {
-        # retreive from memcached
+        # retrieve from memcached
         $self = $memcached->get('kohaconf');
         if (not defined $self) {
             # not in memcached yet
@@ -391,9 +373,7 @@ sub new {
     warn "read_config_file($conf_fname) returned undef" if !defined($self->{"config"});
     return if !defined($self->{"config"});
 
-    $self->{"dbh"} = undef;        # Database handle
     $self->{"Zconn"} = undef;    # Zebra Connections
-    $self->{"stopwords"} = undef; # stopwords list
     $self->{"marcfromkohafield"} = undef; # the hash with relations between koha table fields and MARC field/subfield
     $self->{"userenv"} = undef;        # User env
     $self->{"activeuser"} = undef;        # current active user
@@ -401,6 +381,7 @@ sub new {
     $self->{tz} = undef; # local timezone object
 
     bless $self, $class;
+    $self->{db_driver} = db_scheme2dbi($self->config('db_scheme'));  # cache database driver
     return $self;
 }
 
@@ -532,37 +513,38 @@ with this method.
 
 =cut
 
-# FIXME: running this under mod_perl will require a means of
-# flushing the caching mechanism.
-
-my %sysprefs;
+my $syspref_cache = Koha::Cache->get_instance();
+my %syspref_L1_cache;
 my $use_syspref_cache = 1;
-
 sub preference {
     my $self = shift;
     my $var  = shift;    # The system preference to return
 
-    if ($use_syspref_cache && exists $sysprefs{$var}) {
-        return $sysprefs{$var};
+    $var = lc $var;
+
+    # Return the value if the var has already been accessed
+    if ($use_syspref_cache && exists $syspref_L1_cache{$var}) {
+        return $syspref_L1_cache{$var};
     }
 
-    my $dbh  = C4::Context->dbh or return 0;
+    my $cached_var = $use_syspref_cache
+        ? $syspref_cache->get_from_cache("syspref_$var")
+        : undef;
+    return $cached_var if defined $cached_var;
 
     my $value;
     if ( defined $ENV{"OVERRIDE_SYSPREF_$var"} ) {
         $value = $ENV{"OVERRIDE_SYSPREF_$var"};
     } else {
-        # Look up systempreferences.variable==$var
-        my $sql = q{
-            SELECT  value
-            FROM    systempreferences
-            WHERE   variable = ?
-            LIMIT   1
-        };
-        $value = $dbh->selectrow_array( $sql, {}, $var );
+        my $syspref;
+        eval { $syspref = Koha::Config::SysPrefs->find( lc $var ) };
+        $value = $syspref ? $syspref->value() : undef;
     }
 
-    $sysprefs{$var} = $value;
+    if ( $use_syspref_cache ) {
+        $syspref_cache->set_in_cache("syspref_$var", $value);
+        $syspref_L1_cache{$var} = $value;
+    }
     return $value;
 }
 
@@ -585,6 +567,8 @@ default behavior.
 sub enable_syspref_cache {
     my ($self) = @_;
     $use_syspref_cache = 1;
+    # We need to clear the cache to have it up-to-date
+    $self->clear_syspref_cache();
 }
 
 =head2 disable_syspref_cache
@@ -613,67 +597,100 @@ will not be seen by this process.
 =cut
 
 sub clear_syspref_cache {
-    %sysprefs = ();
+    return unless $use_syspref_cache;
+    $syspref_cache->flush_all;
+    clear_syspref_L1_cache()
+}
+
+sub clear_syspref_L1_cache {
+    %syspref_L1_cache = ();
 }
 
 =head2 set_preference
 
-  C4::Context->set_preference( $variable, $value );
+  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.
+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.
 
 =cut
 
 sub set_preference {
-    my $self = shift;
-    my $var = lc(shift);
-    my $value = shift;
+    my ( $self, $variable, $value, $explanation, $type, $options ) = @_;
 
-    my $dbh = C4::Context->dbh or return 0;
+    $variable = lc $variable;
 
-    my $type = $dbh->selectrow_array( "SELECT type FROM systempreferences WHERE variable = ?", {}, $var );
+    my $syspref = Koha::Config::SysPrefs->find($variable);
+    $type =
+        $type    ? $type
+      : $syspref ? $syspref->type
+      :            undef;
 
     $value = 0 if ( $type && $type eq 'YesNo' && $value eq '' );
 
-    my $sth = $dbh->prepare( "
-      INSERT INTO systempreferences
-        ( variable, value )
-        VALUES( ?, ? )
-        ON DUPLICATE KEY UPDATE value = VALUES(value)
-    " );
+    # force explicit protocol on OPACBaseURL
+    if ( $variable eq 'opacbaseurl' && substr( $value, 0, 4 ) !~ /http/ ) {
+        $value = 'http://' . $value;
+    }
+
+    if ($syspref) {
+        $syspref->set(
+            {   ( defined $value ? ( value       => $value )       : () ),
+                ( $explanation   ? ( explanation => $explanation ) : () ),
+                ( $type          ? ( type        => $type )        : () ),
+                ( $options       ? ( options     => $options )     : () ),
+            }
+        )->store;
+    } else {
+        $syspref = Koha::Config::SysPref->new(
+            {   variable    => $variable,
+                value       => $value,
+                explanation => $explanation || undef,
+                type        => $type,
+                options     => $options || undef,
+            }
+        )->store();
+    }
 
-    if($sth->execute( $var, $value )) {
-        $sysprefs{$var} = $value;
+    if ( $use_syspref_cache ) {
+        $syspref_cache->set_in_cache( "syspref_$variable", $value );
+        $syspref_L1_cache{$variable} = $value;
     }
-    $sth->finish;
+
+    return $syspref;
 }
 
-# AUTOLOAD
-# This implements C4::Config->foo, and simply returns
-# C4::Context->config("foo"), as described in the documentation for
-# &config, above.
+=head2 delete_preference
 
-# FIXME - Perhaps this should be extended to check &config first, and
-# then &preference if that fails. OTOH, AUTOLOAD could lead to crappy
-# code, so it'd probably be best to delete it altogether so as not to
-# encourage people to use it.
-sub AUTOLOAD
-{
-    my $self = shift;
+    C4::Context->delete_preference( $variable );
 
-    $AUTOLOAD =~ s/.*:://;        # Chop off the package name,
-                    # leaving only the function name.
-    return $self->config($AUTOLOAD);
+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.
+
+=cut
+
+sub delete_preference {
+    my ( $self, $var ) = @_;
+
+    if ( Koha::Config::SysPrefs->find( $var )->delete ) {
+        if ( $use_syspref_cache ) {
+            $syspref_cache->clear_from_cache("syspref_$var");
+            delete $syspref_L1_cache{$var};
+        }
+
+        return 1;
+    }
+    return 0;
 }
 
 =head2 Zconn
 
   $Zconn = C4::Context->Zconn
 
-Returns a connection to the Zebra database for the current
-context. If no connection has yet been made, this method 
-creates one and connects.
+Returns a connection to the Zebra database
 
 C<$self> 
 
@@ -681,35 +698,18 @@ C<$server> one of the servers defined in the koha-conf.xml file
 
 C<$async> whether this is a asynchronous connection
 
-C<$auth> whether this connection has rw access (1) or just r access (0 or NULL)
-
-
 =cut
 
 sub Zconn {
-    my $self=shift;
-    my $server=shift;
-    my $async=shift;
-    my $auth=shift;
-    my $piggyback=shift;
-    my $syntax=shift;
-    if ( defined($context->{"Zconn"}->{$server}) && (0 == $context->{"Zconn"}->{$server}->errcode()) ) {
-        return $context->{"Zconn"}->{$server};
-    # No connection object or it died. Create one.
-    }else {
-        # release resources if we're closing a connection and making a new one
-        # FIXME: this needs to be smarter -- an error due to a malformed query or
-        # a missing index does not necessarily require us to close the connection
-        # and make a new one, particularly for a batch job.  However, at
-        # first glance it does not look like there's a way to easily check
-        # the basic health of a ZOOM::Connection
-        $context->{"Zconn"}->{$server}->destroy() if defined($context->{"Zconn"}->{$server});
-
-        $context->{"Zconn"}->{$server} = &_new_Zconn($server,$async,$auth,$piggyback,$syntax);
-        $context->{ Zconn }->{ $server }->option(
-            preferredRecordSyntax => C4::Context->preference("marcflavour") );
-        return $context->{"Zconn"}->{$server};
+    my ($self, $server, $async ) = @_;
+    my $cache_key = join ('::', (map { $_ // '' } ($server, $async )));
+    if ( (!defined($ENV{GATEWAY_INTERFACE})) && defined($context->{"Zconn"}->{$cache_key}) && (0 == $context->{"Zconn"}->{$cache_key}->errcode()) ) {
+        # if we are running the script from the commandline, lets try to use the caching
+        return $context->{"Zconn"}->{$cache_key};
     }
+    $context->{"Zconn"}->{$cache_key}->destroy() if defined($context->{"Zconn"}->{$cache_key}); #destroy old connection before making a new one
+    $context->{"Zconn"}->{$cache_key} = &_new_Zconn( $server, $async );
+    return $context->{"Zconn"}->{$cache_key};
 }
 
 =head2 _new_Zconn
@@ -727,31 +727,47 @@ C<$auth> whether this connection has rw access (1) or just r access (0 or NULL)
 =cut
 
 sub _new_Zconn {
-    my ($server,$async,$auth,$piggyback,$syntax) = @_;
+    my ( $server, $async ) = @_;
 
     my $tried=0; # first attempt
     my $Zconn; # connection object
-    $server = "biblioserver" unless $server;
-    $syntax = "usmarc" unless $syntax;
+    my $elementSetName;
+    my $index_mode;
+    my $syntax;
+
+    $server //= "biblioserver";
+
+    if ( $server eq 'biblioserver' ) {
+        $index_mode = $context->{'config'}->{'zebra_bib_index_mode'} // 'dom';
+    } elsif ( $server eq 'authorityserver' ) {
+        $index_mode = $context->{'config'}->{'zebra_auth_index_mode'} // 'dom';
+    }
+
+    if ( $index_mode eq 'grs1' ) {
+        $elementSetName = 'F';
+        $syntax = ( $context->preference("marcflavour") eq 'UNIMARC' )
+                ? 'unimarc'
+                : 'usmarc';
+
+    } else { # $index_mode eq 'dom'
+        $syntax = 'xml';
+        $elementSetName = 'marcxml';
+    }
 
     my $host = $context->{'listen'}->{$server}->{'content'};
-    my $servername = $context->{"config"}->{$server};
     my $user = $context->{"serverinfo"}->{$server}->{"user"};
     my $password = $context->{"serverinfo"}->{$server}->{"password"};
- $auth = 1 if($user && $password);   
-    retry:
     eval {
         # set options
         my $o = new ZOOM::Options();
-        $o->option(user=>$user) if $auth;
-        $o->option(password=>$password) if $auth;
+        $o->option(user => $user) if $user && $password;
+        $o->option(password => $password) if $user && $password;
         $o->option(async => 1) if $async;
-        $o->option(count => $piggyback) if $piggyback;
         $o->option(cqlfile=> $context->{"server"}->{$server}->{"cql2rpn"});
         $o->option(cclfile=> $context->{"serverinfo"}->{$server}->{"ccl2rpn"});
         $o->option(preferredRecordSyntax => $syntax);
-        $o->option(elementSetName => "F"); # F for 'full' as opposed to B for 'brief'
-        $o->option(databaseName => ($servername?$servername:"biblios"));
+        $o->option(elementSetName => $elementSetName) if $elementSetName;
+        $o->option(databaseName => $context->{"config"}->{$server}||"biblios");
 
         # create a new connection object
         $Zconn= create ZOOM::Connection($o);
@@ -763,25 +779,7 @@ sub _new_Zconn {
         if ($Zconn->errcode() !=0) {
             warn "something wrong with the connection: ". $Zconn->errmsg();
         }
-
     };
-#     if ($@) {
-#         # Koha manages the Zebra server -- this doesn't work currently for me because of permissions issues
-#         # Also, I'm skeptical about whether it's the best approach
-#         warn "problem with Zebra";
-#         if ( C4::Context->preference("ManageZebra") ) {
-#             if ($@->code==10000 && $tried==0) { ##No connection try restarting Zebra
-#                 $tried=1;
-#                 warn "trying to restart Zebra";
-#                 my $res=system("zebrasrv -f $ENV{'KOHA_CONF'} >/koha/log/zebra-error.log");
-#                 goto "retry";
-#             } else {
-#                 warn "Error ", $@->code(), ": ", $@->message(), "\n";
-#                 $Zconn="error";
-#                 return $Zconn;
-#             }
-#         }
-#     }
     return $Zconn;
 }
 
@@ -792,51 +790,7 @@ sub _new_Zconn {
 sub _new_dbh
 {
 
-    ## $context
-    ## correct name for db_schme        
-    my $db_driver;
-    if ($context->config("db_scheme")){
-        $db_driver=db_scheme2dbi($context->config("db_scheme"));
-    }else{
-        $db_driver="mysql";
-    }
-
-    my $db_name   = $context->config("database");
-    my $db_host   = $context->config("hostname");
-    my $db_port   = $context->config("port") || '';
-    my $db_user   = $context->config("user");
-    my $db_passwd = $context->config("pass");
-    # MJR added or die here, as we can't work without dbh
-    my $dbh = DBI->connect("DBI:$db_driver:dbname=$db_name;host=$db_host;port=$db_port",
-    $db_user, $db_passwd, {'RaiseError' => $ENV{DEBUG}?1:0 }) or die $DBI::errstr;
-
-    # Check for the existence of a systempreference table; if we don't have this, we don't
-    # have a valid database and should not set RaiseError in order to allow the installer
-    # to run; installer will not run otherwise since we raise all db errors
-
-    eval {
-                local $dbh->{PrintError} = 0;
-                local $dbh->{RaiseError} = 1;
-                $dbh->do(qq{SELECT * FROM systempreferences WHERE 1 = 0 });
-    };
-
-    if ($@) {
-        $dbh->{RaiseError} = 0;
-    }
-
-       my $tz = $ENV{TZ};
-    if ( $db_driver eq 'mysql' ) { 
-        # Koha 3.0 is utf-8, so force utf8 communication between mySQL and koha, whatever the mysql default config.
-        # this is better than modifying my.cnf (and forcing all communications to be in utf8)
-        $dbh->{'mysql_enable_utf8'}=1; #enable
-        $dbh->do("set NAMES 'utf8'");
-        ($tz) and $dbh->do(qq(SET time_zone = "$tz"));
-    }
-    elsif ( $db_driver eq 'Pg' ) {
-           $dbh->do( "set client_encoding = 'UTF8';" );
-        ($tz) and $dbh->do(qq(SET TIME ZONE = "$tz"));
-    }
-    return $dbh;
+    Koha::Database->schema({ new => 1 })->storage->dbh;
 }
 
 =head2 dbh
@@ -858,16 +812,14 @@ possibly C<&set_dbh>.
 sub dbh
 {
     my $self = shift;
+    my $params = shift;
     my $sth;
 
-    if (defined($context->{"dbh"}) && $context->{"dbh"}->ping()) {
-       return $context->{"dbh"};
+    unless ( $params->{new} ) {
+        return Koha::Database->schema->storage->dbh;
     }
 
-    # No database handle or it died . Create one.
-    $context->{"dbh"} = &_new_dbh();
-
-    return $context->{"dbh"};
+    return Koha::Database->schema({ new => 1 })->storage->dbh;
 }
 
 =head2 new_dbh
@@ -888,7 +840,7 @@ sub new_dbh
 {
     my $self = shift;
 
-    return &_new_dbh();
+    return &dbh({ new => 1 });
 }
 
 =head2 set_dbh
@@ -987,6 +939,8 @@ sub _new_queryparser {
         my $config_file = $context->config('queryparser_config');
         $config_file ||= '/etc/koha/searchengine/queryparser.yaml';
         if ( $QParser->load_config($config_file) ) {
+            # Set 'keyword' as the default search class
+            $QParser->default_search_class('keyword');
             # TODO: allow indexes to be configured in the database
             return $QParser;
         }
@@ -1020,8 +974,6 @@ sub marcfromkohafield
 }
 
 # _new_marcfromkohafield
-# Internal helper function (not a method!). This creates a new
-# hash with stopwords
 sub _new_marcfromkohafield
 {
     my $dbh = C4::Context->dbh;
@@ -1035,47 +987,6 @@ sub _new_marcfromkohafield
     return $marcfromkohafield;
 }
 
-=head2 stopwords
-
-  $dbh = C4::Context->stopwords;
-
-Returns a hash with stopwords.
-
-This hash is cached for future use: if you call
-C<C4::Context-E<gt>stopwords> twice, you will get the same hash without real DB access
-
-=cut
-
-#'
-sub stopwords
-{
-    my $retval = {};
-
-    # If the hash already exists, return it.
-    return $context->{"stopwords"} if defined($context->{"stopwords"});
-
-    # No hash. Create one.
-    $context->{"stopwords"} = &_new_stopwords();
-
-    return $context->{"stopwords"};
-}
-
-# _new_stopwords
-# Internal helper function (not a method!). This creates a new
-# hash with stopwords
-sub _new_stopwords
-{
-    my $dbh = C4::Context->dbh;
-    my $stopwordlist;
-    my $sth = $dbh->prepare("select word from stopwords");
-    $sth->execute;
-    while (my $stopword = $sth->fetchrow_array) {
-        $stopwordlist->{$stopword} = uc($stopword);
-    }
-    $stopwordlist->{A} = "A" unless $stopwordlist;
-    return $stopwordlist;
-}
-
 =head2 userenv
 
   C4::Context->userenv;
@@ -1099,9 +1010,10 @@ sub userenv {
 
 =head2 set_userenv
 
-  C4::Context->set_userenv($usernum, $userid, $usercnum, $userfirstname, 
-                  $usersurname, $userbranch, $userflags, $emailaddress, $branchprinter,
-                  $persona);
+  C4::Context->set_userenv($usernum, $userid, $usercnum,
+                           $userfirstname, $usersurname,
+                           $userbranch, $branchname, $userflags,
+                           $emailaddress, $branchprinter, $persona);
 
 Establish a hash of user environment variables.
 
@@ -1111,7 +1023,10 @@ set_userenv is called in Auth.pm
 
 #'
 sub set_userenv {
-    my ($usernum, $userid, $usercnum, $userfirstname, $usersurname, $userbranch, $branchname, $userflags, $emailaddress, $branchprinter, $persona)= @_;
+    shift @_;
+    my ($usernum, $userid, $usercnum, $userfirstname, $usersurname, $userbranch, $branchname, $userflags, $emailaddress, $branchprinter, $persona, $shibboleth)=
+    map { Encode::is_utf8( $_ ) ? $_ : Encode::decode('UTF-8', $_) } # CGI::Session doesn't handle utf-8, so we decode it here
+    @_;
     my $var=$context->{"activeuser"} || '';
     my $cell = {
         "number"     => $usernum,
@@ -1126,6 +1041,7 @@ sub set_userenv {
         "emailaddress"     => $emailaddress,
         "branchprinter"    => $branchprinter,
         "persona"    => $persona,
+        "shibboleth" => $shibboleth,
     };
     $context->{userenv}->{$var} = $cell;
     return $cell;
@@ -1202,14 +1118,15 @@ Gets various version info, for core Koha packages, Currently called from carp ha
 # A little example sub to show more debugging info for CGI::Carp
 sub get_versions {
     my %versions;
-    $versions{kohaVersion}  = KOHAVERSION();
+    $versions{kohaVersion}  = Koha::version();
     $versions{kohaDbVersion} = C4::Context->preference('version');
     $versions{osVersion} = join(" ", POSIX::uname());
     $versions{perlVersion} = $];
     {
         no warnings qw(exec); # suppress warnings if unable to find a program in $PATH
         $versions{mysqlVersion}  = `mysql -V`;
-        $versions{apacheVersion} = `httpd -v`;
+        $versions{apacheVersion} = (`apache2ctl -v`)[0];
+        $versions{apacheVersion} = `httpd -v`             unless  $versions{apacheVersion} ;
         $versions{apacheVersion} = `httpd2 -v`            unless  $versions{apacheVersion} ;
         $versions{apacheVersion} = `apache2 -v`           unless  $versions{apacheVersion} ;
         $versions{apacheVersion} = `/usr/sbin/apache2 -v` unless  $versions{apacheVersion} ;
@@ -1235,6 +1152,50 @@ sub tz {
 }
 
 
+=head2 IsSuperLibrarian
+
+    C4::Context->IsSuperLibrarian();
+
+=cut
+
+sub IsSuperLibrarian {
+    my $userenv = C4::Context->userenv;
+
+    unless ( $userenv and exists $userenv->{flags} ) {
+        # If we reach this without a user environment,
+        # assume that we're running from a command-line script,
+        # and act as a superlibrarian.
+        carp("C4::Context->userenv not defined!");
+        return 1;
+    }
+
+    return ($userenv->{flags}//0) % 2;
+}
+
+=head2 interface
+
+Sets the current interface for later retrieval in any Perl module
+
+    C4::Context->interface('opac');
+    C4::Context->interface('intranet');
+    my $interface = C4::Context->interface;
+
+=cut
+
+sub interface {
+    my ($class, $interface) = @_;
+
+    if (defined $interface) {
+        $interface = lc $interface;
+        if ($interface eq 'opac' || $interface eq 'intranet' || $interface eq 'sip' || $interface eq 'commandline') {
+            $context->{interface} = $interface;
+        } else {
+            warn "invalid interface : '$interface'";
+        }
+    }
+
+    return $context->{interface} // 'opac';
+}
 
 1;
 __END__
@@ -1255,4 +1216,3 @@ Andrew Arensburger <arensb at ooblick dot com>
 
 Joshua Ferraro <jmf at liblime dot com>
 
-=cut