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,
129 # -------------------------------------------------------------------
130 # Load the pre-defined Z server configs
131 # -------------------------------------------------------------------
133 $sclient = OpenSRF::Utils::SettingsClient->new();
134 $default_service = $sclient->config_value("z3950", "default" );
135 my $servs = $sclient->config_value("z3950", "services" );
136 $services{$_} = $$servs{$_} for keys %$servs;
140 # -------------------------------------------------------------------
141 # High-level class based search.
142 # -------------------------------------------------------------------
143 sub do_class_search {
150 if (!ref($$args{service})) {
151 $$args{service} = [$$args{service}];
152 $$args{username} = [$$args{username}];
153 $$args{password} = [$$args{password}];
161 for (my $i = 0; $i < @{$$args{service}}; $i++) {
162 my %tmp_args = %$args;
163 $tmp_args{service} = $$args{service}[$i];
164 $tmp_args{username} = $$args{username}[$i];
165 $tmp_args{password} = $$args{password}[$i];
167 $logger->debug("z3950: service: $tmp_args{service}, async: $tmp_args{async}");
169 if ($tmp_args{service} eq 'native-evergreen-catalog') {
170 my $method = $self->method_lookup('open-ils.search.biblio.zstyle');
172 $self->method_lookup('open-ils.search.biblio.zstyle')->run($auth, \%tmp_args)
177 $tmp_args{query} = compile_query('and', $tmp_args{service}, $tmp_args{search});
179 my $res = do_service_search( $self, $conn, $auth, \%tmp_args );
181 if ($U->event_code($res)) {
182 $conn->respond($res) if $U->event_code($res);
185 push @services, $tmp_args{service};
186 push @results, $res->{result};
187 push @connections, $res->{connection};
191 $logger->debug("z3950: Result object: $results[$i], Connection object: $connections[$i]");
194 $logger->debug("z3950: Connections created");
196 return undef unless (@connections);
199 # local catalog search is not processed with other z39 results;
200 $$args{service} = [grep {$_ ne 'native-evergreen-catalog'} @{$$args{service}}];
202 while ((my $index = OpenILS::Utils::ZClient::event( \@connections )) != 0) {
203 my $ev = $connections[$index - 1]->last_event();
204 $logger->debug("z3950: Received event $ev");
205 if ($ev == OpenILS::Utils::ZClient::EVENT_END()) {
206 my $munged = process_results( $results[$index - 1], $$args{limit}, $$args{offset}, $$args{service}[$index -1] );
207 $$munged{service} = $$args{service}[$index - 1];
208 $conn->respond($munged);
212 $logger->debug("z3950: Search Complete");
217 # -------------------------------------------------------------------
218 # This handles the host settings, but expects a fully formed z query
219 # -------------------------------------------------------------------
220 sub do_service_search {
227 my $info = $services{$$args{service}};
229 $$args{host} = $$info{host};
230 $$args{port} = $$info{port};
231 $$args{db} = $$info{db};
232 $logger->debug("z3950: do_search...");
234 return do_search( $self, $conn, $auth, $args );
239 # -------------------------------------------------------------------
240 # This is the low level search method. All config and query
241 # data must be provided to this method
242 # -------------------------------------------------------------------
250 my $host = $$args{host} or return undef;
251 my $port = $$args{port} or return undef;
252 my $db = $$args{db} or return undef;
253 my $query = $$args{query} or return undef;
254 my $async = $$args{async} || 0;
256 my $limit = $$args{limit} || 10;
257 my $offset = $$args{offset} || 0;
259 my $username = $$args{username} || "";
260 my $password = $$args{password} || "";
262 my $tformat = $services{$args->{service}}->{transmission_format} || $output;
264 my $editor = new_editor(authtoken => $auth);
265 return $editor->event unless $editor->checkauth;
266 return $editor->event unless $editor->allowed('REMOTE_Z3950_QUERY');
268 $logger->info("z3950: connecting to server $host:$port:$db as $username");
270 my $connection = OpenILS::Utils::ZClient->new(
274 password => $password,
276 preferredRecordSyntax => $tformat,
279 if( ! $connection ) {
280 $logger->error("z3950: Unable to connect to Z server: ".
281 "$host:$port:$db:$username:$password");
282 return OpenILS::Event->new('Z3950_LOGIN_FAILED') unless $connection;
289 $logger->info("z3950: query => $query");
292 $results = $connection->search_pqf( $query );
293 } catch Error with { $err = shift; };
295 return OpenILS::Event->new(
296 'Z3950_BAD_QUERY', payload => $query, debug => "$err") if $err;
298 return OpenILS::Event->new('Z3950_SEARCH_FAILED',
299 debug => $connection->errcode." => ".$connection->errmsg." : query = $query") unless $results;
301 $logger->info("z3950: search [$query] took ".(time - $start)." seconds");
303 return {result => $results, connection => $connection} if ($async);
305 my $munged = process_results($results, $limit, $offset, $$args{service});
306 $munged->{query} = $query;
312 # -------------------------------------------------------------------
313 # Takes a result batch and returns the hitcount and a list of xml
315 # -------------------------------------------------------------------
316 sub process_results {
318 my $limit = shift || 10;
319 my $offset = shift || 0;
322 my $rformat = $services{$service}->{record_format};
323 my $tformat = $services{$service}->{transmission_format} || $output;
325 $results->option(elementSetName => $rformat);
326 $results->option(preferredRecordSyntax => $tformat);
327 $logger->info("z3950: using record format '$rformat' and transmission format '$tformat'");
331 my $count = $$res{count} = $results->size;
333 $logger->info("z3950: search returned $count hits");
335 my $tend = $limit + $offset;
337 my $end = ($tend <= $count) ? $tend : $count;
339 for($offset..$end - 1) {
347 $logger->info("z3950: fetching record $_");
351 my $rec = $results->record($_);
353 if ($tformat eq 'usmarc') {
354 $marc = MARC::Record->new_from_usmarc($rec->raw());
355 } elsif ($tformat eq 'xml') {
356 $marc = MARC::Record->new_from_xml($rec->raw());
358 die "Unsupported record transmission format $tformat"
361 $marcs = entityize($marc->as_xml_record);
362 my $doc = XML::LibXML->new->parse_string($marcs);
363 $marcxml = entityize( $doc->documentElement->toString );
365 my $u = OpenILS::Utils::ModsParser->new();
366 $u->start_mods_batch( $marcxml );
367 $mods = $u->finish_mods_batch();
370 } catch Error with { $err = shift; };
372 push @records, { 'mvr' => $mods, 'marcxml' => $marcxml } unless $err;
373 $logger->error("z3950: bad XML : $err") if $err;
376 warn "\n\n$marcs\n\n";
380 $res->{records} = \@records;
386 # -------------------------------------------------------------------
387 # Compiles the class based search query
388 # -------------------------------------------------------------------
391 my $seperator = shift;
395 my $count = scalar(keys %$hash);
398 $str .= "\@$seperator " for (1..$count-1);
400 # -------------------------------------------------------------------
401 # "code" is the bib-1 "use attribute", "format" is the bib-1
402 # "structure attribute"
403 # -------------------------------------------------------------------
405 next unless ( exists $services{$service}->{attrs}->{$_} );
406 $str .= '@attr 1=' . $services{$service}->{attrs}->{$_}->{code} . # add the use attribute
407 ' @attr 4=' . $services{$service}->{attrs}->{$_}->{format}; # add the structure attribute
408 if (exists $services{$service}->{attrs}->{$_}->{truncation}){
409 $str .= ' @attr 5=' . $services{$service}->{attrs}->{$_}->{truncation};
411 $str .= " \"" . $$hash{$_} . "\" "; # add the search term
418 # -------------------------------------------------------------------
419 # Handles the unicode
420 # -------------------------------------------------------------------
423 my $form = shift || "";
426 $stuff = NFD($stuff);
428 $stuff = NFC($stuff);
431 $stuff =~ s/([\x{0080}-\x{fffd}])/sprintf('&#x%X;',ord($1))/sgoe;
433 # strip some other unfriendly chars that may leak in
434 $stuff =~ s/([\x{0000}-\x{0008}])//sgoe;