1 package OpenILS::Application::Search::Z3950;
2 use strict; use warnings;
3 use base qw/OpenILS::Application/;
5 use OpenILS::Utils::ZClient;
7 use MARC::File::XML (BinaryEncoding => 'UTF-8');
9 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 MARC::Charset->assume_unicode(1);
21 MARC::Charset->ignore_errors(1);
23 my $output = "usmarc";
24 my $U = 'OpenILS::Application::AppUtils';
31 __PACKAGE__->register_method(
32 method => 'do_class_search',
33 api_name => 'open-ils.search.z3950.search_class',
36 Performs a class based Z search. The classes available
37 are defined by the 'attr' fields in the config for the
39 @param auth The login session key
40 @param shash The search hash : { attr : value, attr2: value, ...}
41 @param service The service to connect to
42 @param username The username to use when connecting to the service
43 @param password The password to use when connecting to the service
47 __PACKAGE__->register_method(
48 method => 'do_service_search',
49 api_name => 'open-ils.search.z3950.search_service',
51 @param auth The login session key
52 @param query The Z3950 search string to use
53 @param service The service to connect to
54 @param username The username to use when connecting to the service
55 @param password The password to use when connecting to the service
60 __PACKAGE__->register_method(
61 method => 'do_service_search',
62 api_name => 'open-ils.search.z3950.search_raw',
64 @param auth The login session key
65 @param args An object of search params which must include:
66 host, port, db and query.
67 optional fields include username and password
72 __PACKAGE__->register_method(
73 method => "query_services",
74 api_name => "open-ils.search.z3950.retrieve_services",
76 Returns a list of service names that we have config
83 # -------------------------------------------------------------------
84 # What services do we have config info for?
85 # -------------------------------------------------------------------
87 my( $self, $client, $auth ) = @_;
88 my $e = new_editor(authtoken=>$auth);
89 return $e->event unless $e->checkauth;
90 return $e->event unless $e->allowed('REMOTE_Z3950_QUERY');
92 return fetch_service_defs();
95 # -------------------------------------------------------------------
96 # What services do we have config info for?
97 # -------------------------------------------------------------------
98 sub fetch_service_defs {
100 my $hash = $sclient->config_value('z3950', 'services');
102 # overlay config file values with in-db values
103 my $e = new_editor();
104 if($e->can('search_config_z3950_source')) {
106 my $sources = $e->search_config_z3950_source(
107 [ { name => { '!=' => undef } },
108 { flesh => 1, flesh_fields => { czs => ['attrs'] } } ]
111 for my $s ( @$sources ) {
112 $$hash{ $s->name } = {
118 record_format => $s->record_format,
119 transmission_format => $s->transmission_format,
123 for my $a ( @{ $s->attrs } ) {
124 $$hash{ $a->source }{attrs}{ $a->name } = {
128 format => $a->format,
129 source => $a->source,
130 truncation => $a->truncation,
136 # Define the set of native catalog services
137 # XXX There are i18n problems here, but let's get the staff client working first
138 # XXX Move into the DB?
139 $hash->{'native-evergreen-catalog'} = {
141 title => {code => 'title', label => 'Title'},
142 author => {code => 'author', label => 'Author'},
143 subject => {code => 'subject', label => 'Subject'},
144 keyword => {code => 'keyword', label => 'Keyword'},
145 tcn => {code => 'tcn', label => 'TCN'},
146 isbn => {code => 'isbn', label => 'ISBN'},
147 issn => {code => 'issn', label => 'ISSN'},
148 publisher => {code => 'publisher', label => 'Publisher'},
149 pubdate => {code => 'pubdate', label => 'Pub Date'},
150 item_type => {code => 'item_type', label => 'Item Type'},
154 %services = %$hash; # cache these internally so we can actually use the db-configured sources
160 # -------------------------------------------------------------------
161 # Load the pre-defined Z server configs
162 # -------------------------------------------------------------------
164 $sclient = OpenSRF::Utils::SettingsClient->new();
165 $default_service = $sclient->config_value("z3950", "default" );
169 # -------------------------------------------------------------------
170 # High-level class based search.
171 # -------------------------------------------------------------------
172 sub do_class_search {
174 fetch_service_defs() unless (scalar(keys(%services)));
181 if (!ref($$args{service})) {
182 $$args{service} = [$$args{service}];
183 $$args{username} = [$$args{username}];
184 $$args{password} = [$$args{password}];
192 for (my $i = 0; $i < @{$$args{service}}; $i++) {
193 my %tmp_args = %$args;
194 $tmp_args{service} = $$args{service}[$i];
195 $tmp_args{username} = $$args{username}[$i];
196 $tmp_args{password} = $$args{password}[$i];
198 $logger->debug("z3950: service: $tmp_args{service}, async: $tmp_args{async}");
200 if ($tmp_args{service} eq 'native-evergreen-catalog') {
201 my $method = $self->method_lookup('open-ils.search.biblio.zstyle.staff');
203 $self->method_lookup('open-ils.search.biblio.zstyle.staff')->run($auth, \%tmp_args)
208 $tmp_args{query} = compile_query('and', $tmp_args{service}, $tmp_args{search});
210 my $res = do_service_search( $self, $conn, $auth, \%tmp_args );
212 if ($U->event_code($res)) {
213 $conn->respond($res) if $U->event_code($res);
216 push @services, $tmp_args{service};
217 push @results, $res->{result};
218 push @connections, $res->{connection};
222 $logger->debug("z3950: Result object: $results[$i], Connection object: $connections[$i]");
225 $logger->debug("z3950: Connections created");
227 return undef unless (@connections);
230 # local catalog search is not processed with other z39 results;
231 $$args{service} = [grep {$_ ne 'native-evergreen-catalog'} @{$$args{service}}];
233 @connections = grep {defined $_} @connections;
234 return undef unless @connections;
236 while ((my $index = OpenILS::Utils::ZClient::event( \@connections )) != 0) {
237 my $ev = $connections[$index - 1]->last_event();
238 $logger->debug("z3950: Received event $ev");
239 if ($ev == OpenILS::Utils::ZClient::EVENT_END()) {
240 my $munged = process_results( $results[$index - 1], $$args{limit}, $$args{offset}, $$args{service}[$index -1] );
241 $$munged{service} = $$args{service}[$index - 1];
242 $conn->respond($munged);
246 $logger->debug("z3950: Search Complete");
251 # -------------------------------------------------------------------
252 # This handles the host settings, but expects a fully formed z query
253 # -------------------------------------------------------------------
254 sub do_service_search {
256 fetch_service_defs() unless (scalar(keys(%services)));
263 my $info = $services{$$args{service}};
265 $$args{host} = $$info{host};
266 $$args{port} = $$info{port};
267 $$args{db} = $$info{db};
268 $logger->debug("z3950: do_search...");
270 return do_search( $self, $conn, $auth, $args );
275 # -------------------------------------------------------------------
276 # This is the low level search method. All config and query
277 # data must be provided to this method
278 # -------------------------------------------------------------------
281 fetch_service_defs() unless (scalar(keys(%services)));
288 my $host = $$args{host} or return undef;
289 my $port = $$args{port} or return undef;
290 my $db = $$args{db} or return undef;
291 my $query = $$args{query} or return undef;
292 my $async = $$args{async} || 0;
294 my $limit = $$args{limit} || 10;
295 my $offset = $$args{offset} || 0;
297 my $username = $$args{username} || "";
298 my $password = $$args{password} || "";
300 my $tformat = $services{$args->{service}}->{transmission_format} || $output;
302 my $editor = new_editor(authtoken => $auth);
303 return $editor->event unless $editor->checkauth;
304 return $editor->event unless $editor->allowed('REMOTE_Z3950_QUERY');
306 $logger->info("z3950: connecting to server $host:$port:$db as $username");
308 my $connection = OpenILS::Utils::ZClient->new(
312 password => $password,
314 preferredRecordSyntax => $tformat,
317 if( ! $connection ) {
318 $logger->error("z3950: Unable to connect to Z server: ".
319 "$host:$port:$db:$username:$password");
320 return OpenILS::Event->new('Z3950_LOGIN_FAILED') unless $connection;
327 $logger->info("z3950: query => $query");
330 $results = $connection->search_pqf( $query );
331 } catch Error with { $err = shift; };
333 return OpenILS::Event->new(
334 'Z3950_BAD_QUERY', payload => $query, debug => "$err") if $err;
336 return OpenILS::Event->new('Z3950_SEARCH_FAILED',
337 debug => $connection->errcode." => ".$connection->errmsg." : query = $query") unless $results;
339 $logger->info("z3950: search [$query] took ".(time - $start)." seconds");
341 return {result => $results, connection => $connection} if ($async);
343 my $munged = process_results($results, $limit, $offset, $$args{service});
344 $munged->{query} = $query;
350 # -------------------------------------------------------------------
351 # Takes a result batch and returns the hitcount and a list of xml
353 # -------------------------------------------------------------------
354 sub process_results {
356 fetch_service_defs() unless (scalar(keys(%services)));
359 my $limit = shift || 10;
360 my $offset = shift || 0;
363 my $rformat = $services{$service}->{record_format};
364 my $tformat = $services{$service}->{transmission_format} || $output;
366 $results->option(elementSetName => $rformat);
367 $results->option(preferredRecordSyntax => $tformat);
368 $logger->info("z3950: using record format '$rformat' and transmission format '$tformat'");
372 my $count = $$res{count} = $results->size;
374 $logger->info("z3950: search returned $count hits");
376 my $tend = $limit + $offset;
378 my $end = ($tend <= $count) ? $tend : $count;
380 for($offset..$end - 1) {
388 $logger->info("z3950: fetching record $_");
392 my $rec = $results->record($_);
394 if ($tformat eq 'usmarc') {
395 $marc = MARC::Record->new_from_usmarc($rec->raw());
396 } elsif ($tformat eq 'xml') {
397 $marc = MARC::Record->new_from_xml($rec->raw());
399 die "Unsupported record transmission format $tformat"
402 $marcs = $U->entityize($marc->as_xml_record);
403 $marcs = $U->strip_ctrl_chars($marcs);
404 my $doc = XML::LibXML->new->parse_string($marcs);
405 $marcxml = $U->entityize($doc->documentElement->toString);
406 $marcxml = $U->strip_ctrl_chars($marcxml);
408 my $u = OpenILS::Utils::ModsParser->new();
409 $u->start_mods_batch( $marcxml );
410 $mods = $u->finish_mods_batch();
413 } catch Error with { $err = shift; };
415 push @records, { 'mvr' => $mods, 'marcxml' => $marcxml } unless $err;
416 $logger->error("z3950: bad XML : $err") if $err;
419 warn "\n\n$marcs\n\n";
423 $res->{records} = \@records;
429 # -------------------------------------------------------------------
430 # Compiles the class based search query
431 # -------------------------------------------------------------------
434 fetch_service_defs() unless (scalar(keys(%services)));
436 my $separator = shift;
440 my $count = scalar(keys %$hash);
443 $str .= "\@$separator " for (1..$count-1);
445 # -------------------------------------------------------------------
446 # "code" is the bib-1 "use attribute", "format" is the bib-1
447 # "structure attribute"
448 # -------------------------------------------------------------------
450 next unless ( exists $services{$service}->{attrs}->{$_} );
451 $str .= '@attr 1=' . $services{$service}->{attrs}->{$_}->{code} . # add the use attribute
452 ' @attr 4=' . $services{$service}->{attrs}->{$_}->{format}; # add the structure attribute
453 if (exists $services{$service}->{attrs}->{$_}->{truncation}
454 && $services{$service}->{attrs}->{$_}->{truncation} >= 0) {
455 $str .= ' @attr 5=' . $services{$service}->{attrs}->{$_}->{truncation};
457 $str .= " \"" . $$hash{$_} . "\" "; # add the search term