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