Bug 32612: (QA follow-up) Add BINMODE method to C4::SIP::Trapper
[koha-ffzg.git] / C4 / Context.pm
index 2dab73e..1aec123 100644 (file)
@@ -21,86 +21,29 @@ use Modern::Perl;
 
 use vars qw($AUTOLOAD $context @context_stack);
 BEGIN {
-       if ($ENV{'HTTP_USER_AGENT'})    {
-               require CGI::Carp;
-        # FIXME for future reference, CGI::Carp doc says
-        #  "Note that fatalsToBrowser does not work with mod_perl version 2.0 and higher."
-               import CGI::Carp qw(fatalsToBrowser);
-                       sub handle_errors {
-                           my $msg = shift;
-                           my $debug_level;
-                           eval {C4::Context->dbh();};
-                           if ($@){
-                               $debug_level = 1;
-                           } 
-                           else {
-                               $debug_level =  C4::Context->preference("DebugLevel");
-                           }
-
-                print q(<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
-                            "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
-                       <html lang="en" xml:lang="en"  xmlns="http://www.w3.org/1999/xhtml">
-                       <head><title>Koha Error</title></head>
-                       <body>
-                );
-                               if ($debug_level eq "2"){
-                                       # debug 2 , print extra info too.
-                                       my %versions = get_versions();
-
-               # a little example table with various version info";
-                                       print "
-                                               <h1>Koha error</h1>
-                                               <p>The following fatal error has occurred:</p> 
-                        <pre><code>$msg</code></pre>
-                                               <table>
-                                               <tr><th>Apache</th><td>  $versions{apacheVersion}</td></tr>
-                                               <tr><th>Koha</th><td>    $versions{kohaVersion}</td></tr>
-                                               <tr><th>Koha DB</th><td> $versions{kohaDbVersion}</td></tr>
-                                               <tr><th>MySQL</th><td>   $versions{mysqlVersion}</td></tr>
-                                               <tr><th>OS</th><td>      $versions{osVersion}</td></tr>
-                                               <tr><th>Perl</th><td>    $versions{perlVersion}</td></tr>
-                                               </table>";
-
-                               } elsif ($debug_level eq "1"){
-                                       print "
-                                               <h1>Koha error</h1>
-                                               <p>The following fatal error has occurred:</p> 
-                        <pre><code>$msg</code></pre>";
-                               } else {
-                                       print "<p>production mode - trapped fatal error</p>";
-                               }       
-                print "</body></html>";
-                       }
-               #CGI::Carp::set_message(\&handle_errors);
-               ## give a stack backtrace if KOHA_BACKTRACES is set
-               ## can't rely on DebugLevel for this, as we're not yet connected
-               if ($ENV{KOHA_BACKTRACES}) {
-                       $main::SIG{__DIE__} = \&CGI::Carp::confess;
-               }
+    if ( $ENV{'HTTP_USER_AGENT'} ) { # Only hit when plack is not enabled
 
         # Redefine multi_param if cgi version is < 4.08
         # Remove the "CGI::param called in list context" warning in this case
-        require CGI; # Can't check version without the require.
-        if (!defined($CGI::VERSION) || $CGI::VERSION < 4.08) {
+        require CGI;    # Can't check version without the require.
+        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!
-}
+    }
+};
 
-use Carp;
+use Carp qw( carp );
 use DateTime::TimeZone;
 use Encode;
 use File::Spec;
-use Module::Load::Conditional qw(can_load);
-use POSIX ();
-use YAML qw/Load/;
+use POSIX;
+use YAML::XS;
 use ZOOM;
+use List::MoreUtils qw(any);
 
-use C4::Boolean;
-use C4::Debug;
 use Koha::Caches;
 use Koha::Config::SysPref;
 use Koha::Config::SysPrefs;
@@ -175,22 +118,6 @@ environment variable to the pathname of a configuration file to use.
 $context = undef;        # Initially, no context is set
 @context_stack = ();        # Initially, no saved contexts
 
-=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 $scheme = shift // '';
-    return $scheme eq 'Pg' ? $scheme : 'mysql';
-}
-
 sub import {
     # Create the default context ($C4::Context::Context)
     # the first time the module is called
@@ -233,7 +160,6 @@ that, use C<&set_context>.
 sub new {
     my $class = shift;
     my $conf_fname = shift;        # Config file to load
-    my $self = {};
 
     # check that the specified config file exists and is not empty
     undef $conf_fname unless 
@@ -247,19 +173,9 @@ sub new {
         }
     }
 
-    my $conf_cache = Koha::Caches->get_instance('config');
-    if ( $conf_cache->cache ) {
-        $self = $conf_cache->get_from_cache('koha_conf');
-    }
-    unless ( $self and %$self ) {
-        $self = Koha::Config->read_from_file($conf_fname);
-        if ( $conf_cache->memcached_cache ) {
-            # FIXME it may be better to use the memcached servers from the config file
-            # to cache it
-            $conf_cache->set_in_cache('koha_conf', $self)
-        }
-    }
-    unless ( exists $self->{config} or defined $self->{config} ) {
+    my $self = {};
+    $self->{config} = Koha::Config->get_instance($conf_fname);
+    unless ( defined $self->{config} ) {
         warn "The config file ($conf_fname) has not been parsed correctly";
         return;
     }
@@ -271,7 +187,6 @@ 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;
 }
 
@@ -353,28 +268,17 @@ sub restore_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
-C<C4::Config-E<gt>new> will not return it.
-
 =cut
 
 sub _common_config {
-       my $var = shift;
-       my $term = shift;
-    return if !defined($context->{$term});
-       # Presumably $self->{$term} might be
-       # undefined if the config file given to &new
-       # didn't exist, and the caller didn't bother
-       # to check the return value.
-
-    # Return the value of the requested config variable
-    return $context->{$term}->{$var};
+    my ($var, $term) = @_;
+
+    return unless defined $context and defined $context->{config};
+
+    return $context->{config}->get($var, $term);
 }
 
 sub config {
@@ -400,19 +304,18 @@ with this method.
 
 =cut
 
-my $syspref_cache = Koha::Caches->get_instance('syspref');
 my $use_syspref_cache = 1;
 sub preference {
     my $self = shift;
     my $var  = shift;    # The system preference to return
 
-    return $ENV{"OVERRIDE_SYSPREF_$var"}
+    return Encode::decode_utf8($ENV{"OVERRIDE_SYSPREF_$var"})
         if defined $ENV{"OVERRIDE_SYSPREF_$var"};
 
     $var = lc $var;
 
     if ($use_syspref_cache) {
-        $syspref_cache = Koha::Caches->get_instance('syspref') unless $syspref_cache;
+        my $syspref_cache = Koha::Caches->get_instance('syspref');
         my $cached_var = $syspref_cache->get_from_cache("syspref_$var");
         return $cached_var if defined $cached_var;
     }
@@ -422,18 +325,12 @@ sub preference {
     my $value = $syspref ? $syspref->value() : undef;
 
     if ( $use_syspref_cache ) {
+        my $syspref_cache = Koha::Caches->get_instance('syspref');
         $syspref_cache->set_in_cache("syspref_$var", $value);
     }
     return $value;
 }
 
-sub boolean_preference {
-    my $self = shift;
-    my $var = shift;        # The system preference to return
-    my $it = preference($self, $var);
-    return defined($it)? C4::Boolean::true_p($it): undef;
-}
-
 =head2 yaml_preference
 
 Retrieves the required system preference value, and converts it
@@ -445,7 +342,7 @@ the value cannot be properly decoded as YAML.
 sub yaml_preference {
     my ( $self, $preference ) = @_;
 
-    my $yaml = eval { YAML::Load( $self->preference( $preference ) ); };
+    my $yaml = eval { YAML::XS::Load( Encode::encode_utf8( $self->preference( $preference ) ) ); };
     if ($@) {
         warn "Unable to parse $preference syspref : $@";
         return;
@@ -497,6 +394,7 @@ will not be seen by this process.
 
 sub clear_syspref_cache {
     return unless $use_syspref_cache;
+    my $syspref_cache = Koha::Caches->get_instance('syspref');
     $syspref_cache->flush_all;
 }
 
@@ -550,6 +448,7 @@ sub set_preference {
     }
 
     if ( $use_syspref_cache ) {
+        my $syspref_cache = Koha::Caches->get_instance('syspref');
         $syspref_cache->set_in_cache( "syspref_$variable", $value );
     }
 
@@ -571,6 +470,7 @@ sub delete_preference {
 
     if ( Koha::Config::SysPrefs->find( $var )->delete ) {
         if ( $use_syspref_cache ) {
+            my $syspref_cache = Koha::Caches->get_instance('syspref');
             $syspref_cache->clear_from_cache("syspref_$var");
         }
 
@@ -579,6 +479,26 @@ sub delete_preference {
     return 0;
 }
 
+=head2 csv_delimiter
+
+    $delimiter = C4::Context->csv_delimiter;
+
+    Returns preferred CSV delimiter, using system preference 'CSVDelimiter'.
+    If this preference is missing or empty, comma will be returned.
+    This method is needed because of special behavior for tabulation.
+
+    You can, optionally, pass a value parameter to this routine
+    in the case of existing delimiter.
+
+=cut
+
+sub csv_delimiter {
+    my ( $self, $value ) = @_;
+    my $delimiter = $value || $self->preference('CSVDelimiter') || ',';
+    $delimiter = "\t" if $delimiter eq 'tabulation';
+    return $delimiter;
+}
+
 =head2 Zconn
 
   $Zconn = C4::Context->Zconn
@@ -632,20 +552,23 @@ sub _new_Zconn {
     $syntax = 'xml';
     $elementSetName = 'marcxml';
 
-    my $host = $context->{'listen'}->{$server}->{'content'};
-    my $user = $context->{"serverinfo"}->{$server}->{"user"};
-    my $password = $context->{"serverinfo"}->{$server}->{"password"};
+    my $host = _common_config($server, 'listen')->{content};
+    my $serverinfo = _common_config($server, 'serverinfo');
+    my $user = $serverinfo->{user};
+    my $password = $serverinfo->{password};
     eval {
         # set options
         my $o = ZOOM::Options->new();
         $o->option(user => $user) if $user && $password;
         $o->option(password => $password) if $user && $password;
         $o->option(async => 1) if $async;
-        $o->option(cqlfile=> $context->{"server"}->{$server}->{"cql2rpn"});
-        $o->option(cclfile=> $context->{"serverinfo"}->{$server}->{"ccl2rpn"});
+        $o->option(cqlfile=> _common_config($server, 'server')->{cql2rpn});
+        $o->option(cclfile=> $serverinfo->{ccl2rpn});
         $o->option(preferredRecordSyntax => $syntax);
         $o->option(elementSetName => $elementSetName) if $elementSetName;
-        $o->option(databaseName => $context->{"config"}->{$server}||"biblios");
+        $o->option(databaseName => _common_config($server, 'config') || 'biblios');
+        my $timeout = C4::Context->config('zebra_connection_timeout') || 30;
+        $o->option(timeout => $timeout);
 
         # create a new connection object
         $Zconn= create ZOOM::Connection($o);
@@ -805,7 +728,8 @@ sub userenv {
                            $userfirstname, $usersurname,
                            $userbranch, $branchname, $userflags,
                            $emailaddress, $shibboleth
-                           $desk_id, $desk_name);
+                           $desk_id, $desk_name,
+                           $register_id, $register_name);
 
 Establish a hash of user environment variables.
 
@@ -816,9 +740,13 @@ set_userenv is called in Auth.pm
 #'
 sub set_userenv {
     shift @_;
-    my ($usernum, $userid, $usercnum, $userfirstname, $usersurname, $userbranch, $branchname, $userflags, $emailaddress, $shibboleth, $desk_id, $desk_name)=
-    map { Encode::is_utf8( $_ ) ? $_ : Encode::decode('UTF-8', $_) } # CGI::Session doesn't handle utf-8, so we decode it here
-    @_;
+    my (
+        $usernum,      $userid,     $usercnum,   $userfirstname,
+        $usersurname,  $userbranch, $branchname, $userflags,
+        $emailaddress, $shibboleth, $desk_id,    $desk_name,
+        $register_id,  $register_name
+    ) = @_;
+
     my $var=$context->{"activeuser"} || '';
     my $cell = {
         "number"     => $usernum,
@@ -826,39 +754,22 @@ sub set_userenv {
         "cardnumber" => $usercnum,
         "firstname"  => $userfirstname,
         "surname"    => $usersurname,
+
         #possibly a law problem
-        "branch"     => $userbranch,
-        "branchname" => $branchname,
-        "desk_id"    => $desk_id,
-        "desk_name"  => $desk_name,
-        "flags"      => $userflags,
-        "emailaddress"     => $emailaddress,
-        "shibboleth" => $shibboleth,
+        "branch"        => $userbranch,
+        "branchname"    => $branchname,
+        "flags"         => $userflags,
+        "emailaddress"  => $emailaddress,
+        "shibboleth"    => $shibboleth,
+        "desk_id"       => $desk_id,
+        "desk_name"     => $desk_name,
+        "register_id"   => $register_id,
+        "register_name" => $register_name
     };
     $context->{userenv}->{$var} = $cell;
     return $cell;
 }
 
-sub set_shelves_userenv {
-       my ($type, $shelves) = @_ or return;
-       my $activeuser = $context->{activeuser} or return;
-       $context->{userenv}->{$activeuser}->{barshelves} = $shelves if $type eq 'bar';
-       $context->{userenv}->{$activeuser}->{pubshelves} = $shelves if $type eq 'pub';
-       $context->{userenv}->{$activeuser}->{totshelves} = $shelves if $type eq 'tot';
-}
-
-sub get_shelves_userenv {
-       my $active;
-       unless ($active = $context->{userenv}->{$context->{activeuser}}) {
-               $debug and warn "get_shelves_userenv cannot retrieve context->{userenv}->{context->{activeuser}}";
-               return;
-       }
-       my $totshelves = $active->{totshelves} or undef;
-       my $pubshelves = $active->{pubshelves} or undef;
-       my $barshelves = $active->{barshelves} or undef;
-       return ($totshelves, $pubshelves, $barshelves);
-}
-
 =head2 _new_userenv
 
   C4::Context->_new_userenv($session);  # FIXME: This calling style is wrong for what looks like an _internal function
@@ -893,7 +804,7 @@ Destroys the hash for activeuser user environment variables.
 sub _unset_userenv
 {
     my ($sessionID)= @_;
-    undef $context->{"activeuser"} if ($context->{"activeuser"} eq $sessionID);
+    undef $context->{activeuser} if $sessionID && $context->{activeuser} && $context->{activeuser} eq $sessionID;
 }
 
 
@@ -926,26 +837,6 @@ sub get_versions {
     return %versions;
 }
 
-=head2 timezone
-
-  my $C4::Context->timzone
-
-  Returns a timezone code for the instance of Koha
-
-=cut
-
-sub timezone {
-    my $self = shift;
-
-    my $timezone = C4::Context->config('timezone') || $ENV{TZ} || 'local';
-    if ( !DateTime::TimeZone->is_valid_name( $timezone ) ) {
-        warn "Invalid timezone in koha-conf.xml ($timezone)";
-        $timezone = 'local';
-    }
-
-    return $timezone;
-}
-
 =head2 tz
 
   C4::Context->tz
@@ -957,7 +848,7 @@ sub timezone {
 sub tz {
     my $self = shift;
     if (!defined $context->{tz}) {
-        my $timezone = $self->timezone;
+        my $timezone = $context->{config}->timezone;
         $context->{tz} = DateTime::TimeZone->new(name => $timezone);
     }
     return $context->{tz};
@@ -1110,6 +1001,37 @@ sub needs_install {
     return ($self->preference('Version')) ? 0 : 1;
 }
 
+=head3 psgi_env
+
+psgi_env returns true if there is an environmental variable
+prefixed with "psgi" or "plack". This is useful for detecting whether
+this is a PSGI app or a CGI app, and implementing code as appropriate.
+
+=cut
+
+sub psgi_env {
+    my ( $self ) = @_;
+    return any { /^(psgi\.|plack\.|PLACK_ENV$)/i } keys %ENV;
+}
+
+=head3 is_internal_PSGI_request
+
+is_internal_PSGI_request is used to detect if this request was made
+from within the individual PSGI app or externally from the mounted PSGI
+app
+
+=cut
+
+#NOTE: This is not a very robust method but it's the best we have so far
+sub is_internal_PSGI_request {
+    my ( $self ) = @_;
+    my $is_internal = 0;
+    if( $self->psgi_env && ( $ENV{REQUEST_URI} !~ /^(\/intranet|\/opac)/ ) ) {
+        $is_internal = 1;
+    }
+    return $is_internal;
+}
+
 __END__
 
 =head1 ENVIRONMENT
@@ -1118,10 +1040,6 @@ __END__
 
 Specifies the configuration file to read.
 
-=head1 SEE ALSO
-
-XML::Simple
-
 =head1 AUTHORS
 
 Andrew Arensburger <arensb at ooblick dot com>