]> git.evergreen-ils.org Git - working/Evergreen.git/blob - Open-ILS/src/perlmods/lib/OpenILS/Application/Search/Z3950.pm
Merge branch 'opac-tt-poc' of git+ssh://yeti.esilibrary.com/home/evergreen/evergreen...
[working/Evergreen.git] / Open-ILS / src / perlmods / lib / OpenILS / Application / Search / Z3950.pm
1 package OpenILS::Application::Search::Z3950;
2 use strict; use warnings;
3 use base qw/OpenILS::Application/;
4
5 use OpenILS::Utils::ZClient;
6 use MARC::Record;
7 use MARC::File::XML (BinaryEncoding => 'UTF-8');
8 use MARC::Charset;
9 use Unicode::Normalize;
10 use XML::LibXML;
11
12 use OpenILS::Event;
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/;
19
20 MARC::Charset->assume_unicode(1);
21 MARC::Charset->ignore_errors(1);
22
23 my $output = "usmarc"; 
24 my $U = 'OpenILS::Application::AppUtils'; 
25
26 my $sclient;
27 my %services;
28 my $default_service;
29
30
31 __PACKAGE__->register_method(
32     method    => 'do_class_search',
33     api_name  => 'open-ils.search.z3950.search_class',
34     stream    => 1,
35     signature => q/
36         Performs a class based Z search.  The classes available
37         are defined by the 'attr' fields in the config for the
38         requested service.
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
44     /
45 );
46
47 __PACKAGE__->register_method(
48     method    => 'do_service_search',
49     api_name  => 'open-ils.search.z3950.search_service',
50     signature => q/
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
56     /
57 );
58
59
60 __PACKAGE__->register_method(
61     method    => 'do_service_search',
62     api_name  => 'open-ils.search.z3950.search_raw',
63     signature => q/
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
68     /
69 );
70
71
72 __PACKAGE__->register_method(
73     method    => "query_services",
74     api_name  => "open-ils.search.z3950.retrieve_services",
75     signature => q/
76         Returns a list of service names that we have config
77         data for
78     /
79 );
80
81
82
83 # -------------------------------------------------------------------
84 # What services do we have config info for?
85 # -------------------------------------------------------------------
86 sub query_services {
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');
91
92     return fetch_service_defs();
93 }
94
95 # -------------------------------------------------------------------
96 # What services do we have config info for?
97 # -------------------------------------------------------------------
98 sub fetch_service_defs {
99
100     my $hash = $sclient->config_value('z3950', 'services');
101
102     # overlay config file values with in-db values
103     my $e = new_editor();
104     if($e->can('search_config_z3950_source')) {
105
106         my $sources = $e->search_config_z3950_source(
107             [ { name => { '!=' => undef } },
108               { flesh => 1, flesh_fields => { czs => ['attrs'] } } ]
109         );
110
111         for my $s ( @$sources ) {
112             $$hash{ $s->name } = {
113                 name => $s->name,
114                 label => $s->label,
115                 host => $s->host,
116                 port => $s->port,
117                 db => $s->db,
118                 record_format => $s->record_format,
119                 transmission_format => $s->transmission_format,
120                 auth => $s->auth,
121             };
122
123             for my $a ( @{ $s->attrs } ) {
124                 $$hash{ $a->source }{attrs}{ $a->name } = {
125                     name => $a->name,
126                     label => $a->label,
127                     code => $a->code,
128                     format => $a->format,
129                     source => $a->source,
130                     truncation => $a->truncation,
131                 };
132             }
133         }
134     }
135
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'} = {
140         attrs => {
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'},
151         }
152     };
153
154     %services = %$hash; # cache these internally so we can actually use the db-configured sources
155     return $hash;
156 }
157
158
159
160 # -------------------------------------------------------------------
161 # Load the pre-defined Z server configs
162 # -------------------------------------------------------------------
163 sub child_init {
164     $sclient = OpenSRF::Utils::SettingsClient->new();
165     $default_service = $sclient->config_value("z3950", "default" );
166 }
167
168
169 # -------------------------------------------------------------------
170 # High-level class based search. 
171 # -------------------------------------------------------------------
172 sub do_class_search {
173
174     fetch_service_defs() unless (scalar(keys(%services)));
175
176     my $self = shift;
177     my $conn = shift;
178     my $auth = shift;
179     my $args = shift;
180
181     if (!ref($$args{service})) {
182         $$args{service} = [$$args{service}];
183         $$args{username} = [$$args{username}];
184         $$args{password} = [$$args{password}];
185     }
186
187     $$args{async} = 1;
188
189     my @connections;
190     my @results;
191     my @services; 
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];
197
198         $logger->debug("z3950: service: $tmp_args{service}, async: $tmp_args{async}");
199
200         if ($tmp_args{service} eq 'native-evergreen-catalog') { 
201             my $method = $self->method_lookup('open-ils.search.biblio.zstyle.staff'); 
202             $conn->respond( 
203                 $self->method_lookup('open-ils.search.biblio.zstyle.staff')->run($auth, \%tmp_args) 
204             ); 
205
206         } else { 
207
208             $tmp_args{query} = compile_query('and', $tmp_args{service}, $tmp_args{search}); 
209     
210             my $res = do_service_search( $self, $conn, $auth, \%tmp_args ); 
211     
212             if ($U->event_code($res)) { 
213                 $conn->respond($res) if $U->event_code($res); 
214
215             } else { 
216                 push @services, $tmp_args{service}; 
217                 push @results, $res->{result}; 
218                 push @connections, $res->{connection}; 
219             } 
220         }
221
222         $logger->debug("z3950: Result object: $results[$i], Connection object: $connections[$i]");
223     }
224
225     $logger->debug("z3950: Connections created");
226
227     return undef unless (@connections);
228     my @records;
229
230     # local catalog search is not processed with other z39 results;
231     $$args{service} = [grep {$_ ne 'native-evergreen-catalog'} @{$$args{service}}];
232
233     @connections = grep {defined $_} @connections;
234     return undef unless @connections;
235
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);
243         }
244     }
245
246     $logger->debug("z3950: Search Complete");
247     return undef;
248 }
249
250
251 # -------------------------------------------------------------------
252 # This handles the host settings, but expects a fully formed z query
253 # -------------------------------------------------------------------
254 sub do_service_search {
255
256     fetch_service_defs() unless (scalar(keys(%services)));
257
258     my $self = shift;
259     my $conn = shift;
260     my $auth = shift;
261     my $args = shift;
262     
263     my $info = $services{$$args{service}};
264
265     $$args{host} = $$info{host};
266     $$args{port} = $$info{port};
267     $$args{db} = $$info{db};
268     $logger->debug("z3950: do_search...");
269
270     return do_search( $self, $conn, $auth, $args );
271 }
272
273
274
275 # -------------------------------------------------------------------
276 # This is the low level search method.  All config and query
277 # data must be provided to this method
278 # -------------------------------------------------------------------
279 sub do_search {
280
281     fetch_service_defs() unless (scalar(keys(%services)));
282
283     my $self = shift;
284     my $conn = shift;
285     my $auth = shift;
286     my $args = shift;
287
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;
293
294     my $limit = $$args{limit} || 10;
295     my $offset = $$args{offset} || 0;
296
297     my $username = $$args{username} || "";
298     my $password = $$args{password} || "";
299
300     my $tformat = $services{$args->{service}}->{transmission_format} || $output;
301
302     my $editor = new_editor(authtoken => $auth);
303     return $editor->event unless $editor->checkauth;
304     return $editor->event unless $editor->allowed('REMOTE_Z3950_QUERY');
305
306     $logger->info("z3950: connecting to server $host:$port:$db as $username");
307
308     my $connection = OpenILS::Utils::ZClient->new(
309         $host, $port,
310         databaseName => $db, 
311         user => $username,
312         password => $password,
313         async => $async,
314         preferredRecordSyntax => $tformat, 
315     );
316
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;
321     }
322
323     my $start = time;
324     my $results;
325     my $err;
326
327     $logger->info("z3950: query => $query");
328
329     try {
330         $results = $connection->search_pqf( $query );
331     } catch Error with { $err = shift; };
332
333     return OpenILS::Event->new(
334         'Z3950_BAD_QUERY', payload => $query, debug => "$err") if $err;
335
336     return OpenILS::Event->new('Z3950_SEARCH_FAILED', 
337         debug => $connection->errcode." => ".$connection->errmsg." : query = $query") unless $results;
338
339     $logger->info("z3950: search [$query] took ".(time - $start)." seconds");
340
341     return {result => $results, connection => $connection} if ($async);
342
343     my $munged = process_results($results, $limit, $offset, $$args{service});
344     $munged->{query} = $query;
345
346     return $munged;
347 }
348
349
350 # -------------------------------------------------------------------
351 # Takes a result batch and returns the hitcount and a list of xml
352 # and mvr objects
353 # -------------------------------------------------------------------
354 sub process_results {
355
356     fetch_service_defs() unless (scalar(keys(%services)));
357
358     my $results = shift;
359     my $limit = shift || 10;
360     my $offset = shift || 0;
361     my $service = shift;
362
363     my $rformat = $services{$service}->{record_format};
364     my $tformat = $services{$service}->{transmission_format} || $output;
365
366     $results->option(elementSetName => $rformat);
367     $results->option(preferredRecordSyntax => $tformat);
368     $logger->info("z3950: using record format '$rformat' and transmission format '$tformat'");
369
370     my @records;
371     my $res = {};
372     my $count = $$res{count} = $results->size;
373
374     $logger->info("z3950: search returned $count hits");
375
376     my $tend = $limit + $offset;
377
378     my $end = ($tend <= $count) ? $tend : $count;
379
380     for($offset..$end - 1) {
381
382         my $err;
383         my $mods;
384         my $marc;
385         my $marcs;
386         my $marcxml;
387
388         $logger->info("z3950: fetching record $_");
389
390         try {
391
392             my $rec = $results->record($_);
393
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());
398             } else {
399                 die "Unsupported record transmission format $tformat"
400             }
401
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);
407     
408             my $u = OpenILS::Utils::ModsParser->new();
409             $u->start_mods_batch( $marcxml );
410             $mods = $u->finish_mods_batch();
411     
412
413         } catch Error with { $err = shift; };
414
415         push @records, { 'mvr' => $mods, 'marcxml' => $marcxml } unless $err;
416         $logger->error("z3950: bad XML : $err") if $err;
417
418         if( $err ) {
419             warn "\n\n$marcs\n\n";
420         }
421     }
422     
423     $res->{records} = \@records;
424     return $res;
425 }
426
427
428
429 # -------------------------------------------------------------------
430 # Compiles the class based search query
431 # -------------------------------------------------------------------
432 sub compile_query {
433
434     fetch_service_defs() unless (scalar(keys(%services)));
435
436     my $separator = shift;
437     my $service = shift;
438     my $hash = shift;
439
440     my $count = scalar(keys %$hash);
441
442     my $str = "";
443     $str .= "\@$separator " for (1..$count-1);
444     
445     # -------------------------------------------------------------------
446     # "code" is the bib-1 "use attribute", "format" is the bib-1 
447     # "structure attribute"
448     # -------------------------------------------------------------------
449     for( keys %$hash ) {
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};
456         }
457         $str .= " \"" . $$hash{$_} . "\" "; # add the search term
458     }
459     return $str;
460 }
461
462 1;
463 # vim:et:ts=4:sw=4: