adding XSLT for intranet (UNIMARC only, MARC21 will be done by kf)
[koha.git] / C4 / Auth.pm
old mode 100644 (file)
new mode 100755 (executable)
index 6058a6b..b96f796
@@ -1,7 +1,3 @@
-
-# -*- tab-width: 8 -*-
-# NOTE: This file uses 8-character tabs; do not change the tab size!
-
 package C4::Auth;
 
 # Copyright 2000-2002 Katipo Communications
@@ -23,6 +19,8 @@ package C4::Auth;
 
 use strict;
 use Digest::MD5 qw(md5_base64);
+use Storable qw(thaw freeze);
+use URI::Escape;
 use CGI::Session;
 
 require Exporter;
@@ -32,6 +30,7 @@ use C4::Members;
 use C4::Koha;
 use C4::Branch; # GetBranches
 use C4::VirtualShelves;
+use POSIX qw/strftime/;
 
 # use utf8;
 use vars qw($VERSION @ISA @EXPORT @EXPORT_OK %EXPORT_TAGS $debug $ldap);
@@ -40,7 +39,7 @@ BEGIN {
     $VERSION = 3.02;        # set version for version checking
     $debug = $ENV{DEBUG} || 0 ;
     @ISA   = qw(Exporter);
-    @EXPORT    = qw(&checkauth &get_template_and_user);
+    @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;
@@ -62,7 +61,7 @@ C4::Auth - Authenticates Koha users
 
   my $query = new CGI;
 
-  my ($template, $borrowernumber, $cookie) 
+  my ($template, $borrowernumber, $cookie)
     = get_template_and_user(
         {
             template_name   => "opac-main.tmpl",
@@ -164,11 +163,11 @@ sub get_template_and_user {
         my @bordat;
         $bordat[0] = $borr;
         $template->param( "USER_INFO" => \@bordat );
-        
+
         my $all_perms = get_all_subpermissions();
 
         my @flagroots = qw(circulate catalogue parameters borrowers permissions reserveforothers borrow
-                            editcatalogue updatecharges management tools editauthorities serials reports);
+                            editcatalogue updatecharges management tools editauthorities serials reports acquisition);
         # We are going to use the $flags returned by checkauth
         # to create the template's parameters that will indicate
         # which menus the user can access.
@@ -184,7 +183,7 @@ sub get_template_and_user {
             $template->param( CAN_user_updatecharges     => 1 );
             $template->param( CAN_user_acquisition      => 1 );
             $template->param( CAN_user_management       => 1 );
-            $template->param( CAN_user_tools            => 1 ); 
+            $template->param( CAN_user_tools            => 1 );
             $template->param( CAN_user_editauthorities  => 1 );
             $template->param( CAN_user_serials          => 1 );
             $template->param( CAN_user_reports          => 1 );
@@ -228,6 +227,58 @@ sub get_template_and_user {
                 }
             }
         }
+               # Logged-in opac search history
+               # If the requested template is an opac one and opac search history is enabled
+               if ($in->{'type'} == "opac" && C4::Context->preference('EnableOpacSearchHistory')) {
+                       my $dbh = C4::Context->dbh;
+                       my $query = "SELECT COUNT(*) FROM search_history WHERE userid=?";
+                       my $sth = $dbh->prepare($query);
+                       $sth->execute($borrowernumber);
+                       
+                       # If at least one search has already been performed
+                       if ($sth->fetchrow_array > 0) { 
+                       # We show the link in opac
+                       $template->param(ShowOpacRecentSearchLink => 1);
+                       }
+
+                       # And if there's a cookie with searches performed when the user was not logged in, 
+                       # we add them to the logged-in search history
+                       my @recentSearches;
+                       my $searchcookie = $in->{'query'}->cookie('KohaOpacRecentSearches');
+                       if ($searchcookie){
+                               $searchcookie = uri_unescape($searchcookie);
+                               if (thaw($searchcookie)) {
+                                       @recentSearches = @{thaw($searchcookie)};
+                               }
+
+                               if (@recentSearches > 0) {
+                                       my $query = "INSERT INTO search_history(userid, sessionid, query_desc, query_cgi, total, time) VALUES";
+                                       my $icount = 1;
+                                       foreach my $asearch (@recentSearches) {
+                                               $query .= "(";
+                                               $query .= $borrowernumber . ", ";
+                                               $query .= '"' . $in->{'query'}->cookie("CGISESSID") . "\", ";
+                                               $query .= '"' . $asearch->{'query_desc'} . "\", ";
+                                               $query .= '"' . $asearch->{'query_cgi'} . "\", ";
+                                               $query .=       $asearch->{'total'} . ", ";
+                                               $query .= 'FROM_UNIXTIME(' . $asearch->{'time'} . "))";
+                                               if ($icount < @recentSearches) { $query .= ", ";}
+                                               $icount++;
+                                       }
+
+                                       my $sth = $dbh->prepare($query);
+                                       $sth->execute;
+
+                                       # And then, delete the cookie's content
+                                       my $newsearchcookie = $in->{'query'}->cookie(
+                                                                                               -name => 'KohaOpacRecentSearches',
+                                                                                               -value => freeze([]),
+                                                                                               -expires => ''
+                                                                                        );
+                                       $cookie = [$cookie, $newsearchcookie];
+                               }
+                       }
+               }
     }
        else {  # if this is an anonymous session, setup to display public lists...
 
@@ -243,16 +294,27 @@ sub get_template_and_user {
         $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::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));
+        }
 
