Bug 9454: Use placeholders when adding basket
[koha_fer] / C4 / Auth.pm
index 143fe3f..0c57a3f 100644 (file)
@@ -18,7 +18,7 @@ package C4::Auth;
 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 
 use strict;
-#use warnings; FIXME - Bug 2505
+use warnings;
 use Digest::MD5 qw(md5_base64);
 use Storable qw(thaw freeze);
 use URI::Escape;
@@ -129,6 +129,7 @@ my $SEARCH_HISTORY_INSERT_SQL =<<EOQ;
 INSERT INTO search_history(userid, sessionid, query_desc, query_cgi, total, time            )
 VALUES                    (     ?,         ?,          ?,         ?,          ?, FROM_UNIXTIME(?))
 EOQ
+
 sub get_template_and_user {
     my $in       = shift;
     my $template =
@@ -146,14 +147,15 @@ sub get_template_and_user {
     my $borrowernumber;
     my $insecure = C4::Context->preference('insecure');
     if ($user or $insecure) {
+        require C4::Members;
         # 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;
+            my $borrower = C4::Members::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};
@@ -172,7 +174,6 @@ sub get_template_and_user {
             barshelvesloop  => $barshelves,
         );
 
-        require C4::Members;
         my ( $borr ) = C4::Members::GetMemberDetails( $borrowernumber );
         my @bordat;
         $bordat[0] = $borr;
@@ -263,12 +264,13 @@ sub get_template_and_user {
                                                       $_->{'time'},
                             ) foreach @recentSearches;
 
-                                       # And then, delete the cookie's content
-                                       my $newsearchcookie = $in->{'query'}->cookie(
-                                                                                               -name => 'KohaOpacRecentSearches',
-                                                                                               -value => freeze([]),
-                                                                                               -expires => ''
-                                                                                        );
+                    # And then, delete the cookie's content
+                    my $newsearchcookie = $in->{'query'}->cookie(
+                                                -name => 'KohaOpacRecentSearches',
+                                                -value => freeze([]),
+                                                -HttpOnly => 1,
+                                                -expires => ''
+                                             );
                                        $cookie = [$cookie, $newsearchcookie];
                                }
                        }
