Bug 14385: Extend OpacHiddenItems to allow specifying exempt borrower categories
[koha.git] / catalogue / search.pl
index 892ff15..d9961a0 100755 (executable)
@@ -7,18 +7,18 @@
 #
 # This file is part of Koha
 #
-# Koha is free software; you can redistribute it and/or modify it under the
-# terms of the GNU General Public License as published by the Free Software
-# Foundation; either version 2 of the License, or (at your option) any later
-# version.
+# Koha is free software; you can redistribute it and/or modify it
+# under the terms of the GNU General Public License as published by
+# the Free Software Foundation; either version 3 of the License, or
+# (at your option) any later version.
 #
-# Koha is distributed in the hope that it will be useful, but WITHOUT ANY
-# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
-# A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
+# Koha is distributed in the hope that it will be useful, but
+# WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
+# GNU General Public License for more details.
 #
-# You should have received a copy of the GNU General Public License along
-# with Koha; if not, write to the Free Software Foundation, Inc.,
-# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
+# You should have received a copy of the GNU General Public License
+# along with Koha; if not, see <http://www.gnu.org/licenses>.
 
 =head1 NAME
 
@@ -132,8 +132,7 @@ Not yet completed...
 
 =cut
 
-use strict;            # always use
-#use warnings; FIXME - Bug 2505
+use Modern::Perl;
 
 ## STEP 1. Load things that are used in both search page and
 # results page and decide which template to load, operations 
@@ -144,36 +143,41 @@ use C4::Context;
 use C4::Output;
 use C4::Auth qw(:DEFAULT get_session);
 use C4::Search;
-use C4::Languages qw(getAllLanguages);
+use C4::Languages qw(getLanguages);
 use C4::Koha;
-use C4::Members qw(GetMember);
-use C4::VirtualShelves;
 use URI::Escape;
 use POSIX qw(ceil floor);
-use String::Random;
-use C4::Branch; # GetBranches
+use C4::Search::History;
+
+use Koha::ItemTypes;
+use Koha::Library::Groups;
+use Koha::Patrons;
+use Koha::SearchEngine::Search;
+use Koha::SearchEngine::QueryBuilder;
+use Koha::Virtualshelves;
+
+use URI::Escape;
 
 my $DisplayMultiPlaceHold = C4::Context->preference("DisplayMultiPlaceHold");
 # create a new CGI object
 # FIXME: no_undef_params needs to be tested
-use CGI qw('-no_undef_params');
+use CGI qw('-no_undef_params' -utf8 );
 my $cgi = new CGI;
 
-my ($template,$borrowernumber,$cookie);
-my $lang = C4::Templates::getlanguage($cgi, 'intranet');
 # decide which template to use
 my $template_name;
 my $template_type;
-my @params = $cgi->param("limit");
+my @params = $cgi->multi_param("limit");
 if ((@params>=1) || ($cgi->param("q")) || ($cgi->param('multibranchlimit')) || ($cgi->param('limit-yr')) ) {
-    $template_name = 'catalogue/results.tmpl';
+    $template_name = 'catalogue/results.tt';
+    $template_type = 'results';
 }
 else {
-    $template_name = 'catalogue/advsearch.tmpl';
+    $template_name = 'catalogue/advsearch.tt';
     $template_type = 'advsearch';
 }
 # load the template