-       }
+    }
+       # Anonymous opac search history
+       # If opac search history is enabled and at least one search has already been performed
+       if (C4::Context->preference('EnableOpacSearchHistory') && $in->{'query'}->cookie('KohaOpacRecentSearches')) {
+           # We show the link in opac
+           if (thaw(uri_unescape($in->{'query'}->cookie('KohaOpacRecentSearches')))) {
+                       my @recentSearches = @{thaw(uri_unescape($in->{'query'}->cookie('KohaOpacRecentSearches')))};
+                       if (@recentSearches > 0) {
+                               $template->param(ShowOpacRecentSearchLink => 1);
+                       }
+           }
+       }
 
     # these template parameters are set the same regardless of $in->{'type'}
     $template->param(
@@ -265,10 +327,11 @@ sub get_template_and_user {
             LoginSurname                 => C4::Context->userenv?C4::Context->userenv->{"surname"}:"Inconnu",
             TagsEnabled                  => C4::Context->preference("TagsEnabled"),
             hide_marc                    => C4::Context->preference("hide_marc"),
-            dateformat                   => C4::Context->preference("dateformat"),
             'item-level_itypes'          => C4::Context->preference('item-level_itypes'),
             patronimages                 => C4::Context->preference("patronimages"),
             singleBranchMode             => C4::Context->preference("singleBranchMode"),
+            XSLTDetailsDisplay        => C4::Context->preference("XSLTDetailsDisplay"),
+            XSLTResultsDisplay        => C4::Context->preference("XSLTResultsDisplay"),
                  );
 
     if ( $in->{'type'} eq "intranet" ) {
@@ -291,16 +354,30 @@ sub get_template_and_user {
             intranetreadinghistory      => C4::Context->preference("intranetreadinghistory"),
             intranetstylesheet          => C4::Context->preference("intranetstylesheet"),
             intranetuserjs              => C4::Context->preference("intranetuserjs"),
+            intranetbookbag             => C4::Context->preference("intranetbookbag"),
             noItemTypeImages            => C4::Context->preference("noItemTypeImages"),
             suggestion                  => C4::Context->preference("suggestion"),
             virtualshelves              => C4::Context->preference("virtualshelves"),
+            StaffSerialIssueDisplayCount => C4::Context->preference("StaffSerialIssueDisplayCount"),
+            NoZebra                     => C4::Context->preference('NoZebra'),
         );
     }
     else {
         warn "template type should be OPAC, here it is=[" . $in->{'type'} . "]" unless ( $in->{'type'} eq 'opac' );
+        #TODO : replace LibraryName syspref with 'system name', and remove this html processing
         my $LibraryNameTitle = C4::Context->preference("LibraryName");
         $LibraryNameTitle =~ s/<(?:\/?)(?:br|p)\s*(?:\/?)>/ /sgi;
         $LibraryNameTitle =~ s/<(?:[^<>'"]|'(?:[^']*)'|"(?:[^"]*)")*>//sg;
+        # 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'};
+        my $mylibraryfirst = C4::Context->preference("SearchMyLibraryFirst");
+        my $opac_name;
+        if($opac_limit_override && ($opac_search_limit =~ /branch:(\w+)/) ){
+             $opac_name = C4::Branch::GetBranchName($1)   # opac_search_limit is a branch, so we use it.
+        } elsif($mylibraryfirst){
+            $opac_name = C4::Branch::GetBranchName($mylibraryfirst);
+        }
         $template->param(
             AmazonContent             => "" . C4::Context->preference("AmazonContent"),
             AnonSuggestions           => "" . C4::Context->preference("AnonSuggestions"),
@@ -316,28 +393,32 @@ sub get_template_and_user {
             OPACUserCSS               => "". C4::Context->preference("OPACUserCSS"),
             OPACViewOthersSuggestions => "" . C4::Context->preference("OPACViewOthersSuggestions"),
             OpacAuthorities           => C4::Context->preference("OpacAuthorities"),
-            OPACBaseURL               => ($in->{'query'}->https() ? "https://" : "http://") .
-                   $ENV{'SERVER_NAME'} .
+            OPACBaseURL               => ($in->{'query'}->https() ? "https://" : "http://") . $ENV{'SERVER_NAME'} .
                    ($ENV{'SERVER_PORT'} eq ($in->{'query'}->https() ? "443" : "80") ? '' : ":$ENV{'SERVER_PORT'}"),
+            opac_name             => $opac_name,
+            opac_css_override           => $ENV{'OPAC_CSS_OVERRIDE'},
+            opac_search_limit         => $opac_search_limit,
+            opac_limit_override       => $opac_limit_override,
             OpacBrowser               => C4::Context->preference("OpacBrowser"),
             OpacCloud                 => C4::Context->preference("OpacCloud"),
             OpacMainUserBlock         => "" . C4::Context->preference("OpacMainUserBlock"),
             OpacNav                   => "" . C4::Context->preference("OpacNav"),
             OpacPasswordChange        => C4::Context->preference("OpacPasswordChange"),
+            OPACPatronDetails        => C4::Context->preference("OPACPatronDetails"),
+            OPACFinesTab              => C4::Context->preference("OPACFinesTab"),
             OpacTopissue              => C4::Context->preference("OpacTopissue"),
             RequestOnOpac             => C4::Context->preference("RequestOnOpac"),
             TemplateEncoding          => "". C4::Context->preference("TemplateEncoding"),
             'Version'                 => C4::Context->preference('Version'),
-            XSLTDetailsDisplay        => C4::Context->preference("XSLTDetailsDisplay"),
-            XSLTResultsDisplay        => C4::Context->preference("XSLTResultsDisplay"),
             hidelostitems             => C4::Context->preference("hidelostitems"),
-            mylibraryfirst            => C4::Context->preference("SearchMyLibraryFirst"),
+            mylibraryfirst            => (C4::Context->preference("SearchMyLibraryFirst") && C4::Context->userenv) ? C4::Context->userenv->{'branch'} : '',
+            opaclayoutstylesheet      => "" . C4::Context->preference("opaclayoutstylesheet"),
+            opaccolorstylesheet       => "" . C4::Context->preference("opaccolorstylesheet"),
+            opacstylesheet            => "" . C4::Context->preference("opacstylesheet"),
             opacbookbag               => "" . C4::Context->preference("opacbookbag"),
-            opaccolorstylesheet       => "". C4::Context->preference("opaccolorstylesheet"),
             opaccredits               => "" . C4::Context->preference("opaccredits"),
             opacheader                => "" . C4::Context->preference("opacheader"),
-            opaclanguagesdisplay      => "". C4::Context->preference("opaclanguagesdisplay"),
-            opaclayoutstylesheet      => "". C4::Context->preference("opaclayoutstylesheet"),
+            opaclanguagesdisplay      => "" . C4::Context->preference("opaclanguagesdisplay"),
             opacreadinghistory        => C4::Context->preference("opacreadinghistory"),
             opacsmallimage            => "" . C4::Context->preference("opacsmallimage"),
             opacuserjs                => C4::Context->preference("opacuserjs"),
@@ -345,6 +426,7 @@ sub get_template_and_user {
             reviewson                 => C4::Context->preference("reviewson"),
             suggestion                => "" . C4::Context->preference("suggestion"),
             virtualshelves            => "" . C4::Context->preference("virtualshelves"),
+                       OPACSerialIssueDisplayCount => C4::Context->preference("OPACSerialIssueDisplayCount"),
         );
     }
        $template->param(listloop=>[{shelfname=>"Freelist", shelfnumber=>110}]);
@@ -419,7 +501,7 @@ user has authenticated, C<&checkauth> restarts the original script
 
 The login page is provided using a HTML::Template, which is set in the
 systempreferences table or at the top of this file. The variable C<$type>
-selects which template to use, either the opac or the intranet 
+selects which template to use, either the opac or the intranet
 authentification template.
 
 C<&checkauth> returns a user ID, a cookie, and a session ID. The
@@ -443,7 +525,7 @@ sub _version_check ($$) {
       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");
@@ -467,7 +549,7 @@ sub _version_check ($$) {
         } else {
             warn sprintf("OPAC: " . $warning, 'maintenance');
             print $query->redirect("/cgi-bin/koha/maintenance.pl");
-        }       
+        }
         exit;
     }
 }
@@ -512,7 +594,7 @@ sub checkauth {
         );
         $loggedin = 1;
     }
-    elsif ( $sessionID = $query->cookie("CGISESSID")) {     # assignment, not comparison 
+    elsif ( $sessionID = $query->cookie("CGISESSID")) {     # assignment, not comparison
         my $session = get_session($sessionID);
         C4::Context->_new_userenv($sessionID);
         my ($ip, $lasttime, $sessiontype);
@@ -534,10 +616,10 @@ sub checkauth {
                        $sessiontype = $session->param('sessiontype');
         }
    
-               if ( ($query->param('koha_login_context')) && ($query->param('userid') ne $session->param('id')) ) {
-                       #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');
+        if ( ($query->param('koha_login_context')) && ($query->param('userid') ne $session->param('id')) ) {
+            #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');
             $session->flush;      
             $session->delete();
             C4::Context->_unset_userenv($sessionID);
@@ -546,45 +628,45 @@ sub checkauth {
                }
         elsif ($logout) {
             # voluntary logout the user
-            $session->flush;      
+            $session->flush;
             $session->delete();
             C4::Context->_unset_userenv($sessionID);
-            _session_log(sprintf "%20s from %16s logged out at %30s (manually).\n", $userid,$ip,localtime);
+            _session_log(sprintf "%20s from %16s logged out at %30s (manually).\n", $userid,$ip,(strftime "%c",localtime));
             $sessionID = undef;
             $userid    = undef;
         }
-               elsif ( $lasttime < time() - $timeout ) {
-                       # timed logout
-                       $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,localtime);
-                       $userid    = undef;
-                       $sessionID = undef;
-               }
-               elsif ( $ip ne $ENV{'REMOTE_ADDR'} ) {
-                       # Different ip than originally logged in from
-                       $info{'oldip'}        = $ip;
-                       $info{'newip'}        = $ENV{'REMOTE_ADDR'};
-                       $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,localtime, $info{'newip'});
-                       $sessionID = undef;
-                       $userid    = undef;
-               }
-               else {
-                       $cookie = $query->cookie( CGISESSID => $session->id );
-                       $session->param('lasttime',time());
-                       unless ( $sessiontype eq 'anon' ) {     #if this is an anonymous session, we want to update the session, but not behave as if they are logged in...
-                               $flags = haspermission( $dbh, $userid, $flagsrequired );
-                               if ($flags) {
-                                       $loggedin = 1;
-                               } else {
-                                       $info{'nopermission'} = 1;
-                               }
-                       }
-               }
+        elsif ( $lasttime < time() - $timeout ) {
+            # timed logout
+            $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));
+            $userid    = undef;
+            $sessionID = undef;
+        }
+        elsif ( $ip ne $ENV{'REMOTE_ADDR'} ) {
+            # Different ip than originally logged in from
+            $info{'oldip'}        = $ip;
+            $info{'newip'}        = $ENV{'REMOTE_ADDR'};
+            $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'});
+            $sessionID = undef;
+            $userid    = undef;
+        }
+        else {
+            $cookie = $query->cookie( CGISESSID => $session->id );
+            $session->param('lasttime',time());
+            unless ( $sessiontype eq 'anon' ) { #if this is an anonymous session, we want to update the session, but not behave as if they are logged in...
+                $flags = haspermission($userid, $flagsrequired);
+                if ($flags) {
+                    $loggedin = 1;
+                } else {
+                    $info{'nopermission'} = 1;
+                }
+            }
+        }
     }
     unless ($userid || $sessionID) {
         #we initiate a session prior to checking for a username to allow for anonymous sessions...
@@ -592,53 +674,53 @@ sub checkauth {
         my $sessionID = $session->id;
                C4::Context->_new_userenv($sessionID);
         $cookie = $query->cookie(CGISESSID => $sessionID);
-               if ( $userid    = $query->param('userid') ) {
-               my $password = $query->param('password');
-               my ( $return, $cardnumber ) = checkpw( $dbh, $userid, $password );
-               if ($return) {
-               _session_log(sprintf "%20s from %16s logged in  at %30s.\n", $userid,$ENV{'REMOTE_ADDR'},localtime);
-               if ( $flags = haspermission( $dbh, $userid, $flagsrequired ) ) {
-                                       $loggedin = 1;
-               }
-                       else {
-                       $info{'nopermission'} = 1;
-                       C4::Context->_unset_userenv($sessionID);
-               }
+        if ( $userid    = $query->param('userid') ) {
+            my $password = $query->param('password');
+            my ( $return, $cardnumber ) = checkpw( $dbh, $userid, $password );
+            if ($return) {
+                _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;
+                }
+                else {
+                    $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.
@@ -719,7 +801,7 @@ sub checkauth {
                                $session->param('barshelves', $barshelves->[0]);
                                $session->param('pubshelves', $pubshelves->[0]);
                                $session->param('totshelves', $total);
-                               
+
                                C4::Context::set_shelves_userenv('bar',$barshelves->[0]);
                                C4::Context::set_shelves_userenv('pub',$pubshelves->[0]);
                                C4::Context::set_shelves_userenv('tot',$total);
@@ -731,7 +813,7 @@ sub checkauth {
                }
                        }
         }      # END if ( $userid    = $query->param('userid') )
-               elsif ($type eq "opac") {       
+               elsif ($type eq "opac") {
             # if we are here this is an anonymous session; add public lists to it and a few other items...
             # anonymous sessions are created only for the OPAC
                        $debug and warn "Initiating an anonymous session...";
@@ -745,7 +827,7 @@ sub checkauth {
                        $session->param('totshelves', $total);
                        C4::Context::set_shelves_userenv('pub',$pubshelves->[0]);
                        C4::Context::set_shelves_userenv('tot',$total);
-                       
+
                        # setting a couple of other session vars...
                        $session->param('ip',$session->remote_addr());
                        $session->param('lasttime',time());
@@ -769,7 +851,7 @@ sub checkauth {
 # AUTH rejected, show the login/password template, after checking the DB.
 #
 #
-    
+
     # get the inputs from the incoming query
     my @inputs = ();
     foreach my $name ( param $query) {
@@ -813,6 +895,7 @@ sub checkauth {
         intranetcolorstylesheet =>
                                                                C4::Context->preference("intranetcolorstylesheet"),
         intranetstylesheet => C4::Context->preference("intranetstylesheet"),
+        intranetbookbag    => C4::Context->preference("intranetbookbag"),
         IntranetNav        => C4::Context->preference("IntranetNav"),
         intranetuserjs     => C4::Context->preference("intranetuserjs"),
         TemplateEncoding   => C4::Context->preference("TemplateEncoding"),
@@ -820,7 +903,6 @@ sub checkauth {
         AutoLocation       => C4::Context->preference("AutoLocation"),
                wrongip            => $info{'wrongip'}
     );
-    
     $template->param( loginprompt => 1 ) unless $info{'nopermission'};
 
     my $self_url = $query->url( -absolute => 1 );
@@ -942,7 +1024,7 @@ sub check_api_auth {
             } else {
                 my $cookie = $query->cookie( CGISESSID => $session->id );
                 $session->param('lasttime',time());
-                my $flags = haspermission( $dbh, $userid, $flagsrequired );
+                my $flags = haspermission($userid, $flagsrequired);
                 if ($flags) {
                     return ("ok", $cookie, $sessionID);
                 } else {
@@ -958,14 +1040,14 @@ sub check_api_auth {
         }
     } else {
         # new login
-        my $userid = $query->param('userid');   
-        my $password = $query->param('password');   
+        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 ) = checkpw( $dbh, $userid, $password );
-        if ($return and haspermission( $dbh, $userid, $flagsrequired)) {
+        if ($return and haspermission($userid, $flagsrequired)) {
             my $session = get_session("");
             return ("failed", undef, undef) unless $session;
 
@@ -1052,7 +1134,7 @@ sub check_api_auth {
                 $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'),
@@ -1064,7 +1146,7 @@ sub check_api_auth {
         } else {
             return ("failed", undef, undef);
         }
-    } 
+    }
 }
 
 =item check_cookie_auth
@@ -1160,7 +1242,7 @@ sub check_cookie_auth {
             return ("expired", undef);
         } else {
             $session->param('lasttime',time());
-            my $flags = haspermission( $dbh, $userid, $flagsrequired );
+            my $flags = haspermission($userid, $flagsrequired);
             if ($flags) {
                 return ("ok", $sessionID);
             } else {
@@ -1182,7 +1264,7 @@ sub check_cookie_auth {
   my $session = get_session($sessionID);
 
 Given a session ID, retrieve the CGI::Session object used to store
-the session's state.  The session object can be used to store 
+the session's state.  The session object can be used to store
 data that needs to be accessed by different scripts during a
 user's session.
 
@@ -1273,10 +1355,12 @@ sub checkpw {
 
 =item getuserflags
 
- $authflags = getuserflags($flags,$dbh);
+    my $authflags = getuserflags($flags, $userid, [$dbh]);
+
 Translates integer flags into permissions strings hash.
 
 C<$flags> is the integer userflags value ( borrowers.userflags )
+C<$userid> is the members.userid, used for building subpermissions
 C<$authflags> is a hashref of permissions
 
 =cut
@@ -1284,7 +1368,7 @@ C<$authflags> is a hashref of permissions
 sub getuserflags {
     my $flags   = shift;
     my $userid  = shift;
-    my $dbh     = shift;
+    my $dbh     = @_ ? shift : C4::Context->dbh;
     my $userflags;
     $flags = 0 unless $flags;
     my $sth = $dbh->prepare("SELECT bit, flag, defaulton FROM userflags");
@@ -1309,7 +1393,7 @@ sub getuserflags {
     return $userflags;
 }
 
-=item get_user_subpermissions 
+=item get_user_subpermissions
 
 =over 4
 
@@ -1318,10 +1402,10 @@ my $user_perm_hashref = get_user_subpermissions($userid);
 =back
 
 Given the userid (note, not the borrowernumber) of a staff user,
-return a hashref of hashrefs of the specific subpermissions 
+return a hashref of hashrefs of the specific subpermissions
 accorded to the user.  An example return is
 
-{ 
+{
     tools => {
         export_catalog => 1,
         import_patrons => 1,
@@ -1342,7 +1426,7 @@ sub get_user_subpermissions {
     my $userid = shift;
 
     my $dbh = C4::Context->dbh;
-    my $sth = $dbh->prepare("SELECT flag, code
+    my $sth = $dbh->prepare("SELECT flag, user_permissions.code
                              FROM user_permissions
                              JOIN permissions USING (module_bit, code)
                              JOIN userflags ON (module_bit = bit)
@@ -1387,11 +1471,11 @@ sub get_all_subpermissions {
     return $all_perms;
 }
 
-=item haspermission 
+=item haspermission
 
-  $flags = ($dbh,$member,$flagsrequired);
+  $flags = ($userid, $flagsrequired);
 
-C<$member> may be either userid or overloaded with $borrower hashref from GetMemberDetails.
+C<$userid> the userid of the member
 C<$flags> is a hashref of required flags like C<$borrower-&lt;{authflags}> 
 
 Returns member's flags or 0 if a permission is not met.
@@ -1399,22 +1483,15 @@ Returns member's flags or 0 if a permission is not met.
 =cut
 
 sub haspermission {
-    my ( $dbh, $userid, $flagsrequired ) = @_;
-    my ($flags,$intflags);
-    $dbh=C4::Context->dbh unless($dbh);
-    if(ref($userid)) {
-        $intflags = $userid->{'flags'};  
-    } else {
-        my $sth = $dbh->prepare("SELECT flags FROM borrowers WHERE userid=?");
-        $sth->execute($userid);
-        my ($intflags) = $sth->fetchrow;
-        $flags = getuserflags( $intflags, $userid, $dbh );
-    }
+    my ($userid, $flagsrequired) = @_;
+    my $sth = C4::Context->dbh->prepare("SELECT flags FROM borrowers WHERE userid=?");
+    $sth->execute($userid);
+    my $flags = getuserflags( $sth->fetchrow(), $userid );
     if ( $userid eq C4::Context->config('user') ) {
         # Super User Account from /etc/koha.conf
         $flags->{'superlibrarian'} = 1;
     }
-    if ( $userid eq 'demo' && C4::Context->config('demo') ) {
+    elsif ( $userid eq 'demo' && C4::Context->config('demo') ) {
         # Demo user that can do "anything" (demo=1 in /etc/koha.conf)
         $flags->{'superlibrarian'} = 1;
     }
@@ -1426,10 +1503,10 @@ sub haspermission {
                 return 0 unless ( $flags->{$module} == 1 or ref($flags->{$module}) );
             } else {
                 return 0 unless ( $flags->{$module} == 1 or
-                                    ( ref($flags->{$module}) and 
-                                      exists $flags->{$module}->{$subperm} and 
-                                      $flags->{$module}->{$subperm} == 1 
-                                    ) 
+                                    ( ref($flags->{$module}) and
+                                      exists $flags->{$module}->{$subperm} and
+                                      $flags->{$module}->{$subperm} == 1
+                                    )
                                 );
             }
         } else {
@@ -1443,6 +1520,10 @@ sub haspermission {
 
 sub getborrowernumber {
     my ($userid) = @_;
+    my $userenv = C4::Context->userenv;
+    if ( defined( $userenv ) && ref( $userenv ) eq 'HASH' && $userenv->{number} ) {
+        return $userenv->{number};
+    }
     my $dbh = C4::Context->dbh;
     for my $field ( 'userid', 'cardnumber' ) {
         my $sth =