Bug 7310: Code changes for Improving list permissions
[koha.git] / C4 / Auth.pm
index b416449..0b737e7 100644 (file)
@@ -26,44 +26,40 @@ use CGI::Session;
 
 require Exporter;
 use C4::Context;
-use C4::Output;    # to get the template
-use C4::Members;
-use C4::Koha;
+use C4::Templates;    # to get the template
 use C4::Branch; # GetBranches
 use C4::VirtualShelves;
 use POSIX qw/strftime/;
+use List::MoreUtils qw/ any /;
 
 # use utf8;
-use vars qw($VERSION @ISA @EXPORT @EXPORT_OK %EXPORT_TAGS $debug $ldap $cas $caslogout $servers $memcached);
+use vars qw($VERSION @ISA @EXPORT @EXPORT_OK %EXPORT_TAGS $debug $ldap $cas $caslogout);
 
 BEGIN {
-    $VERSION = 3.02;        # set version for version checking
-    $debug = $ENV{DEBUG};
-    @ISA   = qw(Exporter);
-    @EXPORT    = qw(&checkauth &get_template_and_user &haspermission &get_user_subpermissions);
-    @EXPORT_OK = qw(&check_api_auth &get_session &check_cookie_auth &checkpw &get_all_subpermissions &get_user_subpermissions);
-    %EXPORT_TAGS = (EditPermissions => [qw(get_all_subpermissions get_user_subpermissions)]);
-    $ldap = C4::Context->config('useldapserver') || 0;
-    $cas = C4::Context->preference('casAuthentication');
-    $caslogout = C4::Context->preference('casLogout');
+    sub psgi_env { any { /^psgi\./ } keys %ENV }
+    sub safe_exit {
+       if ( psgi_env ) { die 'psgi:exit' }
+       else { exit }
+    }
+
+    $VERSION     = 3.02;                                                                                                            # set version for version checking
+    $debug       = $ENV{DEBUG};
+    @ISA         = qw(Exporter);
+    @EXPORT      = qw(&checkauth &get_template_and_user &haspermission &get_user_subpermissions);
+    @EXPORT_OK   = qw(&check_api_auth &get_session &check_cookie_auth &checkpw &get_all_subpermissions &get_user_subpermissions);
+    %EXPORT_TAGS = ( EditPermissions => [qw(get_all_subpermissions get_user_subpermissions)] );
+    $ldap        = C4::Context->config('useldapserver') || 0;
+    $cas         = C4::Context->preference('casAuthentication');
+    $caslogout   = C4::Context->preference('casLogout');
+    require C4::Auth_with_cas;             # no import
     if ($ldap) {
-        require C4::Auth_with_ldap;             # no import
-        import  C4::Auth_with_ldap qw(checkpw_ldap);
+       require C4::Auth_with_ldap;
+       import C4::Auth_with_ldap qw(checkpw_ldap);
     }
     if ($cas) {
-        require C4::Auth_with_cas;             # no import
-        import  C4::Auth_with_cas qw(checkpw_cas login_cas logout_cas login_cas_url);
-    }
-    $servers = C4::Context->config('memcached_servers');
-    if ($servers) {
-       require Cache::Memcached;
-        $memcached = Cache::Memcached->new({
-                                              servers => [ $servers ],
-                                              debug   => 0,
-                                              compress_threshold => 10_000,
-                                              namespace => C4::Context->config('memcached_namespace') || 'koha',
-                                          });
+        import  C4::Auth_with_cas qw(check_api_auth_cas checkpw_cas login_cas logout_cas login_cas_url);
     }
+
 }
 
 =head1 NAME
@@ -131,55 +127,53 @@ Output.pm module.
 
 my $SEARCH_HISTORY_INSERT_SQL =<<EOQ;
 INSERT INTO search_history(userid, sessionid, query_desc, query_cgi, total, time            )
