Koha 3.8.0 Translation Update
[koha.git] / opac / opac-search.pl
blob5f3ad8608c085ee2f8b3befefe88d948c89781f1
1 #!/usr/bin/perl
3 # Copyright 2008 Garry Collum and the Koha Development team
4 # Copyright 2010 BibLibre
5 # Copyright 2011 KohaAloha, NZ
7 # This file is part of Koha.
9 # Koha is free software; you can redistribute it and/or modify it under the
10 # terms of the GNU General Public License as published by the Free Software
11 # Foundation; either version 2 of the License, or (at your option) any later
12 # version.
14 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
15 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
16 # A PARTICULAR PURPOSE. See the GNU General Public License for more details.
18 # You should have received a copy of the GNU General Public License along
19 # with Koha; if not, write to the Free Software Foundation, Inc.,
20 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
22 # Script to perform searching
23 # Mostly copied from search.pl, see POD there
24 use strict; # always use
25 use warnings;
27 ## STEP 1. Load things that are used in both search page and
28 # results page and decide which template to load, operations
29 # to perform, etc.
30 ## load Koha modules
31 use C4::Context;
32 use C4::Output;
33 use C4::Auth qw(:DEFAULT get_session);
34 use C4::Languages qw(getAllLanguages);
35 use C4::Search;
36 use C4::Biblio; # GetBiblioData
37 use C4::Koha;
38 use C4::Tags qw(get_tags);
39 use C4::Branch; # GetBranches
40 use C4::SocialData;
41 use C4::Ratings;
43 use POSIX qw(ceil floor strftime);
44 use URI::Escape;
45 use Storable qw(thaw freeze);
46 use Business::ISBN;
48 my $DisplayMultiPlaceHold = C4::Context->preference("DisplayMultiPlaceHold");
49 # create a new CGI object
50 # FIXME: no_undef_params needs to be tested
51 use CGI qw('-no_undef_params');
52 my $cgi = new CGI;
54 BEGIN {
55 if (C4::Context->preference('BakerTaylorEnabled')) {
56 require C4::External::BakerTaylor;
57 import C4::External::BakerTaylor qw(&image_url &link_url);
61 my ($template,$borrowernumber,$cookie);
63 # decide which template to use
64 my $template_name;
65 my $template_type = 'basic';
66 my @params = $cgi->param("limit");
68 my $format = $cgi->param("format") || '';
69 my $build_grouped_results = C4::Context->preference('OPACGroupResults');
70 if ($format =~ /(rss|atom|opensearchdescription)/) {
71 $template_name = 'opac-opensearch.tmpl';
73 elsif (@params && $build_grouped_results) {
74 $template_name = 'opac-results-grouped.tmpl';
76 elsif ((@params>=1) || ($cgi->param("q")) || ($cgi->param('multibranchlimit')) || ($cgi->param('limit-yr')) ) {
77 $template_name = 'opac-results.tmpl';
79 else {
80 $template_name = 'opac-advsearch.tmpl';
81 $template_type = 'advsearch';
83 # load the template
84 ($template, $borrowernumber, $cookie) = get_template_and_user({
85 template_name => $template_name,
86 query => $cgi,
87 type => "opac",
88 authnotrequired => ( C4::Context->preference("OpacPublic") ? 1 : 0 ),
91 if ($template_name eq 'opac-results.tmpl') {
92 $template->param('COinSinOPACResults' => C4::Context->preference('COinSinOPACResults'));
95 # get biblionumbers stored in the cart
96 my @cart_list;
98 if($cgi->cookie("bib_list")){
99 my $cart_list = $cgi->cookie("bib_list");
100 @cart_list = split(/\//, $cart_list);
103 if ($format eq 'rss2' or $format eq 'opensearchdescription' or $format eq 'atom') {
104 $template->param($format => 1);
105 $template->param(timestamp => strftime("%Y-%m-%dT%H:%M:%S-00:00", gmtime)) if ($format eq 'atom');
106 # FIXME - the timestamp is a hack - the biblio update timestamp should be used for each
107 # entry, but not sure if that's worth an extra database query for each bib
109 if (C4::Context->preference("marcflavour") eq "UNIMARC" ) {
110 $template->param('UNIMARC' => 1);
112 elsif (C4::Context->preference("marcflavour") eq "MARC21" ) {
113 $template->param('usmarc' => 1);
115 $template->param( 'AllowOnShelfHolds' => C4::Context->preference('AllowOnShelfHolds') );
116 $template->param( 'OPACNoResultsFound' => C4::Context->preference('OPACNoResultsFound') );
118 $template->param(
119 OpacStarRatings => C4::Context->preference("OpacStarRatings") );
121 if (C4::Context->preference('BakerTaylorEnabled')) {
122 $template->param(
123 BakerTaylorEnabled => 1,
124 BakerTaylorImageURL => &image_url(),
125 BakerTaylorLinkURL => &link_url(),
126 BakerTaylorBookstoreURL => C4::Context->preference('BakerTaylorBookstoreURL'),
130 if (C4::Context->preference('TagsEnabled')) {
131 $template->param(TagsEnabled => 1);
132 foreach (qw(TagsShowOnList TagsInputOnList)) {
133 C4::Context->preference($_) and $template->param($_ => 1);
137 ## URI Re-Writing
138 # Deprecated, but preserved because it's interesting :-)
139 # The same thing can be accomplished with mod_rewrite in
140 # a more elegant way
142 #my $rewrite_flag;
143 #my $uri = $cgi->url(-base => 1);
144 #my $relative_url = $cgi->url(-relative=>1);
145 #$uri.="/".$relative_url."?";
146 #warn "URI:$uri";
147 #my @cgi_params_list = $cgi->param();
148 #my $url_params = $cgi->Vars;
150 #for my $each_param_set (@cgi_params_list) {
151 # $uri.= join "", map "\&$each_param_set=".$_, split("\0",$url_params->{$each_param_set}) if $url_params->{$each_param_set};
153 #warn "New URI:$uri";
154 # Only re-write a URI if there are params or if it already hasn't been re-written
155 #unless (($cgi->param('r')) || (!$cgi->param()) ) {
156 # print $cgi->redirect( -uri=>$uri."&r=1",
157 # -cookie => $cookie);
158 # exit;
161 # load the branches
163 my $branches = GetBranches(); # used later in *getRecords, probably should be internalized by those functions after caching in C4::Branch is established
164 $template->param(
165 searchdomainloop => GetBranchCategories(undef,'searchdomain'),
168 # load the language limits (for search)
169 my $languages_limit_loop = getAllLanguages();
170 $template->param(search_languages_loop => $languages_limit_loop,);
172 # load the Type stuff
173 my $itemtypes = GetItemTypes;
174 # the index parameter is different for item-level itemtypes
175 my $itype_or_itemtype = (C4::Context->preference("item-level_itypes"))?'itype':'itemtype';
176 my @advancedsearchesloop;
177 my $cnt;
178 my $advanced_search_types = C4::Context->preference("AdvancedSearchTypes") || "itemtypes";
179 my @advanced_search_types = split(/\|/, $advanced_search_types);
181 foreach my $advanced_srch_type (@advanced_search_types) {
182 if ($advanced_srch_type eq 'itemtypes') {
183 # itemtype is a special case, since it's not defined in authorized values
184 my @itypesloop;
185 foreach my $thisitemtype ( sort {$itemtypes->{$a}->{'description'} cmp $itemtypes->{$b}->{'description'} } keys %$itemtypes ) {
186 my %row =( number=>$cnt++,
187 ccl => "$itype_or_itemtype,phr",
188 code => $thisitemtype,
189 description => $itemtypes->{$thisitemtype}->{'description'},
190 imageurl=> getitemtypeimagelocation( 'opac', $itemtypes->{$thisitemtype}->{'imageurl'} ),
192 push @itypesloop, \%row;
194 my %search_code = ( advanced_search_type => $advanced_srch_type,
195 code_loop => \@itypesloop );
196 push @advancedsearchesloop, \%search_code;
197 } else {
198 # covers all the other cases: non-itemtype authorized values
199 my $advsearchtypes = GetAuthorisedValues($advanced_srch_type, '', 'opac');
200 my @authvalueloop;
201 for my $thisitemtype (@$advsearchtypes) {
202 my %row =(
203 number=>$cnt++,
204 ccl => $advanced_srch_type,
205 code => $thisitemtype->{authorised_value},
206 description => $thisitemtype->{'lib_opac'} || $thisitemtype->{'lib'},
207 imageurl => getitemtypeimagelocation( 'opac', $thisitemtype->{'imageurl'} ),
209 push @authvalueloop, \%row;
211 my %search_code = ( advanced_search_type => $advanced_srch_type,
212 code_loop => \@authvalueloop );
213 push @advancedsearchesloop, \%search_code;
216 $template->param(advancedsearchesloop => \@advancedsearchesloop);
218 # # load the itypes (Called item types in the template -- just authorized values for searching)
219 # my ($itypecount,@itype_loop) = GetCcodes();
220 # $template->param(itypeloop=>\@itype_loop,);
222 # The following should only be loaded if we're bringing up the advanced search template
223 if ( $template_type && $template_type eq 'advsearch' ) {
224 # load the servers (used for searching -- to do federated searching, etc.)
225 my $primary_servers_loop;# = displayPrimaryServers();
226 $template->param(outer_servers_loop => $primary_servers_loop,);
228 my $secondary_servers_loop;
229 $template->param(outer_sup_servers_loop => $secondary_servers_loop,);
231 # set the default sorting
232 if ( C4::Context->preference('OPACdefaultSortField')
233 && C4::Context->preference('OPACdefaultSortOrder') ) {
234 my $default_sort_by =
235 C4::Context->preference('OPACdefaultSortField') . '_'
236 . C4::Context->preference('OPACdefaultSortOrder');
237 $template->param( sort_by => $default_sort_by );
240 # determine what to display next to the search boxes (ie, boolean option
241 # shouldn't appear on the first one, scan indexes should, adding a new
242 # box should only appear on the last, etc.
243 my @search_boxes_array;
244 my $search_boxes_count = 3; # begin whith 3 boxes
245 for (my $i=1;$i<=$search_boxes_count;$i++) {
246 # if it's the first one, don't display boolean option, but show scan indexes
247 if ($i==1) {
248 push @search_boxes_array,
250 scan_index => 1,
254 # if it's the last one, show the 'add field' box
255 elsif ($i==$search_boxes_count) {
256 push @search_boxes_array,
258 boolean => 1,
259 add_field => 1,
262 else {
263 push @search_boxes_array,
265 boolean => 1,
270 $template->param(uc( C4::Context->preference("marcflavour")) => 1, # we already did this for UNIMARC
271 advsearch => 1,
272 search_boxes_loop => \@search_boxes_array);
274 # use the global setting by default
275 if ( C4::Context->preference("expandedSearchOption") == 1 ) {
276 $template->param( expanded_options => C4::Context->preference("expandedSearchOption") );
278 # but let the user override it
279 if (defined $cgi->param('expanded_options')) {
280 if ( ($cgi->param('expanded_options') == 0) || ($cgi->param('expanded_options') == 1 ) ) {
281 $template->param( expanded_options => $cgi->param('expanded_options'));
284 output_html_with_http_headers $cgi, $cookie, $template->output;
285 exit;
288 ### OK, if we're this far, we're performing an actual search
290 # Fetch the paramater list as a hash in scalar context:
291 # * returns paramater list as tied hash ref
292 # * we can edit the values by changing the key
293 # * multivalued CGI paramaters are returned as a packaged string separated by "\0" (null)
294 my $params = $cgi->Vars;
295 my $tag;
296 $tag = $params->{tag} if $params->{tag};
299 # String with params with the search criteria for the paging in opac-detail
300 my $pasarParams = '';
301 my $j = 0;
302 for (keys %$params) {
303 my @pasarParam = split("\0", $params->{$_});
304 for my $paramValue(@pasarParam) {
305 $pasarParams .= '&amp;' if ($j > 0);
306 $pasarParams .= $_ . '=' . $paramValue;
307 $j++;
311 # Params that can have more than one value
312 # sort by is used to sort the query
313 # in theory can have more than one but generally there's just one
314 my @sort_by;
315 my $default_sort_by;
316 if ( C4::Context->preference('OPACdefaultSortField')
317 && C4::Context->preference('OPACdefaultSortOrder') ) {
318 $default_sort_by =
319 C4::Context->preference('OPACdefaultSortField') . '_'
320 . C4::Context->preference('OPACdefaultSortOrder');
323 my @allowed_sortby = qw /acqdate_asc acqdate_dsc author_az author_za call_number_asc call_number_dsc popularity_asc popularity_dsc pubdate_asc pubdate_dsc relevance title_az title_za/;
324 @sort_by = split("\0",$params->{'sort_by'}) if $params->{'sort_by'};
325 $sort_by[0] = $default_sort_by if !$sort_by[0] && defined($default_sort_by);
326 foreach my $sort (@sort_by) {
327 if ( $sort ~~ @allowed_sortby ) {
328 $template->param($sort => 1);
331 $template->param('sort_by' => $sort_by[0]);
333 # Use the servers defined, or just search our local catalog(default)
334 my @servers;
335 @servers = split("\0",$params->{'server'}) if $params->{'server'};
336 unless (@servers) {
337 #FIXME: this should be handled using Context.pm
338 @servers = ("biblioserver");
339 # @servers = C4::Context->config("biblioserver");
342 # operators include boolean and proximity operators and are used
343 # to evaluate multiple operands
344 my @operators;
345 @operators = split("\0",$params->{'op'}) if $params->{'op'};
347 # indexes are query qualifiers, like 'title', 'author', etc. They
348 # can be single or multiple parameters separated by comma: kw,right-Truncation
349 my @indexes;
350 @indexes = split("\0",$params->{'idx'}) if $params->{'idx'};
352 # if a simple index (only one) display the index used in the top search box
353 if ($indexes[0] && !$indexes[1]) {
354 $template->param("ms_".$indexes[0] => 1);
356 # an operand can be a single term, a phrase, or a complete ccl query
357 my @operands;
358 @operands = split("\0",$params->{'q'}) if $params->{'q'};
360 # if a simple search, display the value in the search box
361 if ($operands[0] && !$operands[1]) {
362 $template->param(ms_value => $operands[0]);
365 # limits are use to limit to results to a pre-defined category such as branch or language
366 my @limits;
367 @limits = split("\0",$params->{'limit'}) if $params->{'limit'};
369 if($params->{'multibranchlimit'}) {
370 push @limits, '('.join( " or ", map { "branch: $_ " } @{ GetBranchesInCategory( $params->{'multibranchlimit'} ) } ).')';
373 my $available;
374 foreach my $limit(@limits) {
375 if ($limit =~/available/) {
376 $available = 1;
379 $template->param(available => $available);
381 # append year limits if they exist
382 if ($params->{'limit-yr'}) {
383 if ($params->{'limit-yr'} =~ /\d{4}-\d{4}/) {
384 my ($yr1,$yr2) = split(/-/, $params->{'limit-yr'});
385 push @limits, "yr,st-numeric,ge=$yr1 and yr,st-numeric,le=$yr2";
387 elsif ($params->{'limit-yr'} =~ /\d{4}/) {
388 push @limits, "yr,st-numeric=$params->{'limit-yr'}";
390 else {
391 #FIXME: Should return a error to the user, incorect date format specified
395 # Params that can only have one value
396 my $scan = $params->{'scan'};
397 my $count = C4::Context->preference('OPACnumSearchResults') || 20;
398 my $countRSS = C4::Context->preference('numSearchRSSResults') || 50;
399 my $results_per_page = $params->{'count'} || $count;
400 my $offset = $params->{'offset'} || 0;
401 my $page = $cgi->param('page') || 1;
402 $offset = ($page-1)*$results_per_page if $page>1;
403 my $hits;
404 my $expanded_facet = $params->{'expand'};
406 # Define some global variables
407 my ($error,$query,$simple_query,$query_cgi,$query_desc,$limit,$limit_cgi,$limit_desc,$stopwords_removed,$query_type);
409 my @results;
411 ## I. BUILD THE QUERY
412 my $lang = C4::Templates::getlanguage($cgi, 'opac');
413 ( $error,$query,$simple_query,$query_cgi,$query_desc,$limit,$limit_cgi,$limit_desc,$stopwords_removed,$query_type) = buildQuery(\@operators,\@operands,\@indexes,\@limits,\@sort_by, 0, $lang);
415 sub _input_cgi_parse {
416 my @elements;
417 for my $this_cgi ( split('&',shift) ) {
418 next unless $this_cgi;
419 $this_cgi =~ /(.*?)=(.*)/;
420 push @elements, { input_name => $1, input_value => $2 };
422 return @elements;
425 ## parse the query_cgi string and put it into a form suitable for <input>s
426 my @query_inputs = _input_cgi_parse($query_cgi);
427 $template->param ( QUERY_INPUTS => \@query_inputs );
429 ## parse the limit_cgi string and put it into a form suitable for <input>s
430 my @limit_inputs = $limit_cgi ? _input_cgi_parse($limit_cgi) : ();
432 # add OPAC 'hidelostitems'
433 #if (C4::Context->preference('hidelostitems') == 1) {
434 # # either lost ge 0 or no value in the lost register
435 # $query ="($query) and ( (lost,st-numeric <= 0) or ( allrecords,AlwaysMatches='' not lost,AlwaysMatches='') )";
438 # add OPAC suppression - requires at least one item indexed with Suppress
439 if (C4::Context->preference('OpacSuppression')) {
440 $query = "($query) not Suppress=1";
443 $template->param ( LIMIT_INPUTS => \@limit_inputs );
444 $template->param ( OPACResultsSidebar => C4::Context->preference('OPACResultsSidebar'));
446 ## II. DO THE SEARCH AND GET THE RESULTS
447 my $total = 0; # the total results for the whole set
448 my $facets; # this object stores the faceted results that display on the left-hand of the results page
449 my @results_array;
450 my $results_hashref;
451 my @coins;
453 if ($tag) {
454 $query_cgi = "tag=" .$tag . "&" . $query_cgi;
455 my $taglist = get_tags({term=>$tag, approved=>1});
456 $results_hashref->{biblioserver}->{hits} = scalar (@$taglist);
457 my @biblist = (map {GetBiblioData($_->{biblionumber})} @$taglist);
458 my @marclist = (map {$_->{marc}} @biblist );
459 $DEBUG and printf STDERR "taglist (%s biblionumber)\nmarclist (%s records)\n", scalar(@$taglist), scalar(@marclist);
460 $results_hashref->{biblioserver}->{RECORDS} = \@marclist;
461 # FIXME: tag search and standard search should work together, not exclusively
462 # FIXME: No facets for tags search.
464 elsif (C4::Context->preference('NoZebra')) {
465 eval {
466 ($error, $results_hashref, $facets) = NZgetRecords($query,$simple_query,\@sort_by,\@servers,$results_per_page,$offset,$expanded_facet,$branches,$query_type,$scan);
468 } elsif ($build_grouped_results) {
469 eval {
470 ($error, $results_hashref, $facets) = C4::Search::pazGetRecords($query,$simple_query,\@sort_by,\@servers,$results_per_page,$offset,$expanded_facet,$branches,$query_type,$scan);
472 } else {
473 $pasarParams .= '&amp;query=' . $query;
474 $pasarParams .= '&amp;count=' . $results_per_page;
475 $pasarParams .= '&amp;simple_query=' . $simple_query;
476 $pasarParams .= '&amp;query_type=' . $query_type if ($query_type);
477 eval {
478 ($error, $results_hashref, $facets) = getRecords($query,$simple_query,\@sort_by,\@servers,$results_per_page,$offset,$expanded_facet,$branches,$query_type,$scan);
481 # This sorts the facets into alphabetical order
482 if ($facets) {
483 foreach my $f (@$facets) {
484 $f->{facets} = [ sort { uc($a->{facet_title_value}) cmp uc($b->{facet_title_value}) } @{ $f->{facets} } ];
486 @$facets = sort {$a->{expand} cmp $b->{expand}} @$facets;
489 # use Data::Dumper; print STDERR "-" x 25, "\n", Dumper($results_hashref);
490 if ($@ || $error) {
491 $template->param(query_error => $error.$@);
492 output_html_with_http_headers $cgi, $cookie, $template->output;
493 exit;
496 # At this point, each server has given us a result set
497 # now we build that set for template display
498 my @sup_results_array;
499 for (my $i=0;$i<@servers;$i++) {
500 my $server = $servers[$i];
501 if ($server && $server =~/biblioserver/) { # this is the local bibliographic server
502 $hits = $results_hashref->{$server}->{"hits"};
503 my $page = $cgi->param('page') || 0;
504 my @newresults;
505 if ($build_grouped_results) {
506 foreach my $group (@{ $results_hashref->{$server}->{"GROUPS"} }) {
507 # because pazGetRecords handles retieving only the records
508 # we want as specified by $offset and $results_per_page,
509 # we need to set the offset parameter of searchResults to 0
510 my @group_results = searchResults( 'opac', $query_desc, $group->{'group_count'},$results_per_page, 0, $scan,
511 $group->{"RECORDS"});
512 push @newresults, { group_label => $group->{'group_label'}, GROUP_RESULTS => \@group_results };
514 } else {
515 @newresults = searchResults('opac', $query_desc, $hits, $results_per_page, $offset, $scan,
516 $results_hashref->{$server}->{"RECORDS"});
519 # must define a value for size if not present in DB
520 # in order to avoid problems generated by the default size value in TT
521 foreach my $line (@newresults) {
522 if ( not exists $line->{'size'} ) { $line->{'size'} = "" }
523 # while we're checking each line, see if item is in the cart
524 if ( grep {$_ eq $line->{'biblionumber'}} @cart_list) {
525 $line->{'incart'} = 1;
530 my $tag_quantity;
531 if (C4::Context->preference('TagsEnabled') and
532 $tag_quantity = C4::Context->preference('TagsShowOnList')) {
533 foreach (@newresults) {
534 my $bibnum = $_->{biblionumber} or next;
535 $_->{itemsissued} = CountItemsIssued( $bibnum );
536 $_ ->{'TagLoop'} = get_tags({biblionumber=>$bibnum, approved=>1, 'sort'=>'-weight',
537 limit=>$tag_quantity });
541 if (C4::Context->preference('COinSinOPACResults')) {
542 foreach (@newresults) {
543 my $record = GetMarcBiblio($_->{'biblionumber'});
544 $_->{coins} = GetCOinSBiblio($record);
545 if ( C4::Context->preference( "Babeltheque" ) and $_->{normalized_isbn} ) {
546 my $isbn = Business::ISBN->new( $_->{normalized_isbn} );
547 next if not $isbn;
548 $isbn = $isbn->as_isbn13->as_string;
549 $isbn =~ s/-//g;
550 my $social_datas = C4::SocialData::get_data( $isbn );
551 next if not $social_datas;
552 for my $key ( keys %$social_datas ) {
553 $_->{$key} = $$social_datas{$key};
554 if ( $key eq 'score_avg' ){
555 $_->{score_int} = sprintf("%.0f", $$social_datas{score_avg} );
563 if ( C4::Context->preference('OpacStarRatings') eq 'all' ) {
564 foreach my $res (@newresults) {
565 my $rating = GetRating( $res->{'biblionumber'}, $borrowernumber );
566 $res->{'rating_value'} = $rating->{'rating_value'};
567 $res->{'rating_total'} = $rating->{'rating_total'};
568 $res->{'rating_avg'} = $rating->{'rating_avg'};
569 $res->{'rating_avg_int'} = $rating->{'rating_avg_int'};
573 if ($results_hashref->{$server}->{"hits"}){
574 $total = $total + $results_hashref->{$server}->{"hits"};
577 # Opac search history
578 my $newsearchcookie;
579 if (C4::Context->preference('EnableOpacSearchHistory')) {
580 my @recentSearches;
582 # Getting the (maybe) already sent cookie
583 my $searchcookie = $cgi->cookie('KohaOpacRecentSearches');
584 if ($searchcookie){
585 $searchcookie = uri_unescape($searchcookie);
586 if (thaw($searchcookie)) {
587 @recentSearches = @{thaw($searchcookie)};
591 # Adding the new search if needed
592 if (!$borrowernumber || $borrowernumber eq '') {
593 # To a cookie (the user is not logged in)
594 if (($params->{'offset'}||'') eq '') {
595 push @recentSearches, {
596 "query_desc" => $query_desc || "unknown",
597 "query_cgi" => $query_cgi || "unknown",
598 "time" => time(),
599 "total" => $total
601 $template->param(ShowOpacRecentSearchLink => 1);
604 shift @recentSearches if (@recentSearches > 15);
605 # Pushing the cookie back
606 $newsearchcookie = $cgi->cookie(
607 -name => 'KohaOpacRecentSearches',
608 # We uri_escape the whole freezed structure so we're sure we won't have any encoding problems
609 -value => uri_escape(freeze(\@recentSearches)),
610 -expires => ''
612 $cookie = [$cookie, $newsearchcookie];
614 else {
615 # To the session (the user is logged in)
616 if (($params->{'offset'}||'') eq '') {
617 AddSearchHistory($borrowernumber, $cgi->cookie("CGISESSID"), $query_desc, $query_cgi, $total);
618 $template->param(ShowOpacRecentSearchLink => 1);
622 ## If there's just one result, redirect to the detail page
623 if ($total == 1 && $format ne 'rss2'
624 && $format ne 'opensearchdescription' && $format ne 'atom') {
625 my $biblionumber=$newresults[0]->{biblionumber};
626 if (C4::Context->preference('BiblioDefaultView') eq 'isbd') {
627 print $cgi->redirect("/cgi-bin/koha/opac-ISBDdetail.pl?biblionumber=$biblionumber");
628 } elsif (C4::Context->preference('BiblioDefaultView') eq 'marc') {
629 print $cgi->redirect("/cgi-bin/koha/opac-MARCdetail.pl?biblionumber=$biblionumber");
630 } else {
631 print $cgi->redirect("/cgi-bin/koha/opac-detail.pl?biblionumber=$biblionumber");
633 exit;
635 if ($hits) {
636 if (!C4::Context->preference('NoZebra') && !$build_grouped_results) {
637 # We build the encrypted list of first OPACnumSearchResults biblios to pass with the search criteria for paging on opac-detail
638 $pasarParams .= '&amp;listBiblios=';
639 my $j = 0;
640 foreach (@newresults) {
641 my $bibnum = ($_->{biblionumber})?$_->{biblionumber}:0;
642 $pasarParams .= $bibnum . ',';
643 $j++;
644 last if ($j == $results_per_page);
646 chop $pasarParams if ($pasarParams =~ /,$/);
647 $pasarParams .= '&amp;total=' . int($total) if ($pasarParams !~ /total=(?:[0-9]+)?/);
648 if ($pasarParams) {
649 my $session = get_session($cgi->cookie("CGISESSID"));
650 $session->param('busc' => $pasarParams);
654 $template->param(total => $hits);
655 my $limit_cgi_not_availablity = $limit_cgi;
656 $limit_cgi_not_availablity =~ s/&limit=available//g if defined $limit_cgi_not_availablity;
657 $template->param(limit_cgi_not_availablity => $limit_cgi_not_availablity);
658 $template->param(limit_cgi => $limit_cgi);
659 $template->param(countrss => $countRSS );
660 $template->param(query_cgi => $query_cgi);
661 $template->param(query_desc => $query_desc);
662 $template->param(limit_desc => $limit_desc);
663 $template->param(offset => $offset);
664 $template->param(DisplayMultiPlaceHold => $DisplayMultiPlaceHold);
665 if ($query_desc || $limit_desc) {
666 $template->param(searchdesc => 1);
668 $template->param(stopwords_removed => "@$stopwords_removed") if $stopwords_removed;
669 $template->param(results_per_page => $results_per_page);
670 my $hide = C4::Context->preference('OpacHiddenItems');
671 $hide = ($hide =~ m/\S/) if $hide; # Just in case it has some spaces/new lines
672 $template->param(
673 SEARCH_RESULTS => \@newresults,
674 OPACItemsResultsDisplay => (C4::Context->preference("OPACItemsResultsDisplay") eq "itemdetails"?1:0),
675 suppress_result_number => $hide,
677 if (C4::Context->preference("OPACLocalCoverImages")){
678 $template->param(OPACLocalCoverImages => 1);
679 $template->param(OPACLocalCoverImagesPriority => C4::Context->preference("OPACLocalCoverImagesPriority"));
681 ## Build the page numbers on the bottom of the page
682 my @page_numbers;
683 # total number of pages there will be
684 my $pages = ceil($hits / $results_per_page);
685 # default page number
686 my $current_page_number = 1;
687 if ($offset) {
688 $current_page_number = ( $offset / $results_per_page + 1 );
690 my $previous_page_offset;
691 if ( $offset >= $results_per_page ) {
692 $previous_page_offset = $offset - $results_per_page;
694 my $next_page_offset = $offset + $results_per_page;
695 # If we're within the first 10 pages, keep it simple
696 #warn "current page:".$current_page_number;
697 if ($current_page_number < 10) {
698 # just show the first 10 pages
699 # Loop through the pages
700 my $pages_to_show = 10;
701 $pages_to_show = $pages if $pages<10;
702 for ($i=1; $i<=$pages_to_show;$i++) {
703 # the offset for this page
704 my $this_offset = (($i*$results_per_page)-$results_per_page);
705 # the page number for this page
706 my $this_page_number = $i;
707 # put it in the array
708 push @page_numbers,
709 { offset => $this_offset,
710 pg => $this_page_number,
711 highlight => $this_page_number == $current_page_number,
712 sort_by => join ' ', @sort_by
718 # now, show twenty pages, with the current one smack in the middle
719 else {
720 for ($i=$current_page_number; $i<=($current_page_number + 20 );$i++) {
721 my $this_offset = ((($i-9)*$results_per_page)-$results_per_page);
722 my $this_page_number = $i-9;
723 if ( $this_page_number <= $pages ) {
724 push @page_numbers,
725 { offset => $this_offset,
726 pg => $this_page_number,
727 highlight => $this_page_number == $current_page_number,
728 sort_by => join ' ', @sort_by
734 $template->param( PAGE_NUMBERS => \@page_numbers,
735 previous_page_offset => $previous_page_offset) unless $pages < 2;
736 $template->param(next_page_offset => $next_page_offset) unless $pages eq $current_page_number;
738 # no hits
739 else {
740 $template->param(
741 searchdesc => 1,
742 query_desc => $query_desc,
743 limit_desc => $limit_desc,
744 query_cgi => $query_cgi,
745 limit_cgi => $limit_cgi
748 } # end of the if local
749 # asynchronously search the authority server
750 elsif ($server && $server =~/authorityserver/) { # this is the local authority server
751 my @inner_sup_results_array;
752 for my $sup_record ( @{$results_hashref->{$server}->{"RECORDS"}} ) {
753 my $marc_record_object = MARC::Record->new_from_usmarc($sup_record);
754 my $title_field = $marc_record_object->field(100);
755 push @inner_sup_results_array, {
756 'title' => $title_field->subfield('a'),
757 'link' => "&amp;idx=an&amp;q=".$marc_record_object->field('001')->as_string(),
760 my $servername = $server;
761 push @sup_results_array, { servername => $servername,
762 inner_sup_results_loop => \@inner_sup_results_array} if @inner_sup_results_array;
764 # FIXME: can add support for other targets as needed here
765 $template->param( outer_sup_results_loop => \@sup_results_array);
766 } #/end of the for loop
767 #$template->param(FEDERATED_RESULTS => \@results_array);
769 $template->param(
770 #classlist => $classlist,
771 total => $total,
772 opacfacets => 1,
773 facets_loop => $facets,
774 displayFacetCount=> C4::Context->preference('displayFacetCount')||0,
775 scan => $scan,
776 search_error => $error,
779 if ($query_desc || $limit_desc) {
780 $template->param(searchdesc => 1);
783 # VI. BUILD THE TEMPLATE
784 # Build drop-down list for 'Add To:' menu...
785 my ($totalref, $pubshelves, $barshelves)=
786 C4::VirtualShelves::GetSomeShelfNames($borrowernumber,'COMBO',1);
787 $template->param(
788 addbarshelves => $totalref->{bartotal},
789 addbarshelvesloop => $barshelves,
790 addpubshelves => $totalref->{pubtotal},
791 addpubshelvesloop => $pubshelves,
794 my $content_type = ($format eq 'rss' or $format eq 'atom') ? $format : 'html';
796 # If GoogleIndicTransliteration system preference is On Set paramter to load Google's javascript in OPAC search screens
797 if (C4::Context->preference('GoogleIndicTransliteration')) {
798 $template->param('GoogleIndicTransliteration' => 1);
801 $template->param( borrowernumber => $borrowernumber);
802 output_with_http_headers $cgi, $cookie, $template->output, $content_type;