@@ -299,6 +301,7 @@ sub get_template_and_user {
        }
 
     if(C4::Context->preference('dateformat')){
+        $template->param( dateformat => C4::Context->preference('dateformat') );
         if(C4::Context->preference('dateformat') eq "metric"){
             $template->param(dateformat_metric => 1);
         } elsif(C4::Context->preference('dateformat') eq "us"){
@@ -334,10 +337,7 @@ sub get_template_and_user {
 
     if ( $in->{'type'} eq "intranet" ) {
         $template->param(
-            AmazonContent               => C4::Context->preference("AmazonContent"),
             AmazonCoverImages           => C4::Context->preference("AmazonCoverImages"),
-            AmazonEnabled               => C4::Context->preference("AmazonEnabled"),
-            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,
@@ -365,6 +365,7 @@ sub get_template_and_user {
             LocalCoverImages            => C4::Context->preference('LocalCoverImages'),
             OPACLocalCoverImages        => C4::Context->preference('OPACLocalCoverImages'),
             AllowMultipleCovers         => C4::Context->preference('AllowMultipleCovers'),
+            EnableBorrowerFiles         => C4::Context->preference('EnableBorrowerFiles'),
         );
     }
     else {
@@ -382,22 +383,13 @@ sub get_template_and_user {
         my $opac_search_limit = $ENV{'OPAC_SEARCH_LIMIT'};
         my $opac_limit_override = $ENV{'OPAC_LIMIT_OVERRIDE'};
         my $opac_name = '';
-        if (($opac_search_limit =~ /branch:(\w+)/ && $opac_limit_override) || $in->{'query'}->param('limit') =~ /branch:(\w+)/){
+        if (($opac_search_limit && $opac_search_limit =~ /branch:(\w+)/ && $opac_limit_override) || ($in->{'query'}->param('limit') && $in->{'query'}->param('limit') =~ /branch:(\w+)/)){
             $opac_name = $1;   # opac_search_limit is a branch, so we use it.
         } elsif (C4::Context->preference("SearchMyLibraryFirst") && C4::Context->userenv && C4::Context->userenv->{'branch'}) {
             $opac_name = C4::Context->userenv->{'branch'};
         }
-       my $checkstyle = C4::Context->preference("opaccolorstylesheet");
-       if ($checkstyle =~ /http/)
-       {
-               $template->param( opacexternalsheet => $checkstyle);
-       } else
-       {
-               my $opaccolorstylesheet = C4::Context->preference("opaccolorstylesheet");  
-            $template->param( opaccolorstylesheet => $opaccolorstylesheet);
-       }
         $template->param(
-            AmazonContent             => "" . C4::Context->preference("AmazonContent"),
+            opaccolorstylesheet       => C4::Context->preference("opaccolorstylesheet"),
             AnonSuggestions           => "" . C4::Context->preference("AnonSuggestions"),
             AuthorisedValueImages     => C4::Context->preference("AuthorisedValueImages"),
             BranchesLoop              => GetBranchesLoop($opac_name),
@@ -405,10 +397,7 @@ sub get_template_and_user {
             LibraryName               => "" . C4::Context->preference("LibraryName"),
             LibraryNameTitle          => "" . $LibraryNameTitle,
             LoginBranchname           => C4::Context->userenv?C4::Context->userenv->{"branchname"}:"",
-            OPACAmazonEnabled         => C4::Context->preference("OPACAmazonEnabled"),
-            OPACAmazonSimilarItems    => C4::Context->preference("OPACAmazonSimilarItems"),
             OPACAmazonCoverImages     => C4::Context->preference("OPACAmazonCoverImages"),
-            OPACAmazonReviews         => C4::Context->preference("OPACAmazonReviews"),
             OPACFRBRizeEditions       => C4::Context->preference("OPACFRBRizeEditions"),
             OpacHighlightedWords       => C4::Context->preference("OpacHighlightedWords"),
             OPACItemHolds             => C4::Context->preference("OPACItemHolds"),
@@ -416,6 +405,7 @@ sub get_template_and_user {
             OpacShowRecentComments    => C4::Context->preference("OpacShowRecentComments"),
             OPACURLOpenInNewWindow    => "" . C4::Context->preference("OPACURLOpenInNewWindow"),
             OPACUserCSS               => "". C4::Context->preference("OPACUserCSS"),
+            OPACMobileUserCSS         => "". C4::Context->preference("OPACMobileUserCSS"),
             OPACViewOthersSuggestions => "" . C4::Context->preference("OPACViewOthersSuggestions"),
             OpacAuthorities           => C4::Context->preference("OpacAuthorities"),
             OPACBaseURL               => ($in->{'query'}->https() ? "https://" : "http://") . $ENV{'SERVER_NAME'} .
@@ -427,6 +417,9 @@ sub get_template_and_user {
             OpacCloud                 => C4::Context->preference("OpacCloud"),
             OpacKohaUrl               => C4::Context->preference("OpacKohaUrl"),
             OpacMainUserBlock         => "" . C4::Context->preference("OpacMainUserBlock"),
+            OpacMainUserBlockMobile   => "" . C4::Context->preference("OpacMainUserBlockMobile"),
+            OpacShowFiltersPulldownMobile => C4::Context->preference("OpacShowFiltersPulldownMobile"),
+            OpacShowLibrariesPulldownMobile => C4::Context->preference("OpacShowLibrariesPulldownMobile"),
             OpacNav                   => "" . C4::Context->preference("OpacNav"),
             OpacNavRight              => "" . C4::Context->preference("OpacNavRight"),
             OpacNavBottom             => "" . C4::Context->preference("OpacNavBottom"),
@@ -440,7 +433,6 @@ sub get_template_and_user {
             hidelostitems             => C4::Context->preference("hidelostitems"),
             mylibraryfirst            => (C4::Context->preference("SearchMyLibraryFirst") && C4::Context->userenv) ? C4::Context->userenv->{'branch'} : '',
             opaclayoutstylesheet      => "" . C4::Context->preference("opaclayoutstylesheet"),
-            opacstylesheet            => "" . C4::Context->preference("opacstylesheet"),
             opacbookbag               => "" . C4::Context->preference("opacbookbag"),
             opaccredits               => "" . C4::Context->preference("opaccredits"),
             OpacFavicon               => C4::Context->preference("OpacFavicon"),
@@ -472,6 +464,8 @@ sub get_template_and_user {
             SyndeticsSeries              => C4::Context->preference("SyndeticsSeries"),
             SyndeticsCoverImageSize      => C4::Context->preference("SyndeticsCoverImageSize"),
             OPACLocalCoverImages         => C4::Context->preference("OPACLocalCoverImages"),
+            PatronSelfRegistration       => C4::Context->preference("PatronSelfRegistration"),
+            PatronSelfRegistrationDefaultCategory => C4::Context->preference("PatronSelfRegistrationDefaultCategory"),
         );
 
         $template->param(OpacPublic => '1') if ($user || C4::Context->preference("OpacPublic"));
@@ -557,7 +551,7 @@ has authenticated.
 
 =cut
 
-sub _version_check ($$) {
+sub _version_check {
     my $type = shift;
     my $query = shift;
     my $version;
@@ -567,6 +561,7 @@ sub _version_check ($$) {
        if (C4::Context->preference('OpacMaintenance') && $type eq 'opac') {
         warn "OPAC Install required, redirecting to maintenance";
         print $query->redirect("/cgi-bin/koha/maintenance.pl");
+        safe_exit;
     }
     unless ( $version = C4::Context->preference('Version') ) {    # assignment, not comparison
         if ( $type ne 'opac' ) {
@@ -602,9 +597,18 @@ sub _version_check ($$) {
 
 sub _session_log {
     (@_) or return 0;
-    open L, ">>/tmp/sessionlog" or warn "ERROR: Cannot append to /tmp/sessionlog";
-    printf L join("\n",@_);
-    close L;
+    open my $fh, '>>', "/tmp/sessionlog" or warn "ERROR: Cannot append to /tmp/sessionlog";
+    printf $fh join("\n",@_);
+    close $fh;
+}
+
+sub _timeout_syspref {
+    my $timeout = C4::Context->preference('timeout') || 600;
+    # value in days, convert in seconds
+    if ($timeout =~ /(\d+)[dD]/) {
+        $timeout = $1 * 86400;
+    };
+    return $timeout;
 }
 
 sub checkauth {
@@ -617,12 +621,7 @@ sub checkauth {
     $type = 'opac' unless $type;
 
     my $dbh     = C4::Context->dbh;
-    my $timeout = C4::Context->preference('timeout');
-    # days
-    if ($timeout =~ /(\d+)[dD]/) {
-        $timeout = $1 * 86400;
-    };
-    $timeout = 600 unless $timeout;
+    my $timeout = _timeout_syspref();
 
     _version_check($type,$query);
     # state variables
@@ -635,16 +634,18 @@ sub checkauth {
     # 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
+        if ( $userid = $ENV{'REMOTE_USER'} ) {
+            # Using Basic Authentication, no cookies required
         $cookie = $query->cookie(
-            -name    => 'CGISESSID',
-            -value   => '',
-            -expires => ''
+            -name     => 'CGISESSID',
+            -value    => '',
+            -expires  => '',
+            -HttpOnly => 1,
         );
         $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);
@@ -663,7 +664,7 @@ sub checkauth {
             $ip       = $session->param('ip');
             $lasttime = $session->param('lasttime');
             $userid   = $session->param('id');
-                       $sessiontype = $session->param('sessiontype');
+            $sessiontype = $session->param('sessiontype') || '';
         }
         if ( ( ($query->param('koha_login_context')) && ($query->param('userid') ne $session->param('id')) )
           || ( $cas && $query->param('ticket') ) ) {
@@ -710,9 +711,13 @@ sub checkauth {
             $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...
+            $cookie = $query->cookie(
+                -name     => 'CGISESSID',
+                -value    => $session->id,
+                -HttpOnly => 1
+            );
+            $session->param( 'lasttime', time() );
+            unless ( $sessiontype && $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;
@@ -727,8 +732,12 @@ sub checkauth {
         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');
+        $cookie = $query->cookie(
+            -name     => 'CGISESSID',
+            -value    => $session->id,
+            -HttpOnly => 1
+        );
+    $userid = $query->param('userid');
         if (   ( $cas && $query->param('ticket') )
             || $userid
             || ( my $pki_field = C4::Context->preference('AllowPKIAuth') ) ne
@@ -919,7 +928,11 @@ sub checkauth {
     {
         # successful login
         unless ($cookie) {
-            $cookie = $query->cookie( CGISESSID => '' );
+            $cookie = $query->cookie(
+                -name     => 'CGISESSID',
+                -value    => '',
+                -HttpOnly => 1
+            );
         }
         return ( $userid, $cookie, $sessionID, $flags );
     }
@@ -937,27 +950,14 @@ sub checkauth {
         my $value = $query->param($name);
         push @inputs, { name => $name, value => $value };
     }
-    # get the branchloop, which we need for authentication
-    my $branches = GetBranches();
-    my @branch_loop;
-    for my $branch_hash (sort keys %$branches) {
-               push @branch_loop, {branchcode => "$branch_hash", branchname => $branches->{$branch_hash}->{'branchname'}, };
-    }
 
     my $template_name = ( $type eq 'opac' ) ? 'opac-auth.tmpl' : 'auth.tmpl';
-    my $template = C4::Templates::gettemplate( $template_name, $type, $query );
-    $template->param(branchloop => \@branch_loop,);
-    my $checkstyle = C4::Context->preference("opaccolorstylesheet");
-    if ($checkstyle =~ /\//)
-       {
-               $template->param( opacexternalsheet => $checkstyle);
-       } else
-       {
-               my $opaccolorstylesheet = C4::Context->preference("opaccolorstylesheet");  
-            $template->param( opaccolorstylesheet => $opaccolorstylesheet);
-       }
+    my $template = C4::Templates::gettemplate($template_name, $type, $query );
     $template->param(
-    login        => 1,
+        branchloop           => GetBranchesLoop(),
+        opaccolorstylesheet  => C4::Context->preference("opaccolorstylesheet"),
+        opaclayoutstylesheet => C4::Context->preference("opaclayoutstylesheet"),
+        login                => 1,
         INPUTS               => \@inputs,
         casAuthentication    => C4::Context->preference("casAuthentication"),
         suggestion           => C4::Context->preference("suggestion"),
@@ -971,7 +971,6 @@ sub checkauth {
         OpacFavicon          => C4::Context->preference("OpacFavicon"),
         opacreadinghistory   => C4::Context->preference("opacreadinghistory"),
         opacsmallimage       => C4::Context->preference("opacsmallimage"),
-        opaclayoutstylesheet => C4::Context->preference("opaclayoutstylesheet"),
         opaclanguagesdisplay => C4::Context->preference("opaclanguagesdisplay"),
         opacuserjs           => C4::Context->preference("opacuserjs"),
         opacbookbag          => "" . C4::Context->preference("opacbookbag"),
@@ -980,18 +979,19 @@ sub checkauth {
         OpacAuthorities      => C4::Context->preference("OpacAuthorities"),
         OpacBrowser          => C4::Context->preference("OpacBrowser"),
         opacheader           => C4::Context->preference("opacheader"),
-        TagsEnabled                  => C4::Context->preference("TagsEnabled"),
+        TagsEnabled          => C4::Context->preference("TagsEnabled"),
         OPACUserCSS           => C4::Context->preference("OPACUserCSS"),
-        opacstylesheet       => C4::Context->preference("opacstylesheet"),
-        intranetcolorstylesheet =>
-                                                               C4::Context->preference("intranetcolorstylesheet"),
+        intranetcolorstylesheet => C4::Context->preference("intranetcolorstylesheet"),
         intranetstylesheet => C4::Context->preference("intranetstylesheet"),
         intranetbookbag    => C4::Context->preference("intranetbookbag"),
         IntranetNav        => C4::Context->preference("IntranetNav"),
+        IntranetFavicon    => C4::Context->preference("IntranetFavicon"),
         intranetuserjs     => C4::Context->preference("intranetuserjs"),
         IndependantBranches=> C4::Context->preference("IndependantBranches"),
         AutoLocation       => C4::Context->preference("AutoLocation"),
-               wrongip            => $info{'wrongip'},
+        wrongip            => $info{'wrongip'},
+        PatronSelfRegistration => C4::Context->preference("PatronSelfRegistration"),
+        PatronSelfRegistrationDefaultCategory => C4::Context->preference("PatronSelfRegistrationDefaultCategory"),
     );
 
     $template->param( OpacPublic => C4::Context->preference("OpacPublic"));
@@ -1077,8 +1077,7 @@ sub check_api_auth {
     my $flagsrequired = shift;
 
     my $dbh     = C4::Context->dbh;
-    my $timeout = C4::Context->preference('timeout');
-    $timeout = 600 unless $timeout;
+    my $timeout = _timeout_syspref();
 
     unless (C4::Context->preference('Version')) {
         # database has not been installed yet
@@ -1138,7 +1137,11 @@ sub check_api_auth {
                 $sessionID = undef;
                 return ("expired", undef, undef);
             } else {
-                my $cookie = $query->cookie( CGISESSID => $session->id );
+                my $cookie = $query->cookie(
+                    -name  => 'CGISESSID',
+                    -value => $session->id,
+                    -HttpOnly => 1,
+                );
                 $session->param('lasttime',time());
                 my $flags = haspermission($userid, $flagsrequired);
                 if ($flags) {
@@ -1182,7 +1185,11 @@ sub check_api_auth {
 
             my $sessionID = $session->id;
             C4::Context->_new_userenv($sessionID);
-            my $cookie = $query->cookie(CGISESSID => $sessionID);
+            my $cookie = $query->cookie(
+                -name  => 'CGISESSID',
+                -value => $sessionID,
+                -HttpOnly => 1,
+            );
             if ( $return == 1 ) {
                 my (
                     $borrowernumber, $firstname,  $surname,
@@ -1310,8 +1317,7 @@ sub check_cookie_auth {
     my $flagsrequired = shift;
 
     my $dbh     = C4::Context->dbh;
-    my $timeout = C4::Context->preference('timeout');
-    $timeout = 600 unless $timeout;
+    my $timeout = _timeout_syspref();
 
     unless (C4::Context->preference('Version')) {
         # database has not been installed yet
@@ -1511,7 +1517,13 @@ sub getuserflags {
     my $userid  = shift;
     my $dbh     = @_ ? shift : C4::Context->dbh;
     my $userflags;
-    $flags = 0 unless $flags;
+    {
+        # I don't want to do this, but if someone logs in as the database
+        # user, it would be preferable not to spam them to death with
+        # numeric warnings. So, we make $flags numeric.
+        no warnings 'numeric';
+        $flags += 0;
+    }
     my $sth = $dbh->prepare("SELECT bit, flag, defaulton FROM userflags");
     $sth->execute;