-VALUES                    (     ?,         ?,          ?,         ?,     ?, FROM_UNIXTIME(?))
+VALUES                    (     ?,         ?,          ?,         ?,          ?, FROM_UNIXTIME(?))
 EOQ
 sub get_template_and_user {
     my $in       = shift;
     my $template =
-      gettemplate( $in->{'template_name'}, $in->{'type'}, $in->{'query'} );
-    my ( $user, $cookie, $sessionID, $flags ) = checkauth(
-        $in->{'query'},
-        $in->{'authnotrequired'},
-        $in->{'flagsrequired'},
-        $in->{'type'}
-    ) unless ($in->{'template_name'}=~/maintenance/);
+      C4::Templates::gettemplate( $in->{'template_name'}, $in->{'type'}, $in->{'query'} );
+    my ( $user, $cookie, $sessionID, $flags );
+    if ( $in->{'template_name'} !~m/maintenance/ ) {
+        ( $user, $cookie, $sessionID, $flags ) = checkauth(
+            $in->{'query'},
+            $in->{'authnotrequired'},
+            $in->{'flagsrequired'},
+            $in->{'type'}
+        );
+    }
 
     my $borrowernumber;
     my $insecure = C4::Context->preference('insecure');
     if ($user or $insecure) {
-
-        # load the template variables for stylesheets and JavaScript
-        $template->param( css_libs => $in->{'css_libs'} );
-        $template->param( css_module => $in->{'css_module'} );
-        $template->param( css_page => $in->{'css_page'} );
-        $template->param( css_widgets => $in->{'css_widgets'} );
-
-        $template->param( js_libs => $in->{'js_libs'} );
-        $template->param( js_module => $in->{'js_module'} );
-        $template->param( js_page => $in->{'js_page'} );
-        $template->param( js_widgets => $in->{'js_widgets'} );
+        # It's possible for $user to be the borrowernumber if they don't have a
+        # userid defined (and are logging in through some other method, such
+        # as SSL certs against an email address)
+        $borrowernumber = getborrowernumber($user) if defined($user);
+        if (!defined($borrowernumber) && defined($user)) {
+               my $borrower = GetMember(borrowernumber => $user);
+               if ($borrower) {
+               $borrowernumber = $user;
+                # A bit of a hack, but I don't know there's a nicer way
+                # to do it.
+                $user = $borrower->{firstname} . ' ' . $borrower->{surname};
+            }
+        }
 
         # user info
         $template->param( loggedinusername => $user );
         $template->param( sessionID        => $sessionID );
 
-        my ($total, $pubshelves, $barshelves) = C4::Context->get_shelves_userenv();
-        if (defined($pubshelves)) {
-            $template->param( pubshelves     => scalar @{$pubshelves},
-                              pubshelvesloop => $pubshelves,
-            );
-            $template->param( pubtotal   => $total->{'pubtotal'}, ) if ($total->{'pubtotal'} > scalar @{$pubshelves});
-        }
-        if (defined($barshelves)) {
-            $template->param( barshelves      => scalar @{$barshelves},
-                              barshelvesloop  => $barshelves,
-            );
-            $template->param( bartotal  => $total->{'bartotal'}, ) if ($total->{'bartotal'} > scalar @{$barshelves});
-        }
-
-        $borrowernumber = getborrowernumber($user) if defined($user);
+        my ($total, $pubshelves, $barshelves) = C4::VirtualShelves::GetSomeShelfNames($borrowernumber, 'MASTHEAD');
+        $template->param(
+            pubshelves     => $total->{pubtotal},
+            pubshelvesloop => $pubshelves,
+            barshelves      => $total->{bartotal},
+            barshelvesloop  => $barshelves,
+        );
 
-        my ( $borr ) = GetMemberDetails( $borrowernumber );
+        require C4::Members;
+        my ( $borr ) = C4::Members::GetMemberDetails( $borrowernumber );
         my @bordat;
         $bordat[0] = $borr;
         $template->param( "USER_INFO" => \@bordat );
@@ -267,7 +261,7 @@ sub get_template_and_user {
                                                       $_->{'query_cgi'},
                                                       $_->{'total'},
                                                       $_->{'time'},
-                                        ) foreach @recentSearches;
+                            ) foreach @recentSearches;
 
                                        # And then, delete the cookie's content
                                        my $newsearchcookie = $in->{'query'}->cookie(
@@ -282,27 +276,13 @@ sub get_template_and_user {
     }
        else {  # if this is an anonymous session, setup to display public lists...
 
-        # load the template variables for stylesheets and JavaScript
-        $template->param( css_libs => $in->{'css_libs'} );
-        $template->param( css_module => $in->{'css_module'} );
-        $template->param( css_page => $in->{'css_page'} );
-        $template->param( css_widgets => $in->{'css_widgets'} );
-
-        $template->param( js_libs => $in->{'js_libs'} );
-        $template->param( js_module => $in->{'js_module'} );
-        $template->param( js_page => $in->{'js_page'} );
-        $template->param( js_widgets => $in->{'js_widgets'} );
-
         $template->param( sessionID        => $sessionID );
         
-        my ($total, $pubshelves) = C4::Context->get_shelves_userenv();  # an anonymous user has no 'barshelves'...
-        if (defined $pubshelves) {
-            $template->param(   pubshelves      => scalar @{$pubshelves},
-                                pubshelvesloop  => $pubshelves,
-                            );
-            $template->param(   pubtotal        => $total->{'pubtotal'}, ) if ($total->{'pubtotal'} > scalar @{$pubshelves});
-        }
-
+        my ($total, $pubshelves) = C4::VirtualShelves::GetSomeShelfNames(undef, 'MASTHEAD');
+       $template->param(
+           pubshelves     => $total->{pubtotal},
+           pubshelvesloop => $pubshelves,
+       );
     }
        # Anonymous opac search history
        # If opac search history is enabled and at least one search has already been performed
@@ -335,6 +315,7 @@ sub get_template_and_user {
             "BiblioDefaultView".C4::Context->preference("BiblioDefaultView")         => 1,
             EnhancedMessagingPreferences => C4::Context->preference('EnhancedMessagingPreferences'),
             GoogleJackets                => C4::Context->preference("GoogleJackets"),
+           OpenLibraryCovers            => C4::Context->preference("OpenLibraryCovers"),
             KohaAdminEmailAddress        => "" . C4::Context->preference("KohaAdminEmailAddress"),
             LoginBranchcode              => (C4::Context->userenv?C4::Context->userenv->{"branch"}:"insecure"),
             LoginFirstname               => (C4::Context->userenv?C4::Context->userenv->{"firstname"}:"Bel"),
@@ -358,6 +339,7 @@ sub get_template_and_user {
             AmazonSimilarItems          => C4::Context->preference("AmazonSimilarItems"),
             AutoLocation                => C4::Context->preference("AutoLocation"),
             "BiblioDefaultView".C4::Context->preference("IntranetBiblioDefaultView") => 1,
+            CalendarFirstDayOfWeek      => (C4::Context->preference("CalendarFirstDayOfWeek") eq "Sunday")?0:1,
             CircAutocompl               => C4::Context->preference("CircAutocompl"),
             FRBRizeEditions             => C4::Context->preference("FRBRizeEditions"),
             IndependantBranches         => C4::Context->preference("IndependantBranches"),
@@ -378,6 +360,10 @@ sub get_template_and_user {
             virtualshelves              => C4::Context->preference("virtualshelves"),
             StaffSerialIssueDisplayCount => C4::Context->preference("StaffSerialIssueDisplayCount"),
             NoZebra                     => C4::Context->preference('NoZebra'),
+            EasyAnalyticalRecords       => C4::Context->preference('EasyAnalyticalRecords'),
+            LocalCoverImages            => C4::Context->preference('LocalCoverImages'),
+            OPACLocalCoverImages        => C4::Context->preference('OPACLocalCoverImages'),
+            AllowMultipleCovers         => C4::Context->preference('AllowMultipleCovers'),
         );
     }
     else {
@@ -386,6 +372,11 @@ sub get_template_and_user {
         my $LibraryNameTitle = C4::Context->preference("LibraryName");
         $LibraryNameTitle =~ s/<(?:\/?)(?:br|p)\s*(?:\/?)>/ /sgi;
         $LibraryNameTitle =~ s/<(?:[^<>'"]|'(?:[^']*)'|"(?:[^"]*)")*>//sg;
+        # clean up the busc param in the session if the page is not opac-detail
+        if ($in->{'template_name'} =~ /opac-(.+)\.(?:tt|tmpl)$/ && $1 !~ /^(?:MARC|ISBD)?detail$/) {
+            my $sessionSearch = get_session($sessionID || $in->{'query'}->cookie("CGISESSID"));
+            $sessionSearch->clear(["busc"]) if ($sessionSearch->param("busc"));
+        }
         # variables passed from CGI: opac_css_override and opac_search_limits.
         my $opac_search_limit = $ENV{'OPAC_SEARCH_LIMIT'};
         my $opac_limit_override = $ENV{'OPAC_LIMIT_OVERRIDE'};
@@ -409,6 +400,7 @@ sub get_template_and_user {
             AnonSuggestions           => "" . C4::Context->preference("AnonSuggestions"),
             AuthorisedValueImages     => C4::Context->preference("AuthorisedValueImages"),
             BranchesLoop              => GetBranchesLoop($opac_name),
+            CalendarFirstDayOfWeek      => (C4::Context->preference("CalendarFirstDayOfWeek") eq "Sunday")?0:1,
             LibraryName               => "" . C4::Context->preference("LibraryName"),
             LibraryNameTitle          => "" . $LibraryNameTitle,
             LoginBranchname           => C4::Context->userenv?C4::Context->userenv->{"branchname"}:"",
@@ -420,6 +412,7 @@ sub get_template_and_user {
             OpacHighlightedWords       => C4::Context->preference("OpacHighlightedWords"),
             OPACItemHolds             => C4::Context->preference("OPACItemHolds"),
             OPACShelfBrowser          => "". C4::Context->preference("OPACShelfBrowser"),
+            OpacShowRecentComments    => C4::Context->preference("OpacShowRecentComments"),
             OPACURLOpenInNewWindow    => "" . C4::Context->preference("OPACURLOpenInNewWindow"),
             OPACUserCSS               => "". C4::Context->preference("OPACUserCSS"),
             OPACViewOthersSuggestions => "" . C4::Context->preference("OPACViewOthersSuggestions"),
@@ -431,8 +424,10 @@ sub get_template_and_user {
             opac_limit_override       => $opac_limit_override,
             OpacBrowser               => C4::Context->preference("OpacBrowser"),
             OpacCloud                 => C4::Context->preference("OpacCloud"),
+            OpacKohaUrl               => C4::Context->preference("OpacKohaUrl"),
             OpacMainUserBlock         => "" . C4::Context->preference("OpacMainUserBlock"),
             OpacNav                   => "" . C4::Context->preference("OpacNav"),
+            OpacNavBottom             => "" . C4::Context->preference("OpacNavBottom"),
             OpacPasswordChange        => C4::Context->preference("OpacPasswordChange"),
             OPACPatronDetails        => C4::Context->preference("OPACPatronDetails"),
             OPACPrivacy               => C4::Context->preference("OPACPrivacy"),
@@ -455,6 +450,7 @@ sub get_template_and_user {
             opacuserlogin             => "" . C4::Context->preference("opacuserlogin"),
             reviewson                 => C4::Context->preference("reviewson"),
             ShowReviewer              => C4::Context->preference("ShowReviewer"),
+            ShowReviewerPhoto         => C4::Context->preference("ShowReviewerPhoto"),
             suggestion                => "" . C4::Context->preference("suggestion"),
             virtualshelves            => "" . C4::Context->preference("virtualshelves"),
             OPACSerialIssueDisplayCount => C4::Context->preference("OPACSerialIssueDisplayCount"),
@@ -473,11 +469,11 @@ sub get_template_and_user {
             SyndeticsAwards              => C4::Context->preference("SyndeticsAwards"),
             SyndeticsSeries              => C4::Context->preference("SyndeticsSeries"),
             SyndeticsCoverImageSize      => C4::Context->preference("SyndeticsCoverImageSize"),
+            OPACLocalCoverImages         => C4::Context->preference("OPACLocalCoverImages"),
         );
 
         $template->param(OpacPublic => '1') if ($user || C4::Context->preference("OpacPublic"));
     }
-       $template->param(listloop=>[{shelfname=>"Freelist", shelfnumber=>110}]);
     return ( $template, $borrowernumber, $cookie, $flags);
 }
 
@@ -567,19 +563,18 @@ sub _version_check ($$) {
     # and so we must redirect to OPAC maintenance page or to the WebInstaller
        # also, if OpacMaintenance is ON, OPAC should redirect to maintenance
        if (C4::Context->preference('OpacMaintenance') && $type eq 'opac') {
-               warn "OPAC Install required, redirecting to maintenance";
-               print $query->redirect("/cgi-bin/koha/maintenance.pl");
-       }
-    unless ($version = C4::Context->preference('Version')) {    # assignment, not comparison
-      if ($type ne 'opac') {
-        warn "Install required, redirecting to Installer";
-        print $query->redirect("/cgi-bin/koha/installer/install.pl");
-      }
-      else {
         warn "OPAC Install required, redirecting to maintenance";
         print $query->redirect("/cgi-bin/koha/maintenance.pl");
-      }
-      exit;
+    }
+    unless ( $version = C4::Context->preference('Version') ) {    # assignment, not comparison
+        if ( $type ne 'opac' ) {
+            warn "Install required, redirecting to Installer";
+            print $query->redirect("/cgi-bin/koha/installer/install.pl");
+        } else {
+            warn "OPAC Install required, redirecting to maintenance";
+            print $query->redirect("/cgi-bin/koha/maintenance.pl");
+        }
+        safe_exit;
     }
 
     # check that database and koha version are the same
@@ -599,7 +594,7 @@ sub _version_check ($$) {
             warn sprintf("OPAC: " . $warning, 'maintenance');
             print $query->redirect("/cgi-bin/koha/maintenance.pl");
         }
-        exit;
+        safe_exit;
     }
 }
 
@@ -634,6 +629,10 @@ sub checkauth {
     my ( $userid, $cookie, $sessionID, $flags, $barshelves, $pubshelves );
     my $logout = $query->param('logout.x');
 
+    # This parameter is the name of the CAS server we want to authenticate against,
+    # when using authentication against multiple CAS servers, as configured in Auth_cas_servers.yaml
+    my $casparam = $query->param('cas');
+
     if ( $userid = $ENV{'REMOTE_USER'} ) {
         # Using Basic Authentication, no cookies required
         $cookie = $query->cookie(
@@ -664,7 +663,8 @@ sub checkauth {
             $userid   = $session->param('id');
                        $sessiontype = $session->param('sessiontype');
         }
-        if ( ($query->param('koha_login_context')) && ($query->param('userid') ne $session->param('id')) ) {
+        if ( ( ($query->param('koha_login_context')) && ($query->param('userid') ne $session->param('id')) )
+          || ( $cas && $query->param('ticket') ) ) {
             #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...
             $debug and warn "query id = " . $query->param('userid') . " but session id = " . $session->param('id');
@@ -679,7 +679,7 @@ sub checkauth {
             $session->flush;
             $session->delete();
             C4::Context->_unset_userenv($sessionID);
-            _session_log(sprintf "%20s from %16s logged out at %30s (manually).\n", $userid,$ip,(strftime "%c",localtime));
+            #_session_log(sprintf "%20s from %16s logged out at %30s (manually).\n", $userid,$ip,(strftime "%c",localtime));
             $sessionID = undef;
             $userid    = undef;
 
@@ -692,7 +692,7 @@ sub checkauth {
             $info{'timed_out'} = 1;
             $session->delete();
             C4::Context->_unset_userenv($sessionID);
-            _session_log(sprintf "%20s from %16s logged out at %30s (inactivity).\n", $userid,$ip,(strftime "%c",localtime));
+            #_session_log(sprintf "%20s from %16s logged out at %30s (inactivity).\n", $userid,$ip,(strftime "%c",localtime));
             $userid    = undef;
             $sessionID = undef;
         }
@@ -703,7 +703,7 @@ sub checkauth {
             $info{'different_ip'} = 1;
             $session->delete();
             C4::Context->_unset_userenv($sessionID);
-            _session_log(sprintf "%20s from %16s logged out at %30s (ip changed to %16s).\n", $userid,$ip,(strftime "%c",localtime), $info{'newip'});
+            #_session_log(sprintf "%20s from %16s logged out at %30s (ip changed to %16s).\n", $userid,$ip,(strftime "%c",localtime), $info{'newip'});
             $sessionID = undef;
             $userid    = undef;
         }
@@ -722,26 +722,65 @@ sub checkauth {
     }
     unless ($userid || $sessionID) {
         #we initiate a session prior to checking for a username to allow for anonymous sessions...
-               my $session = get_session("") or die "Auth ERROR: Cannot get_session()";
+        my $session = get_session("") or die "Auth ERROR: Cannot get_session()";
         my $sessionID = $session->id;
-               C4::Context->_new_userenv($sessionID);
-        $cookie = $query->cookie(CGISESSID => $sessionID);
-           $userid    = $query->param('userid');
-           if ($cas || $userid) {
-               my $password = $query->param('password');
-               my ($return, $cardnumber);
-               if ($cas && $query->param('ticket')) {
-                   my $retuserid;
-                   ( $return, $cardnumber, $retuserid ) = checkpw( $dbh, $userid, $password, $query );
-                   $userid = $retuserid;
-                   $info{'invalidCasLogin'} = 1 unless ($return);
-               } else {
-                   my $retuserid;
-                   ( $return, $retuserid ) = checkpw( $dbh, $userid, $password, $query );
-                   $userid = $retuserid if ($retuserid ne '');
-               }
+        C4::Context->_new_userenv($sessionID);
+        $cookie = $query->cookie( CGISESSID => $sessionID );
+        $userid = $query->param('userid');
+        if (   ( $cas && $query->param('ticket') )
+            || $userid
+            || ( my $pki_field = C4::Context->preference('AllowPKIAuth') ) ne
+            'None' )
+        {
+            my $password = $query->param('password');
+            my ( $return, $cardnumber );
+            if ( $cas && $query->param('ticket') ) {
+                my $retuserid;
+                ( $return, $cardnumber, $retuserid ) =
+                  checkpw( $dbh, $userid, $password, $query );
+                $userid = $retuserid;
+                $info{'invalidCasLogin'} = 1 unless ($return);
+            }
+            elsif (
+                ( $pki_field eq 'Common Name' && $ENV{'SSL_CLIENT_S_DN_CN'} )
+                || (   $pki_field eq 'emailAddress'
+                    && $ENV{'SSL_CLIENT_S_DN_Email'} )
+              )
+            {
+                my $value;
+                if ( $pki_field eq 'Common Name' ) {
+                    $value = $ENV{'SSL_CLIENT_S_DN_CN'};
+                }
+                elsif ( $pki_field eq 'emailAddress' ) {
+                    $value = $ENV{'SSL_CLIENT_S_DN_Email'};
+
+              # If we're looking up the email, there's a chance that the person
+              # doesn't have a userid. So if there is none, we pass along the
+              # borrower number, and the bits of code that need to know the user
+              # ID will have to be smart enough to handle that.
+                    require C4::Members;
+                    my @users_info = C4::Members::GetBorrowersWithEmail($value);
+                    if (@users_info) {
+
+                        # First the userid, then the borrowernum
+                        $value = $users_info[0][1] || $users_info[0][0];
+                    } else {
+                        undef $value;
+                    }
+                }
+
+                # 0 for no user, 1 for normal, 2 for demo user.
+                $return = $value ? 1 : 0;
+                $userid = $value;
+            }
+            else {
+                my $retuserid;
+                ( $return, $cardnumber, $retuserid ) =
+                  checkpw( $dbh, $userid, $password, $query );
+                $userid = $retuserid if ( $retuserid ne '' );
+            }
                if ($return) {
-               _session_log(sprintf "%20s from %16s logged in  at %30s.\n", $userid,$ENV{'REMOTE_ADDR'},(strftime '%c', localtime));
+               #_session_log(sprintf "%20s from %16s logged in  at %30s.\n", $userid,$ENV{'REMOTE_ADDR'},(strftime '%c', localtime));
                if ( $flags = haspermission(  $userid, $flagsrequired ) ) {
                                        $loggedin = 1;
                }
@@ -749,127 +788,110 @@ sub checkauth {
                        $info{'nopermission'} = 1;
                        C4::Context->_unset_userenv($sessionID);
                }
-
-                               my ($borrowernumber, $firstname, $surname, $userflags,
-                                       $branchcode, $branchname, $branchprinter, $emailaddress);
-
-               if ( $return == 1 ) {
-                       my $select = "
-                       SELECT borrowernumber, firstname, surname, flags, borrowers.branchcode, 
-                           branches.branchname    as branchname, 
-                               branches.branchprinter as branchprinter, 
-                               email 
-                       FROM borrowers 
-                       LEFT JOIN branches on borrowers.branchcode=branches.branchcode
-                       ";
-                       my $sth = $dbh->prepare("$select where userid=?");
-                       $sth->execute($userid);
-                       unless ($sth->rows) {
-                           $debug and print STDERR "AUTH_1: no rows for userid='$userid'\n";
-                           $sth = $dbh->prepare("$select where cardnumber=?");
-                           $sth->execute($cardnumber);
-
-                           unless ($sth->rows) {
-                               $debug and print STDERR "AUTH_2a: no rows for cardnumber='$cardnumber'\n";
-                               $sth->execute($userid);
-                               unless ($sth->rows) {
-                                   $debug and print STDERR "AUTH_2b: no rows for userid='$userid' AS cardnumber\n";
-                               }
-                           }
-                       }
-                       if ($sth->rows) {
-                           ($borrowernumber, $firstname, $surname, $userflags,
-                               $branchcode, $branchname, $branchprinter, $emailaddress) = $sth->fetchrow;
-                                               $debug and print STDERR "AUTH_3 results: " .
-                                                       "$cardnumber,$borrowernumber,$userid,$firstname,$surname,$userflags,$branchcode,$emailaddress\n";
-                                       } else {
-                                               print STDERR "AUTH_3: no results for userid='$userid', cardnumber='$cardnumber'.\n";
-                                       }
+                my ($borrowernumber, $firstname, $surname, $userflags,
+                    $branchcode, $branchname, $branchprinter, $emailaddress);
+
+                if ( $return == 1 ) {
+                    my $select = "
+                    SELECT borrowernumber, firstname, surname, flags, borrowers.branchcode,
+                    branches.branchname    as branchname,
+                    branches.branchprinter as branchprinter,
+                    email
+                    FROM borrowers
+                    LEFT JOIN branches on borrowers.branchcode=branches.branchcode
+                    ";
+                    my $sth = $dbh->prepare("$select where userid=?");
+                    $sth->execute($userid);
+                    unless ($sth->rows) {
+                        $debug and print STDERR "AUTH_1: no rows for userid='$userid'\n";
+                        $sth = $dbh->prepare("$select where cardnumber=?");
+                        $sth->execute($cardnumber);
+
+                        unless ($sth->rows) {
+                            $debug and print STDERR "AUTH_2a: no rows for cardnumber='$cardnumber'\n";
+                            $sth->execute($userid);
+                            unless ($sth->rows) {
+                                $debug and print STDERR "AUTH_2b: no rows for userid='$userid' AS cardnumber\n";
+                            }
+                        }
+                    }
+                    if ($sth->rows) {
+                        ($borrowernumber, $firstname, $surname, $userflags,
+                            $branchcode, $branchname, $branchprinter, $emailaddress) = $sth->fetchrow;
+                        $debug and print STDERR "AUTH_3 results: " .
+                        "$cardnumber,$borrowernumber,$userid,$firstname,$surname,$userflags,$branchcode,$emailaddress\n";
+                    } else {
+                        print STDERR "AUTH_3: no results for userid='$userid', cardnumber='$cardnumber'.\n";
+                    }
 
 # launch a sequence to check if we have a ip for the branch, i
 # if we have one we replace the branchcode of the userenv by the branch bound in the ip.
 
-                                       my $ip       = $ENV{'REMOTE_ADDR'};
-                                       # if they specify at login, use that
-                                       if ($query->param('branch')) {
-                                               $branchcode  = $query->param('branch');
-                                               $branchname = GetBranchName($branchcode);
-                                       }
-                                       my $branches = GetBranches();
-                                       if (C4::Context->boolean_preference('IndependantBranches') && C4::Context->boolean_preference('Autolocation')){
-                                               # we have to check they are coming from the right ip range
-                                               my $domain = $branches->{$branchcode}->{'branchip'};
-                                               if ($ip !~ /^$domain/){
-                                                       $loggedin=0;
-                                                       $info{'wrongip'} = 1;
-                                               }
-                                       }
-
-                                       my @branchesloop;
-                                       foreach my $br ( keys %$branches ) {
-                                               #     now we work with the treatment of ip
-                                               my $domain = $branches->{$br}->{'branchip'};
-                                               if ( $domain && $ip =~ /^$domain/ ) {
-                                                       $branchcode = $branches->{$br}->{'branchcode'};
-
-                                                       # new op dev : add the branchprinter and branchname in the cookie
-                                                       $branchprinter = $branches->{$br}->{'branchprinter'};
-                                                       $branchname    = $branches->{$br}->{'branchname'};
-                                               }
-                                       }
-                                       $session->param('number',$borrowernumber);
-                                       $session->param('id',$userid);
-                                       $session->param('cardnumber',$cardnumber);
-                                       $session->param('firstname',$firstname);
-                                       $session->param('surname',$surname);
-                                       $session->param('branch',$branchcode);
-                                       $session->param('branchname',$branchname);
-                                       $session->param('flags',$userflags);
-                                       $session->param('emailaddress',$emailaddress);
-                                       $session->param('ip',$session->remote_addr());
-                                       $session->param('lasttime',time());
-                                       $debug and printf STDERR "AUTH_4: (%s)\t%s %s - %s\n", map {$session->param($_)} qw(cardnumber firstname surname branch) ;
-                               }
-                               elsif ( $return == 2 ) {
-                                       #We suppose the user is the superlibrarian
-                                       $borrowernumber = 0;
-                                       $session->param('number',0);
-                                       $session->param('id',C4::Context->config('user'));
-                                       $session->param('cardnumber',C4::Context->config('user'));
-                                       $session->param('firstname',C4::Context->config('user'));
-                                       $session->param('surname',C4::Context->config('user'));
-                                       $session->param('branch','NO_LIBRARY_SET');
-                                       $session->param('branchname','NO_LIBRARY_SET');
-                                       $session->param('flags',1);
-                                       $session->param('emailaddress', C4::Context->preference('KohaAdminEmailAddress'));
-                                       $session->param('ip',$session->remote_addr());
-                                       $session->param('lasttime',time());
-                               }
-                               C4::Context::set_userenv(
-                                       $session->param('number'),       $session->param('id'),
-                                       $session->param('cardnumber'),   $session->param('firstname'),
-                                       $session->param('surname'),      $session->param('branch'),
-                                       $session->param('branchname'),   $session->param('flags'),
-                                       $session->param('emailaddress'), $session->param('branchprinter')
-                               );
-
-                               # Grab borrower's shelves and public shelves and add them to the session
-                               # $row_count determines how many records are returned from the db query
-                               # and the number of lists to be displayed of each type in the 'Lists' button drop down
-                               my $row_count = 10; # FIXME:This probably should be a syspref
-                               my ($total, $totshelves, $barshelves, $pubshelves);
-                               ($barshelves, $totshelves) = C4::VirtualShelves::GetRecentShelves(1, $row_count, $borrowernumber);
-                               $total->{'bartotal'} = $totshelves;
-                               ($pubshelves, $totshelves) = C4::VirtualShelves::GetRecentShelves(2, $row_count, undef);
-                               $total->{'pubtotal'} = $totshelves;
-                               $session->param('barshelves', $barshelves);
-                               $session->param('pubshelves', $pubshelves);
-                               $session->param('totshelves', $total);
-
-                               C4::Context::set_shelves_userenv('bar',$barshelves);
-                               C4::Context::set_shelves_userenv('pub',$pubshelves);
-                               C4::Context::set_shelves_userenv('tot',$total);
-                       }
+                    my $ip       = $ENV{'REMOTE_ADDR'};
+                    # if they specify at login, use that
+                    if ($query->param('branch')) {
+                        $branchcode  = $query->param('branch');
+                        $branchname = GetBranchName($branchcode);
+                    }
+                    my $branches = GetBranches();
+                    if (C4::Context->boolean_preference('IndependantBranches') && C4::Context->boolean_preference('Autolocation')){
+                        # we have to check they are coming from the right ip range
+                        my $domain = $branches->{$branchcode}->{'branchip'};
+                        if ($ip !~ /^$domain/){
+                            $loggedin=0;
+                            $info{'wrongip'} = 1;
+                        }
+                    }
+
+                    my @branchesloop;
+                    foreach my $br ( keys %$branches ) {
+                        #     now we work with the treatment of ip
+                        my $domain = $branches->{$br}->{'branchip'};
+                        if ( $domain && $ip =~ /^$domain/ ) {
+                            $branchcode = $branches->{$br}->{'branchcode'};
+
+                            # new op dev : add the branchprinter and branchname in the cookie
+                            $branchprinter = $branches->{$br}->{'branchprinter'};
+                            $branchname    = $branches->{$br}->{'branchname'};
+                        }
+                    }
+                    $session->param('number',$borrowernumber);
+                    $session->param('id',$userid);
+                    $session->param('cardnumber',$cardnumber);
+                    $session->param('firstname',$firstname);
+                    $session->param('surname',$surname);
+                    $session->param('branch',$branchcode);
+                    $session->param('branchname',$branchname);
+                    $session->param('flags',$userflags);
+                    $session->param('emailaddress',$emailaddress);
+                    $session->param('ip',$session->remote_addr());
+                    $session->param('lasttime',time());
+                    $debug and printf STDERR "AUTH_4: (%s)\t%s %s - %s\n", map {$session->param($_)} qw(cardnumber firstname surname branch) ;
+                }
+                elsif ( $return == 2 ) {
+                    #We suppose the user is the superlibrarian
+                    $borrowernumber = 0;
+                    $session->param('number',0);
+                    $session->param('id',C4::Context->config('user'));
+                    $session->param('cardnumber',C4::Context->config('user'));
+                    $session->param('firstname',C4::Context->config('user'));
+                    $session->param('surname',C4::Context->config('user'));
+                    $session->param('branch','NO_LIBRARY_SET');
+                    $session->param('branchname','NO_LIBRARY_SET');
+                    $session->param('flags',1);
+                    $session->param('emailaddress', C4::Context->preference('KohaAdminEmailAddress'));
+                    $session->param('ip',$session->remote_addr());
+                    $session->param('lasttime',time());
+                }
+                C4::Context::set_userenv(
+                    $session->param('number'),       $session->param('id'),
+                    $session->param('cardnumber'),   $session->param('firstname'),
+                    $session->param('surname'),      $session->param('branch'),
+                    $session->param('branchname'),   $session->param('flags'),
+                    $session->param('emailaddress'), $session->param('branchprinter')
+                );
+
+            }
                else {
                if ($userid) {
                        $info{'invalid_username_or_password'} = 1;
@@ -882,16 +904,6 @@ sub checkauth {
             # anonymous sessions are created only for the OPAC
                        $debug and warn "Initiating an anonymous session...";
 
-                       # Grab the public shelves and add to the session...
-                       my $row_count = 20; # FIXME:This probably should be a syspref
-                       my ($total, $totshelves, $pubshelves);
-                       ($pubshelves, $totshelves) = C4::VirtualShelves::GetRecentShelves(2, $row_count, undef);
-                       $total->{'pubtotal'} = $totshelves;
-                       $session->param('pubshelves', $pubshelves);
-                       $session->param('totshelves', $total);
-                       C4::Context::set_shelves_userenv('pub',$pubshelves);
-                       C4::Context::set_shelves_userenv('tot',$total);
-
                        # setting a couple of other session vars...
                        $session->param('ip',$session->remote_addr());
                        $session->param('lasttime',time());
@@ -931,7 +943,7 @@ sub checkauth {
     }
 
     my $template_name = ( $type eq 'opac' ) ? 'opac-auth.tmpl' : 'auth.tmpl';
-    my $template = gettemplate( $template_name, $type, $query );
+    my $template = C4::Templates::gettemplate( $template_name, $type, $query );
     $template->param(branchloop => \@branch_loop,);
     my $checkstyle = C4::Context->preference("opaccolorstylesheet");
     if ($checkstyle =~ /\//)
@@ -951,6 +963,7 @@ sub checkauth {
         LibraryName          => C4::Context->preference("LibraryName"),
         opacuserlogin        => C4::Context->preference("opacuserlogin"),
         OpacNav              => C4::Context->preference("OpacNav"),
+        OpacNavBottom        => C4::Context->preference("OpacNavBottom"),
         opaccredits          => C4::Context->preference("opaccredits"),
         OpacFavicon          => C4::Context->preference("OpacFavicon"),
         opacreadinghistory   => C4::Context->preference("opacreadinghistory"),
@@ -981,11 +994,28 @@ sub checkauth {
     $template->param( OpacPublic => C4::Context->preference("OpacPublic"));
     $template->param( loginprompt => 1 ) unless $info{'nopermission'};
 
-    if ($cas) { 
+    if ($cas) {
+
+       # Is authentication against multiple CAS servers enabled?
+        if (C4::Auth_with_cas::multipleAuth && !$casparam) {
+           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" };
+           }
+           #warn Data::Dumper::Dumper(\@tmplservers);
+           $template->param(
+               casServersLoop => \@tmplservers
+           );
+       } else {
+        $template->param(
+            casServerUrl    => login_cas_url($query),
+           );
+       }
+
        $template->param(
-           casServerUrl    => login_cas_url(),
-           invalidCasLogin => $info{'invalidCasLogin'}
-       );
+            invalidCasLogin => $info{'invalidCasLogin'}
+        );
     }
 
     my $self_url = $query->url( -absolute => 1 );
@@ -1002,7 +1032,7 @@ sub checkauth {
         -cookie => $cookie
       ),
       $template->output;
-    exit;
+    safe_exit;
 }
 
 =head2 check_api_auth
@@ -1075,7 +1105,7 @@ sub check_api_auth {
     unless ($query->param('userid')) {
         $sessionID = $query->cookie("CGISESSID");
     }
-    if ($sessionID) {
+    if ($sessionID && not ($cas && $query->param('PT')) ) {
         my $session = get_session($sessionID);
         C4::Context->_new_userenv($sessionID);
         if ($session) {
@@ -1125,18 +1155,24 @@ sub check_api_auth {
         # new login
         my $userid = $query->param('userid');
         my $password = $query->param('password');
-        unless ($userid and $password) {
-            # caller did something wrong, fail the authenticateion
-            return ("failed", undef, undef);
-        }
-       my ($return, $cardnumber);
-       if ($cas && $query->param('ticket')) {
+               my ($return, $cardnumber);
+
+       # Proxy CAS auth
+       if ($cas && $query->param('PT')) {
            my $retuserid;
-           ( $return, $cardnumber, $retuserid ) = checkpw( $dbh, $userid, $password, $query );
-           $userid = $retuserid;
+           $debug and print STDERR "## check_api_auth - checking CAS\n";
+           # In case of a CAS authentication, we use the ticket instead of the password
+           my $PT = $query->param('PT');
+           ($return,$cardnumber,$userid) = check_api_auth_cas($dbh, $PT, $query);    # EXTERNAL AUTH
        } else {
+           # User / password auth
+           unless ($userid and $password) {
+               # caller did something wrong, fail the authenticateion
+               return ("failed", undef, undef);
+           }
            ( $return, $cardnumber ) = checkpw( $dbh, $userid, $password, $query );
        }
+
         if ($return and haspermission(  $userid, $flagsrequired)) {
             my $session = get_session("");
             return ("failed", undef, undef) unless $session;
@@ -1374,8 +1410,8 @@ sub get_session {
     elsif ($storage_method eq 'Pg') {
         $session = new CGI::Session("driver:PostgreSQL;serializer:yaml;id:md5", $sessionID, {Handle=>$dbh});
     }
-    elsif ($storage_method eq 'memcached' && $servers){
-       $session = new CGI::Session("driver:memcached;serializer:yaml;id:md5", $sessionID, { Memcached => $memcached } );
+    elsif ($storage_method eq 'memcached' && C4::Context->ismemcached){
+       $session = new CGI::Session("driver:memcached;serializer:yaml;id:md5", $sessionID, { Memcached => C4::Context->memcached } );
     }
     else {
         # catch all defaults to tmp should work on all systems
@@ -1389,11 +1425,11 @@ sub checkpw {
     my ( $dbh, $userid, $password, $query ) = @_;
     if ($ldap) {
         $debug and print "## checkpw - checking LDAP\n";
-        my ($retval,$retcard) = checkpw_ldap(@_);    # EXTERNAL AUTH
-        ($retval) and return ($retval,$retcard);
+        my ($retval,$retcard,$retuserid) = checkpw_ldap(@_);    # EXTERNAL AUTH
+        ($retval) and return ($retval,$retcard,$retuserid);
     }
 
-    if ($cas && $query->param('ticket')) {
+    if ($cas && $query && $query->param('ticket')) {
         $debug and print STDERR "## checkpw - checking CAS\n";
        # In case of a CAS authentication, we use the ticket instead of the password
        my $ticket = $query->param('ticket');
@@ -1416,7 +1452,7 @@ sub checkpw {
 
             C4::Context->set_userenv( "$borrowernumber", $userid, $cardnumber,
                 $firstname, $surname, $branchcode, $flags );
-            return 1, $userid;
+            return 1, $cardnumber, $userid;
         }
     }
     $sth =
@@ -1432,7 +1468,7 @@ sub checkpw {
 
             C4::Context->set_userenv( $borrowernumber, $userid, $cardnumber,
                 $firstname, $surname, $branchcode, $flags );
-            return 1, $userid;
+            return 1, $cardnumber, $userid;
         }
     }
     if (   $userid && $userid eq C4::Context->config('user')