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 $sclient = OpenSRF::Utils::SettingsClient->new();
98 my $hash = $sclient->config_value('z3950', 'services');
100 # overlay config file values with in-db values
101 my $e = new_editor();
102 if($e->can('search_config_z3950_source')) {
104 my $sources = $e->search_config_z3950_source(
105 [ { name => { '!=' => undef } },
106 { flesh => 1, flesh_fields => { czs => ['attrs'] } } ]
109 for my $s ( @$sources ) {
110 $$hash{ $s->name } = {
116 record_format => $s->record_format,
117 transmission_format => $s->transmission_format,
121 for my $a ( @{ $s->attrs } ) {
122 $$hash{ $a->source }{attrs}{ $a->name } = {
126 format => $a->format,
127 source => $a->source,
128 truncation => $a->truncation,
134 # Define the set of native catalog services
135 # XXX There are i18n problems here, but let's get the staff client working first
136 # XXX Move into the DB?
137 $hash->{'native-evergreen-catalog'} = {
139 title => {code => 'title', label => 'Title'},
140 author => {code => 'author', label => 'Author'},
141 subject => {code => 'subject', label => 'Subject'},
142 keyword => {code => 'keyword', label => 'Keyword'},
143 tcn => {code => 'tcn', label => 'TCN'},
144 isbn => {code => 'isbn', label => 'ISBN'},
145 issn => {code => 'issn', label => 'ISSN'},
146 publisher => {code => 'publisher', label => 'Publisher'},
147 pubdate => {code => 'pubdate', label => 'Pub Date'},
148 item_type => {code => 'item_type', label => 'Item Type'},
152 %services = %$hash; # cache these internally so we can actually use the db-configured sources
158 # -------------------------------------------------------------------
159 # Load the pre-defined Z server configs
160 # -------------------------------------------------------------------
162 fetch_service_defs();
163 $default_service = $sclient->config_value("z3950", "default" );
167 # -------------------------------------------------------------------
168 # High-level class based search.
169 # -------------------------------------------------------------------
170 sub do_class_search {
177 if (!ref($$args{service})) {
178 $$args{service} = [$$args{service}];
179 $$args{username} = [$$args{username}];
180 $$args{password} = [$$args{password}];
188 for (my $i = 0; $i < @{$$args{service}}; $i++) {
189 my %tmp_args = %$args;
190 $tmp_args{service} = $$args{service}[$i];
191 $tmp_args{username} = $$args{username}[$i];
192 $tmp_args{password} = $$args{password}[$i];
194 $logger->debug("z3950: service: $tmp_args{service}, async: $tmp_args{async}");
196 if ($tmp_args{service} eq 'native-evergreen-catalog') {
197 my $method = $self->method_lookup('open-ils.search.biblio.zstyle.staff');
199 $self->method_lookup('open-ils.search.biblio.zstyle.staff')->run($auth, \%tmp_args)
204 $tmp_args{query} = compile_query('and', $tmp_args{service}, $tmp_args{search});
206 my $res = do_service_search( $self, $conn, $auth, \%tmp_args );
208 if ($U->event_code($res)) {
209 $conn->respond($res) if $U->event_code($res);
212 push @services, $tmp_args{service};
213 push @results, $res->{result};
214 push @connections, $res->{connection};
218 $logger->debug("z3950: Result object: $results[$i], Connection object: $connections[$i]");
221 $logger->debug("z3950: Connections created");
223 return undef unless (@connections);
226 # local catalog search is not processed with other z39 results;
227 $$args{service} = [grep {$_ ne 'native-evergreen-catalog'} @{$$args{service}}];
229 @connections = grep {defined $_} @connections;
230 return undef unless @connections;
232 while ((my $index = OpenILS::Utils::ZClient::event( \@connections )) != 0) {
233 my $ev = $connections[$index - 1]->last_event();
234 $logger->debug("z3950: Received event $ev");
235 if ($ev == OpenILS::Utils::ZClient::EVENT_END()) {
236 my $munged = process_results( $results[$index - 1], $$args{limit}, $$args{offset}, $$args{service}[$index -1] );
237 $$munged{service} = $$args{service}[$index - 1];
238 $conn->respond($munged);
242 $logger->debug("z3950: Search Complete");
247 # -------------------------------------------------------------------
248 # This handles the host settings, but expects a fully formed z query
249 # -------------------------------------------------------------------
250 sub do_service_search {
257 my $info = $services{$$args{service}};
259 $$args{host} = $$info{host};
260 $$args{port} = $$info{port};
261 $$args{db} = $$info{db};
262 $logger->debug("z3950: do_search...");
264 return do_search( $self, $conn, $auth, $args );
269 # -------------------------------------------------------------------
270 # This is the low level search method. All config and query
271 # data must be provided to this method
272 # -------------------------------------------------------------------
280 my $host = $$args{host} or return undef;
281 my $port = $$args{port} or return undef;
282 my $db = $$args{db} or return undef;
283 my $query = $$args{query} or return undef;
284 my $async = $$args{async} || 0;
286 my $limit = $$args{limit} || 10;
287 my $offset = $$args{offset} || 0;
289 my $username = $$args{username} || "";
290 my $password = $$args{password} || "";
292 my $tformat = $services{$args->{service}}->{transmission_format} || $output;
294 my $editor = new_editor(authtoken => $auth);
295 return $editor->event unless $editor->checkauth;
296 return $editor->event unless $editor->allowed('REMOTE_Z3950_QUERY');
298 $logger->info("z3950: connecting to server $host:$port:$db as $username");
300 my $connection = OpenILS::Utils::ZClient->new(
304 password => $password,
306 preferredRecordSyntax => $tformat,
309 if( ! $connection ) {
310 $logger->error("z3950: Unable to connect to Z server: ".
311 "$host:$port:$db:$username:$password");
312 return OpenILS::Event->new('Z3950_LOGIN_FAILED') unless $connection;
319 $logger->info("z3950: query => $query");
322 $results = $connection->search_pqf( $query );
323 } catch Error with { $err = shift; };
325 return OpenILS::Event->new(
326 'Z3950_BAD_QUERY', payload => $query, debug => "$err") if $err;
328 return OpenILS::Event->new('Z3950_SEARCH_FAILED',
329 debug => $connection->errcode." => ".$connection->errmsg." : query = $query") unless $results;
331 $logger->info("z3950: search [$query] took ".(time - $start)." seconds");
333 return {result => $results, connection => $connection} if ($async);
335 my $munged = process_results($results, $limit, $offset, $$args{service});
336 $munged->{query} = $query;
342 # -------------------------------------------------------------------
343 # Takes a result batch and returns the hitcount and a list of xml
345 # -------------------------------------------------------------------
346 sub process_results {
348 my $limit = shift || 10;
349 my $offset = shift || 0;
352 my $rformat = $services{$service}->{record_format};
353 my $tformat = $services{$service}->{transmission_format} || $output;
355 $results->option(elementSetName => $rformat);
356 $results->option(preferredRecordSyntax => $tformat);
357 $logger->info("z3950: using record format '$rformat' and transmission format '$tformat'");
361 my $count = $$res{count} = $results->size;
363 $logger->info("z3950: search returned $count hits");
365 my $tend = $limit + $offset;
367 my $end = ($tend <= $count) ? $tend : $count;
369 for($offset..$end - 1) {
377 $logger->info("z3950: fetching record $_");
381 my $rec = $results->record($_);
383 if ($tformat eq 'usmarc') {
384 $marc = MARC::Record->new_from_usmarc($rec->raw());
385 } elsif ($tformat eq 'xml') {
386 $marc = MARC::Record->new_from_xml($rec->raw());
388 die "Unsupported record transmission format $tformat"
391 $marcs = $U->entityize($marc->as_xml_record);
392 $marcs = $U->strip_ctrl_chars($marcs);
393 my $doc = XML::LibXML->new->parse_string($marcs);
394 $marcxml = $U->entityize($doc->documentElement->toString);
395 $marcxml = $U->strip_ctrl_chars($marcxml);
397 my $u = OpenILS::Utils::ModsParser->new();
398 $u->start_mods_batch( $marcxml );
399 $mods = $u->finish_mods_batch();
402 } catch Error with { $err = shift; };
404 push @records, { 'mvr' => $mods, 'marcxml' => $marcxml } unless $err;
405 $logger->error("z3950: bad XML : $err") if $err;
408 warn "\n\n$marcs\n\n";
412 $res->{records} = \@records;
418 # -------------------------------------------------------------------
419 # Compiles the class based search query
420 # -------------------------------------------------------------------
423 my $seperator = shift;
427 my $count = scalar(keys %$hash);
430 $str .= "\@$seperator " for (1..$count-1);
432 # -------------------------------------------------------------------
433 # "code" is the bib-1 "use attribute", "format" is the bib-1
434 # "structure attribute"
435 # -------------------------------------------------------------------
437 next unless ( exists $services{$service}->{attrs}->{$_} );
438 $str .= '@attr 1=' . $services{$service}->{attrs}->{$_}->{code} . # add the use attribute
439 ' @attr 4=' . $services{$service}->{attrs}->{$_}->{format}; # add the structure attribute
440 if (exists $services{$service}->{attrs}->{$_}->{truncation}){
441 $str .= ' @attr 5=' . $services{$service}->{attrs}->{$_}->{truncation};
443 $str .= " \"" . $$hash{$_} . "\" "; # add the search term