2 # Script to perform searching
3 # Mostly copied from search.pl, see POD there
4 use strict; # always use
6 ## STEP 1. Load things that are used in both search page and
7 # results page and decide which template to load, operations
12 use C4::Auth qw(:DEFAULT get_session);
14 use C4::Biblio; # GetBiblioData
16 use C4::Tags qw(get_tags);
17 use POSIX qw(ceil floor strftime);
18 use C4::Branch; # GetBranches
20 # create a new CGI object
21 # FIXME: no_undef_params needs to be tested
22 use CGI qw('-no_undef_params');
26 if (C4::Context->preference('BakerTaylorEnabled')) {
27 require C4::External::BakerTaylor;
28 import C4::External::BakerTaylor qw(&image_url &link_url);
32 my ($template,$borrowernumber,$cookie);
34 # decide which template to use
36 my $template_type = 'basic';
37 my @params = $cgi->param("limit");
39 my $format = $cgi->param("format") || '';
40 my $build_grouped_results = C4::Context->preference('OPACGroupResults');
41 if ($format =~ /(rss|atom|opensearchdescription)/) {
42 $template_name = 'opac-opensearch.tmpl';
44 elsif ($build_grouped_results) {
45 $template_name = 'opac-results-grouped.tmpl';
47 elsif ((@params>=1) || ($cgi->param("q")) || ($cgi->param('multibranchlimit')) || ($cgi->param('limit-yr')) ) {
48 $template_name = 'opac-results.tmpl';
51 $template_name = 'opac-advsearch.tmpl';
52 $template_type = 'advsearch';
55 ($template, $borrowernumber, $cookie) = get_template_and_user({
56 template_name => $template_name,
63 if ($format eq 'rss2' or $format eq 'opensearchdescription' or $format eq 'atom') {
64 $template->param($format => 1);
65 $template->param(timestamp => strftime("%Y-%m-%dT%H:%M:%S-00:00", gmtime)) if ($format eq 'atom');
66 # FIXME - the timestamp is a hack - the biblio update timestamp should be used for each
67 # entry, but not sure if that's worth an extra database query for each bib
69 if (C4::Context->preference("marcflavour") eq "UNIMARC" ) {
70 $template->param('UNIMARC' => 1);
72 elsif (C4::Context->preference("marcflavour") eq "MARC21" ) {
73 $template->param('usmarc' => 1);
76 if (C4::Context->preference('BakerTaylorEnabled')) {
78 BakerTaylorEnabled => 1,
79 BakerTaylorImageURL => &image_url(),
80 BakerTaylorLinkURL => &link_url(),
81 BakerTaylorBookstoreURL => C4::Context->preference('BakerTaylorBookstoreURL'),
84 if (C4::Context->preference('TagsEnabled')) {
85 $template->param(TagsEnabled => 1);
86 foreach (qw(TagsShowOnList TagsInputOnList)) {
87 C4::Context->preference($_) and $template->param($_ => 1);
92 # Deprecated, but preserved because it's interesting :-)
93 # The same thing can be accomplished with mod_rewrite in
97 #my $uri = $cgi->url(-base => 1);
98 #my $relative_url = $cgi->url(-relative=>1);
99 #$uri.="/".$relative_url."?";
101 #my @cgi_params_list = $cgi->param();
102 #my $url_params = $cgi->Vars;
104 #for my $each_param_set (@cgi_params_list) {
105 # $uri.= join "", map "\&$each_param_set=".$_, split("\0",$url_params->{$each_param_set}) if $url_params->{$each_param_set};
107 #warn "New URI:$uri";
108 # Only re-write a URI if there are params or if it already hasn't been re-written
109 #unless (($cgi->param('r')) || (!$cgi->param()) ) {
110 # print $cgi->redirect( -uri=>$uri."&r=1",
111 # -cookie => $cookie);
116 my $mybranch = ( C4::Context->preference('SearchMyLibraryFirst') && C4::Context->userenv && C4::Context->userenv->{branch} ) ? C4::Context->userenv->{branch} : '';
117 my $branches = GetBranches(); # used later in *getRecords, probably should be internalized by those functions after caching in C4::Branch is established
119 branchloop => GetBranchesLoop($mybranch, 0),
120 searchdomainloop => GetBranchCategories(undef,'searchdomain'),
123 # load the Type stuff
124 my $itemtypes = GetItemTypes;
125 # the index parameter is different for item-level itemtypes
126 my $itype_or_itemtype = (C4::Context->preference("item-level_itypes"))?'itype':'itemtype';
130 my $advanced_search_types = C4::Context->preference("AdvancedSearchTypes");
132 if (!$advanced_search_types or $advanced_search_types eq 'itemtypes') {
133 foreach my $thisitemtype ( sort {$itemtypes->{$a}->{'description'} cmp $itemtypes->{$b}->{'description'} } keys %$itemtypes ) {
134 my %row =( number=>$cnt++,
135 ccl => $itype_or_itemtype,
136 code => $thisitemtype,
137 selected => $selected,
138 description => $itemtypes->{$thisitemtype}->{'description'},
140 imageurl=> getitemtypeimagelocation( 'opac', $itemtypes->{$thisitemtype}->{'imageurl'} ),
142 $selected = 0; # set to zero after first pass through
143 push @itemtypesloop, \%row;
146 my $advsearchtypes = GetAuthorisedValues($advanced_search_types);
147 for my $thisitemtype (@$advsearchtypes) {
150 ccl => $advanced_search_types,
151 code => $thisitemtype->{authorised_value},
152 selected => $selected,
153 description => $thisitemtype->{'lib'},
155 imageurl=> getitemtypeimagelocation( 'opac', $thisitemtype->{'imageurl'} ),
157 push @itemtypesloop, \%row;
160 $template->param(itemtypeloop => \@itemtypesloop);
162 # # load the itypes (Called item types in the template -- just authorized values for searching)
163 # my ($itypecount,@itype_loop) = GetCcodes();
164 # $template->param(itypeloop=>\@itype_loop,);
166 # The following should only be loaded if we're bringing up the advanced search template
167 if ( $template_type eq 'advsearch' ) {
169 # load the servers (used for searching -- to do federated searching, etc.)
170 my $primary_servers_loop;# = displayPrimaryServers();
171 $template->param(outer_servers_loop => $primary_servers_loop,);
173 my $secondary_servers_loop;# = displaySecondaryServers();
174 $template->param(outer_sup_servers_loop => $secondary_servers_loop,);
176 # set the default sorting
177 my $default_sort_by = C4::Context->preference('OPACdefaultSortField')."_".C4::Context->preference('OPACdefaultSortOrder')
178 if (C4::Context->preference('OPACdefaultSortField') && C4::Context->preference('OPACdefaultSortOrder'));
179 $template->param($default_sort_by => 1);
181 # determine what to display next to the search boxes (ie, boolean option
182 # shouldn't appear on the first one, scan indexes should, adding a new
183 # box should only appear on the last, etc.
184 my @search_boxes_array;
185 my $search_boxes_count = C4::Context->preference("OPACAdvSearchInputCount") || 3;
186 for (my $i=1;$i<=$search_boxes_count;$i++) {
187 # if it's the first one, don't display boolean option, but show scan indexes
189 push @search_boxes_array,
195 # if it's the last one, show the 'add field' box
196 elsif ($i==$search_boxes_count) {
197 push @search_boxes_array,
204 push @search_boxes_array,
211 $template->param(uc(C4::Context->preference("marcflavour")) => 1, # we already did this for UNIMARC
213 search_boxes_loop => \@search_boxes_array);
215 # use the global setting by default
216 if ( C4::Context->preference("expandedSearchOption") == 1 ) {
217 $template->param( expanded_options => C4::Context->preference("expandedSearchOption") );
219 # but let the user override it
220 if ( ($cgi->param('expanded_options') == 0) || ($cgi->param('expanded_options') == 1 ) ) {
221 $template->param( expanded_options => $cgi->param('expanded_options'));
224 output_html_with_http_headers $cgi, $cookie, $template->output;
228 ### OK, if we're this far, we're performing an actual search
230 # Fetch the paramater list as a hash in scalar context:
231 # * returns paramater list as tied hash ref
232 # * we can edit the values by changing the key
233 # * multivalued CGI paramaters are returned as a packaged string separated by "\0" (null)
234 my $params = $cgi->Vars;
236 $tag = $params->{tag} if $params->{tag};
238 # Params that can have more than one value
239 # sort by is used to sort the query
240 # in theory can have more than one but generally there's just one
242 my $default_sort_by = C4::Context->preference('OPACdefaultSortField')."_".C4::Context->preference('OPACdefaultSortOrder')
243 if (C4::Context->preference('OPACdefaultSortField') && C4::Context->preference('OPACdefaultSortOrder'));
245 @sort_by = split("\0",$params->{'sort_by'}) if $params->{'sort_by'};
246 $sort_by[0] = $default_sort_by if !$sort_by[0] && defined($default_sort_by);
247 foreach my $sort (@sort_by) {
248 $template->param($sort => 1); # FIXME: security hole. can set any TMPL_VAR here
250 $template->param('sort_by' => $sort_by[0]);
252 # Use the servers defined, or just search our local catalog(default)
254 @servers = split("\0",$params->{'server'}) if $params->{'server'};
256 #FIXME: this should be handled using Context.pm
257 @servers = ("biblioserver");
258 # @servers = C4::Context->config("biblioserver");
261 # operators include boolean and proximity operators and are used
262 # to evaluate multiple operands
264 @operators = split("\0",$params->{'op'}) if $params->{'op'};
266 # indexes are query qualifiers, like 'title', 'author', etc. They
267 # can be single or multiple parameters separated by comma: kw,right-Truncation
268 my @indexes = exists($params->{'idx'}) ? split("\0",$params->{'idx'}) : ();
270 # if a simple index (only one) display the index used in the top search box
271 if ($indexes[0] && !$indexes[1]) {
272 $template->param("ms_".$indexes[0] => 1);
274 # an operand can be a single term, a phrase, or a complete ccl query
276 @operands = split("\0",$params->{'q'}) if $params->{'q'};
278 # if a simple search, display the value in the search box
279 if ($operands[0] && !$operands[1]) {
280 $template->param(ms_value => $operands[0]);
283 # limits are use to limit to results to a pre-defined category such as branch or language
285 @limits = split("\0",$params->{'limit'}) if $params->{'limit'};
287 if($params->{'multibranchlimit'}) {
288 push @limits, join(" or ", map { "branch: $_ "} @{GetBranchesInCategory($params->{'multibranchlimit'})}) ;
292 foreach my $limit(@limits) {
293 if ($limit =~/available/) {
297 $template->param(available => $available);
299 # append year limits if they exist
300 if ($params->{'limit-yr'}) {
301 if ($params->{'limit-yr'} =~ /\d{4}-\d{4}/) {
302 my ($yr1,$yr2) = split(/-/, $params->{'limit-yr'});
303 push @limits, "yr,st-numeric,ge=$yr1 and yr,st-numeric,le=$yr2";
305 elsif ($params->{'limit-yr'} =~ /\d{4}/) {
306 push @limits, "yr,st-numeric=$params->{'limit-yr'}";
309 #FIXME: Should return a error to the user, incorect date format specified
313 # Params that can only have one value
314 my $scan = $params->{'scan'};
315 my $count = C4::Context->preference('OPACnumSearchResults') || 20;
316 my $results_per_page = $params->{'count'} || $count;
317 my $offset = $params->{'offset'} || 0;
318 my $page = $cgi->param('page') || 1;
319 $offset = ($page-1)*$results_per_page if $page>1;
321 my $expanded_facet = $params->{'expand'};
323 # Define some global variables
324 my ($error,$query,$simple_query,$query_cgi,$query_desc,$limit,$limit_cgi,$limit_desc,$stopwords_removed,$query_type);
328 ## I. BUILD THE QUERY
329 ( $error,$query,$simple_query,$query_cgi,$query_desc,$limit,$limit_cgi,$limit_desc,$stopwords_removed,$query_type) = buildQuery(\@operators,\@operands,\@indexes,\@limits,\@sort_by);
331 sub _input_cgi_parse ($) {
333 for my $this_cgi ( split('&',shift) ) {
334 next unless $this_cgi;
335 $this_cgi =~ /(.*?)=(.*)/;
336 push @elements, { input_name => $1, input_value => $2 };
341 ## parse the query_cgi string and put it into a form suitable for <input>s
342 my @query_inputs = _input_cgi_parse($query_cgi);
343 $template->param ( QUERY_INPUTS => \@query_inputs );
345 ## parse the limit_cgi string and put it into a form suitable for <input>s
346 my @limit_inputs = $limit_cgi ? _input_cgi_parse($limit_cgi) : ();
348 # add OPAC 'hidelostitems'
349 if (C4::Context->preference('hidelostitems') == 1) {
350 # either lost ge 0 or no value in the lost register
351 $query ="($query) and ( (lost,st-numeric <= 0) or ( allrecords,AlwaysMatches='' not lost,AlwaysMatches='') )";
354 # add OPAC suppression - requires at least one item indexed with Suppress
355 if (C4::Context->preference('OpacSuppression')) {
356 $query = "($query) not Suppress=1";
359 $template->param ( LIMIT_INPUTS => \@limit_inputs );
361 ## II. DO THE SEARCH AND GET THE RESULTS
362 my $total = 0; # the total results for the whole set
363 my $facets; # this object stores the faceted results that display on the left-hand of the results page
368 $query_cgi = "tag=" .$tag . "&" . $query_cgi;
369 my $taglist = get_tags({term=>$tag, approved=>1});
370 $results_hashref->{biblioserver}->{hits} = scalar (@$taglist);
371 my @biblist = (map {GetBiblioData($_->{biblionumber})} @$taglist);
372 my @marclist = (map {$_->{marc}} @biblist );
373 $DEBUG and printf STDERR "taglist (%s biblionumber)\nmarclist (%s records)\n", scalar(@$taglist), scalar(@marclist);
374 $results_hashref->{biblioserver}->{RECORDS} = \@marclist;
375 # FIXME: tag search and standard search should work together, not exclusively
376 # FIXME: No facets for tags search.
378 elsif (C4::Context->preference('NoZebra')) {
380 ($error, $results_hashref, $facets) = NZgetRecords($query,$simple_query,\@sort_by,\@servers,$results_per_page,$offset,$expanded_facet,$branches,$query_type,$scan);
382 } elsif ($build_grouped_results) {
384 ($error, $results_hashref, $facets) = C4::Search::pazGetRecords($query,$simple_query,\@sort_by,\@servers,$results_per_page,$offset,$expanded_facet,$branches,$query_type,$scan);
388 ($error, $results_hashref, $facets) = getRecords($query,$simple_query,\@sort_by,\@servers,$results_per_page,$offset,$expanded_facet,$branches,$query_type,$scan);
391 # use Data::Dumper; print STDERR "-" x 25, "\n", Dumper($results_hashref);
393 $template->param(query_error => $error.$@);
394 output_html_with_http_headers $cgi, $cookie, $template->output;
398 # At this point, each server has given us a result set
399 # now we build that set for template display
400 my @sup_results_array;
401 for (my $i=0;$i<=@servers;$i++) {
402 my $server = $servers[$i];
403 if ($server =~/biblioserver/) { # this is the local bibliographic server
404 $hits = $results_hashref->{$server}->{"hits"};
405 my $page = $cgi->param('page') || 0;
407 if ($build_grouped_results) {
408 foreach my $group (@{ $results_hashref->{$server}->{"GROUPS"} }) {
409 # because pazGetRecords handles retieving only the records
410 # we want as specified by $offset and $results_per_page,
411 # we need to set the offset parameter of searchResults to 0
412 my @group_results = searchResults( $query_desc, $group->{'group_count'},$results_per_page, 0, $scan,
413 @{ $group->{"RECORDS"} });
414 push @newresults, { group_label => $group->{'group_label'}, GROUP_RESULTS => \@group_results };
417 @newresults = searchResults( $query_desc,$hits,$results_per_page,$offset,$scan,@{$results_hashref->{$server}->{"RECORDS"}});
420 if (C4::Context->preference('TagsEnabled') and
421 $tag_quantity = C4::Context->preference('TagsShowOnList')) {
422 foreach (@newresults) {
423 my $bibnum = $_->{biblionumber} or next;
424 $_ ->{'TagLoop'} = get_tags({biblionumber=>$bibnum, approved=>1, 'sort'=>'-weight',
425 limit=>$tag_quantity });
428 foreach (@newresults) {
429 $_->{'coins'} = GetCOinSBiblio($_->{'biblionumber'});
430 my $clean = $_->{isbn} or next;
432 $clean =~ /\b(\d{13})\b/ or
433 $clean =~ /\b(\d{10})\b/ or
434 $clean =~ /\b(\d{9}X)\b/i
438 $_ ->{'clean_isbn'} = $1;
441 if ($results_hashref->{$server}->{"hits"}){
442 $total = $total + $results_hashref->{$server}->{"hits"};
444 ## If there's just one result, redirect to the detail page
446 my $biblionumber=$newresults[0]->{biblionumber};
447 if (C4::Context->preference('BiblioDefaultView') eq 'isbd') {
448 print $cgi->redirect("/cgi-bin/koha/opac-ISBDdetail.pl?biblionumber=$biblionumber");
449 } elsif (C4::Context->preference('BiblioDefaultView') eq 'marc') {
450 print $cgi->redirect("/cgi-bin/koha/opac-MARCdetail.pl?biblionumber=$biblionumber");
452 print $cgi->redirect("/cgi-bin/koha/opac-detail.pl?biblionumber=$biblionumber");
457 $template->param(total => $hits);
458 my $limit_cgi_not_availablity = $limit_cgi;
459 $limit_cgi_not_availablity =~ s/&limit=available//g if defined $limit_cgi_not_availablity;
460 $template->param(limit_cgi_not_availablity => $limit_cgi_not_availablity);
461 $template->param(limit_cgi => $limit_cgi);
462 $template->param(query_cgi => $query_cgi);
463 $template->param(query_desc => $query_desc);
464 $template->param(limit_desc => $limit_desc);
465 if ($query_desc || $limit_desc) {
466 $template->param(searchdesc => 1);
468 $template->param(stopwords_removed => "@$stopwords_removed") if $stopwords_removed;
469 $template->param(results_per_page => $results_per_page);
470 $template->param(SEARCH_RESULTS => \@newresults,
471 OPACItemsResultsDisplay => (C4::Context->preference("OPACItemsResultsDisplay") eq "itemdetails"?1:0),
473 ## Build the page numbers on the bottom of the page
475 # total number of pages there will be
476 my $pages = ceil($hits / $results_per_page);
477 # default page number
478 my $current_page_number = 1;
479 $current_page_number = ($offset / $results_per_page + 1) if $offset;
480 my $previous_page_offset = $offset - $results_per_page unless ($offset - $results_per_page <0);
481 my $next_page_offset = $offset + $results_per_page;
482 # If we're within the first 10 pages, keep it simple
483 #warn "current page:".$current_page_number;
484 if ($current_page_number < 10) {
485 # just show the first 10 pages
486 # Loop through the pages
487 my $pages_to_show = 10;
488 $pages_to_show = $pages if $pages<10;
489 for ($i=1; $i<=$pages_to_show;$i++) {
490 # the offset for this page
491 my $this_offset = (($i*$results_per_page)-$results_per_page);
492 # the page number for this page
493 my $this_page_number = $i;
494 # it should only be highlighted if it's the current page
495 my $highlight = 1 if ($this_page_number == $current_page_number);
496 # put it in the array
497 push @page_numbers, { offset => $this_offset, pg => $this_page_number, highlight => $highlight, sort_by => join " ",@sort_by };
502 # now, show twenty pages, with the current one smack in the middle
504 for ($i=$current_page_number; $i<=($current_page_number + 20 );$i++) {
505 my $this_offset = ((($i-9)*$results_per_page)-$results_per_page);
506 my $this_page_number = $i-9;
507 my $highlight = 1 if ($this_page_number == $current_page_number);
508 if ($this_page_number <= $pages) {
509 push @page_numbers, { offset => $this_offset, pg => $this_page_number, highlight => $highlight, sort_by => join " ",@sort_by };
514 $template->param( PAGE_NUMBERS => \@page_numbers,
515 previous_page_offset => $previous_page_offset) unless $pages < 2;
516 $template->param(next_page_offset => $next_page_offset) unless $pages eq $current_page_number;
520 $template->param(searchdesc => 1,query_desc => $query_desc,limit_desc => $limit_desc);
522 } # end of the if local
523 # asynchronously search the authority server
524 elsif ($server =~/authorityserver/) { # this is the local authority server
525 my @inner_sup_results_array;
526 for my $sup_record ( @{$results_hashref->{$server}->{"RECORDS"}} ) {
527 my $marc_record_object = MARC::Record->new_from_usmarc($sup_record);
528 my $title_field = $marc_record_object->field(100);
529 warn "Authority Found: ".$marc_record_object->as_formatted();
530 push @inner_sup_results_array, {
531 'title' => $title_field->subfield('a'),
532 'link' => "&idx=an&q=".$marc_record_object->field('001')->as_string(),
535 my $servername = $server;
536 push @sup_results_array, { servername => $servername,
537 inner_sup_results_loop => \@inner_sup_results_array} if @inner_sup_results_array;
539 # FIXME: can add support for other targets as needed here
540 $template->param( outer_sup_results_loop => \@sup_results_array);
541 } #/end of the for loop
542 #$template->param(FEDERATED_RESULTS => \@results_array);
545 #classlist => $classlist,
548 facets_loop => $facets,
550 search_error => $error,
553 if ($query_desc || $limit_desc) {
554 $template->param(searchdesc => 1);
557 # VI. BUILD THE TEMPLATE
558 # NOTE: not using application/atom+xml or application/rss+xml beccause of Internet Explorer 6;
560 my $content_type = ($cgi->param('format') && $cgi->param('format') =~ /rss|atom/) ? "application/xml" :
563 # Build drop-down list for 'Add To:' menu...
564 my $session = get_session($cgi->cookie("CGISESSID"));
566 my $pubshelves = $session->param('pubshelves');
567 my $barshelves = $session->param('barshelves');
568 foreach my $shelf (@$pubshelves) {
569 next if ( ($shelf->{'owner'} != ($borrowernumber ? $borrowernumber : -1)) && ($shelf->{'category'} < 3) );
570 push (@addpubshelves, $shelf);
573 if (@addpubshelves) {
574 $template->param( addpubshelves => scalar (@addpubshelves));
575 $template->param( addpubshelvesloop => \@addpubshelves);
578 if (defined $barshelves) {
579 $template->param( addbarshelves => scalar (@$barshelves));
580 $template->param( addbarshelvesloop => $barshelves);
583 my $content_type = ($format eq 'rss' or $format eq 'atom') ? $format : 'html';
585 output_html_with_http_headers $cgi, $cookie, $template->output, $content_type;