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 if($e->can('search_config_z3950_source')) {
91 my $sources = $e->search_config_z3950_source(
92 [ { name => { '!=' => undef } },
93 { flesh => 1, flesh_fields => { czs => ['attrs'] } }]
97 for my $s ( @$sources ) {
107 for my $a ( @{ $s->attrs } ) {
108 $hash{ $a->source }{attrs}{ $a->name } = {
112 format => $a->format,
113 source => $a->source,
121 return $sclient->config_value('z3950', 'services');
127 # -------------------------------------------------------------------
128 # Load the pre-defined Z server configs
129 # -------------------------------------------------------------------
131 $sclient = OpenSRF::Utils::SettingsClient->new();
132 $default_service = $sclient->config_value("z3950", "default" );
133 my $servs = $sclient->config_value("z3950", "services" );
134 $services{$_} = $$servs{$_} for keys %$servs;
138 # -------------------------------------------------------------------
139 # High-level class based search.
140 # -------------------------------------------------------------------
141 sub do_class_search {
148 if (!ref($$args{service})) {
149 $$args{service} = [$$args{service}];
150 $$args{username} = [$$args{username}];
151 $$args{password} = [$$args{password}];
159 for (my $i = 0; $i < @{$$args{service}}; $i++) {
160 my %tmp_args = %$args;
161 $tmp_args{service} = $$args{service}[$i];
162 $tmp_args{username} = $$args{username}[$i];
163 $tmp_args{password} = $$args{password}[$i];
165 $logger->debug("z3950: service: $tmp_args{service}, async: $tmp_args{async}");
167 if ($tmp_args{service} eq 'native-evergreen-catalog') {
168 my $method = $self->method_lookup('open-ils.search.biblio.zstyle');
170 $self->method_lookup('open-ils.search.biblio.zstyle')->run($auth, \%tmp_args)
175 $tmp_args{query} = compile_query('and', $tmp_args{service}, $tmp_args{search});
177 my $res = do_service_search( $self, $conn, $auth, \%tmp_args );
179 if ($U->event_code($res)) {
180 $conn->respond($res) if $U->event_code($res);
183 push @services, $tmp_args{service};
184 push @results, $res->{result};
185 push @connections, $res->{connection};
189 $logger->debug("z3950: Result object: $results[$i], Connection object: $connections[$i]");
192 $logger->debug("z3950: Connections created");
194 return undef unless (@connections);
197 while ((my $index = OpenILS::Utils::ZClient::event( \@connections )) != 0) {
198 my $ev = $connections[$index - 1]->last_event();
199 $logger->debug("z3950: Received event $ev");
200 if ($ev == OpenILS::Utils::ZClient::EVENT_END()) {
201 my $munged = process_results( $results[$index - 1], $$args{limit}, $$args{offset}, $$args{service}[$index -1] );
202 $$munged{service} = $$args{service}[$index - 1];
203 $conn->respond($munged);
207 $logger->debug("z3950: Search Complete");
212 # -------------------------------------------------------------------
213 # This handles the host settings, but expects a fully formed z query
214 # -------------------------------------------------------------------
215 sub do_service_search {
222 my $info = $services{$$args{service}};
224 $$args{host} = $$info{host};
225 $$args{port} = $$info{port};
226 $$args{db} = $$info{db};
227 $logger->debug("z3950: do_search...");
229 return do_search( $self, $conn, $auth, $args );
234 # -------------------------------------------------------------------
235 # This is the low level search method. All config and query
236 # data must be provided to this method
237 # -------------------------------------------------------------------
245 my $host = $$args{host} or return undef;
246 my $port = $$args{port} or return undef;
247 my $db = $$args{db} or return undef;
248 my $query = $$args{query} or return undef;
249 my $async = $$args{async} || 0;
251 my $limit = $$args{limit} || 10;
252 my $offset = $$args{offset} || 0;
254 my $username = $$args{username} || "";
255 my $password = $$args{password} || "";
257 my $tformat = $services{$args->{service}}->{transmission_format} || $output;
259 my $editor = new_editor(authtoken => $auth);
260 return $editor->event unless $editor->checkauth;
261 return $editor->event unless $editor->allowed('REMOTE_Z3950_QUERY');
263 $logger->info("z3950: connecting to server $host:$port:$db as $username");
265 my $connection = OpenILS::Utils::ZClient->new(
269 password => $password,
271 preferredRecordSyntax => $tformat,
274 if( ! $connection ) {
275 $logger->error("z3950: Unable to connect to Z server: ".
276 "$host:$port:$db:$username:$password");
277 return OpenILS::Event->new('Z3950_LOGIN_FAILED') unless $connection;
284 $logger->info("z3950: query => $query");
287 $results = $connection->search_pqf( $query );
288 } catch Error with { $err = shift; };
290 return OpenILS::Event->new(
291 'Z3950_BAD_QUERY', payload => $query, debug => "$err") if $err;
293 return OpenILS::Event->new('Z3950_SEARCH_FAILED',
294 debug => $connection->errcode." => ".$connection->errmsg." : query = $query") unless $results;
296 $logger->info("z3950: search [$query] took ".(time - $start)." seconds");
298 return {result => $results, connection => $connection} if ($async);
300 my $munged = process_results($results, $limit, $offset, $$args{service});
301 $munged->{query} = $query;
307 # -------------------------------------------------------------------
308 # Takes a result batch and returns the hitcount and a list of xml
310 # -------------------------------------------------------------------
311 sub process_results {
313 my $limit = shift || 10;
314 my $offset = shift || 0;
317 my $rformat = $services{$service}->{record_format};
318 my $tformat = $services{$service}->{transmission_format} || $output;
320 $results->option(elementSetName => $rformat);
321 $results->option(preferredRecordSyntax => $tformat);
322 $logger->info("z3950: using record format '$rformat' and transmission format '$tformat'");
326 my $count = $$res{count} = $results->size;
328 $logger->info("z3950: search returned $count hits");
330 my $tend = $limit + $offset;
332 my $end = ($tend <= $count) ? $tend : $count;
334 for($offset..$end - 1) {
342 $logger->info("z3950: fetching record $_");
346 my $rec = $results->record($_);
348 if ($tformat eq 'usmarc') {
349 $marc = MARC::Record->new_from_usmarc($rec->raw());
350 } elsif ($tformat eq 'xml') {
351 $marc = MARC::Record->new_from_xml($rec->raw());
353 die "Unsupported record transmission format $tformat"
356 $marcs = entityize($marc->as_xml_record);
357 my $doc = XML::LibXML->new->parse_string($marcs);
358 $marcxml = entityize( $doc->documentElement->toString );
360 my $u = OpenILS::Utils::ModsParser->new();
361 $u->start_mods_batch( $marcxml );
362 $mods = $u->finish_mods_batch();
365 } catch Error with { $err = shift; };
367 push @records, { 'mvr' => $mods, 'marcxml' => $marcxml } unless $err;
368 $logger->error("z3950: bad XML : $err") if $err;
371 warn "\n\n$marcs\n\n";
375 $res->{records} = \@records;
381 # -------------------------------------------------------------------
382 # Compiles the class based search query
383 # -------------------------------------------------------------------
386 my $seperator = shift;
390 my $count = scalar(keys %$hash);
393 $str .= "\@$seperator " for (1..$count-1);
395 # -------------------------------------------------------------------
396 # "code" is the bib-1 "use attribute", "format" is the bib-1
397 # "structure attribute"
398 # -------------------------------------------------------------------
400 next unless ( exists $services{$service}->{attrs}->{$_} );
401 $str .= '@attr 1=' . $services{$service}->{attrs}->{$_}->{code} . # add the use attribute
402 ' @attr 4=' . $services{$service}->{attrs}->{$_}->{format}; # add the structure attribute
403 if (exists $services{$service}->{attrs}->{$_}->{truncation}){
404 $str .= ' @attr 5=' . $services{$service}->{attrs}->{$_}->{truncation};
406 $str .= " \"" . $$hash{$_} . "\" "; # add the search term
413 # -------------------------------------------------------------------
414 # Handles the unicode
415 # -------------------------------------------------------------------
418 my $form = shift || "";
421 $stuff = NFD($stuff);
423 $stuff = NFC($stuff);
426 $stuff =~ s/([\x{0080}-\x{fffd}])/sprintf('&#x%X;',ord($1))/sgoe;
428 # strip some other unfriendly chars that may leak in
429 $stuff =~ s/([\x{0000}-\x{0008}])//sgoe;