Bug 11178: Make the Bootstrap OPAC theme the default for new installs
[koha.git] / authorities / ysearch.pl
index 56ef8e2..b669c08 100755 (executable)
@@ -3,6 +3,7 @@
 # This software is placed under the gnu General Public License, v2 (http://www.gnu.org/licenses/gpl.html)
 
 # Copyright 2011 BibLibre
+# Parts copyright 2012 Athens County Public Libraries
 #
 # This file is part of Koha.
 #
@@ -28,29 +29,27 @@ This script allows ajax call for dynamic authorities search
 
 use CGI;
 use Modern::Perl;
+use JSON;
+
 use C4::Context;
 use C4::Charset;
 use C4::AuthoritiesMarc;
 use C4::Auth qw/check_cookie_auth/;
+use C4::Output;
 
 my $query = new CGI;
 
-binmode STDOUT, ':encoding(UTF-8)';
-print $query->header( -type => 'text/plain', -charset => 'UTF-8' );
+my ( $auth_status, $sessionID ) = check_cookie_auth( $query->cookie('CGISESSID'), { catalogue => 1 } );
 
-my ( $auth_status, $sessionID ) = check_cookie_auth( $query->cookie('CGISESSID'), { } );
 if ( $auth_status ne "ok" ) {
+    # send empty response
+    my $reply = CGI->new("");
+    print $reply->header(-type => 'text/html');
     exit 0;
 }
 
-    my $searchstr = $query->param('query');
+    my @value      = $query->param('term');
     my $searchtype = $query->param('querytype');
-    my @value;
-    given ($searchtype) {
-        when (/^marclist$/)      { @value = (undef, undef, $searchstr); }
-        when (/^mainentry$/)     { @value = (undef, $searchstr, undef); }
-        when (/^mainmainentry$/) { @value = ($searchstr, undef, undef); }
-    }
     my @marclist  = ($searchtype);
     my $authtypecode = $query->param('authtypecode');
     my @and_or    = $query->param('and_or');
@@ -62,10 +61,27 @@ if ( $auth_status ne "ok" ) {
     my $startfrom = 0;
 
     my ( $results, $total ) = SearchAuthorities( \@marclist, \@and_or, \@excluding, \@operator, \@value, $startfrom * $resultsperpage, $resultsperpage, $authtypecode, $orderby );
-    foreach (@$results) {
-       my ($value) = $_->{'summary'};
-        # Removes new lines
-        $value =~ s/<br \/>/ /g;
-        $value =~ s/\n//g;
-       print nsb_clean($value) . "\n";
+
+    my %used_summaries; # hash to avoid duplicates
+    my @summaries;
+    foreach my $result (@$results) {
+        my $authorized = $result->{'summary'}->{'authorized'};
+        my $summary    = join(
+            ' ',
+            map {
+                ( $searchtype eq 'mainmainentry' )
+                  ? $_->{'hemain'}
+                  : $_->{'heading'}
+              } @$authorized
+        );
+        $summary =~ s/^\s+//;
+        $summary =~ s/\s+$//;
+        $summary = nsb_clean($summary);
+        # test if already added ignoring case
+        unless ( exists $used_summaries{ lc($summary) } ) {
+            push @summaries, { 'summary' => $summary };
+            $used_summaries{ lc($summary) } = 1;
+        }
     }
+
+output_with_http_headers $query, undef, to_json(\@summaries, { utf8 => 1 }), 'json';