]> git.evergreen-ils.org Git - working/Evergreen.git/blob - Open-ILS/src/perlmods/lib/OpenILS/Application/Search/Z3950.pm
Merge branch 'master' of git.evergreen-ils.org:Evergreen into template-toolkit-opac...
[working/Evergreen.git] / Open-ILS / src / perlmods / lib / 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 (BinaryEncoding => 'UTF-8');
8 use MARC::Charset;
9 use Unicode::Normalize;
10 use XML::LibXML;
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 MARC::Charset->assume_unicode(1);
21 MARC::Charset->ignore_errors(1);
22
23 my $output = "usmarc"; 
24 my $U = 'OpenILS::Application::AppUtils'; 
25
26 my $sclient;
27 my %services;
28 my $default_service;
29
30
31 __PACKAGE__->register_method(
32     method    => 'do_class_search',
33     api_name  => 'open-ils.search.z3950.search_class',
34     stream    => 1,
35     signature => q/
36         Performs a class based Z search.  The classes available
37         are defined by the 'attr' fields in the config for the
38         requested service.
39         @param auth The login session key
40         @param shash The search hash : { attr : value, attr2: value, ...}
41         @param service The service to connect to
42         @param username The username to use when connecting to the service
43         @param password The password to use when connecting to the service
44     /
45 );
46
47 __PACKAGE__->register_method(
48     method    => 'do_service_search',
49     api_name  => 'open-ils.search.z3950.search_service',
50     signature => q/
51         @param auth The login session key
52         @param query The Z3950 search string to use
53         @param service The service to connect to
54         @param username The username to use when connecting to the service
55         @param password The password to use when connecting to the service
56     /
57 );
58
59
60 __PACKAGE__->register_method(
61     method    => 'do_service_search',
62     api_name  => 'open-ils.search.z3950.search_raw',
63     signature => q/
64         @param auth The login session key
65         @param args An object of search params which must include:
66             host, port, db and query.  
67             optional fields include username and password
68     /
69 );
70
71
72 __PACKAGE__->register_method(
73     method    => "query_services",
74     api_name  => "open-ils.search.z3950.retrieve_services",
75     signature => q/
76         @param auth The login session key
77         Returns a list of service names that we have config
78         data for
79     /
80 );
81
82
83
84 # -------------------------------------------------------------------
85 # What services do we have config info for?
86 # -------------------------------------------------------------------
87 sub query_services {
88     my( $self, $client, $auth ) = @_;
89     my $e = new_editor(authtoken=>$auth);
90     return $e->event unless $e->checkauth;
91     return $e->event unless $e->allowed('REMOTE_Z3950_QUERY');
92
93     return fetch_service_defs($e);
94 }
95
96 # -------------------------------------------------------------------
97 # What services do we have config info for?
98 # -------------------------------------------------------------------
99 sub fetch_service_defs {
100
101     my $editor_with_authtoken = shift;
102
103     my $hash = $sclient->config_value('z3950', 'services');
104
105     # overlay config file values with in-db values
106     my $e = $editor_with_authtoken || new_editor();
107     if($e->can('search_config_z3950_source')) {
108
109         my $sources = $e->search_config_z3950_source(
110             [ { name => { '!=' => undef } },
111               { flesh => 1, flesh_fields => { czs => ['attrs'] } } ]
112         );
113
114         for my $s ( @$sources ) {
115             $$hash{ $s->name } = {
116                 name => $s->name,
117                 label => $s->label,
118                 host => $s->host,
119                 port => $s->port,
120                 db => $s->db,
121                 record_format => $s->record_format,
122                 transmission_format => $s->transmission_format,
123                 auth => $s->auth,
124                 use_perm => ($s->use_perm) ? 
125                     $e->retrieve_permission_perm_list($s->use_perm)->code : ''
126             };
127
128             for my $a ( @{ $s->attrs } ) {
129                 $$hash{ $a->source }{attrs}{ $a->name } = {
130                     name => $a->name,
131                     label => $a->label,
132                     code => $a->code,
133                     format => $a->format,
134                     source => $a->source,
135                     truncation => $a->truncation,
136                 };
137             }
138         }
139     }
140
141     # Define the set of native catalog services
142     # XXX There are i18n problems here, but let's get the staff client working first
143     # XXX Move into the DB?
144     $hash->{'native-evergreen-catalog'} = {
145         attrs => {
146             title => {code => 'title', label => 'Title'},
147             author => {code => 'author', label => 'Author'},
148             subject => {code => 'subject', label => 'Subject'},
149             keyword => {code => 'keyword', label => 'Keyword'},
150             tcn => {code => 'tcn', label => 'TCN'},
151             isbn => {code => 'isbn', label => 'ISBN'},
152             issn => {code => 'issn', label => 'ISSN'},
153             publisher => {code => 'publisher', label => 'Publisher'},
154             pubdate => {code => 'pubdate', label => 'Pub Date'},
155             item_type => {code => 'item_type', label => 'Item Type'},
156         }
157     };
158
159     # then filter out any services which the requestor lacks the perm for
160     foreach my $s (keys %{ $hash }) {
161         if ($$hash{$s}{use_perm}) {
162             if ($U->check_perms(
163                 $e->requestor->id,
164                 $e->requestor->ws_ou,
165                 $$hash{$s}{use_perm}
166             )) {
167                 delete $$hash{$s};
168             }
169         };
170     }
171
172     %services = %$hash; # cache these internally so we can actually use the db-configured sources
173     return $hash;
174 }
175
176
177
178 # -------------------------------------------------------------------
179 # Load the pre-defined Z server configs
180 # -------------------------------------------------------------------
181 sub child_init {
182     $sclient = OpenSRF::Utils::SettingsClient->new();
183     $default_service = $sclient->config_value("z3950", "default" );
184 }
185
186
187 # -------------------------------------------------------------------
188 # High-level class based search. 
189 # -------------------------------------------------------------------
190 sub do_class_search {
191
192     fetch_service_defs() unless (scalar(keys(%services)));
193
194     my $self = shift;
195     my $conn = shift;
196     my $auth = shift;
197     my $args = shift;
198
199     if (!ref($$args{service})) {
200         $$args{service} = [$$args{service}];
201         $$args{username} = [$$args{username}];
202         $$args{password} = [$$args{password}];
203     }
204
205     $$args{async} = 1;
206
207     my @connections;
208     my @results;
209     my @services; 
210     for (my $i = 0; $i < @{$$args{service}}; $i++) {
211         my %tmp_args = %$args;
212         $tmp_args{service} = $$args{service}[$i];
213         $tmp_args{username} = $$args{username}[$i];
214         $tmp_args{password} = $$args{password}[$i];
215
216         $logger->debug("z3950: service: $tmp_args{service}, async: $tmp_args{async}");
217
218         if ($tmp_args{service} eq 'native-evergreen-catalog') { 
219             my $method = $self->method_lookup('open-ils.search.biblio.zstyle.staff'); 
220             $conn->respond( 
221                 $self->method_lookup('open-ils.search.biblio.zstyle.staff')->run($auth, \%tmp_args) 
222             ); 
223
224         } else { 
225
226             $tmp_args{query} = compile_query('and', $tmp_args{service}, $tmp_args{search}); 
227     
228             my $res = do_service_search( $self, $conn, $auth, \%tmp_args ); 
229     
230             if ($U->event_code($res)) { 
231                 $conn->respond($res) if $U->event_code($res); 
232
233             } else { 
234                 push @services, $tmp_args{service}; 
235                 push @results, $res->{result}; 
236                 push @connections, $res->{connection}; 
237             } 
238         }
239
240         $logger->debug("z3950: Result object: $results[$i], Connection object: $connections[$i]");
241     }
242
243     $logger->debug("z3950: Connections created");
244
245     return undef unless (@connections);
246     my @records;
247
248     # local catalog search is not processed with other z39 results;
249     $$args{service} = [grep {$_ ne 'native-evergreen-catalog'} @{$$args{service}}];
250
251     @connections = grep {defined $_} @connections;
252     return undef unless @connections;
253
254     while ((my $index = OpenILS::Utils::ZClient::event( \@connections )) != 0) {
255         my $ev = $connections[$index - 1]->last_event();
256         $logger->debug("z3950: Received event $ev");
257         if ($ev == OpenILS::Utils::ZClient::EVENT_END()) {
258             my $munged = process_results( $results[$index - 1], $$args{limit}, $$args{offset}, $$args{service}[$index -1] );
259             $$munged{service} = $$args{service}[$index - 1];
260             $conn->respond($munged);
261         }
262     }
263
264     $logger->debug("z3950: Search Complete");
265     return undef;
266 }
267
268
269 # -------------------------------------------------------------------
270 # This handles the host settings, but expects a fully formed z query
271 # -------------------------------------------------------------------
272 sub do_service_search {
273
274     fetch_service_defs() unless (scalar(keys(%services)));
275
276     my $self = shift;
277     my $conn = shift;
278     my $auth = shift;
279     my $args = shift;
280     
281     my $info = $services{$$args{service}};
282
283     $$args{host} = $$info{host};
284     $$args{port} = $$info{port};
285     $$args{db} = $$info{db};
286     $logger->debug("z3950: do_search...");
287
288     return do_search( $self, $conn, $auth, $args );
289 }
290
291
292
293 # -------------------------------------------------------------------
294 # This is the low level search method.  All config and query
295 # data must be provided to this method
296 # -------------------------------------------------------------------
297 sub do_search {
298
299     fetch_service_defs() unless (scalar(keys(%services)));
300
301     my $self = shift;
302     my $conn = shift;
303     my $auth = shift;
304     my $args = shift;
305
306     my $host = $$args{host} or return undef;
307     my $port = $$args{port} or return undef;
308     my $db = $$args{db} or return undef;
309     my $query = $$args{query} or return undef;
310     my $async = $$args{async} || 0;
311
312     my $limit = $$args{limit} || 10;
313     my $offset = $$args{offset} || 0;
314
315     my $username = $$args{username} || "";
316     my $password = $$args{password} || "";
317
318     my $tformat = $services{$args->{service}}->{transmission_format} || $output;
319
320     my $editor = new_editor(authtoken => $auth);
321     return $editor->event unless $editor->checkauth;
322     return $editor->event unless $editor->allowed('REMOTE_Z3950_QUERY');
323
324     $logger->info("z3950: connecting to server $host:$port:$db as $username");
325
326     my $connection = OpenILS::Utils::ZClient->new(
327         $host, $port,
328         databaseName => $db, 
329         user => $username,
330         password => $password,
331         async => $async,
332         preferredRecordSyntax => $tformat, 
333     );
334
335     if( ! $connection ) {
336         $logger->error("z3950: Unable to connect to Z server: ".
337             "$host:$port:$db:$username:$password");
338         return OpenILS::Event->new('Z3950_LOGIN_FAILED') unless $connection;
339     }
340
341     my $start = time;
342     my $results;
343     my $err;
344
345     $logger->info("z3950: query => $query");
346
347     try {
348         $results = $connection->search_pqf( $query );
349     } catch Error with { $err = shift; };
350
351     return OpenILS::Event->new(
352         'Z3950_BAD_QUERY', payload => $query, debug => "$err") if $err;
353
354     return OpenILS::Event->new('Z3950_SEARCH_FAILED', 
355         debug => $connection->errcode." => ".$connection->errmsg." : query = $query") unless $results;
356
357     $logger->info("z3950: search [$query] took ".(time - $start)." seconds");
358
359     return {result => $results, connection => $connection} if ($async);
360
361     my $munged = process_results($results, $limit, $offset, $$args{service});
362     $munged->{query} = $query;
363
364     return $munged;
365 }
366
367
368 # -------------------------------------------------------------------
369 # Takes a result batch and returns the hitcount and a list of xml
370 # and mvr objects
371 # -------------------------------------------------------------------
372 sub process_results {
373
374     fetch_service_defs() unless (scalar(keys(%services)));
375
376     my $results = shift;
377     my $limit = shift || 10;
378     my $offset = shift || 0;
379     my $service = shift;
380
381     my $rformat = $services{$service}->{record_format};
382     my $tformat = $services{$service}->{transmission_format} || $output;
383
384     $results->option(elementSetName => $rformat);
385     $results->option(preferredRecordSyntax => $tformat);
386     $logger->info("z3950: using record format '$rformat' and transmission format '$tformat'");
387
388     my @records;
389     my $res = {};
390     my $count = $$res{count} = $results->size;
391
392     $logger->info("z3950: search returned $count hits");
393
394     my $tend = $limit + $offset;
395
396     my $end = ($tend <= $count) ? $tend : $count;
397
398     for($offset..$end - 1) {
399
400         my $err;
401         my $mods;
402         my $marc;
403         my $marcs;
404         my $marcxml;
405
406         $logger->info("z3950: fetching record $_");
407
408         try {
409
410             my $rec = $results->record($_);
411
412             if ($tformat eq 'usmarc') {
413                 $marc = MARC::Record->new_from_usmarc($rec->raw());
414             } elsif ($tformat eq 'xml') {
415                 $marc = MARC::Record->new_from_xml($rec->raw());
416             } else {
417                 die "Unsupported record transmission format $tformat"
418             }
419
420             $marcs = $U->entityize($marc->as_xml_record);
421             $marcs = $U->strip_ctrl_chars($marcs);
422             my $doc = XML::LibXML->new->parse_string($marcs);
423             $marcxml = $U->entityize($doc->documentElement->toString);
424             $marcxml = $U->strip_ctrl_chars($marcxml);
425     
426             my $u = OpenILS::Utils::ModsParser->new();
427             $u->start_mods_batch( $marcxml );
428             $mods = $u->finish_mods_batch();
429     
430
431         } catch Error with { $err = shift; };
432
433         push @records, { 'mvr' => $mods, 'marcxml' => $marcxml } unless $err;
434         $logger->error("z3950: bad XML : $err") if $err;
435
436         if( $err ) {
437             warn "\n\n$marcs\n\n";
438         }
439     }
440     
441     $res->{records} = \@records;
442     return $res;
443 }
444
445
446
447 # -------------------------------------------------------------------
448 # Compiles the class based search query
449 # -------------------------------------------------------------------
450 sub compile_query {
451
452     fetch_service_defs() unless (scalar(keys(%services)));
453
454     my $separator = shift;
455     my $service = shift;
456     my $hash = shift;
457
458     my $count = scalar(keys %$hash);
459
460     my $str = "";
461     $str .= "\@$separator " for (1..$count-1);
462     
463     # -------------------------------------------------------------------
464     # "code" is the bib-1 "use attribute", "format" is the bib-1 
465     # "structure attribute"
466     # -------------------------------------------------------------------
467     for( keys %$hash ) {
468         next unless ( exists $services{$service}->{attrs}->{$_} );
469         $str .= '@attr 1=' . $services{$service}->{attrs}->{$_}->{code} . # add the use attribute
470             ' @attr 4=' . $services{$service}->{attrs}->{$_}->{format}; # add the structure attribute
471         if (exists $services{$service}->{attrs}->{$_}->{truncation}
472                 && $services{$service}->{attrs}->{$_}->{truncation} >= 0) {
473             $str .= ' @attr 5=' . $services{$service}->{attrs}->{$_}->{truncation};
474         }
475         $str .= " \"" . $$hash{$_} . "\" "; # add the search term
476     }
477     return $str;
478 }
479
480 1;
481 # vim:et:ts=4:sw=4: