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