]> git.evergreen-ils.org Git - Evergreen.git/blob - Open-ILS/src/perlmods/OpenILS/Application/Search/Z3950.pm
added event for bad queries
[Evergreen.git] / Open-ILS / src / perlmods / OpenILS / Application / Search / Z3950.pm
1 #!/usr/bin/perl
2 package OpenILS::Application::Search::Z3950;
3 use strict; use warnings;
4 use base qw/OpenSRF::Application/;
5
6 use Net::Z3950;
7 use MARC::Record;
8 use MARC::File::XML;
9 use Unicode::Normalize;
10 use XML::LibXML;
11 use Data::Dumper;
12
13 use OpenILS::Event;
14 use OpenSRF::EX qw(:try);
15 use OpenILS::Utils::ModsParser;
16 use OpenSRF::Utils::SettingsClient;
17 use OpenILS::Application::AppUtils;
18 use OpenSRF::Utils::Logger qw/$logger/;
19 use OpenILS::Utils::Editor q/:funcs/;
20
21 my $output      = "USMARC"; 
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         signature       => q/
32                 Performs a class based Z search.  The classes available
33                 are defined by the 'attr' fields in the config for the
34                 requested service.
35                 @param auth The login session key
36                 @param shash The search hash : { attr : value, attr2: value, ...}
37                 @param service The service to connect to
38                 @param username The username to use when connecting to the service
39                 @param password The password to use when connecting to the service
40         /
41 );
42
43 __PACKAGE__->register_method(
44         method          => 'do_service_search',
45         api_name                => 'open-ils.search.z3950.search_service',
46         signature       => q/
47                 @param auth The login session key
48                 @param query The Z3950 search string to use
49                 @param service The service to connect to
50                 @param username The username to use when connecting to the service
51                 @param password The password to use when connecting to the service
52         /
53 );
54
55
56 __PACKAGE__->register_method(
57         method          => 'do_service_search',
58         api_name                => 'open-ils.search.z3950.search_raw',
59         signature       => q/
60                 @param auth The login session key
61                 @param args An object of search params which must include:
62                         host, port, db and query.  
63                         optional fields include username and password
64         /
65 );
66
67
68 __PACKAGE__->register_method(
69         method  => "query_services",
70         api_name        => "open-ils.search.z3950.retrieve_services",
71         signature       => q/
72                 Returns a list of service names that we have config
73                 data for
74         /
75 );
76
77
78
79 # -------------------------------------------------------------------
80 # What services do we have config info for?
81 # -------------------------------------------------------------------
82 sub query_services {
83         my( $self, $client, $auth ) = @_;
84         my $e = new_editor(authtoken=>$auth);
85         return $e->event unless $e->checkauth;
86         return $e->event unless $e->allowed('REMOTE_Z3950_QUERY');
87         return $sclient->config_value('z3950', 'services');
88 }
89
90
91
92 # -------------------------------------------------------------------
93 # Load the pre-defined Z server configs
94 # -------------------------------------------------------------------
95 sub initialize {
96         $sclient = OpenSRF::Utils::SettingsClient->new();
97         $default_service = $sclient->config_value("z3950", "default" );
98         my $servs = $sclient->config_value("z3950", "services" );
99         $services{$_} = $$servs{$_} for keys %$servs;
100 }
101
102
103 # -------------------------------------------------------------------
104 # High-level class based search. 
105 # -------------------------------------------------------------------
106 sub do_class_search {
107
108         my $self                        = shift;
109         my $conn                        = shift;
110         my $auth                        = shift;
111         my $args                        = shift;
112
113         $$args{query} = 
114                 compile_query('and', $$args{service}, $$args{search});
115
116         return $self->do_service_search( $conn, $auth, $args );
117 }
118
119
120 # -------------------------------------------------------------------
121 # This handles the host settings, but expects a fully formed z query
122 # -------------------------------------------------------------------
123 sub do_service_search {
124
125         my $self                        = shift;
126         my $conn                        = shift;
127         my $auth                        = shift;
128         my $args                        = shift;
129         
130         my $info = $services{$$args{service}};
131
132         $$args{host}    = $$info{host},
133         $$args{port}    = $$info{port},
134         $$args{db}              = $$info{db},
135
136         return $self->do_search( $conn, $auth, $args );
137 }
138
139
140
141 # -------------------------------------------------------------------
142 # This is the low level search method.  All config and query
143 # data must be provided to this method
144 # -------------------------------------------------------------------
145 sub do_search {
146
147         my $self        = shift;
148         my $conn        = shift;
149         my $auth = shift;
150         my $args = shift;
151
152         my $host                = $$args{host} or return undef;
153         my $port                = $$args{port} or return undef;
154         my $db          = $$args{db}    or return undef;
155         my $query       = $$args{query} or return undef;
156
157         my $limit       = $$args{limit} || 10;
158         my $offset      = $$args{offset} || 0;
159
160         my $username = $$args{username} || "";
161         my $password = $$args{password} || "";
162
163         my $editor = new_editor(authtoken => $auth);
164         return $editor->event unless $editor->checkauth;
165         return $editor->event unless $editor->allowed('REMOTE_Z3950_QUERY');
166
167         my $connection = new Net::Z3950::Connection(
168                 $host, $port,
169                 databaseName                            => $db, 
170                 user                                                    => $username,
171                 password                                                => $password,
172                 preferredRecordSyntax   => $output, 
173         );
174
175         if( ! $connection ) {
176                 $logger->error("z3950: Unable to connect to Z server: ".
177                         "$host:$port:$db:$username:$password");
178                 return OpenILS::Event->new('Z3950_LOGIN_FAILED') unless $connection;
179         }
180
181         my $start = time;
182         my $results;
183         my $err;
184         try {
185                 $results = $connection->search( $query );
186         } catch Error with { $err = shift; };
187
188         return OpenILS::Event->new(
189                 'Z3950_BAD_QUERY', payload => $query, debug => "$err") if $err;
190
191         return OpenILS::Event->new('Z3950_SEARCH_FAILED') unless $results;
192
193         $logger->info("z3950: search [$query] took ".(time - $start)." seconds");
194
195         my $munged = process_results($results, $limit, $offset);
196         $munged->{query} = $query;
197
198         return $munged;
199 }
200
201
202 # -------------------------------------------------------------------
203 # Takes a result batch and returns the hitcount and a list of xml
204 # and mvr objects
205 # -------------------------------------------------------------------
206 sub process_results {
207         my $results     = shift;
208         my $limit       = shift;
209         my $offset      = shift;
210
211         $results->option(elementSetName => "FI"); # full records with no holdings
212
213         my @records;
214         my $res = {};
215         my $count = $$res{count} = $results->size;
216
217         $logger->info("z3950: search returned $count hits");
218
219         my $tend = $limit + $offset;
220         $offset++; # records start at 1
221
222         my $end = ($tend <= $count) ? $tend : $count;
223
224         for($offset..$end) {
225
226                 my $err;
227                 my $mods;
228                 my $marcxml;
229
230                 $logger->info("z3950: fetching record $_");
231
232                 try {
233
234                         my $rec = $results->record($_);
235                         my $marc = MARC::Record->new_from_usmarc($rec->rawdata());
236                         my $doc = XML::LibXML->new->parse_string($marc->as_xml_record);
237                         $marcxml = entityize( $doc->documentElement->toString );
238         
239                         my $u = OpenILS::Utils::ModsParser->new();
240                         $u->start_mods_batch( $marcxml );
241                         $mods = $u->finish_mods_batch();
242         
243
244                 } catch Error with { $err = shift; };
245
246                 push @records, { 'mvr' => $mods, 'marcxml' => $marcxml } unless $err;
247                 $logger->error("z3950: bad XML : $err") if $err;
248         }
249         
250         $res->{records} = \@records;
251         return $res;
252 }
253
254
255
256 # -------------------------------------------------------------------
257 # Compiles the class based search query
258 # -------------------------------------------------------------------
259 sub compile_query {
260
261         my $seperator   = shift;
262         my $service             = shift;
263         my $hash                        = shift;
264
265         my $count = scalar(keys %$hash);
266
267         my $str = "";
268         $str .= "\@$seperator " for (1..$count-1);
269         
270         for( keys %$hash ) {
271                 $str .= '@attr 1=' . $services{$service}->{attrs}->{$_} . " \"" . $$hash{$_} . "\" ";           
272         }
273         return $str;
274 }
275
276
277
278 # -------------------------------------------------------------------
279 # Handles the unicode
280 # -------------------------------------------------------------------
281 sub entityize {
282         my $stuff = shift;
283         my $form = shift || "";
284         
285         if ($form eq 'D') {
286                 $stuff = NFD($stuff);
287         } else {
288                 $stuff = NFC($stuff);
289         }
290         
291         $stuff =~ s/([\x{0080}-\x{fffd}])/sprintf('&#x%X;',ord($1))/sgoe;
292         return $stuff;
293 }
294
295
296 1;