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