1 package OpenILS::Application::Search::Z3950;
2 use strict; use warnings;
3 use base qw/OpenILS::Application/;
5 use OpenILS::Utils::ZClient;
8 use Unicode::Normalize;
13 use OpenSRF::EX qw(:try);
14 use OpenILS::Utils::ModsParser;
15 use OpenSRF::Utils::SettingsClient;
16 use OpenILS::Application::AppUtils;
17 use OpenSRF::Utils::Logger qw/$logger/;
18 use OpenILS::Utils::CStoreEditor q/:funcs/;
20 my $output = "usmarc";
21 my $U = 'OpenILS::Application::AppUtils';
28 __PACKAGE__->register_method(
29 method => 'do_class_search',
30 api_name => 'open-ils.search.z3950.search_class',
33 Performs a class based Z search. The classes available
34 are defined by the 'attr' fields in the config for the
36 @param auth The login session key
37 @param shash The search hash : { attr : value, attr2: value, ...}
38 @param service The service to connect to
39 @param username The username to use when connecting to the service
40 @param password The password to use when connecting to the service
44 __PACKAGE__->register_method(
45 method => 'do_service_search',
46 api_name => 'open-ils.search.z3950.search_service',
48 @param auth The login session key
49 @param query The Z3950 search string to use
50 @param service The service to connect to
51 @param username The username to use when connecting to the service
52 @param password The password to use when connecting to the service
57 __PACKAGE__->register_method(
58 method => 'do_service_search',
59 api_name => 'open-ils.search.z3950.search_raw',
61 @param auth The login session key
62 @param args An object of search params which must include:
63 host, port, db and query.
64 optional fields include username and password
69 __PACKAGE__->register_method(
70 method => "query_services",
71 api_name => "open-ils.search.z3950.retrieve_services",
73 Returns a list of service names that we have config
80 # -------------------------------------------------------------------
81 # What services do we have config info for?
82 # -------------------------------------------------------------------
84 my( $self, $client, $auth ) = @_;
85 my $e = new_editor(authtoken=>$auth);
86 return $e->event unless $e->checkauth;
87 return $e->event unless $e->allowed('REMOTE_Z3950_QUERY');
89 my $hash = $sclient->config_value('z3950', 'services');
91 # overlay config file values with in-db values
92 if($e->can('search_config_z3950_source')) {
94 my $sources = $e->search_config_z3950_source(
95 [ { name => { '!=' => undef } },
96 { flesh => 1, flesh_fields => { czs => ['attrs'] } } ]
99 for my $s ( @$sources ) {
100 $$hash{ $s->name } = {
106 record_format => $s->record_format,
107 transmission_format => $s->transmission_format,
111 for my $a ( @{ $s->attrs } ) {
112 $$hash{ $a->source }{attrs}{ $a->name } = {
116 format => $a->format,
117 source => $a->source,
118 truncation => $a->truncation,
124 # Define the set of native catalog services
125 # XXX There are i18n problems here, but let's get the staff client working first
126 # XXX Move into the DB?
127 $hash->{'native-evergreen-catalog'} = {
129 title => {code => 'title', label => 'Title'},
130 author => {code => 'author', label => 'Author'},
131 subject => {code => 'subject', label => 'Subject'},
132 keyword => {code => 'keyword', label => 'Keyword'},
133 tcn => {code => 'tcn', label => 'TCN'},
134 isbn => {code => 'isbn', label => 'ISBN'},
135 issn => {code => 'issn', label => 'ISSN'},
136 publisher => {code => 'publisher', label => 'Publisher'},
137 pubdate => {code => 'pubdate', label => 'Pub Date'},
138 item_type => {code => 'item_type', label => 'Item Type'},
147 # -------------------------------------------------------------------
148 # Load the pre-defined Z server configs
149 # -------------------------------------------------------------------
151 $sclient = OpenSRF::Utils::SettingsClient->new();
152 $default_service = $sclient->config_value("z3950", "default" );
153 my $servs = $sclient->config_value("z3950", "services" );
154 $services{$_} = $$servs{$_} for keys %$servs;
158 # -------------------------------------------------------------------
159 # High-level class based search.
160 # -------------------------------------------------------------------
161 sub do_class_search {
168 if (!ref($$args{service})) {
169 $$args{service} = [$$args{service}];
170 $$args{username} = [$$args{username}];
171 $$args{password} = [$$args{password}];
179 for (my $i = 0; $i < @{$$args{service}}; $i++) {
180 my %tmp_args = %$args;
181 $tmp_args{service} = $$args{service}[$i];
182 $tmp_args{username} = $$args{username}[$i];
183 $tmp_args{password} = $$args{password}[$i];
185 $logger->debug("z3950: service: $tmp_args{service}, async: $tmp_args{async}");
187 if ($tmp_args{service} eq 'native-evergreen-catalog') {
188 my $method = $self->method_lookup('open-ils.search.biblio.zstyle');
190 $self->method_lookup('open-ils.search.biblio.zstyle')->run($auth, \%tmp_args)
195 $tmp_args{query} = compile_query('and', $tmp_args{service}, $tmp_args{search});
197 my $res = do_service_search( $self, $conn, $auth, \%tmp_args );
199 if ($U->event_code($res)) {
200 $conn->respond($res) if $U->event_code($res);
203 push @services, $tmp_args{service};
204 push @results, $res->{result};
205 push @connections, $res->{connection};
209 $logger->debug("z3950: Result object: $results[$i], Connection object: $connections[$i]");
212 $logger->debug("z3950: Connections created");
214 return undef unless (@connections);
217 # local catalog search is not processed with other z39 results;
218 $$args{service} = [grep {$_ ne 'native-evergreen-catalog'} @{$$args{service}}];
220 while ((my $index = OpenILS::Utils::ZClient::event( \@connections )) != 0) {
221 my $ev = $connections[$index - 1]->last_event();
222 $logger->debug("z3950: Received event $ev");
223 if ($ev == OpenILS::Utils::ZClient::EVENT_END()) {
224 my $munged = process_results( $results[$index - 1], $$args{limit}, $$args{offset}, $$args{service}[$index -1] );
225 $$munged{service} = $$args{service}[$index - 1];
226 $conn->respond($munged);
230 $logger->debug("z3950: Search Complete");
235 # -------------------------------------------------------------------
236 # This handles the host settings, but expects a fully formed z query
237 # -------------------------------------------------------------------
238 sub do_service_search {
245 my $info = $services{$$args{service}};
247 $$args{host} = $$info{host};
248 $$args{port} = $$info{port};
249 $$args{db} = $$info{db};
250 $logger->debug("z3950: do_search...");
252 return do_search( $self, $conn, $auth, $args );
257 # -------------------------------------------------------------------
258 # This is the low level search method. All config and query
259 # data must be provided to this method
260 # -------------------------------------------------------------------
268 my $host = $$args{host} or return undef;
269 my $port = $$args{port} or return undef;
270 my $db = $$args{db} or return undef;
271 my $query = $$args{query} or return undef;
272 my $async = $$args{async} || 0;
274 my $limit = $$args{limit} || 10;
275 my $offset = $$args{offset} || 0;
277 my $username = $$args{username} || "";
278 my $password = $$args{password} || "";
280 my $tformat = $services{$args->{service}}->{transmission_format} || $output;
282 my $editor = new_editor(authtoken => $auth);
283 return $editor->event unless $editor->checkauth;
284 return $editor->event unless $editor->allowed('REMOTE_Z3950_QUERY');
286 $logger->info("z3950: connecting to server $host:$port:$db as $username");
288 my $connection = OpenILS::Utils::ZClient->new(
292 password => $password,
294 preferredRecordSyntax => $tformat,
297 if( ! $connection ) {
298 $logger->error("z3950: Unable to connect to Z server: ".
299 "$host:$port:$db:$username:$password");
300 return OpenILS::Event->new('Z3950_LOGIN_FAILED') unless $connection;
307 $logger->info("z3950: query => $query");
310 $results = $connection->search_pqf( $query );
311 } catch Error with { $err = shift; };
313 return OpenILS::Event->new(
314 'Z3950_BAD_QUERY', payload => $query, debug => "$err") if $err;
316 return OpenILS::Event->new('Z3950_SEARCH_FAILED',
317 debug => $connection->errcode." => ".$connection->errmsg." : query = $query") unless $results;
319 $logger->info("z3950: search [$query] took ".(time - $start)." seconds");
321 return {result => $results, connection => $connection} if ($async);
323 my $munged = process_results($results, $limit, $offset, $$args{service});
324 $munged->{query} = $query;
330 # -------------------------------------------------------------------
331 # Takes a result batch and returns the hitcount and a list of xml
333 # -------------------------------------------------------------------
334 sub process_results {
336 my $limit = shift || 10;
337 my $offset = shift || 0;
340 my $rformat = $services{$service}->{record_format};
341 my $tformat = $services{$service}->{transmission_format} || $output;
343 $results->option(elementSetName => $rformat);
344 $results->option(preferredRecordSyntax => $tformat);
345 $logger->info("z3950: using record format '$rformat' and transmission format '$tformat'");
349 my $count = $$res{count} = $results->size;
351 $logger->info("z3950: search returned $count hits");
353 my $tend = $limit + $offset;
355 my $end = ($tend <= $count) ? $tend : $count;
357 for($offset..$end - 1) {
365 $logger->info("z3950: fetching record $_");
369 my $rec = $results->record($_);
371 if ($tformat eq 'usmarc') {
372 $marc = MARC::Record->new_from_usmarc($rec->raw());
373 } elsif ($tformat eq 'xml') {
374 $marc = MARC::Record->new_from_xml($rec->raw());
376 die "Unsupported record transmission format $tformat"
379 $marcs = entityize($marc->as_xml_record);
380 my $doc = XML::LibXML->new->parse_string($marcs);
381 $marcxml = entityize( $doc->documentElement->toString );
383 my $u = OpenILS::Utils::ModsParser->new();
384 $u->start_mods_batch( $marcxml );
385 $mods = $u->finish_mods_batch();
388 } catch Error with { $err = shift; };
390 push @records, { 'mvr' => $mods, 'marcxml' => $marcxml } unless $err;
391 $logger->error("z3950: bad XML : $err") if $err;
394 warn "\n\n$marcs\n\n";
398 $res->{records} = \@records;
404 # -------------------------------------------------------------------
405 # Compiles the class based search query
406 # -------------------------------------------------------------------
409 my $seperator = shift;
413 my $count = scalar(keys %$hash);
416 $str .= "\@$seperator " for (1..$count-1);
418 # -------------------------------------------------------------------
419 # "code" is the bib-1 "use attribute", "format" is the bib-1
420 # "structure attribute"
421 # -------------------------------------------------------------------
423 next unless ( exists $services{$service}->{attrs}->{$_} );
424 $str .= '@attr 1=' . $services{$service}->{attrs}->{$_}->{code} . # add the use attribute
425 ' @attr 4=' . $services{$service}->{attrs}->{$_}->{format}; # add the structure attribute
426 if (exists $services{$service}->{attrs}->{$_}->{truncation}){
427 $str .= ' @attr 5=' . $services{$service}->{attrs}->{$_}->{truncation};
429 $str .= " \"" . $$hash{$_} . "\" "; # add the search term
436 # -------------------------------------------------------------------
437 # Handles the unicode
438 # -------------------------------------------------------------------
441 my $form = shift || "";
444 $stuff = NFD($stuff);
446 $stuff = NFC($stuff);
449 $stuff =~ s/([\x{0080}-\x{fffd}])/sprintf('&#x%X;',ord($1))/sgoe;
451 # strip some other unfriendly chars that may leak in
452 $stuff =~ s/([\x{0000}-\x{0008}])//sgoe;