Bug 12478 - authority work in progress
[koha.git] / opac / opac-search.pl
1 #!/usr/bin/perl
2
3 # Copyright 2008 Garry Collum and the Koha Development team
4 # Copyright 2010 BibLibre
5 # Copyright 2011 KohaAloha, NZ
6 #
7 # This file is part of Koha.
8 #
9 # Koha is free software; you can redistribute it and/or modify it
10 # under the terms of the GNU General Public License as published by
11 # the Free Software Foundation; either version 3 of the License, or
12 # (at your option) any later version.
13 #
14 # Koha is distributed in the hope that it will be useful, but
15 # WITHOUT ANY WARRANTY; without even the implied warranty of
16 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 # GNU General Public License for more details.
18 #
19 # You should have received a copy of the GNU General Public License
20 # along with Koha; if not, see <http://www.gnu.org/licenses>.
21
22 # Script to perform searching
23 # Mostly copied from search.pl, see POD there
24 use Modern::Perl;
25
26 ## STEP 1. Load things that are used in both search page and
27 # results page and decide which template to load, operations 
28 # to perform, etc.
29 ## load Koha modules
30 use C4::Context;
31 use List::MoreUtils q/any/;
32
33 use Data::Dumper; # TODO remove
34
35 use Koha::ElasticSearch::Search;
36 use Koha::SearchEngine::QueryBuilder;
37 use Koha::SearchEngine::Zebra::Search;
38
39 my $searchengine = C4::Context->preference("SearchEngine");
40 my ($builder, $searcher);
41 #$searchengine = 'Zebra'; # XXX
42 $builder = Koha::SearchEngine::QueryBuilder->new();
43 for ( $searchengine ) {
44     when ( /^Solr$/ ) {
45         warn "We use Solr";
46         require 'opac/search.pl';
47         exit;
48     }
49     when ( /^Zebra$/ ) {
50         $searcher=Koha::SearchEngine::Zebra::Search->new();
51     }
52     when (/^Elasticsearch$/) {
53         # TODO refactor Koha::ES::Search into Koha::SE::ES::Search
54         $searcher=Koha::ElasticSearch::Search->new({index => 'biblios'});
55     }
56 }
57
58 use C4::Output;
59 use C4::Auth qw(:DEFAULT get_session);
60 use C4::Languages qw(getLanguages);
61 use C4::Search;
62 use C4::Search::History;
63 use C4::Biblio;  # GetBiblioData
64 use C4::Koha;
65 use C4::Tags qw(get_tags);
66 use C4::Branch; # GetBranches
67 use C4::SocialData;
68 use C4::Ratings;
69 use C4::External::OverDrive;
70
71 use Koha::LibraryCategories;
72
73 use POSIX qw(ceil floor strftime);
74 use URI::Escape;
75 use JSON qw/decode_json encode_json/;
76 use Business::ISBN;
77
78 my $DisplayMultiPlaceHold = C4::Context->preference("DisplayMultiPlaceHold");
79 # create a new CGI object
80 # FIXME: no_undef_params needs to be tested
81 use CGI qw('-no_undef_params' -utf8);
82 my $cgi = new CGI;
83
84 my $branch_group_limit = $cgi->param("branch_group_limit");
85 if ( $branch_group_limit ) {
86     if ( $branch_group_limit =~ /^multibranchlimit-/ ) {
87         # For search groups we are going to convert this branch_group_limit CGI
88         # parameter into a multibranchlimit CGI parameter for the purposes of
89         # actually performing the query
90         $cgi->param(
91             -name => 'multibranchlimit',
92             -values => substr($branch_group_limit, 17)
93         );
94     } else {
95         $cgi->append(
96             -name => 'limit',
97             -values => [ $branch_group_limit ]
98         );
99     }
100 }
101
102 BEGIN {
103     if (C4::Context->preference('BakerTaylorEnabled')) {
104         require C4::External::BakerTaylor;
105         import C4::External::BakerTaylor qw(&image_url &link_url);
106     }
107 }
108
109 my ($template,$borrowernumber,$cookie);
110 # decide which template to use
111 my $template_name;
112 my $template_type = 'basic';
113 my @params = $cgi->param("limit");
114 my @searchCategories = $cgi->param('searchcat');
115
116 my $format = $cgi->param("format") || '';
117 my $build_grouped_results = C4::Context->preference('OPACGroupResults');
118 if ($format =~ /(rss|atom|opensearchdescription)/) {
119     $template_name = 'opac-opensearch.tt';
120 }
121 elsif (@params && $build_grouped_results) {
122     $template_name = 'opac-results-grouped.tt';
123 }
124 elsif ((@params>=1) || ($cgi->param("q")) || ($cgi->param('multibranchlimit')) || ($cgi->param('limit-yr')) ) {
125     $template_name = 'opac-results.tt';
126 }
127 else {
128     $template_name = 'opac-advsearch.tt';
129     $template_type = 'advsearch';
130 }
131 # load the template
132 ($template, $borrowernumber, $cookie) = get_template_and_user({
133     template_name => $template_name,
134     query => $cgi,
135     type => "opac",
136     authnotrequired => ( C4::Context->preference("OpacPublic") ? 1 : 0 ),
137     }
138 );
139
140 my $lang = C4::Languages::getlanguage($cgi);
141
142 if ($template_name eq 'opac-results.tt') {
143    $template->param('COinSinOPACResults' => C4::Context->preference('COinSinOPACResults'));
144 }
145
146 # get biblionumbers stored in the cart
147 my @cart_list;
148
149 if($cgi->cookie("bib_list")){
150     my $cart_list = $cgi->cookie("bib_list");
151     @cart_list = split(/\//, $cart_list);
152 }
153
154 if ($format eq 'rss2' or $format eq 'opensearchdescription' or $format eq 'atom') {
155     $template->param($format => 1);
156     $template->param(timestamp => strftime("%Y-%m-%dT%H:%M:%S-00:00", gmtime)) if ($format eq 'atom'); 
157     # FIXME - the timestamp is a hack - the biblio update timestamp should be used for each
158     # entry, but not sure if that's worth an extra database query for each bib
159 }
160 if (C4::Context->preference("marcflavour") eq "UNIMARC" ) {
161     $template->param('UNIMARC' => 1);
162 }
163 elsif (C4::Context->preference("marcflavour") eq "MARC21" ) {
164     $template->param('usmarc' => 1);
165 }
166
167 $template->param( 'OPACNoResultsFound' => C4::Context->preference('OPACNoResultsFound') );
168
169 $template->param(
170     OpacStarRatings => C4::Context->preference("OpacStarRatings") );
171
172 if (C4::Context->preference('BakerTaylorEnabled')) {
173     $template->param(
174         BakerTaylorEnabled  => 1,
175         BakerTaylorImageURL => &image_url(),
176         BakerTaylorLinkURL  => &link_url(),
177         BakerTaylorBookstoreURL => C4::Context->preference('BakerTaylorBookstoreURL'),
178     );
179 }
180
181 if (C4::Context->preference('TagsEnabled')) {
182     $template->param(TagsEnabled => 1);
183     foreach (qw(TagsShowOnList TagsInputOnList)) {
184         C4::Context->preference($_) and $template->param($_ => 1);
185     }
186 }
187
188 ## URI Re-Writing
189 # Deprecated, but preserved because it's interesting :-)
190 # The same thing can be accomplished with mod_rewrite in
191 # a more elegant way
192 #                  
193 #my $rewrite_flag;
194 #my $uri = $cgi->url(-base => 1);
195 #my $relative_url = $cgi->url(-relative=>1);
196 #$uri.="/".$relative_url."?";
197 #warn "URI:$uri";
198 #my @cgi_params_list = $cgi->param();
199 #my $url_params = $cgi->Vars;
200 #
201 #for my $each_param_set (@cgi_params_list) {
202 #    $uri.= join "",  map "\&$each_param_set=".$_, split("\0",$url_params->{$each_param_set}) if $url_params->{$each_param_set};
203 #}
204 #warn "New URI:$uri";
205 # Only re-write a URI if there are params or if it already hasn't been re-written
206 #unless (($cgi->param('r')) || (!$cgi->param()) ) {
207 #    print $cgi->redirect(     -uri=>$uri."&r=1",
208 #                            -cookie => $cookie);
209 #    exit;
210 #}
211
212 # load the branches
213
214 if ($cgi->param("returntosearch")) {
215     $template->param('ReturnToSearch' => 1);
216 }
217 if ($cgi->cookie("search_path_code")) {
218     my $pathcode = $cgi->cookie("search_path_code");
219     if ($pathcode eq '"ads"') {
220         $template->param('ReturnPath' => '/cgi-bin/koha/opac-search.pl?returntosearch=1');
221     }
222     elsif ($pathcode eq '"exs"') {
223          $template->param('ReturnPath' => '/cgi-bin/koha/opac-search.pl?expanded_options=1&returntosearch=1');
224     }
225     else {
226         warn "ReturnPath switch error";
227     }
228 }
229
230 my $branches = GetBranches();   # used later in *getRecords, probably should be internalized by those functions after caching in C4::Branch is established
231 my $library_categories = Koha::LibraryCategories->search( { categorytype => 'searchdomain' }, { order_by => [ 'categorytype', 'categorycode' ] } );
232 $template->param( searchdomainloop => $library_categories );
233
234 # load the language limits (for search)
235 my $languages_limit_loop = getLanguages($lang, 1);
236 $template->param(search_languages_loop => $languages_limit_loop,);
237
238 # load the Type stuff
239 my $itemtypes = GetItemTypesCategorized;
240 # add translated_description to itemtypes
241 foreach my $itemtype ( keys %{$itemtypes} ) {
242     # Itemtypes search categories don't have (yet) translated descriptions, they are auth values
243     my $translated_description = getitemtypeinfo( $itemtype, 'opac' )->{translated_description};
244     $itemtypes->{$itemtype}->{translated_description} =
245             ( $translated_description ) ? $translated_description : $itemtypes->{$itemtype}->{description};
246 }
247 # Load the Type stuff without search categories for facets
248 my $itemtypes_nocategory = GetItemTypes;
249 # the index parameter is different for item-level itemtypes
250 my $itype_or_itemtype = (C4::Context->preference("item-level_itypes"))?'itype':'itemtype';
251 my @advancedsearchesloop;
252 my $cnt;
253 my $advanced_search_types = C4::Context->preference("AdvancedSearchTypes") || "itemtypes";
254 my @advanced_search_types = split(/\|/, $advanced_search_types);
255
256 my $hidingrules = {};
257 my $yaml = C4::Context->preference('OpacHiddenItems');
258 if ( $yaml =~ /\S/ ) {
259     $yaml = "$yaml\n\n"; # YAML expects trailing newline. Surplus does not hurt.
260     eval {
261         $hidingrules = YAML::Load($yaml);
262     };
263     if ($@) {
264         warn "Unable to parse OpacHiddenItems syspref : $@";
265     }
266 }
267
268 foreach my $advanced_srch_type (@advanced_search_types) {
269     $advanced_srch_type =~ s/^\s*//;
270     $advanced_srch_type =~ s/\s*$//;
271    if ($advanced_srch_type eq 'itemtypes') {
272    # itemtype is a special case, since it's not defined in authorized values
273         my @itypesloop;
274         foreach my $thisitemtype ( sort {$itemtypes->{$a}->{translated_description} cmp $itemtypes->{$b}->{translated_description} } keys %$itemtypes ) {
275             next if $hidingrules->{itype} && any { $_ eq $thisitemtype } @{$hidingrules->{itype}};
276             next if $hidingrules->{itemtype} && any { $_ eq $thisitemtype } @{$hidingrules->{itemtype}};
277             my %row =(  number=>$cnt++,
278                 ccl => "$itype_or_itemtype,phr",
279                 code => $thisitemtype,
280                 description => $itemtypes->{$thisitemtype}->{translated_description},
281                 imageurl=> getitemtypeimagelocation( 'opac', $itemtypes->{$thisitemtype}->{'imageurl'} ),
282                 cat => $itemtypes->{$thisitemtype}->{'iscat'},
283                 hideinopac => $itemtypes->{$thisitemtype}->{'hideinopac'},
284                 searchcategory => $itemtypes->{$thisitemtype}->{'searchcategory'},
285             );
286             if ( !$itemtypes->{$thisitemtype}->{'hideinopac'} ) {
287                 push @itypesloop, \%row;
288             }
289         }
290         my %search_code = (  advanced_search_type => $advanced_srch_type,
291                              code_loop => \@itypesloop );
292         push @advancedsearchesloop, \%search_code;
293     } else {
294     # covers all the other cases: non-itemtype authorized values
295        my $advsearchtypes = GetAuthorisedValues($advanced_srch_type, 'opac');
296         my @authvalueloop;
297         for my $thisitemtype (@$advsearchtypes) {
298             my $hiding_key = lc $thisitemtype->{category};
299             $hiding_key = "location" if $hiding_key eq 'loc';
300             next if $hidingrules->{$hiding_key} && any { $_ eq $thisitemtype->{authorised_value} } @{$hidingrules->{$hiding_key}};
301                 my %row =(
302                                 number=>$cnt++,
303                                 ccl => $advanced_srch_type,
304                 code => $thisitemtype->{authorised_value},
305                 description => $thisitemtype->{'lib_opac'} || $thisitemtype->{'lib'},
306                 searchcategory => $itemtypes->{$thisitemtype}->{'searchcategory'},
307                 imageurl => getitemtypeimagelocation( 'opac', $thisitemtype->{'imageurl'} ),
308                 );
309                 push @authvalueloop, \%row;
310         }
311         my %search_code = (  advanced_search_type => $advanced_srch_type,
312                              code_loop => \@authvalueloop );
313         push @advancedsearchesloop, \%search_code;
314     }
315 }
316 $template->param(advancedsearchesloop => \@advancedsearchesloop);
317
318 # The following should only be loaded if we're bringing up the advanced search template
319 if ( $template_type && $template_type eq 'advsearch' ) {
320     # load the servers (used for searching -- to do federated searching, etc.)
321     my $primary_servers_loop;# = displayPrimaryServers();
322     $template->param(outer_servers_loop =>  $primary_servers_loop,);
323     
324     my $secondary_servers_loop;
325     $template->param(outer_sup_servers_loop => $secondary_servers_loop,);
326
327     # set the default sorting
328     if (   C4::Context->preference('OPACdefaultSortField')
329         && C4::Context->preference('OPACdefaultSortOrder') ) {
330         my $default_sort_by =
331             C4::Context->preference('OPACdefaultSortField') . '_'
332           . C4::Context->preference('OPACdefaultSortOrder');
333         $template->param( sort_by => $default_sort_by );
334     }
335
336     # determine what to display next to the search boxes (ie, boolean option
337     # shouldn't appear on the first one, scan indexes should, adding a new
338     # box should only appear on the last, etc.
339     my @search_boxes_array;
340     my $search_boxes_count = 3; # begin whith 3 boxes
341     $template->param( search_boxes_count => $search_boxes_count );
342
343     if ($cgi->cookie("num_paragraph")){
344         $search_boxes_count = $cgi->cookie("num_paragraph");
345     }
346
347     for (my $i=1;$i<=$search_boxes_count;$i++) {
348         # if it's the first one, don't display boolean option, but show scan indexes
349         if ($i==1) {
350             push @search_boxes_array,
351                 {
352                 scan_index => 1,
353                 };
354         
355         }
356         # if it's the last one, show the 'add field' box
357         elsif ($i==$search_boxes_count) {
358             push @search_boxes_array,
359                 {
360                 boolean => 1,
361                 add_field => 1,
362                 };
363         }
364         else {
365             push @search_boxes_array,
366                 {
367                 boolean => 1,
368                 };
369         }
370
371     }
372
373     my @advsearch_limits = split /,/, C4::Context->preference('OpacAdvSearchOptions');
374     my @advsearch_more_limits = split /,/,
375       C4::Context->preference('OpacAdvSearchMoreOptions');
376     $template->param(
377         uc( C4::Context->preference("marcflavour") ) => 1,    # we already did this for UNIMARC
378         advsearch         => 1,
379         search_boxes_loop => \@search_boxes_array,
380         OpacAdvSearchOptions     => \@advsearch_limits,
381         OpacAdvSearchMoreOptions => \@advsearch_more_limits,
382     );
383
384     # use the global setting by default
385     if ( C4::Context->preference("expandedSearchOption") == 1 ) {
386         $template->param( expanded_options => C4::Context->preference("expandedSearchOption") );
387     }
388     # but let the user override it
389     if (defined $cgi->param('expanded_options')) {
390         if ( ($cgi->param('expanded_options') == 0) || ($cgi->param('expanded_options') == 1 ) ) {
391             $template->param( expanded_options => $cgi->param('expanded_options'));
392         }
393     }
394
395     if (C4::Context->preference('OPACNumbersPreferPhrase')) {
396         $template->param('numbersphr' => 1);
397     }
398
399     output_html_with_http_headers $cgi, $cookie, $template->output;
400     exit;
401 }
402
403 ### OK, if we're this far, we're performing an actual search
404
405 # Fetch the paramater list as a hash in scalar context:
406 #  * returns paramater list as tied hash ref
407 #  * we can edit the values by changing the key
408 #  * multivalued CGI paramaters are returned as a packaged string separated by "\0" (null)
409 my $params = $cgi->Vars;
410 my $tag;
411 if ( $params->{tag} ) {
412     $tag = $params->{tag};
413     $template->param( tag => $tag );
414 }
415
416 # String with params with the search criteria for the paging in opac-detail
417 # param value is URI encoded and params separator is HTML encode (&amp;)
418 my $pasarParams = '';
419 my $j = 0;
420 for (keys %$params) {
421     my @pasarParam = $cgi->param($_);
422     for my $paramValue(@pasarParam) {
423         $pasarParams .= '&amp;' if ($j > 0);
424         $pasarParams .= $_ . '=' . uri_escape_utf8($paramValue);
425         $j++;
426     }
427 }
428
429 # Params that can have more than one value
430 # sort by is used to sort the query
431 # in theory can have more than one but generally there's just one
432 my @sort_by;
433 my $default_sort_by;
434 if (   C4::Context->preference('OPACdefaultSortField')
435     && C4::Context->preference('OPACdefaultSortOrder') ) {
436     $default_sort_by =
437         C4::Context->preference('OPACdefaultSortField') . '_'
438       . C4::Context->preference('OPACdefaultSortOrder');
439 }
440
441 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/; 
442 @sort_by = $cgi->param('sort_by');
443 $sort_by[0] = $default_sort_by if !$sort_by[0] && defined($default_sort_by);
444 foreach my $sort (@sort_by) {
445     if ( grep { /^$sort$/ } @allowed_sortby ) {
446         $template->param($sort => 1);
447     }
448 }
449 $template->param('sort_by' => $sort_by[0]);
450
451 # Use the servers defined, or just search our local catalog(default)
452 my @servers = $cgi->param('server');
453 unless (@servers) {
454     #FIXME: this should be handled using Context.pm
455     @servers = ("biblioserver");
456     # @servers = C4::Context->config("biblioserver");
457 }
458
459 # operators include boolean and proximity operators and are used
460 # to evaluate multiple operands
461 my @operators = $cgi->param('op');
462 @operators = map { uri_unescape($_) } @operators;
463
464 # indexes are query qualifiers, like 'title', 'author', etc. They
465 # can be single or multiple parameters separated by comma: kw,right-Truncation 
466 my @indexes = $cgi->param('idx');
467 @indexes = map { uri_unescape($_) } @indexes;
468
469 # if a simple index (only one)  display the index used in the top search box
470 if ($indexes[0] && !$indexes[1]) {
471     $template->param("ms_".$indexes[0] => 1);
472 }
473 # an operand can be a single term, a phrase, or a complete ccl query
474 my @operands = $cgi->param('q');
475 @operands = map { uri_unescape($_) } @operands;
476
477 $template->{VARS}->{querystring} = join(' ', @operands);
478
479 # if a simple search, display the value in the search box
480 if ($operands[0] && !$operands[1]) {
481     my $ms_query = $operands[0];
482     $ms_query =~ s/ #\S+//;
483     $template->param(ms_value => $ms_query);
484 }
485
486 # limits are use to limit to results to a pre-defined category such as branch or language
487 my @limits = $cgi->param('limit');
488 @limits = map { uri_unescape($_) } @limits;
489 my @nolimits = $cgi->param('nolimit');
490 @nolimits = map { uri_unescape($_) } @nolimits;
491 my %is_nolimit = map { $_ => 1 } @nolimits;
492 @limits = grep { not $is_nolimit{$_} } @limits;
493
494 if (@searchCategories > 0) {
495     my @tabcat;
496     foreach my $typecategory (@searchCategories) {
497         push (@tabcat, GetItemTypesByCategory($typecategory));
498     }
499
500     foreach my $itemtypeInCategory (@tabcat) {
501         push (@limits, "mc-$itype_or_itemtype,phr:".$itemtypeInCategory);
502     }
503 }
504
505 @limits = map { uri_unescape($_) } @limits;
506
507 if($params->{'multibranchlimit'}) {
508     my $library_category = Koha::LibraryCategories->find( $params->{multibranchlimit} );
509     my @libraries = $library_category->libraries;
510     my $multibranch = '('.join( " or ", map { 'branch: ' . $_->id } @libraries ) .')';
511     push @limits, $multibranch if ($multibranch ne  '()');
512 }
513
514 my $available;
515 foreach my $limit(@limits) {
516     if ($limit =~/available/) {
517         $available = 1;
518     }
519 }
520 $template->param(available => $available);
521
522 # append year limits if they exist
523 if ($params->{'limit-yr'}) {
524     if ($params->{'limit-yr'} =~ /\d{4}-\d{4}/) {
525         my ($yr1,$yr2) = split(/-/, $params->{'limit-yr'});
526         push @limits, "yr,st-numeric,ge=$yr1 and yr,st-numeric,le=$yr2";
527     }
528     elsif ($params->{'limit-yr'} =~ /\d{4}/) {
529         push @limits, "yr,st-numeric=$params->{'limit-yr'}";
530     }
531     else {
532         #FIXME: Should return a error to the user, incorect date format specified
533     }
534 }
535
536 # Params that can only have one value
537 my $scan = $params->{'scan'};
538 my $count = C4::Context->preference('OPACnumSearchResults') || 20;
539 my $countRSS         = C4::Context->preference('numSearchRSSResults') || 50;
540 my $results_per_page = $params->{'count'} || $count;
541 my $offset = $params->{'offset'} || 0;
542 my $page = $cgi->param('page') || 1;
543 $offset = ($page-1)*$results_per_page if $page>1;
544 my $hits;
545 my $expanded_facet = $params->{'expand'};
546
547 # Define some global variables
548 my ($error,$query,$simple_query,$query_cgi,$query_desc,$limit,$limit_cgi,$limit_desc,$query_type);
549
550 my @results;
551
552 ## I. BUILD THE QUERY
553 ( $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, 0, $lang);
554
555 sub _input_cgi_parse {
556     my @elements;
557     my $query_cgi = shift or return @elements;
558     for my $this_cgi ( split('&',$query_cgi) ) {
559         next unless $this_cgi;
560         $this_cgi =~ /(.*?)=(.*)/;
561         push @elements, { input_name => $1, input_value => Encode::decode_utf8( uri_unescape($2) ) };
562     }
563     return @elements;
564 }
565
566 ## parse the query_cgi string and put it into a form suitable for <input>s
567 my @query_inputs = _input_cgi_parse($query_cgi);
568 $template->param ( QUERY_INPUTS => \@query_inputs );
569
570 ## parse the limit_cgi string and put it into a form suitable for <input>s
571 my @limit_inputs = $limit_cgi ? _input_cgi_parse($limit_cgi) : ();
572
573 # add OPAC 'hidelostitems'
574 #if (C4::Context->preference('hidelostitems') == 1) {
575 #    # either lost ge 0 or no value in the lost register
576 #    $query ="($query) and ( (lost,st-numeric <= 0) or ( allrecords,AlwaysMatches='' not lost,AlwaysMatches='') )";
577 #}
578 #
579 # add OPAC suppression - requires at least one item indexed with Suppress
580 if (C4::Context->preference('OpacSuppression')) {
581     # OPAC suppression by IP address
582     if (C4::Context->preference('OpacSuppressionByIPRange')) {
583         my $IPAddress = $ENV{'REMOTE_ADDR'};
584         my $IPRange = C4::Context->preference('OpacSuppressionByIPRange');
585         if ($IPAddress !~ /^$IPRange/)  {
586             if ( $query_type eq 'pqf' ) {
587                 $query = '@not '.$query.' @attr 14=1 @attr 1=9011 1';
588             } else {
589                 $query = "($query) not Suppress=1";
590             }
591         }
592     }
593     else {
594         if ( $query_type eq 'pqf' ) {
595             #$query = "($query) && -(suppress:1)"; #QP syntax
596             $query = '@not '.$query.' @attr 14=1 @attr 1=9011 1'; #PQF syntax
597         } else {
598             $query = "($query) not Suppress=1";
599         }
600     }
601 }
602
603 $template->param ( LIMIT_INPUTS => \@limit_inputs );
604 $template->param ( OPACResultsSidebar => C4::Context->preference('OPACResultsSidebar'));
605
606 ## II. DO THE SEARCH AND GET THE RESULTS
607 my $total = 0; # the total results for the whole set
608 my $facets; # this object stores the faceted results that display on the left-hand of the results page
609 my @results_array;
610 my $results_hashref;
611 my @coins;
612
613 if ($tag) {
614     $query_cgi = "tag=" .$tag . "&" . $query_cgi;
615     my $taglist = get_tags({term=>$tag, approved=>1});
616     $results_hashref->{biblioserver}->{hits} = scalar (@$taglist);
617     my @biblist  = (map {GetBiblioData($_->{biblionumber})} @$taglist);
618     my @marclist = (map { (C4::Context->config('zebra_bib_index_mode') eq 'dom')? $_->{marcxml}: $_->{marc}; } @biblist);
619     $DEBUG and printf STDERR "taglist (%s biblionumber)\nmarclist (%s records)\n", scalar(@$taglist), scalar(@marclist);
620     $results_hashref->{biblioserver}->{RECORDS} = \@marclist;
621     # FIXME: tag search and standard search should work together, not exclusively
622     # FIXME: No facets for tags search.
623 } elsif ($build_grouped_results) {
624     eval {
625         ($error, $results_hashref, $facets) = C4::Search::pazGetRecords($query,$simple_query,\@sort_by,\@servers,$results_per_page,$offset,$expanded_facet,$branches,$query_type,$scan);
626     };
627 } else {
628     $pasarParams .= '&amp;query=' . uri_escape_utf8($query);
629     $pasarParams .= '&amp;count=' . uri_escape_utf8($results_per_page);
630     $pasarParams .= '&amp;simple_query=' . uri_escape_utf8($simple_query);
631     $pasarParams .= '&amp;query_type=' . uri_escape_utf8($query_type) if ($query_type);
632     eval {
633         ($error, $results_hashref, $facets) = $searcher->search_compat($query,$simple_query,\@sort_by,\@servers,$results_per_page,$offset,$expanded_facet,$branches,$itemtypes,$query_type,$scan,1);
634 };
635 }
636
637 # This sorts the facets into alphabetical order
638 if ($facets && @$facets) {
639     foreach my $f (@$facets) {
640         $f->{facets} = [ sort { uc($a->{facet_label_value}) cmp uc($b->{facet_label_value}) } @{ $f->{facets} } ];
641     }
642     @$facets = sort {$a->{expand} cmp $b->{expand}} @$facets;
643 }
644
645 # use Data::Dumper; print STDERR "-" x 25, "\n", Dumper($results_hashref);
646 if ($@ || $error) {
647     $template->param(query_error => $error.$@);
648     output_html_with_http_headers $cgi, $cookie, $template->output;
649     exit;
650 }
651
652 # At this point, each server has given us a result set
653 # now we build that set for template display
654 my @sup_results_array;
655 for (my $i=0;$i<@servers;$i++) {
656     my $server = $servers[$i];
657     if ($server && $server =~/biblioserver/) { # this is the local bibliographic server
658         $hits = $results_hashref->{$server}->{"hits"};
659         my $page = $cgi->param('page') || 0;
660         my @newresults;
661         if ($build_grouped_results) {
662             foreach my $group (@{ $results_hashref->{$server}->{"GROUPS"} }) {
663                 # because pazGetRecords handles retieving only the records
664                 # we want as specified by $offset and $results_per_page,
665                 # we need to set the offset parameter of searchResults to 0
666                 my @group_results = searchResults( 'opac', $query_desc, $group->{'group_count'},$results_per_page, 0, $scan,
667                                                    $group->{"RECORDS"});
668                 push @newresults, { group_label => $group->{'group_label'}, GROUP_RESULTS => \@group_results };
669             }
670         } else {
671             @newresults = searchResults('opac', $query_desc, $hits, $results_per_page, $offset, $scan,
672                                         $results_hashref->{$server}->{"RECORDS"});
673         }
674         $hits = 0 unless @newresults;
675
676         foreach my $res (@newresults) {
677
678             # must define a value for size if not present in DB
679             # in order to avoid problems generated by the default size value in TT
680             if ( not exists $res->{'size'} ) { $res->{'size'} = "" }
681             # while we're checking each line, see if item is in the cart
682             if ( grep {$_ eq $res->{'biblionumber'}} @cart_list) {
683                 $res->{'incart'} = 1;
684             }
685
686             if (C4::Context->preference('COinSinOPACResults')) {
687                 my $record = GetMarcBiblio($res->{'biblionumber'});
688                 $res->{coins} = GetCOinSBiblio($record);
689             }
690             if ( C4::Context->preference( "Babeltheque" ) and $res->{normalized_isbn} ) {
691                 if( my $isbn = Business::ISBN->new( $res->{normalized_isbn} ) ) {
692                     $isbn = $isbn->as_isbn13->as_string;
693                     $isbn =~ s/-//g;
694                     my $social_datas = C4::SocialData::get_data( $isbn );
695                     if ( $social_datas ) {
696                         for my $key ( keys %$social_datas ) {
697                             $res->{$key} = $$social_datas{$key};
698                             if ( $key eq 'score_avg' ){
699                                 $res->{score_int} = sprintf("%.0f", $$social_datas{score_avg} );
700                             }
701                         }
702                     }
703                 }
704             }
705
706             if (C4::Context->preference('TagsEnabled') and
707                 C4::Context->preference('TagsShowOnList')) {
708                 if ( my $bibnum = $res->{biblionumber} ) {
709                     $res->{itemsissued} = CountItemsIssued( $bibnum );
710                     $res->{'TagLoop'} = get_tags({
711                         biblionumber => $bibnum,
712                         approved => 1,
713                         sort => '-weight',
714                         limit => C4::Context->preference('TagsShowOnList')
715                     });
716                 }
717             }
718
719             if ( C4::Context->preference('OpacStarRatings') eq 'all' ) {
720                 my $rating = GetRating( $res->{'biblionumber'}, $borrowernumber );
721                 $res->{'rating_value'}  = $rating->{'rating_value'};
722                 $res->{'rating_total'}  = $rating->{'rating_total'};
723                 $res->{'rating_avg'}    = $rating->{'rating_avg'};
724                 $res->{'rating_avg_int'} = $rating->{'rating_avg_int'};
725             }
726         }
727
728         if ($results_hashref->{$server}->{"hits"}){
729             $total = $total + $hits;
730         }
731
732         # Opac search history
733         if (C4::Context->preference('EnableOpacSearchHistory')) {
734             unless ( $offset ) {
735                 my $path_info = $cgi->url(-path_info=>1);
736                 my $query_cgi_history = $cgi->url(-query=>1);
737                 $query_cgi_history =~ s/^$path_info\?//;
738                 $query_cgi_history =~ s/;/&/g;
739                 my $query_desc_history = join ", ", grep { defined $_ } $query_desc, $limit_desc;
740
741                 unless ( $borrowernumber ) {
742                     my $new_searches = C4::Search::History::add_to_session({
743                             cgi => $cgi,
744                             query_desc => $query_desc_history,
745                             query_cgi => $query_cgi_history,
746                             total => $total,
747                             type => "biblio",
748                     });
749                 } else {
750                     # To the session (the user is logged in)
751                     C4::Search::History::add({
752                         userid => $borrowernumber,
753                         sessionid => $cgi->cookie("CGISESSID"),
754                         query_desc => $query_desc_history,
755                         query_cgi => $query_cgi_history,
756                         total => $total,
757                         type => "biblio",
758                     });
759                 }
760             }
761             $template->param( EnableOpacSearchHistory => 1 );
762         }
763
764         ## If there's just one result, redirect to the detail page
765         if ($total == 1 && $format ne 'rss2'
766         && $format ne 'opensearchdescription' && $format ne 'atom') {
767             my $biblionumber=$newresults[0]->{biblionumber};
768             if (C4::Context->preference('BiblioDefaultView') eq 'isbd') {
769                 print $cgi->redirect("/cgi-bin/koha/opac-ISBDdetail.pl?biblionumber=$biblionumber");
770             } elsif  (C4::Context->preference('BiblioDefaultView') eq 'marc') {
771                 print $cgi->redirect("/cgi-bin/koha/opac-MARCdetail.pl?biblionumber=$biblionumber");
772             } else {
773                 print $cgi->redirect("/cgi-bin/koha/opac-detail.pl?biblionumber=$biblionumber");
774             } 
775             exit;
776         }
777         if ($hits) {
778             if ( !$build_grouped_results ) {
779                 # We build the encrypted list of first OPACnumSearchResults biblios to pass with the search criteria for paging on opac-detail
780                 $pasarParams .= '&amp;listBiblios=';
781                 my $j = 0;
782                 foreach (@newresults) {
783                     my $bibnum = ($_->{biblionumber})?$_->{biblionumber}:0;
784                     $pasarParams .= uri_escape_utf8($bibnum) . ',';
785                     $j++;
786                     last if ($j == $results_per_page);
787                 }
788                 chop $pasarParams if ($pasarParams =~ /,$/);
789                 $pasarParams .= '&amp;total=' . uri_escape_utf8( int($total) ) if ($pasarParams !~ /total=(?:[0-9]+)?/);
790                 if ($pasarParams) {
791                     my $session = get_session($cgi->cookie("CGISESSID"));
792                     $session->param('busc' => $pasarParams);
793                 }
794                 #
795             }
796             $template->param(total => $hits);
797             my $limit_cgi_not_availablity = $limit_cgi;
798             $limit_cgi_not_availablity =~ s/&limit=available//g if defined $limit_cgi_not_availablity;
799             $template->param(limit_cgi_not_availablity => $limit_cgi_not_availablity);
800             $template->param(limit_cgi => $limit_cgi);
801             $template->param(countrss  => $countRSS );
802             $template->param(query_cgi => $query_cgi);
803             $template->param(query_desc => $query_desc);
804             $template->param(limit_desc => $limit_desc);
805             $template->param(offset     => $offset);
806             $template->param(DisplayMultiPlaceHold => $DisplayMultiPlaceHold);
807             if ($query_desc || $limit_desc) {
808                 $template->param(searchdesc => 1);
809             }
810             $template->param(results_per_page =>  $results_per_page);
811             my $hide = C4::Context->preference('OpacHiddenItems');
812             $hide = ($hide =~ m/\S/) if $hide; # Just in case it has some spaces/new lines
813             my $branch = '';
814             if (C4::Context->userenv){
815                 $branch = C4::Context->userenv->{branch};
816             }
817             if ( C4::Context->preference('HighlightOwnItemsOnOPAC') ) {
818                 if (
819                     ( ( C4::Context->preference('HighlightOwnItemsOnOPACWhich') eq 'PatronBranch' ) && $branch )
820                     ||
821                     C4::Context->preference('HighlightOwnItemsOnOPACWhich') eq 'OpacURLBranch'
822                 ) {
823                     my $branchname;
824                     if ( C4::Context->preference('HighlightOwnItemsOnOPACWhich') eq 'PatronBranch' ) {
825                         $branchname = $branches->{$branch}->{'branchname'};
826                     }
827                     elsif (  C4::Context->preference('HighlightOwnItemsOnOPACWhich') eq 'OpacURLBranch' ) {
828                         $branchname = $branches->{ $ENV{'BRANCHCODE'} }->{'branchname'};
829                     }
830
831                     foreach my $res ( @newresults ) {
832                         my @new_loop;
833                         my @top_loop;
834                         my @old_loop = @{$res->{'available_items_loop'}};
835                         foreach my $item ( @old_loop ) {
836                             if ( $item->{'branchname'} eq $branchname ) {
837                                 $item->{'this_branch'} = 1;
838                                 push( @top_loop, $item );
839                             } else {
840                                 push( @new_loop, $item );
841                             }
842                         }
843                         my @complete_loop = ( @top_loop, @new_loop );
844                         $res->{'available_items_loop'} = \@complete_loop;
845                     }
846                 }
847             }
848
849             $template->param(
850                 SEARCH_RESULTS => \@newresults,
851                 OPACItemsResultsDisplay => (C4::Context->preference("OPACItemsResultsDisplay")),
852                 suppress_result_number => $hide,
853                             );
854             if (C4::Context->preference("OPACLocalCoverImages")){
855                 $template->param(OPACLocalCoverImages => 1);
856                 $template->param(OPACLocalCoverImagesPriority => C4::Context->preference("OPACLocalCoverImagesPriority"));
857             }
858             ## Build the page numbers on the bottom of the page
859             my @page_numbers;
860             # total number of pages there will be
861             my $pages = ceil($hits / $results_per_page);
862             # default page number
863             my $current_page_number = 1;
864             if ($offset) {
865                 $current_page_number = ( $offset / $results_per_page + 1 );
866             }
867             my $previous_page_offset;
868             if ( $offset >= $results_per_page ) {
869                 $previous_page_offset = $offset - $results_per_page;
870             }
871             my $next_page_offset = $offset + $results_per_page;
872             # If we're within the first 10 pages, keep it simple
873             #warn "current page:".$current_page_number;
874             if ($current_page_number < 10) {
875                 # just show the first 10 pages
876                 # Loop through the pages
877                 my $pages_to_show = 10;
878                 $pages_to_show = $pages if $pages<10;
879                 for ($i=1; $i<=$pages_to_show;$i++) {
880                     # the offset for this page
881                     my $this_offset = (($i*$results_per_page)-$results_per_page);
882                     # the page number for this page
883                     my $this_page_number = $i;
884                     # put it in the array
885                     push @page_numbers,
886                       { offset    => $this_offset,
887                         pg        => $this_page_number,
888                         highlight => $this_page_number == $current_page_number,
889                         sort_by   => join ' ', @sort_by
890                       };
891
892                 }
893                         
894             }
895             # now, show twenty pages, with the current one smack in the middle
896             else {
897                 for ($i=$current_page_number; $i<=($current_page_number + 20 );$i++) {
898                     my $this_offset = ((($i-9)*$results_per_page)-$results_per_page);
899                     my $this_page_number = $i-9;
900                     if ( $this_page_number <= $pages ) {
901                         push @page_numbers,
902                           { offset    => $this_offset,
903                             pg        => $this_page_number,
904                             highlight => $this_page_number == $current_page_number,
905                             sort_by => join ' ', @sort_by
906                           };
907                     }
908                 }
909                         
910             }
911             $template->param(   PAGE_NUMBERS => \@page_numbers,
912                                 previous_page_offset => $previous_page_offset) unless $pages < 2;
913             $template->param(next_page_offset => $next_page_offset) unless $pages eq $current_page_number;
914         }
915         # no hits
916         else {
917             my $nohits = C4::Context->preference('OPACNoResultsFound');
918             if ($nohits and $nohits=~/{QUERY_KW}/){
919                 # extracting keywords in case of relaunching search
920                 (my $query_kw=$query_desc)=~s/ and|or / /g;
921                 my @query_kw=($query_kw=~ /([-\w]+\b)(?:[^,:]|$)/g);
922                 $query_kw=join('+',@query_kw);
923                 $nohits=~s/{QUERY_KW}/$query_kw/g;
924                 $template->param('OPACNoResultsFound' =>$nohits);
925             }
926             $template->param(
927                 searchdesc => 1,
928                 query_desc => $query_desc,
929                 limit_desc => $limit_desc,
930                 query_cgi  => $query_cgi,
931                 limit_cgi  => $limit_cgi
932             );
933         }
934     } # end of the if local
935     # asynchronously search the authority server
936     elsif ($server && $server =~/authorityserver/) { # this is the local authority server
937         my @inner_sup_results_array;
938         for my $sup_record ( @{$results_hashref->{$server}->{"RECORDS"}} ) {
939             my $marc_record_object = MARC::Record->new_from_usmarc($sup_record);
940             my $title_field = $marc_record_object->field(100);
941             push @inner_sup_results_array, {
942                 'title' => $title_field->subfield('a'),
943                 'link' => "&amp;idx=an&amp;q=".$marc_record_object->field('001')->as_string(),
944             };
945         }
946         my $servername = $server;
947         push @sup_results_array, {  servername => $servername,
948                                     inner_sup_results_loop => \@inner_sup_results_array} if @inner_sup_results_array;
949     }
950     # FIXME: can add support for other targets as needed here
951     $template->param(           outer_sup_results_loop => \@sup_results_array);
952 } #/end of the for loop
953 #$template->param(FEDERATED_RESULTS => \@results_array);
954
955 for my $facet ( @$facets ) {
956     for my $entry ( @{ $facet->{facets} } ) {
957         my $index = $entry->{type_link_value};
958         my $value = $entry->{facet_link_value};
959         $entry->{active} = grep { $_->{input_value} eq qq{$index:$value} } @limit_inputs;
960     }
961 }
962
963
964 $template->param(
965             #classlist => $classlist,
966             total => $total,
967             opacfacets => 1,
968             facets_loop => $facets,
969             displayFacetCount=> C4::Context->preference('displayFacetCount')||0,
970             scan => $scan,
971             search_error => $error,
972 );
973
974 if ($query_desc || $limit_desc) {
975     $template->param(searchdesc => 1);
976 }
977
978 # VI. BUILD THE TEMPLATE
979 my $some_private_shelves = Koha::Virtualshelves->get_some_shelves(
980     {
981         borrowernumber => $borrowernumber,
982         add_allowed    => 1,
983         category       => 1,
984     }
985 );
986 my $some_public_shelves = Koha::Virtualshelves->get_some_shelves(
987     {
988         borrowernumber => $borrowernumber,
989         add_allowed    => 1,
990         category       => 2,
991     }
992 );
993
994 $template->param(
995     add_to_some_private_shelves => $some_private_shelves,
996     add_to_some_public_shelves  => $some_public_shelves,
997 );
998
999 my $content_type = ($format eq 'rss' or $format eq 'atom') ? $format : 'html';
1000
1001 # If GoogleIndicTransliteration system preference is On Set parameter to load Google's javascript in OPAC search screens
1002 if (C4::Context->preference('GoogleIndicTransliteration')) {
1003         $template->param('GoogleIndicTransliteration' => 1);
1004 }
1005
1006 $template->{VARS}->{DidYouMean} =
1007   ( defined C4::Context->preference('OPACdidyoumean')
1008       && C4::Context->preference('OPACdidyoumean') =~ m/enable/ );
1009 $template->{VARS}->{IDreamBooksReviews} = C4::Context->preference('IDreamBooksReviews');
1010 $template->{VARS}->{IDreamBooksReadometer} = C4::Context->preference('IDreamBooksReadometer');
1011 $template->{VARS}->{IDreamBooksResults} = C4::Context->preference('IDreamBooksResults');
1012
1013 if ($offset == 0 && IsOverDriveEnabled()) {
1014     $template->param(OverDriveEnabled => 1);
1015     $template->param(OverDriveLibraryID => C4::Context->preference('OverDriveLibraryID'));
1016 }
1017
1018     $template->param( borrowernumber    => $borrowernumber);
1019 output_with_http_headers $cgi, $cookie, $template->output, $content_type;