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 @param auth The login session key
77 Returns a list of service names that we have config
84 # -------------------------------------------------------------------
85 # What services do we have config info for?
86 # -------------------------------------------------------------------
88 my( $self, $client, $auth ) = @_;
89 my $e = new_editor(authtoken=>$auth);
90 return $e->event unless $e->checkauth;
91 return $e->event unless $e->allowed('REMOTE_Z3950_QUERY');
93 return fetch_service_defs($e);
96 # -------------------------------------------------------------------
97 # What services do we have config info for?
98 # -------------------------------------------------------------------
99 sub fetch_service_defs {
101 my $editor_with_authtoken = shift;
103 my $hash = $sclient->config_value('z3950', 'services');
105 # overlay config file values with in-db values
106 my $e = $editor_with_authtoken || new_editor();
107 if($e->can('search_config_z3950_source')) {
109 my $sources = $e->search_config_z3950_source(
110 [ { name => { '!=' => undef } },
111 { flesh => 1, flesh_fields => { czs => ['attrs'] } } ]
114 for my $s ( @$sources ) {
115 $$hash{ $s->name } = {
121 record_format => $s->record_format,
122 transmission_format => $s->transmission_format,
124 use_perm => ($s->use_perm) ?
125 $e->retrieve_permission_perm_list($s->use_perm)->code : ''
128 for my $a ( @{ $s->attrs } ) {
129 $$hash{ $a->source }{attrs}{ $a->name } = {
133 format => $a->format,
134 source => $a->source,
135 truncation => $a->truncation,
141 # Define the set of native catalog services
142 # XXX There are i18n problems here, but let's get the staff client working first
143 # XXX Move into the DB?
144 $hash->{'native-evergreen-catalog'} = {
146 title => {code => 'title', label => 'Title'},
147 author => {code => 'author', label => 'Author'},
148 subject => {code => 'subject', label => 'Subject'},
149 keyword => {code => 'keyword', label => 'Keyword'},
150 tcn => {code => 'tcn', label => 'TCN'},
151 isbn => {code => 'isbn', label => 'ISBN'},
152 issn => {code => 'issn', label => 'ISSN'},
153 publisher => {code => 'publisher', label => 'Publisher'},
154 pubdate => {code => 'pubdate', label => 'Pub Date'},
155 item_type => {code => 'item_type', label => 'Item Type'},
159 # then filter out any services which the requestor lacks the perm for
160 foreach my $s (keys %{ $hash }) {
161 if ($$hash{$s}{use_perm}) {
164 $e->requestor->ws_ou,
172 %services = %$hash; # cache these internally so we can actually use the db-configured sources
178 # -------------------------------------------------------------------
179 # Load the pre-defined Z server configs
180 # -------------------------------------------------------------------
182 $sclient = OpenSRF::Utils::SettingsClient->new();
183 $default_service = $sclient->config_value("z3950", "default" );
187 # -------------------------------------------------------------------
188 # High-level class based search.
189 # -------------------------------------------------------------------
190 sub do_class_search {
192 fetch_service_defs() unless (scalar(keys(%services)));
199 if (!ref($$args{service})) {
200 $$args{service} = [$$args{service}];
201 $$args{username} = [$$args{username}];
202 $$args{password} = [$$args{password}];
210 for (my $i = 0; $i < @{$$args{service}}; $i++) {
211 my %tmp_args = %$args;
212 $tmp_args{service} = $$args{service}[$i];
213 $tmp_args{username} = $$args{username}[$i];
214 $tmp_args{password} = $$args{password}[$i];
216 $logger->debug("z3950: service: $tmp_args{service}, async: $tmp_args{async}");
218 if ($tmp_args{service} eq 'native-evergreen-catalog') {
219 my $method = $self->method_lookup('open-ils.search.biblio.zstyle.staff');
221 $self->method_lookup('open-ils.search.biblio.zstyle.staff')->run($auth, \%tmp_args)
226 $tmp_args{query} = compile_query('and', $tmp_args{service}, $tmp_args{search});
228 my $res = do_service_search( $self, $conn, $auth, \%tmp_args );
230 if ($U->event_code($res)) {
231 $conn->respond($res) if $U->event_code($res);
234 push @services, $tmp_args{service};
235 push @results, $res->{result};
236 push @connections, $res->{connection};
240 $logger->debug("z3950: Result object: $results[$i], Connection object: $connections[$i]");
243 $logger->debug("z3950: Connections created");
245 return undef unless (@connections);
248 # local catalog search is not processed with other z39 results;
249 $$args{service} = [grep {$_ ne 'native-evergreen-catalog'} @{$$args{service}}];
251 @connections = grep {defined $_} @connections;
252 return undef unless @connections;
254 while ((my $index = OpenILS::Utils::ZClient::event( \@connections )) != 0) {
255 my $ev = $connections[$index - 1]->last_event();
256 $logger->debug("z3950: Received event $ev");
257 if ($ev == OpenILS::Utils::ZClient::EVENT_END()) {
258 my $munged = process_results( $results[$index - 1], $$args{limit}, $$args{offset}, $$args{service}[$index -1] );
259 $$munged{service} = $$args{service}[$index - 1];
260 $conn->respond($munged);
264 $logger->debug("z3950: Search Complete");
269 # -------------------------------------------------------------------
270 # This handles the host settings, but expects a fully formed z query
271 # -------------------------------------------------------------------
272 sub do_service_search {
274 fetch_service_defs() unless (scalar(keys(%services)));
281 my $info = $services{$$args{service}};
283 $$args{host} = $$info{host};
284 $$args{port} = $$info{port};
285 $$args{db} = $$info{db};
286 $logger->debug("z3950: do_search...");
288 return do_search( $self, $conn, $auth, $args );
293 # -------------------------------------------------------------------
294 # This is the low level search method. All config and query
295 # data must be provided to this method
296 # -------------------------------------------------------------------
299 fetch_service_defs() unless (scalar(keys(%services)));
306 my $host = $$args{host} or return undef;
307 my $port = $$args{port} or return undef;
308 my $db = $$args{db} or return undef;
309 my $query = $$args{query} or return undef;
310 my $async = $$args{async} || 0;
312 my $limit = $$args{limit} || 10;
313 my $offset = $$args{offset} || 0;
315 my $username = $$args{username} || "";
316 my $password = $$args{password} || "";
318 my $tformat = $services{$args->{service}}->{transmission_format} || $output;
320 my $editor = new_editor(authtoken => $auth);
321 return $editor->event unless $editor->checkauth;
322 return $editor->event unless $editor->allowed('REMOTE_Z3950_QUERY');
324 $logger->info("z3950: connecting to server $host:$port:$db as $username");
326 my $connection = OpenILS::Utils::ZClient->new(
330 password => $password,
332 preferredRecordSyntax => $tformat,
335 if( ! $connection ) {
336 $logger->error("z3950: Unable to connect to Z server: ".
337 "$host:$port:$db:$username:$password");
338 return OpenILS::Event->new('Z3950_LOGIN_FAILED') unless $connection;
345 $logger->info("z3950: query => $query");
348 $results = $connection->search_pqf( $query );
349 } catch Error with { $err = shift; };
351 return OpenILS::Event->new(
352 'Z3950_BAD_QUERY', payload => $query, debug => "$err") if $err;
354 return OpenILS::Event->new('Z3950_SEARCH_FAILED',
355 debug => $connection->errcode." => ".$connection->errmsg." : query = $query") unless $results;
357 $logger->info("z3950: search [$query] took ".(time - $start)." seconds");
359 return {result => $results, connection => $connection} if ($async);
361 my $munged = process_results($results, $limit, $offset, $$args{service});
362 $munged->{query} = $query;
368 # -------------------------------------------------------------------
369 # Takes a result batch and returns the hitcount and a list of xml
371 # -------------------------------------------------------------------
372 sub process_results {
374 fetch_service_defs() unless (scalar(keys(%services)));
377 my $limit = shift || 10;
378 my $offset = shift || 0;
381 my $rformat = $services{$service}->{record_format};
382 my $tformat = $services{$service}->{transmission_format} || $output;
384 $results->option(elementSetName => $rformat);
385 $results->option(preferredRecordSyntax => $tformat);
386 $logger->info("z3950: using record format '$rformat' and transmission format '$tformat'");
390 my $count = $$res{count} = $results->size;
392 $logger->info("z3950: search returned $count hits");
394 my $tend = $limit + $offset;
396 my $end = ($tend <= $count) ? $tend : $count;
398 for($offset..$end - 1) {
406 $logger->info("z3950: fetching record $_");
410 my $rec = $results->record($_);
412 if ($tformat eq 'usmarc') {
413 $marc = MARC::Record->new_from_usmarc($rec->raw());
414 } elsif ($tformat eq 'xml') {
415 $marc = MARC::Record->new_from_xml($rec->raw());
417 die "Unsupported record transmission format $tformat"
420 $marcs = $U->entityize($marc->as_xml_record);
421 $marcs = $U->strip_ctrl_chars($marcs);
422 my $doc = XML::LibXML->new->parse_string($marcs);
423 $marcxml = $U->entityize($doc->documentElement->toString);
424 $marcxml = $U->strip_ctrl_chars($marcxml);
426 my $u = OpenILS::Utils::ModsParser->new();
427 $u->start_mods_batch( $marcxml );
428 $mods = $u->finish_mods_batch();
431 } catch Error with { $err = shift; };
433 push @records, { 'mvr' => $mods, 'marcxml' => $marcxml } unless $err;
434 $logger->error("z3950: bad XML : $err") if $err;
437 warn "\n\n$marcs\n\n";
441 $res->{records} = \@records;
447 # -------------------------------------------------------------------
448 # Compiles the class based search query
449 # -------------------------------------------------------------------
452 fetch_service_defs() unless (scalar(keys(%services)));
454 my $separator = shift;
458 my $count = scalar(keys %$hash);
461 $str .= "\@$separator " for (1..$count-1);
463 # -------------------------------------------------------------------
464 # "code" is the bib-1 "use attribute", "format" is the bib-1
465 # "structure attribute"
466 # -------------------------------------------------------------------
468 next unless ( exists $services{$service}->{attrs}->{$_} );
469 $str .= '@attr 1=' . $services{$service}->{attrs}->{$_}->{code} . # add the use attribute
470 ' @attr 4=' . $services{$service}->{attrs}->{$_}->{format}; # add the structure attribute
471 if (exists $services{$service}->{attrs}->{$_}->{truncation}
472 && $services{$service}->{attrs}->{$_}->{truncation} >= 0) {
473 $str .= ' @attr 5=' . $services{$service}->{attrs}->{$_}->{truncation};
475 $str .= " \"" . $$hash{$_} . "\" "; # add the search term