]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/src/perlmods/OpenILS/Application/Search/Z3950.pm
ignore the native catalog search when processing async z39 results
[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     if($e->can('search_config_z3950_source')) {
90
91         my $sources = $e->search_config_z3950_source( 
92             [ { name => { '!=' => undef } }, 
93             { flesh => 1, flesh_fields => { czs => ['attrs'] } }]  
94         ); 
95
96         my %hash = (); 
97         for my $s ( @$sources ) { 
98             $hash{ $s->name } = { 
99                 name => $s->name, 
100                 label => $s->label, 
101                 host => $s->host, 
102                 port => $s->port, 
103                 db => $s->db, 
104                 auth => $s->auth, 
105             }; 
106
107             for my $a ( @{ $s->attrs } ) { 
108                 $hash{ $a->source }{attrs}{ $a->name } = { 
109                     name => $a->name, 
110                     label => $a->label, 
111                     code => $a->code, 
112                     format => $a->format, 
113                     source => $a->source, 
114                 }; 
115             } 
116         } 
117
118         return \%hash; 
119
120     } else {
121         return $sclient->config_value('z3950', 'services');
122     }
123 }
124
125
126
127 # -------------------------------------------------------------------
128 # Load the pre-defined Z server configs
129 # -------------------------------------------------------------------
130 sub initialize {
131         $sclient = OpenSRF::Utils::SettingsClient->new();
132         $default_service = $sclient->config_value("z3950", "default" );
133         my $servs = $sclient->config_value("z3950", "services" );
134         $services{$_} = $$servs{$_} for keys %$servs;
135 }
136
137
138 # -------------------------------------------------------------------
139 # High-level class based search. 
140 # -------------------------------------------------------------------
141 sub do_class_search {
142
143         my $self                        = shift;
144         my $conn                        = shift;
145         my $auth                        = shift;
146         my $args                        = shift;
147
148         if (!ref($$args{service})) {
149                 $$args{service} = [$$args{service}];
150                 $$args{username} = [$$args{username}];
151                 $$args{password} = [$$args{password}];
152         }
153
154         $$args{async} = 1;
155
156         my @connections;
157         my @results;
158     my @services; 
159         for (my $i = 0; $i < @{$$args{service}}; $i++) {
160                 my %tmp_args = %$args;
161                 $tmp_args{service} = $$args{service}[$i];
162                 $tmp_args{username} = $$args{username}[$i];
163                 $tmp_args{password} = $$args{password}[$i];
164
165                 $logger->debug("z3950: service: $tmp_args{service}, async: $tmp_args{async}");
166
167         if ($tmp_args{service} eq 'native-evergreen-catalog') { 
168             my $method = $self->method_lookup('open-ils.search.biblio.zstyle'); 
169             $conn->respond( 
170                 $self->method_lookup('open-ils.search.biblio.zstyle')->run($auth, \%tmp_args) 
171             ); 
172
173         } else { 
174
175             $tmp_args{query} = compile_query('and', $tmp_args{service}, $tmp_args{search}); 
176     
177             my $res = do_service_search( $self, $conn, $auth, \%tmp_args ); 
178     
179             if ($U->event_code($res)) { 
180                 $conn->respond($res) if $U->event_code($res); 
181
182             } else { 
183                 push @services, $tmp_args{service}; 
184                 push @results, $res->{result}; 
185                 push @connections, $res->{connection}; 
186             } 
187         }
188
189                 $logger->debug("z3950: Result object: $results[$i], Connection object: $connections[$i]");
190         }
191
192         $logger->debug("z3950: Connections created");
193
194     return undef unless (@connections);
195         my @records;
196
197     # local catalog search is not processed with other z39 results;
198     $$args{service} = [grep {$_ ne 'native-evergreen-catalog'} @{$$args{service}}];
199
200         while ((my $index = OpenILS::Utils::ZClient::event( \@connections )) != 0) {
201                 my $ev = $connections[$index - 1]->last_event();
202                 $logger->debug("z3950: Received event $ev");
203                 if ($ev == OpenILS::Utils::ZClient::EVENT_END()) {
204                         my $munged = process_results( $results[$index - 1], $$args{limit}, $$args{offset}, $$args{service}[$index -1] );
205                         $$munged{service} = $$args{service}[$index - 1];
206                         $conn->respond($munged);
207                 }
208         }
209
210         $logger->debug("z3950: Search Complete");
211     return undef;
212 }
213
214
215 # -------------------------------------------------------------------
216 # This handles the host settings, but expects a fully formed z query
217 # -------------------------------------------------------------------
218 sub do_service_search {
219
220         my $self                        = shift;
221         my $conn                        = shift;
222         my $auth                        = shift;
223         my $args                        = shift;
224         
225         my $info = $services{$$args{service}};
226
227         $$args{host}    = $$info{host};
228         $$args{port}    = $$info{port};
229         $$args{db}              = $$info{db};
230     $logger->debug("z3950: do_search...");
231
232         return do_search( $self, $conn, $auth, $args );
233 }
234
235
236
237 # -------------------------------------------------------------------
238 # This is the low level search method.  All config and query
239 # data must be provided to this method
240 # -------------------------------------------------------------------
241 sub do_search {
242
243         my $self        = shift;
244         my $conn        = shift;
245         my $auth = shift;
246         my $args = shift;
247
248         my $host                = $$args{host} or return undef;
249         my $port                = $$args{port} or return undef;
250         my $db          = $$args{db}    or return undef;
251         my $query       = $$args{query} or return undef;
252         my $async       = $$args{async} || 0;
253
254         my $limit       = $$args{limit} || 10;
255         my $offset      = $$args{offset} || 0;
256
257         my $username = $$args{username} || "";
258         my $password = $$args{password} || "";
259
260     my $tformat = $services{$args->{service}}->{transmission_format} || $output;
261
262         my $editor = new_editor(authtoken => $auth);
263         return $editor->event unless $editor->checkauth;
264         return $editor->event unless $editor->allowed('REMOTE_Z3950_QUERY');
265
266     $logger->info("z3950: connecting to server $host:$port:$db as $username");
267
268         my $connection = OpenILS::Utils::ZClient->new(
269                 $host, $port,
270                 databaseName                            => $db, 
271                 user                                                    => $username,
272                 password                                                => $password,
273                 async                                                   => $async,
274                 preferredRecordSyntax   => $tformat, 
275         );
276
277         if( ! $connection ) {
278                 $logger->error("z3950: Unable to connect to Z server: ".
279                         "$host:$port:$db:$username:$password");
280                 return OpenILS::Event->new('Z3950_LOGIN_FAILED') unless $connection;
281         }
282
283         my $start = time;
284         my $results;
285         my $err;
286
287         $logger->info("z3950: query => $query");
288
289         try {
290                 $results = $connection->search_pqf( $query );
291         } catch Error with { $err = shift; };
292
293         return OpenILS::Event->new(
294                 'Z3950_BAD_QUERY', payload => $query, debug => "$err") if $err;
295
296         return OpenILS::Event->new('Z3950_SEARCH_FAILED', 
297                 debug => $connection->errcode." => ".$connection->errmsg." : query = $query") unless $results;
298
299         $logger->info("z3950: search [$query] took ".(time - $start)." seconds");
300
301         return {result => $results, connection => $connection} if ($async);
302
303         my $munged = process_results($results, $limit, $offset, $$args{service});
304         $munged->{query} = $query;
305
306         return $munged;
307 }
308
309
310 # -------------------------------------------------------------------
311 # Takes a result batch and returns the hitcount and a list of xml
312 # and mvr objects
313 # -------------------------------------------------------------------
314 sub process_results {
315         my $results     = shift;
316         my $limit       = shift || 10;
317         my $offset      = shift || 0;
318     my $service = shift;
319
320     my $rformat = $services{$service}->{record_format};
321     my $tformat = $services{$service}->{transmission_format} || $output;
322
323     $results->option(elementSetName => $rformat);
324     $results->option(preferredRecordSyntax => $tformat);
325     $logger->info("z3950: using record format '$rformat' and transmission format '$tformat'");
326
327         my @records;
328         my $res = {};
329         my $count = $$res{count} = $results->size;
330
331         $logger->info("z3950: search returned $count hits");
332
333         my $tend = $limit + $offset;
334
335         my $end = ($tend <= $count) ? $tend : $count;
336
337         for($offset..$end - 1) {
338
339                 my $err;
340                 my $mods;
341                 my $marc;
342                 my $marcs;
343                 my $marcxml;
344
345                 $logger->info("z3950: fetching record $_");
346
347                 try {
348
349                         my $rec = $results->record($_);
350
351             if ($tformat eq 'usmarc') {
352                         $marc           = MARC::Record->new_from_usmarc($rec->raw());
353             } elsif ($tformat eq 'xml') {
354                         $marc           = MARC::Record->new_from_xml($rec->raw());
355             } else {
356                 die "Unsupported record transmission format $tformat"
357             }
358
359                         $marcs  = entityize($marc->as_xml_record);
360                         my $doc = XML::LibXML->new->parse_string($marcs);
361                         $marcxml = entityize( $doc->documentElement->toString );
362         
363                         my $u = OpenILS::Utils::ModsParser->new();
364                         $u->start_mods_batch( $marcxml );
365                         $mods = $u->finish_mods_batch();
366         
367
368                 } catch Error with { $err = shift; };
369
370                 push @records, { 'mvr' => $mods, 'marcxml' => $marcxml } unless $err;
371                 $logger->error("z3950: bad XML : $err") if $err;
372
373                 if( $err ) {
374                         warn "\n\n$marcs\n\n";
375                 }
376         }
377         
378         $res->{records} = \@records;
379         return $res;
380 }
381
382
383
384 # -------------------------------------------------------------------
385 # Compiles the class based search query
386 # -------------------------------------------------------------------
387 sub compile_query {
388
389         my $seperator   = shift;
390         my $service             = shift;
391         my $hash                        = shift;
392
393         my $count = scalar(keys %$hash);
394
395         my $str = "";
396         $str .= "\@$seperator " for (1..$count-1);
397         
398     # -------------------------------------------------------------------
399     # "code" is the bib-1 "use attribute", "format" is the bib-1 
400     # "structure attribute"
401     # -------------------------------------------------------------------
402         for( keys %$hash ) {
403                 next unless ( exists $services{$service}->{attrs}->{$_} );
404                 $str .= '@attr 1=' . $services{$service}->{attrs}->{$_}->{code} . # add the use attribute
405                         ' @attr 4=' . $services{$service}->{attrs}->{$_}->{format}; # add the structure attribute
406                 if (exists $services{$service}->{attrs}->{$_}->{truncation}){
407                         $str .= ' @attr 5=' . $services{$service}->{attrs}->{$_}->{truncation};
408                 }
409                 $str .= " \"" . $$hash{$_} . "\" "; # add the search term
410         }
411         return $str;
412 }
413
414
415
416 # -------------------------------------------------------------------
417 # Handles the unicode
418 # -------------------------------------------------------------------
419 sub entityize {
420         my $stuff = shift;
421         my $form = shift || "";
422         
423         if ($form eq 'D') {
424                 $stuff = NFD($stuff);
425         } else {
426                 $stuff = NFC($stuff);
427         }
428         
429         $stuff =~ s/([\x{0080}-\x{fffd}])/sprintf('&#x%X;',ord($1))/sgoe;
430
431         # strip some other unfriendly chars that may leak in
432    $stuff =~ s/([\x{0000}-\x{0008}])//sgoe; 
433
434         return $stuff;
435 }
436
437
438 1;