]> git.evergreen-ils.org Git - working/Evergreen.git/blob - Open-ILS/src/perlmods/OpenILS/Application/Search/Z3950.pm
Dedupe code by moving to a common implementation of entityize()
[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.staff'); 
189             $conn->respond( 
190                 $self->method_lookup('open-ils.search.biblio.zstyle.staff')->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     @connections = grep {defined $_} @connections;
221     return undef unless @connections;
222
223         while ((my $index = OpenILS::Utils::ZClient::event( \@connections )) != 0) {
224                 my $ev = $connections[$index - 1]->last_event();
225                 $logger->debug("z3950: Received event $ev");
226                 if ($ev == OpenILS::Utils::ZClient::EVENT_END()) {
227                         my $munged = process_results( $results[$index - 1], $$args{limit}, $$args{offset}, $$args{service}[$index -1] );
228                         $$munged{service} = $$args{service}[$index - 1];
229                         $conn->respond($munged);
230                 }
231         }
232
233         $logger->debug("z3950: Search Complete");
234     return undef;
235 }
236
237
238 # -------------------------------------------------------------------
239 # This handles the host settings, but expects a fully formed z query
240 # -------------------------------------------------------------------
241 sub do_service_search {
242
243         my $self                        = shift;
244         my $conn                        = shift;
245         my $auth                        = shift;
246         my $args                        = shift;
247         
248         my $info = $services{$$args{service}};
249
250         $$args{host}    = $$info{host};
251         $$args{port}    = $$info{port};
252         $$args{db}              = $$info{db};
253     $logger->debug("z3950: do_search...");
254
255         return do_search( $self, $conn, $auth, $args );
256 }
257
258
259
260 # -------------------------------------------------------------------
261 # This is the low level search method.  All config and query
262 # data must be provided to this method
263 # -------------------------------------------------------------------
264 sub do_search {
265
266         my $self        = shift;
267         my $conn        = shift;
268         my $auth = shift;
269         my $args = shift;
270
271         my $host                = $$args{host} or return undef;
272         my $port                = $$args{port} or return undef;
273         my $db          = $$args{db}    or return undef;
274         my $query       = $$args{query} or return undef;
275         my $async       = $$args{async} || 0;
276
277         my $limit       = $$args{limit} || 10;
278         my $offset      = $$args{offset} || 0;
279
280         my $username = $$args{username} || "";
281         my $password = $$args{password} || "";
282
283     my $tformat = $services{$args->{service}}->{transmission_format} || $output;
284
285         my $editor = new_editor(authtoken => $auth);
286         return $editor->event unless $editor->checkauth;
287         return $editor->event unless $editor->allowed('REMOTE_Z3950_QUERY');
288
289     $logger->info("z3950: connecting to server $host:$port:$db as $username");
290
291         my $connection = OpenILS::Utils::ZClient->new(
292                 $host, $port,
293                 databaseName                            => $db, 
294                 user                                                    => $username,
295                 password                                                => $password,
296                 async                                                   => $async,
297                 preferredRecordSyntax   => $tformat, 
298         );
299
300         if( ! $connection ) {
301                 $logger->error("z3950: Unable to connect to Z server: ".
302                         "$host:$port:$db:$username:$password");
303                 return OpenILS::Event->new('Z3950_LOGIN_FAILED') unless $connection;
304         }
305
306         my $start = time;
307         my $results;
308         my $err;
309
310         $logger->info("z3950: query => $query");
311
312         try {
313                 $results = $connection->search_pqf( $query );
314         } catch Error with { $err = shift; };
315
316         return OpenILS::Event->new(
317                 'Z3950_BAD_QUERY', payload => $query, debug => "$err") if $err;
318
319         return OpenILS::Event->new('Z3950_SEARCH_FAILED', 
320                 debug => $connection->errcode." => ".$connection->errmsg." : query = $query") unless $results;
321
322         $logger->info("z3950: search [$query] took ".(time - $start)." seconds");
323
324         return {result => $results, connection => $connection} if ($async);
325
326         my $munged = process_results($results, $limit, $offset, $$args{service});
327         $munged->{query} = $query;
328
329         return $munged;
330 }
331
332
333 # -------------------------------------------------------------------
334 # Takes a result batch and returns the hitcount and a list of xml
335 # and mvr objects
336 # -------------------------------------------------------------------
337 sub process_results {
338         my $results     = shift;
339         my $limit       = shift || 10;
340         my $offset      = shift || 0;
341     my $service = shift;
342
343     my $rformat = $services{$service}->{record_format};
344     my $tformat = $services{$service}->{transmission_format} || $output;
345
346     $results->option(elementSetName => $rformat);
347     $results->option(preferredRecordSyntax => $tformat);
348     $logger->info("z3950: using record format '$rformat' and transmission format '$tformat'");
349
350         my @records;
351         my $res = {};
352         my $count = $$res{count} = $results->size;
353
354         $logger->info("z3950: search returned $count hits");
355
356         my $tend = $limit + $offset;
357
358         my $end = ($tend <= $count) ? $tend : $count;
359
360         for($offset..$end - 1) {
361
362                 my $err;
363                 my $mods;
364                 my $marc;
365                 my $marcs;
366                 my $marcxml;
367
368                 $logger->info("z3950: fetching record $_");
369
370                 try {
371
372                         my $rec = $results->record($_);
373
374             if ($tformat eq 'usmarc') {
375                         $marc           = MARC::Record->new_from_usmarc($rec->raw());
376             } elsif ($tformat eq 'xml') {
377                         $marc           = MARC::Record->new_from_xml($rec->raw());
378             } else {
379                 die "Unsupported record transmission format $tformat"
380             }
381
382                         $marcs  = $U->entityize($marc->as_xml_record);
383                         $marcs  = $U->strip_ctrl_chars($marcs);
384                         my $doc = XML::LibXML->new->parse_string($marcs);
385                         $marcxml = $U->entityize($doc->documentElement->toString);
386                         $marcxml = $U->strip_ctrl_chars($marcxml);
387         
388                         my $u = OpenILS::Utils::ModsParser->new();
389                         $u->start_mods_batch( $marcxml );
390                         $mods = $u->finish_mods_batch();
391         
392
393                 } catch Error with { $err = shift; };
394
395                 push @records, { 'mvr' => $mods, 'marcxml' => $marcxml } unless $err;
396                 $logger->error("z3950: bad XML : $err") if $err;
397
398                 if( $err ) {
399                         warn "\n\n$marcs\n\n";
400                 }
401         }
402         
403         $res->{records} = \@records;
404         return $res;
405 }
406
407
408
409 # -------------------------------------------------------------------
410 # Compiles the class based search query
411 # -------------------------------------------------------------------
412 sub compile_query {
413
414         my $seperator   = shift;
415         my $service             = shift;
416         my $hash                        = shift;
417
418         my $count = scalar(keys %$hash);
419
420         my $str = "";
421         $str .= "\@$seperator " for (1..$count-1);
422         
423     # -------------------------------------------------------------------
424     # "code" is the bib-1 "use attribute", "format" is the bib-1 
425     # "structure attribute"
426     # -------------------------------------------------------------------
427         for( keys %$hash ) {
428                 next unless ( exists $services{$service}->{attrs}->{$_} );
429                 $str .= '@attr 1=' . $services{$service}->{attrs}->{$_}->{code} . # add the use attribute
430                         ' @attr 4=' . $services{$service}->{attrs}->{$_}->{format}; # add the structure attribute
431                 if (exists $services{$service}->{attrs}->{$_}->{truncation}){
432                         $str .= ' @attr 5=' . $services{$service}->{attrs}->{$_}->{truncation};
433                 }
434                 $str .= " \"" . $$hash{$_} . "\" "; # add the search term
435         }
436         return $str;
437 }
438
439 1;