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 return fetch_service_defs();
92 # -------------------------------------------------------------------
93 # What services do we have config info for?
94 # -------------------------------------------------------------------
95 sub fetch_service_defs {
97 my $hash = $sclient->config_value('z3950', 'services');
99 # overlay config file values with in-db values
100 my $e = new_editor();
101 if($e->can('search_config_z3950_source')) {
103 my $sources = $e->search_config_z3950_source(
104 [ { name => { '!=' => undef } },
105 { flesh => 1, flesh_fields => { czs => ['attrs'] } } ]
108 for my $s ( @$sources ) {
109 $$hash{ $s->name } = {
115 record_format => $s->record_format,
116 transmission_format => $s->transmission_format,
120 for my $a ( @{ $s->attrs } ) {
121 $$hash{ $a->source }{attrs}{ $a->name } = {
125 format => $a->format,
126 source => $a->source,
127 truncation => $a->truncation,
133 # Define the set of native catalog services
134 # XXX There are i18n problems here, but let's get the staff client working first
135 # XXX Move into the DB?
136 $hash->{'native-evergreen-catalog'} = {
138 title => {code => 'title', label => 'Title'},
139 author => {code => 'author', label => 'Author'},
140 subject => {code => 'subject', label => 'Subject'},
141 keyword => {code => 'keyword', label => 'Keyword'},
142 tcn => {code => 'tcn', label => 'TCN'},
143 isbn => {code => 'isbn', label => 'ISBN'},
144 issn => {code => 'issn', label => 'ISSN'},
145 publisher => {code => 'publisher', label => 'Publisher'},
146 pubdate => {code => 'pubdate', label => 'Pub Date'},
147 item_type => {code => 'item_type', label => 'Item Type'},
151 %services = %$hash; # cache these internally so we can actually use the db-configured sources
157 # -------------------------------------------------------------------
158 # Load the pre-defined Z server configs
159 # -------------------------------------------------------------------
161 $sclient = OpenSRF::Utils::SettingsClient->new();
162 $default_service = $sclient->config_value("z3950", "default" );
166 # -------------------------------------------------------------------
167 # High-level class based search.
168 # -------------------------------------------------------------------
169 sub do_class_search {
171 fetch_service_defs() unless (scalar(keys(%services)));
178 if (!ref($$args{service})) {
179 $$args{service} = [$$args{service}];
180 $$args{username} = [$$args{username}];
181 $$args{password} = [$$args{password}];
189 for (my $i = 0; $i < @{$$args{service}}; $i++) {
190 my %tmp_args = %$args;
191 $tmp_args{service} = $$args{service}[$i];
192 $tmp_args{username} = $$args{username}[$i];
193 $tmp_args{password} = $$args{password}[$i];
195 $logger->debug("z3950: service: $tmp_args{service}, async: $tmp_args{async}");
197 if ($tmp_args{service} eq 'native-evergreen-catalog') {
198 my $method = $self->method_lookup('open-ils.search.biblio.zstyle.staff');
200 $self->method_lookup('open-ils.search.biblio.zstyle.staff')->run($auth, \%tmp_args)
205 $tmp_args{query} = compile_query('and', $tmp_args{service}, $tmp_args{search});
207 my $res = do_service_search( $self, $conn, $auth, \%tmp_args );
209 if ($U->event_code($res)) {
210 $conn->respond($res) if $U->event_code($res);
213 push @services, $tmp_args{service};
214 push @results, $res->{result};
215 push @connections, $res->{connection};
219 $logger->debug("z3950: Result object: $results[$i], Connection object: $connections[$i]");
222 $logger->debug("z3950: Connections created");
224 return undef unless (@connections);
227 # local catalog search is not processed with other z39 results;
228 $$args{service} = [grep {$_ ne 'native-evergreen-catalog'} @{$$args{service}}];
230 @connections = grep {defined $_} @connections;
231 return undef unless @connections;
233 while ((my $index = OpenILS::Utils::ZClient::event( \@connections )) != 0) {
234 my $ev = $connections[$index - 1]->last_event();
235 $logger->debug("z3950: Received event $ev");
236 if ($ev == OpenILS::Utils::ZClient::EVENT_END()) {
237 my $munged = process_results( $results[$index - 1], $$args{limit}, $$args{offset}, $$args{service}[$index -1] );
238 $$munged{service} = $$args{service}[$index - 1];
239 $conn->respond($munged);
243 $logger->debug("z3950: Search Complete");
248 # -------------------------------------------------------------------
249 # This handles the host settings, but expects a fully formed z query
250 # -------------------------------------------------------------------
251 sub do_service_search {
253 fetch_service_defs() unless (scalar(keys(%services)));
260 my $info = $services{$$args{service}};
262 $$args{host} = $$info{host};
263 $$args{port} = $$info{port};
264 $$args{db} = $$info{db};
265 $logger->debug("z3950: do_search...");
267 return do_search( $self, $conn, $auth, $args );
272 # -------------------------------------------------------------------
273 # This is the low level search method. All config and query
274 # data must be provided to this method
275 # -------------------------------------------------------------------
278 fetch_service_defs() unless (scalar(keys(%services)));
285 my $host = $$args{host} or return undef;
286 my $port = $$args{port} or return undef;
287 my $db = $$args{db} or return undef;
288 my $query = $$args{query} or return undef;
289 my $async = $$args{async} || 0;
291 my $limit = $$args{limit} || 10;
292 my $offset = $$args{offset} || 0;
294 my $username = $$args{username} || "";
295 my $password = $$args{password} || "";
297 my $tformat = $services{$args->{service}}->{transmission_format} || $output;
299 my $editor = new_editor(authtoken => $auth);
300 return $editor->event unless $editor->checkauth;
301 return $editor->event unless $editor->allowed('REMOTE_Z3950_QUERY');
303 $logger->info("z3950: connecting to server $host:$port:$db as $username");
305 my $connection = OpenILS::Utils::ZClient->new(
309 password => $password,
311 preferredRecordSyntax => $tformat,
314 if( ! $connection ) {
315 $logger->error("z3950: Unable to connect to Z server: ".
316 "$host:$port:$db:$username:$password");
317 return OpenILS::Event->new('Z3950_LOGIN_FAILED') unless $connection;
324 $logger->info("z3950: query => $query");
327 $results = $connection->search_pqf( $query );
328 } catch Error with { $err = shift; };
330 return OpenILS::Event->new(
331 'Z3950_BAD_QUERY', payload => $query, debug => "$err") if $err;
333 return OpenILS::Event->new('Z3950_SEARCH_FAILED',
334 debug => $connection->errcode." => ".$connection->errmsg." : query = $query") unless $results;
336 $logger->info("z3950: search [$query] took ".(time - $start)." seconds");
338 return {result => $results, connection => $connection} if ($async);
340 my $munged = process_results($results, $limit, $offset, $$args{service});
341 $munged->{query} = $query;
347 # -------------------------------------------------------------------
348 # Takes a result batch and returns the hitcount and a list of xml
350 # -------------------------------------------------------------------
351 sub process_results {
353 fetch_service_defs() unless (scalar(keys(%services)));
356 my $limit = shift || 10;
357 my $offset = shift || 0;
360 my $rformat = $services{$service}->{record_format};
361 my $tformat = $services{$service}->{transmission_format} || $output;
363 $results->option(elementSetName => $rformat);
364 $results->option(preferredRecordSyntax => $tformat);
365 $logger->info("z3950: using record format '$rformat' and transmission format '$tformat'");
369 my $count = $$res{count} = $results->size;
371 $logger->info("z3950: search returned $count hits");
373 my $tend = $limit + $offset;
375 my $end = ($tend <= $count) ? $tend : $count;
377 for($offset..$end - 1) {
385 $logger->info("z3950: fetching record $_");
389 my $rec = $results->record($_);
391 if ($tformat eq 'usmarc') {
392 $marc = MARC::Record->new_from_usmarc($rec->raw());
393 } elsif ($tformat eq 'xml') {
394 $marc = MARC::Record->new_from_xml($rec->raw());
396 die "Unsupported record transmission format $tformat"
399 $marcs = $U->entityize($marc->as_xml_record);
400 $marcs = $U->strip_ctrl_chars($marcs);
401 my $doc = XML::LibXML->new->parse_string($marcs);
402 $marcxml = $U->entityize($doc->documentElement->toString);
403 $marcxml = $U->strip_ctrl_chars($marcxml);
405 my $u = OpenILS::Utils::ModsParser->new();
406 $u->start_mods_batch( $marcxml );
407 $mods = $u->finish_mods_batch();
410 } catch Error with { $err = shift; };
412 push @records, { 'mvr' => $mods, 'marcxml' => $marcxml } unless $err;
413 $logger->error("z3950: bad XML : $err") if $err;
416 warn "\n\n$marcs\n\n";
420 $res->{records} = \@records;
426 # -------------------------------------------------------------------
427 # Compiles the class based search query
428 # -------------------------------------------------------------------
431 fetch_service_defs() unless (scalar(keys(%services)));
433 my $seperator = shift;
437 my $count = scalar(keys %$hash);
440 $str .= "\@$seperator " for (1..$count-1);
442 # -------------------------------------------------------------------
443 # "code" is the bib-1 "use attribute", "format" is the bib-1
444 # "structure attribute"
445 # -------------------------------------------------------------------
447 next unless ( exists $services{$service}->{attrs}->{$_} );
448 $str .= '@attr 1=' . $services{$service}->{attrs}->{$_}->{code} . # add the use attribute
449 ' @attr 4=' . $services{$service}->{attrs}->{$_}->{format}; # add the structure attribute
450 if (exists $services{$service}->{attrs}->{$_}->{truncation}
451 && $services{$service}->{attrs}->{$_}->{truncation} >= 0) {
452 $str .= ' @attr 5=' . $services{$service}->{attrs}->{$_}->{truncation};
454 $str .= " \"" . $$hash{$_} . "\" "; # add the search term