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