Bug 13899: Add changes as asked in Comment 5
[srvgit] / C4 / Auth.pm
index 2b64364..544bf7e 100644 (file)
@@ -4,18 +4,18 @@ package C4::Auth;
 #
 # 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;
@@ -30,7 +30,7 @@ use C4::Templates;    # to get the template
 use C4::Languages;
 use C4::Branch;       # GetBranches
 use C4::Search::History;
-use C4::VirtualShelves;
+use Koha;
 use Koha::AuthUtils qw(hash_password);
 use POSIX qw/strftime/;
 use List::MoreUtils qw/ any /;
@@ -199,13 +199,16 @@ sub get_template_and_user {
         $template->param( loggedinusernumber => $borrowernumber );
         $template->param( sessionID          => $sessionID );
 
-        my ( $total, $pubshelves, $barshelves ) = C4::VirtualShelves::GetSomeShelfNames( $borrowernumber, 'MASTHEAD' );
-        $template->param(
-            pubshelves     => $total->{pubtotal},
-            pubshelvesloop => $pubshelves,
-            barshelves     => $total->{bartotal},
-            barshelvesloop => $barshelves,
-        );
+        if ( $in->{'type'} eq 'opac' ) {
+            require C4::VirtualShelves;
+            my ( $total, $pubshelves, $barshelves ) = C4::VirtualShelves::GetSomeShelfNames( $borrowernumber, 'MASTHEAD' );
+            $template->param(
+                pubshelves     => $total->{pubtotal},
+                pubshelvesloop => $pubshelves,
+                barshelves     => $total->{bartotal},
+                barshelvesloop => $barshelves,
+            );
+        }
 
         my ($borr) = C4::Members::GetMemberDetails($borrowernumber);
         my @bordat;
@@ -334,11 +337,14 @@ sub get_template_and_user {
 
         $template->param( sessionID => $sessionID );
 
-        my ( $total, $pubshelves ) = C4::VirtualShelves::GetSomeShelfNames( undef, 'MASTHEAD' );
-        $template->param(
-            pubshelves     => $total->{pubtotal},
-            pubshelvesloop => $pubshelves,
-        );
+        if ( $in->{'type'} eq 'opac' ){
+            require C4::VirtualShelves;
+            my ( $total, $pubshelves ) = C4::VirtualShelves::GetSomeShelfNames( undef, 'MASTHEAD' );
+            $template->param(
+                pubshelves     => $total->{pubtotal},
+                pubshelvesloop => $pubshelves,
+            );
+        }
     }
 
     # Anonymous opac search history
@@ -351,7 +357,7 @@ sub get_template_and_user {
     }
 
     if ( C4::Context->preference('dateformat') ) {
-        $template->param( dateformat => C4::Context->preference('dateformat') )
+        $template->param( dateformat => C4::Context->preference('dateformat') );
     }
 
     # these template parameters are set the same regardless of $in->{'type'}
@@ -404,7 +410,7 @@ sub get_template_and_user {
             intranetreadinghistory                                                     => C4::Context->preference("intranetreadinghistory"),
             intranetstylesheet                                                         => C4::Context->preference("intranetstylesheet"),
             IntranetUserCSS                                                            => C4::Context->preference("IntranetUserCSS"),
-            intranetuserjs                                                             => C4::Context->preference("intranetuserjs"),
+            IntranetUserJS                                                             => C4::Context->preference("IntranetUserJS"),
             intranetbookbag                                                            => C4::Context->preference("intranetbookbag"),
             suggestion                                                                 => C4::Context->preference("suggestion"),
             virtualshelves                                                             => C4::Context->preference("virtualshelves"),
@@ -416,6 +422,7 @@ sub get_template_and_user {
             EnableBorrowerFiles                                                        => C4::Context->preference('EnableBorrowerFiles'),
             UseKohaPlugins                                                             => C4::Context->preference('UseKohaPlugins'),
             UseCourseReserves                                                          => C4::Context->preference("UseCourseReserves"),
+            useDischarge                                                               => C4::Context->preference('useDischarge'),
         );
     }
     else {
@@ -459,7 +466,7 @@ sub get_template_and_user {
             $opac_base_url = $ENV{'SERVER_NAME'} . ( $ENV{'SERVER_PORT'} eq ( $using_https ? "443" : "80" ) ? '' : ":$ENV{'SERVER_PORT'}" );
         }
         $template->param(
-            opaccolorstylesheet                   => C4::Context->preference("opaccolorstylesheet"),
+            OpacAdditionalStylesheet                   => C4::Context->preference("OpacAdditionalStylesheet"),
             AnonSuggestions                       => "" . C4::Context->preference("AnonSuggestions"),
             AuthorisedValueImages                 => C4::Context->preference("AuthorisedValueImages"),
             BranchesLoop                          => GetBranchesLoop($opac_name),
@@ -471,7 +478,6 @@ sub get_template_and_user {
             OPACAmazonCoverImages                 => C4::Context->preference("OPACAmazonCoverImages"),
             OPACFRBRizeEditions                   => C4::Context->preference("OPACFRBRizeEditions"),
             OpacHighlightedWords                  => C4::Context->preference("OpacHighlightedWords"),
-            OPACItemHolds                         => C4::Context->preference("OPACItemHolds"),
             OPACShelfBrowser                      => "" . C4::Context->preference("OPACShelfBrowser"),
             OPACURLOpenInNewWindow                => "" . C4::Context->preference("OPACURLOpenInNewWindow"),
             OPACUserCSS                           => "" . C4::Context->preference("OPACUserCSS"),
@@ -504,7 +510,7 @@ sub get_template_and_user {
             opacheader                            => "" . C4::Context->preference("opacheader"),
             opaclanguagesdisplay                  => "" . C4::Context->preference("opaclanguagesdisplay"),
             opacreadinghistory                    => C4::Context->preference("opacreadinghistory"),
-            opacuserjs                            => C4::Context->preference("opacuserjs"),
+            OPACUserJS                            => C4::Context->preference("OPACUserJS"),
             opacuserlogin                         => "" . C4::Context->preference("opacuserlogin"),
             ShowReviewer                          => C4::Context->preference("ShowReviewer"),
             ShowReviewerPhoto                     => C4::Context->preference("ShowReviewerPhoto"),
@@ -528,6 +534,7 @@ sub get_template_and_user {
             OPACLocalCoverImages                  => C4::Context->preference("OPACLocalCoverImages"),
             PatronSelfRegistration                => C4::Context->preference("PatronSelfRegistration"),
             PatronSelfRegistrationDefaultCategory => C4::Context->preference("PatronSelfRegistrationDefaultCategory"),
+            useDischarge                 => C4::Context->preference('useDischarge'),
         );
 
         $template->param( OpacPublic => '1' ) if ( $user || C4::Context->preference("OpacPublic") );
@@ -656,7 +663,7 @@ sub _version_check {
     # there is no DB version, it's a fresh install,
     # go to web installer
     # there is a DB version, compare it to the code version
-    my $kohaversion = C4::Context::KOHAVERSION;
+    my $kohaversion = Koha::version();
 
     # remove the 3 last . to have a Perl number
     $kohaversion =~ s/(.*\..*)\.(.*)\.(.*)/$1$2$3/;
@@ -665,7 +672,7 @@ sub _version_check {
         my $warning = "Database update needed, redirecting to %s. Database is $version and Koha is $kohaversion";
         if ( $type ne 'opac' ) {
             warn sprintf( $warning, 'Installer' );
-            print $query->redirect("/cgi-bin/koha/installer/install.pl?step=3");
+            print $query->redirect("/cgi-bin/koha/installer/install.pl?step=1&op=updatestructure");
         } else {
             warn sprintf( "OPAC: " . $warning, 'maintenance' );
             print $query->redirect("/cgi-bin/koha/maintenance.pl");
@@ -752,7 +759,7 @@ sub checkauth {
         my $s_userid = '';
         if ($session) {
             $s_userid = $session->param('id') // '';
-            C4::Context::set_userenv(
+            C4::Context->set_userenv(
                 $session->param('number'),       $s_userid,
                 $session->param('cardnumber'),   $session->param('firstname'),
                 $session->param('surname'),      $session->param('branch'),
@@ -770,7 +777,7 @@ sub checkauth {
             $sessiontype = $session->param('sessiontype') || '';
         }
         if ( ( $query->param('koha_login_context') && ( $q_userid ne $s_userid ) )
-            || ( $cas && $query->param('ticket') ) || ( $shib && $shib_login && !$logout ) ) {
+            || ( $cas && $query->param('ticket') && !C4::Context->userenv->{'id'} ) || ( $shib && $shib_login && !$logout ) ) {
 
             #if a user enters an id ne to the id in the current session, we need to log them in...
             #first we need to clear the anonymous session...
@@ -795,8 +802,8 @@ sub checkauth {
             $sessionID = undef;
             $userid    = undef;
 
-            if ( $cas and $caslogout ) {
-                logout_cas($query);
+            if ($cas and $caslogout) {
+                logout_cas($query, $type);
             }
 
             # If we are in a shibboleth session (shibboleth is enabled, a shibboleth match attribute is set and matches koha matchpoint)
@@ -820,7 +827,7 @@ sub checkauth {
             $userid    = undef;
             $sessionID = undef;
         }
-        elsif ( $ip ne $ENV{'REMOTE_ADDR'} ) {
+        elsif ( C4::Context->preference('SessionRestrictionByIP') && $ip ne $ENV{'REMOTE_ADDR'} ) {
 
             # Different ip than originally logged in from
             $info{'oldip'}        = $ip;
@@ -903,7 +910,7 @@ sub checkauth {
                 if ( $cas && $query->param('ticket') ) {
                     my $retuserid;
                     ( $return, $cardnumber, $retuserid ) =
-                      checkpw( $dbh, $userid, $password, $query );
+                      checkpw( $dbh, $userid, $password, $query, $type );
                     $userid = $retuserid;
                     $info{'invalidCasLogin'} = 1 unless ($return);
                 }
@@ -964,10 +971,13 @@ sub checkauth {
                 else {
                     my $retuserid;
                     ( $return, $cardnumber, $retuserid ) =
-                      checkpw( $dbh, $userid, $password, $query );
+                      checkpw( $dbh, $userid, $password, $query, $type );
                     $userid = $retuserid if ($retuserid);
                     $info{'invalid_username_or_password'} = 1 unless ($return);
-                } }
+                }
+            }
+
+            # $return: 1 = valid user, 2 = superlibrarian
             if ($return) {
 
                 #_session_log(sprintf "%20s from %16s logged in  at %30s.\n", $userid,$ENV{'REMOTE_ADDR'},(strftime '%c', localtime));
@@ -1081,7 +1091,7 @@ sub checkauth {
                 if ($persona) {
                     $session->param( 'persona', 1 );
                 }
-                C4::Context::set_userenv(
+                C4::Context->set_userenv(
                     $session->param('number'),       $session->param('id'),
                     $session->param('cardnumber'),   $session->param('firstname'),
                     $session->param('surname'),      $session->param('branch'),
@@ -1091,13 +1101,17 @@ sub checkauth {
                 );
 
             }
+            # $return: 0 = invalid user
+            # reset to anonymous session
             else {
+                $debug and warn "Login failed, resetting anonymous session...";
                 if ($userid) {
                     $info{'invalid_username_or_password'} = 1;
                     C4::Context->_unset_userenv($sessionID);
                 }
                 $session->param( 'lasttime', time() );
                 $session->param( 'ip',       $session->remote_addr() );
+                $session->param( 'sessiontype', 'anon' );
             }
         }    # END if ( $userid    = $query->param('userid') )
         elsif ( $type eq "opac" ) {
@@ -1149,12 +1163,13 @@ sub checkauth {
     my $template = C4::Templates::gettemplate( $template_name, $type, $query );
     $template->param(
         branchloop                            => GetBranchesLoop(),
-        opaccolorstylesheet                   => C4::Context->preference("opaccolorstylesheet"),
+        OpacAdditionalStylesheet                   => C4::Context->preference("OpacAdditionalStylesheet"),
         opaclayoutstylesheet                  => C4::Context->preference("opaclayoutstylesheet"),
         login                                 => 1,
         INPUTS                                => \@inputs,
         casAuthentication                     => C4::Context->preference("casAuthentication"),
         shibbolethAuthentication              => $shib,
+        SessionRestrictionByIP                => C4::Context->preference("SessionRestrictionByIP"),
         suggestion                            => C4::Context->preference("suggestion"),
         virtualshelves                        => C4::Context->preference("virtualshelves"),
         LibraryName                           => "" . C4::Context->preference("LibraryName"),
@@ -1167,7 +1182,7 @@ sub checkauth {
         OpacFavicon                           => C4::Context->preference("OpacFavicon"),
         opacreadinghistory                    => C4::Context->preference("opacreadinghistory"),
         opaclanguagesdisplay                  => C4::Context->preference("opaclanguagesdisplay"),
-        opacuserjs                            => C4::Context->preference("opacuserjs"),
+        OPACUserJS                            => C4::Context->preference("OPACUserJS"),
         opacbookbag                           => "" . C4::Context->preference("opacbookbag"),
         OpacCloud                             => C4::Context->preference("OpacCloud"),
         OpacTopissue                          => C4::Context->preference("OpacTopissue"),
@@ -1181,7 +1196,7 @@ sub checkauth {
         intranetbookbag                       => C4::Context->preference("intranetbookbag"),
         IntranetNav                           => C4::Context->preference("IntranetNav"),
         IntranetFavicon                       => C4::Context->preference("IntranetFavicon"),
-        intranetuserjs                        => C4::Context->preference("intranetuserjs"),
+        IntranetUserJS                        => C4::Context->preference("IntranetUserJS"),
         IndependentBranches                   => C4::Context->preference("IndependentBranches"),
         AutoLocation                          => C4::Context->preference("AutoLocation"),
         wrongip                               => $info{'wrongip'},
@@ -1195,6 +1210,7 @@ sub checkauth {
     $template->param( loginprompt => 1 ) unless $info{'nopermission'};
 
     if ( $type eq 'opac' ) {
+        require C4::VirtualShelves;
         my ( $total, $pubshelves ) = C4::VirtualShelves::GetSomeShelfNames( undef, 'MASTHEAD' );
         $template->param(
             pubshelves     => $total->{pubtotal},
@@ -1209,14 +1225,14 @@ sub checkauth {
             my $casservers = C4::Auth_with_cas::getMultipleAuth();
             my @tmplservers;
             foreach my $key ( keys %$casservers ) {
-                push @tmplservers, { name => $key, value => login_cas_url( $query, $key ) . "?cas=$key" };
+                push @tmplservers, { name => $key, value => login_cas_url( $query, $key, $type ) . "?cas=$key" };
             }
             $template->param(
                 casServersLoop => \@tmplservers
             );
         } else {
             $template->param(
-                casServerUrl => login_cas_url($query),
+                casServerUrl => login_cas_url($query, undef, $type),
             );
         }
 
@@ -1296,7 +1312,7 @@ sub check_api_auth {
         # database has not been installed yet
         return ( "maintenance", undef, undef );
     }
-    my $kohaversion = C4::Context::KOHAVERSION;
+    my $kohaversion = Koha::version();
     $kohaversion =~ s/(.*\..*)\.(.*)\.(.*)/$1$2$3/;
     if ( C4::Context->preference('Version') < $kohaversion ) {
 
@@ -1325,7 +1341,7 @@ sub check_api_auth {
         my $session = get_session($sessionID);
         C4::Context->_new_userenv($sessionID);
         if ($session) {
-            C4::Context::set_userenv(
+            C4::Context->set_userenv(
                 $session->param('number'),       $session->param('id'),
                 $session->param('cardnumber'),   $session->param('firstname'),
                 $session->param('surname'),      $session->param('branch'),
@@ -1345,7 +1361,7 @@ sub check_api_auth {
                 $userid    = undef;
                 $sessionID = undef;
                 return ( "expired", undef, undef );
-            } elsif ( $ip ne $ENV{'REMOTE_ADDR'} ) {
+            } elsif ( C4::Context->preference('SessionRestrictionByIP') && $ip ne $ENV{'REMOTE_ADDR'} ) {
 
                 # IP address changed
                 $session->delete();
@@ -1497,7 +1513,7 @@ sub check_api_auth {
                 $session->param( 'ip',           $session->remote_addr() );
                 $session->param( 'lasttime',     time() );
             }
-            C4::Context::set_userenv(
+            C4::Context->set_userenv(
                 $session->param('number'),       $session->param('id'),
                 $session->param('cardnumber'),   $session->param('firstname'),
                 $session->param('surname'),      $session->param('branch'),
@@ -1550,7 +1566,7 @@ sub check_cookie_auth {
         # database has not been installed yet
         return ( "maintenance", undef );
     }
-    my $kohaversion = C4::Context::KOHAVERSION;
+    my $kohaversion = Koha::version();
     $kohaversion =~ s/(.*\..*)\.(.*)\.(.*)/$1$2$3/;
     if ( C4::Context->preference('Version') < $kohaversion ) {
 
@@ -1578,7 +1594,7 @@ sub check_cookie_auth {
     my $session   = get_session($sessionID);
     C4::Context->_new_userenv($sessionID);
     if ($session) {
-        C4::Context::set_userenv(
+        C4::Context->set_userenv(
             $session->param('number'),       $session->param('id'),
             $session->param('cardnumber'),   $session->param('firstname'),
             $session->param('surname'),      $session->param('branch'),
@@ -1597,8 +1613,8 @@ sub check_cookie_auth {
             C4::Context->_unset_userenv($sessionID);
             $userid    = undef;
             $sessionID = undef;
-            return ( "expired", undef );
-        } elsif ( $ip ne $ENV{'REMOTE_ADDR'} ) {
+            return ("expired", undef);
+        } elsif ( C4::Context->preference('SessionRestrictionByIP') && $ip ne $ENV{'REMOTE_ADDR'} ) {
 
             # IP address changed
             $session->delete();
@@ -1663,7 +1679,8 @@ sub get_session {
 }
 
 sub checkpw {
-    my ( $dbh, $userid, $password, $query ) = @_;
+    my ( $dbh, $userid, $password, $query, $type ) = @_;
+    $type = 'opac' unless $type;
     if ($ldap) {
         $debug and print STDERR "## checkpw - checking LDAP\n";
         my ( $retval, $retcard, $retuserid ) = checkpw_ldap(@_);    # EXTERNAL AUTH
@@ -1677,7 +1694,7 @@ sub checkpw {
         # In case of a CAS authentication, we use the ticket instead of the password
         my $ticket = $query->param('ticket');
         $query->delete('ticket');                                   # remove ticket to come back to original URL
-        my ( $retval, $retcard, $retuserid ) = checkpw_cas( $dbh, $ticket, $query );    # EXTERNAL AUTH
+        my ( $retval, $retcard, $retuserid ) = checkpw_cas( $dbh, $ticket, $query, $type );    # EXTERNAL AUTH
         ($retval) and return ( $retval, $retcard, $retuserid );
         return 0;
     }
@@ -1725,35 +1742,35 @@ sub checkpw_internal {
 
     my $sth =
       $dbh->prepare(
-        "select password,cardnumber,borrowernumber,userid,firstname,surname,branchcode,flags from borrowers where userid=?"
+        "select password,cardnumber,borrowernumber,userid,firstname,surname,borrowers.branchcode,branches.branchname,flags from borrowers join branches on borrowers.branchcode=branches.branchcode where userid=?"
       );
     $sth->execute($userid);
     if ( $sth->rows ) {
         my ( $stored_hash, $cardnumber, $borrowernumber, $userid, $firstname,
-            $surname, $branchcode, $flags )
+            $surname, $branchcode, $branchname, $flags )
           = $sth->fetchrow;
 
         if ( checkpw_hash( $password, $stored_hash ) ) {
 
             C4::Context->set_userenv( "$borrowernumber", $userid, $cardnumber,
-                $firstname, $surname, $branchcode, $flags );
+                $firstname, $surname, $branchcode, $branchname, $flags );
             return 1, $cardnumber, $userid;
         }
     }
     $sth =
       $dbh->prepare(
-        "select password,cardnumber,borrowernumber,userid, firstname,surname,branchcode,flags from borrowers where cardnumber=?"
+        "select password,cardnumber,borrowernumber,userid,firstname,surname,borrowers.branchcode,branches.branchname,flags from borrowers join branches on borrowers.branchcode=branches.branchcode where cardnumber=?"
       );
     $sth->execute($userid);
     if ( $sth->rows ) {
         my ( $stored_hash, $cardnumber, $borrowernumber, $userid, $firstname,
-            $surname, $branchcode, $flags )
+            $surname, $branchcode, $branchname, $flags )
           = $sth->fetchrow;
 
         if ( checkpw_hash( $password, $stored_hash ) ) {
 
             C4::Context->set_userenv( $borrowernumber, $userid, $cardnumber,
-                $firstname, $surname, $branchcode, $flags );
+                $firstname, $surname, $branchcode, $branchname, $flags );
             return 1, $cardnumber, $userid;
         }
     }
@@ -1935,11 +1952,13 @@ sub haspermission {
         if ( $subperm eq '*' ) {
             return 0 unless ( $flags->{$module} == 1 or ref( $flags->{$module} ) );
         } else {
-            return 0 unless ( $flags->{$module} == 1 or
+            return 0 unless (
+                ( defined $flags->{$module} and
+                    $flags->{$module} == 1 )
+                or
                 ( ref( $flags->{$module} ) and
                     exists $flags->{$module}->{$subperm} and
-                    $flags->{$module}->{$subperm} == 1
-                )
+                    $flags->{$module}->{$subperm} == 1 )
             );
         }
     }