-($template, $borrowernumber, $cookie) = get_template_and_user({
+my ($template, $borrowernumber, $cookie) = get_template_and_user({
     template_name => $template_name,
     query => $cgi,
     type => "intranet",
@@ -181,70 +185,42 @@ else {
     flagsrequired   => { catalogue => 1 },
     }
 );
+
+my $lang = C4::Languages::getlanguage($cgi);
+
 if (C4::Context->preference("marcflavour") eq "UNIMARC" ) {
     $template->param('UNIMARC' => 1);
 }
-if (C4::Context->preference("IntranetNumbersPreferPhrase")) {
-    $template->param('numbersphr' => 1);
-}
 
 if($cgi->cookie("holdfor")){ 
-    my $holdfor_patron = GetMember('borrowernumber' => $cgi->cookie("holdfor"));
+    my $holdfor_patron = Koha::Patrons->find( $cgi->cookie("holdfor") );
     $template->param(
         holdfor => $cgi->cookie("holdfor"),
-        holdfor_surname => $holdfor_patron->{'surname'},
-        holdfor_firstname => $holdfor_patron->{'firstname'},
-        holdfor_cardnumber => $holdfor_patron->{'cardnumber'},
+        holdfor_surname => $holdfor_patron->surname,
+        holdfor_firstname => $holdfor_patron->firstname,
+        holdfor_cardnumber => $holdfor_patron->cardnumber,
     );
 }
 
-## URI Re-Writing
-# Deprecated, but preserved because it's interesting :-)
-# The same thing can be accomplished with mod_rewrite in
-# a more elegant way
-#
-#my $rewrite_flag;
-#my $uri = $cgi->url(-base => 1);
-#my $relative_url = $cgi->url(-relative=>1);
-#$uri.="/".$relative_url."?";
-#warn "URI:$uri";
-#my @cgi_params_list = $cgi->param();
-#my $url_params = $cgi->Vars;
-#
-#for my $each_param_set (@cgi_params_list) {
-#    $uri.= join "",  map "\&$each_param_set=".$_, split("\0",$url_params->{$each_param_set}) if $url_params->{$each_param_set};
-#}
-#warn "New URI:$uri";
-# Only re-write a URI if there are params or if it already hasn't been re-written
-#unless (($cgi->param('r')) || (!$cgi->param()) ) {
-#    print $cgi->redirect(     -uri=>$uri."&r=1",
-#                            -cookie => $cookie);
-#    exit;
-#}
-
-# load the branches
-my $branches = GetBranches();
-
-# Populate branch_loop with all branches sorted by their name.  If
-# IndependentBranches is activated, set the default branch to the borrower
-# branch, except for superlibrarian who need to search all libraries.
-my $user = C4::Context->userenv;
-my @branch_loop = map {
-     {
-        value      => $_,
-        branchname => $branches->{$_}->{branchname},
-        selected   => $user->{branch} eq $_ && C4::Branch::onlymine(),
-     }
-} sort {
-    $branches->{$a}->{branchname} cmp $branches->{$b}->{branchname}
-} keys %$branches;
-
-my $categories = GetBranchCategories('searchdomain');
-
-$template->param(branchloop => \@branch_loop, searchdomainloop => $categories);
+# get biblionumbers stored in the cart
+my @cart_list;
+
+if($cgi->cookie("intranet_bib_list")){
+    my $cart_list = $cgi->cookie("intranet_bib_list");
+    @cart_list = split(/\//, $cart_list);
+}
+
+my @search_groups =
+  Koha::Library::Groups->get_search_groups( { interface => 'staff' } );
+@search_groups = sort { $a->title cmp $b->title } @search_groups;
+
+$template->param(
+    selected_branchcode => ( C4::Context->IsSuperLibrarian ? C4::Context->userenv : '' ),
+    search_groups    => \@search_groups,
+);
 
 # load the Type stuff
-my $itemtypes = GetItemTypes;
+my $itemtypes = { map { $_->{itemtype} => $_ } @{ Koha::ItemTypes->search_with_localization->unblessed } };
 # the index parameter is different for item-level itemtypes
 my $itype_or_itemtype = (C4::Context->preference("item-level_itypes"))?'itype':'itemtype';
 my @advancedsearchesloop;
@@ -253,14 +229,16 @@ my $advanced_search_types = C4::Context->preference("AdvancedSearchTypes") || "i
 my @advanced_search_types = split(/\|/, $advanced_search_types);
 
 foreach my $advanced_srch_type (@advanced_search_types) {
+    $advanced_srch_type =~ s/^\s*//;
+    $advanced_srch_type =~ s/\s*$//;
    if ($advanced_srch_type eq 'itemtypes') {
    # itemtype is a special case, since it's not defined in authorized values
         my @itypesloop;
-       foreach my $thisitemtype ( sort {$itemtypes->{$a}->{'description'} cmp $itemtypes->{$b}->{'description'} } keys %$itemtypes ) {
+        foreach my $thisitemtype ( sort {$itemtypes->{$a}->{translated_description} cmp $itemtypes->{$b}->{translated_description} } keys %$itemtypes ) {
            my %row =(  number=>$cnt++,
                ccl => "$itype_or_itemtype,phr",
                 code => $thisitemtype,
-                description => $itemtypes->{$thisitemtype}->{'description'},
+                description => $itemtypes->{$thisitemtype}->{translated_description},
                 imageurl=> getitemtypeimagelocation( 'intranet', $itemtypes->{$thisitemtype}->{'imageurl'} ),
             );
            push @itypesloop, \%row;
@@ -288,6 +266,9 @@ foreach my $advanced_srch_type (@advanced_search_types) {
     }
 }
 $template->param(advancedsearchesloop => \@advancedsearchesloop);
+my $types = C4::Context->preference("AdvancedSearchTypes") || "itemtypes";
+my $advancedsearchesloop = prepare_adv_search_types($types);
+$template->param(advancedsearchesloop => $advancedsearchesloop);
 
 # The following should only be loaded if we're bringing up the advanced search template
 if ( $template_type eq 'advsearch' ) {
@@ -339,7 +320,7 @@ if ( $template_type eq 'advsearch' ) {
                       search_boxes_loop => \@search_boxes_array);
 
     # load the language limits (for search)
-    my $languages_limit_loop = getAllLanguages($lang);
+    my $languages_limit_loop = getLanguages($lang, 1);
     $template->param(search_languages_loop => $languages_limit_loop,);
 
     # Expanded search options in advanced search:
@@ -377,7 +358,7 @@ if (   C4::Context->preference('defaultSortField')
       . C4::Context->preference('defaultSortOrder');
 }
 
-@sort_by = $cgi->param('sort_by');
+@sort_by = $cgi->multi_param('sort_by');
 $sort_by[0] = $default_sort_by unless $sort_by[0];
 foreach my $sort (@sort_by) {
     $template->param($sort => 1) if $sort;
@@ -385,7 +366,7 @@ foreach my $sort (@sort_by) {
 $template->param('sort_by' => $sort_by[0]);
 
 # Use the servers defined, or just search our local catalog(default)
-my @servers = $cgi->param('server');
+my @servers = $cgi->multi_param('server');
 unless (@servers) {
     #FIXME: this should be handled using Context.pm
     @servers = ("biblioserver");
@@ -393,11 +374,11 @@ unless (@servers) {
 }
 # operators include boolean and proximity operators and are used
 # to evaluate multiple operands
-my @operators = map uri_unescape($_), $cgi->param('op');
+my @operators = map uri_unescape($_), $cgi->multi_param('op');
 
 # indexes are query qualifiers, like 'title', 'author', etc. They
 # can be single or multiple parameters separated by comma: kw,right-Truncation 
-my @indexes = map uri_unescape($_), $cgi->param('idx');
+my @indexes = map uri_unescape($_), $cgi->multi_param('idx');
 
 # if a simple index (only one)  display the index used in the top search box
 if ($indexes[0] && (!$indexes[1] || $params->{'scan'})) {
@@ -407,13 +388,18 @@ if ($indexes[0] && (!$indexes[1] || $params->{'scan'})) {
 }
 
 # an operand can be a single term, a phrase, or a complete ccl query
-my @operands = map uri_unescape($_), $cgi->param('q');
+my @operands = map uri_unescape($_), $cgi->multi_param('q');
 
 # limits are use to limit to results to a pre-defined category such as branch or language
-my @limits = map uri_unescape($_), $cgi->param('limit');
+my @limits = map uri_unescape($_), $cgi->multi_param('limit');
+my @nolimits = map uri_unescape($_), $cgi->multi_param('nolimit');
+my %is_nolimit = map { $_ => 1 } @nolimits;
+@limits = grep { not $is_nolimit{$_} } @limits;
 
 if($params->{'multibranchlimit'}) {
-    my $multibranch = '('.join( " or ", map { "branch: $_ " } @{ GetBranchesInCategory( $params->{'multibranchlimit'} ) } ).')';
+    my $search_group = Koha::Library::Groups->find( $params->{multibranchlimit} );
+    my @libraries = $search_group->all_libraries;
+    my $multibranch = '('.join( " or ", map { 'branch: ' . $_->branchcode } @libraries ) .')';
     push @limits, $multibranch if ($multibranch ne  '()');
 }
 
@@ -429,12 +415,7 @@ $template->param(available => $available);
 my $limit_yr;
 my $limit_yr_value;
 if ($params->{'limit-yr'}) {
-    if ($params->{'limit-yr'} =~ /\d{4}-\d{4}/) {
-        my ($yr1,$yr2) = split(/-/, $params->{'limit-yr'});
-        $limit_yr = "yr,st-numeric,ge=$yr1 and yr,st-numeric,le=$yr2";
-        $limit_yr_value = "$yr1-$yr2";
-    }
-    elsif ($params->{'limit-yr'} =~ /\d{4}/) {
+    if ($params->{'limit-yr'} =~ /\d{4}/) {
         $limit_yr = "yr,st-numeric=$params->{'limit-yr'}";
         $limit_yr_value = $params->{'limit-yr'};
     }
@@ -466,69 +447,86 @@ my $scan = $params->{'scan'};
 my $count = C4::Context->preference('numSearchResults') || 20;
 my $results_per_page = $params->{'count'} || $count;
 my $offset = $params->{'offset'} || 0;
+$offset = 0 if $offset < 0;
 my $page = $cgi->param('page') || 1;
 #my $offset = ($page-1)*$results_per_page;
-my $hits;
 my $expanded_facet = $params->{'expand'};
 
 # Define some global variables
-my ( $error,$query,$simple_query,$query_cgi,$query_desc,$limit,$limit_cgi,$limit_desc,$stopwords_removed,$query_type);
+my ( $error,$query,$simple_query,$query_cgi,$query_desc,$limit,$limit_cgi,$limit_desc,$query_type);
 
-my @results;
+my $builder = Koha::SearchEngine::QueryBuilder->new(
+    { index => $Koha::SearchEngine::BIBLIOS_INDEX } );
+my $searcher = Koha::SearchEngine::Search->new(
+    { index => $Koha::SearchEngine::BIBLIOS_INDEX } );
 
 ## I. BUILD THE QUERY
-( $error,$query,$simple_query,$query_cgi,$query_desc,$limit,$limit_cgi,$limit_desc,$stopwords_removed,$query_type) = buildQuery(\@operators,\@operands,\@indexes,\@limits,\@sort_by,$scan,$lang);
+(
+    $error,             $query, $simple_query, $query_cgi,
+    $query_desc,        $limit, $limit_cgi,    $limit_desc,
+    $query_type
+  )
+  = $builder->build_query_compat( \@operators, \@operands, \@indexes, \@limits,
+    \@sort_by, $scan, $lang );
 
 ## parse the query_cgi string and put it into a form suitable for <input>s
 my @query_inputs;
 my $scan_index_to_use;
-
-for my $this_cgi ( split('&',$query_cgi) ) {
-    next unless $this_cgi;
-    $this_cgi =~ m/(.*?)=(.*)/;
-    my $input_name = $1;
-    my $input_value = $2;
-    push @query_inputs, { input_name => $input_name, input_value => $input_value };
-    if ($input_name eq 'idx') {
-        $scan_index_to_use = $input_value; # unless $scan_index_to_use;
+my $scan_search_term_to_use;
+
+if ($query_cgi) {
+    for my $this_cgi ( split('&', $query_cgi) ) {
+        next unless $this_cgi;
+        $this_cgi =~ m/(.*?)=(.*)/;
+        my $input_name = $1;
+        my $input_value = $2;
+        push @query_inputs, { input_name => $input_name, input_value => Encode::decode_utf8( uri_unescape( $input_value ) ) };
+        if ($input_name eq 'idx') {
+            $scan_index_to_use = $input_value; # unless $scan_index_to_use;
+        }
+        if ($input_name eq 'q') {
+            $scan_search_term_to_use = Encode::decode_utf8( uri_unescape( $input_value ));
+        }
     }
 }
+
 $template->param ( QUERY_INPUTS => \@query_inputs,
-                   scan_index_to_use => $scan_index_to_use );
+                   scan_index_to_use => $scan_index_to_use,
+                   scan_search_term_to_use => $scan_search_term_to_use );
 
 ## parse the limit_cgi string and put it into a form suitable for <input>s
 my @limit_inputs;
-for my $this_cgi ( split('&',$limit_cgi) ) {
-    next unless $this_cgi;
-    # handle special case limit-yr
-    if ($this_cgi =~ /yr,st-numeric/) {
-        push @limit_inputs, { input_name => 'limit-yr', input_value => $limit_yr_value };   
-        next;
+if ($limit_cgi) {
+    for my $this_cgi ( split('&', $limit_cgi) ) {
+        next unless $this_cgi;
+        # handle special case limit-yr
+        if ($this_cgi =~ /yr,st-numeric/) {
+            push @limit_inputs, { input_name => 'limit-yr', input_value => $limit_yr_value };
+            next;
+        }
+        $this_cgi =~ m/(.*=)(.*)/;
+        my $input_name = $1;
+        my $input_value = $2;
+        $input_name =~ s/=$//;
+        push @limit_inputs, { input_name => $input_name, input_value => Encode::decode_utf8( uri_unescape($input_value) ) };
     }
-    $this_cgi =~ m/(.*=)(.*)/;
-    my $input_name = $1;
-    my $input_value = $2;
-    $input_name =~ s/=$//;
-    push @limit_inputs, { input_name => $input_name, input_value => $input_value };
 }
 $template->param ( LIMIT_INPUTS => \@limit_inputs );
 
 ## II. DO THE SEARCH AND GET THE RESULTS
-my $total; # the total results for the whole set
+my $total = 0; # the total results for the whole set
 my $facets; # this object stores the faceted results that display on the left-hand of the results page
-my @results_array;
 my $results_hashref;
 
 eval {
-    ($error, $results_hashref, $facets) = getRecords($query,$simple_query,\@sort_by,\@servers,$results_per_page,$offset,$expanded_facet,$branches,$itemtypes,$query_type,$scan);
+    my $itemtypes = { map { $_->{itemtype} => $_ } @{ Koha::ItemTypes->search_with_localization->unblessed } };
+    ( $error, $results_hashref, $facets ) = $searcher->search_compat(
+        $query,            $simple_query, \@sort_by,       \@servers,
+        $results_per_page, $offset,       $expanded_facet, undef,
+        $itemtypes,        $query_type,   $scan
+    );
 };
 
-# This sorts the facets into alphabetical order
-if ($facets) {
-    foreach my $f (@$facets) {
-        $f->{facets} = [ sort { uc($a->{facet_title_value}) cmp uc($b->{facet_title_value}) } @{ $f->{facets} } ];
-    }
-}
 if ($@ || $error) {
     $template->param(query_error => $error.$@);
     output_html_with_http_headers $cgi, $cookie, $template->output;
@@ -541,11 +539,35 @@ my @sup_results_array;
 for (my $i=0;$i<@servers;$i++) {
     my $server = $servers[$i];
     if ($server =~/biblioserver/) { # this is the local bibliographic server
-        $hits = $results_hashref->{$server}->{"hits"};
+        my $hits = $results_hashref->{$server}->{"hits"} // 0;
         my $page = $cgi->param('page') || 0;
-        my @newresults = searchResults('intranet', $query_desc, $hits, $results_per_page, $offset, $scan,
+        my @newresults = searchResults({ 'interface' => 'intranet' }, $query_desc, $hits, $results_per_page, $offset, $scan,
                                        $results_hashref->{$server}->{"RECORDS"});
-        $total = $total + $results_hashref->{$server}->{"hits"};
+        $total = $total + $hits;
+
+        # Search history
+        if (C4::Context->preference('EnableSearchHistory')) {
+            unless ( $offset ) {
+                my $path_info = $cgi->url(-path_info=>1);
+                my $query_cgi_history = $cgi->url(-query=>1);
+                $query_cgi_history =~ s/^$path_info\?//;
+                $query_cgi_history =~ s/;/&/g;
+                my $query_desc_history = $query_desc;
+                $query_desc_history .= ", $limit_desc"
+                    if $limit_desc;
+
+                C4::Search::History::add({
+                    userid => $borrowernumber,
+                    sessionid => $cgi->cookie("CGISESSID"),
+                    query_desc => $query_desc_history,
+                    query_cgi => $query_cgi_history,
+                    total => $total,
+                    type => "biblio",
+                });
+            }
+            $template->param( EnableSearchHistory => 1 );
+        }
+
         ## If there's just one result, redirect to the detail page
         if ($total == 1) {         
             my $biblionumber = $newresults[0]->{biblionumber};
@@ -569,9 +591,11 @@ for (my $i=0;$i<@servers;$i++) {
 
         if ($hits) {
             $template->param(total => $hits);
-            my $limit_cgi_not_availablity = $limit_cgi;
-            $limit_cgi_not_availablity =~ s/&limit=available//g;
-            $template->param(limit_cgi_not_availablity => $limit_cgi_not_availablity);
+            if ($limit_cgi) {
+                my $limit_cgi_not_availablity = $limit_cgi;
+                $limit_cgi_not_availablity =~ s/&limit=available//g;
+                $template->param(limit_cgi_not_availablity => $limit_cgi_not_availablity);
+            }
             $template->param(limit_cgi => $limit_cgi);
             $template->param(query_cgi => $query_cgi);
             $template->param(query_desc => $query_desc);
@@ -581,19 +605,26 @@ for (my $i=0;$i<@servers;$i++) {
             if ($query_desc || $limit_desc) {
                 $template->param(searchdesc => 1);
             }
-            $template->param(stopwords_removed => "@$stopwords_removed") if $stopwords_removed;
             $template->param(results_per_page =>  $results_per_page);
             # must define a value for size if not present in DB
             # in order to avoid problems generated by the default size value in TT
             foreach my $line (@newresults) {
                 if ( not exists $line->{'size'} ) { $line->{'size'} = "" }
+                # while we're checking each line, see if item is in the cart
+                if ( grep {$_ eq $line->{'biblionumber'}} @cart_list) {
+                    $line->{'incart'} = 1;
+                }
             }
             $template->param(SEARCH_RESULTS => \@newresults);
             ## FIXME: add a global function for this, it's better than the current global one
             ## Build the page numbers on the bottom of the page
             my @page_numbers;
+            my $max_result_window = $searcher->max_result_window;
+            my $hits_to_paginate = ($max_result_window && $max_result_window < $hits) ? $max_result_window : $hits;
+            $template->param( hits_to_paginate => $hits_to_paginate );
             # total number of pages there will be
-            my $pages = ceil($hits / $results_per_page);
+            my $pages = ceil($hits_to_paginate / $results_per_page);
+            my $last_page_offset = ( $pages -1 ) * $results_per_page;
             # default page number
             my $current_page_number = 1;
             $current_page_number = ($offset / $results_per_page + 1) if $offset;
@@ -644,6 +675,7 @@ for (my $i=0;$i<@servers;$i++) {
             }
             # FIXME: no previous_page_offset when pages < 2
             $template->param(   PAGE_NUMBERS => \@page_numbers,
+                                last_page_offset => $last_page_offset,
                                 previous_page_offset => $previous_page_offset) unless $pages < 2;
             $template->param(   next_page_offset => $next_page_offset) unless $pages eq $current_page_number;
         }
@@ -660,7 +692,10 @@ for (my $i=0;$i<@servers;$i++) {
     elsif ($server =~/authorityserver/) { # this is the local authority server
         my @inner_sup_results_array;
         for my $sup_record ( @{$results_hashref->{$server}->{"RECORDS"}} ) {
-            my $marc_record_object = MARC::Record->new_from_usmarc($sup_record);
+            my $marc_record_object = C4::Search::new_record_from_zebra(
+                'authorityserver',
+                $sup_record
+            );
             # warn "Authority Found: ".$marc_record_object->as_formatted();
             push @inner_sup_results_array, {
                 'title' => $marc_record_object->field(100)->subfield('a'),
@@ -675,16 +710,24 @@ for (my $i=0;$i<@servers;$i++) {
 } #/end of the for loop
 #$template->param(FEDERATED_RESULTS => \@results_array);
 
-$template->{'VARS'}->{'searchid'} = $cgi->param('searchid')
-  || String::Random::random_string('ssssssss');
+$template->{'VARS'}->{'searchid'} = $cgi->param('searchid');
+
 my $gotonumber = $cgi->param('gotoNumber');
-if ($gotonumber eq 'last' || $gotonumber eq 'first') {
+if ( $gotonumber && ( $gotonumber eq 'last' || $gotonumber eq 'first' ) ) {
     $template->{'VARS'}->{'gotoNumber'} = $gotonumber;
 }
 $template->{'VARS'}->{'gotoPage'}   = 'detail.pl';
 my $gotopage = $cgi->param('gotoPage');
 $template->{'VARS'}->{'gotoPage'} = $gotopage
-  if $gotopage =~ m/^(ISBD|labeledMARC|MARC|more)?detail.pl$/;
+  if $gotopage && $gotopage =~ m/^(ISBD|labeledMARC|MARC|more)?detail.pl$/;
+
+for my $facet ( @$facets ) {
+    for my $entry ( @{ $facet->{facets} } ) {
+        my $index = $entry->{type_link_value};
+        my $value = $entry->{facet_link_value};
+        $entry->{active} = grep { $_->{input_value} eq qq{$index:$value} } @limit_inputs;
+    }
+}
 
 $template->param(
             #classlist => $classlist,
@@ -702,14 +745,108 @@ if ($query_desc || $limit_desc) {
 
 # VI. BUILD THE TEMPLATE
 
-# Build drop-down list for 'Add To:' menu...
-my ($totalref, $pubshelves, $barshelves)=
-       C4::VirtualShelves::GetSomeShelfNames($borrowernumber,'COMBO',1);
+my $some_private_shelves = Koha::Virtualshelves->get_some_shelves(
+    {
+        borrowernumber => $borrowernumber,
+        add_allowed    => 1,
+        category       => 1,
+    }
+);
+my $some_public_shelves = Koha::Virtualshelves->get_some_shelves(
+    {
+        borrowernumber => $borrowernumber,
+        add_allowed    => 1,
+        category       => 2,
+    }
+);
+
+
 $template->param(
-        addbarshelves     => $totalref->{bartotal},
-        addbarshelvesloop => $barshelves,
-       addpubshelves     => $totalref->{pubtotal},
-       addpubshelvesloop => $pubshelves,
-       );
+    add_to_some_private_shelves => $some_private_shelves,
+    add_to_some_public_shelves  => $some_public_shelves,
+);
 
 output_html_with_http_headers $cgi, $cookie, $template->output;
+
+
+=head2 prepare_adv_search_types
+
+    my $type = C4::Context->preference("AdvancedSearchTypes") || "itemtypes";
+    my @advanced_search_types = prepare_adv_search_types($type);
+
+Different types can be searched for in the advanced search. This takes the
+system preference that defines these types and parses it into an arrayref for
+the template.
+
+"itemtypes" is handled specially, as itemtypes aren't an authorised value.
+It also accounts for the "item-level_itypes" system preference.
+
+=cut
+
+sub prepare_adv_search_types {
+    my ($types) = @_;
+
+    my @advanced_search_types = split( /\|/, $types );
+
+    # the index parameter is different for item-level itemtypes
+    my $itype_or_itemtype =
+      ( C4::Context->preference("item-level_itypes") ) ? 'itype' : 'itemtype';
+    my $itemtypes = { map { $_->{itemtype} => $_ } @{ Koha::ItemTypes->search_with_localization->unblessed } };
+
+    my ( $cnt, @result );
+    foreach my $advanced_srch_type (@advanced_search_types) {
+        $advanced_srch_type =~ s/^\s*//;
+        $advanced_srch_type =~ s/\s*$//;
+        if ( $advanced_srch_type eq 'itemtypes' ) {
+
+       # itemtype is a special case, since it's not defined in authorized values
+            my @itypesloop;
+            foreach my $thisitemtype (
+                sort {
+                    $itemtypes->{$a}->{'translated_description'}
+                      cmp $itemtypes->{$b}->{'translated_description'}
+                } keys %$itemtypes
+              )
+            {
+                my %row = (
+                    number      => $cnt++,
+                    ccl         => "$itype_or_itemtype,phr",
+                    code        => $thisitemtype,
+                    description => $itemtypes->{$thisitemtype}->{'translated_description'},
+                    imageurl    => getitemtypeimagelocation(
+                        'intranet', $itemtypes->{$thisitemtype}->{'imageurl'}
+                    ),
+                );
+                push @itypesloop, \%row;
+            }
+            my %search_code = (
+                advanced_search_type => $advanced_srch_type,
+                code_loop            => \@itypesloop
+            );
+            push @result, \%search_code;
+        }
+        else {
+            # covers all the other cases: non-itemtype authorized values
+            my $advsearchtypes = GetAuthorisedValues($advanced_srch_type);
+            my @authvalueloop;
+            for my $thisitemtype (@$advsearchtypes) {
+                my %row = (
+                    number      => $cnt++,
+                    ccl         => $advanced_srch_type,
+                    code        => $thisitemtype->{authorised_value},
+                    description => $thisitemtype->{'lib'},
+                    imageurl    => getitemtypeimagelocation(
+                        'intranet', $thisitemtype->{'imageurl'}
+                    ),
+                );
+                push @authvalueloop, \%row;
+            }
+            my %search_code = (
+                advanced_search_type => $advanced_srch_type,
+                code_loop            => \@authvalueloop
+            );
+            push @result, \%search_code;
+        }
+    }
+    return \@result;
+}