]> git.evergreen-ils.org Git - working/Evergreen.git/blob - Open-ILS/src/perlmods/OpenILS/Application/Search/Z3950.pm
new api, added paging and classed searches
[working/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         my $services = $sclient->config_value('z3950', 'services');
88         $services = { $services } unless ref($services);
89         return [ keys %$services ];
90 }
91
92
93
94 # -------------------------------------------------------------------
95 # Load the pre-defined Z server configs
96 # -------------------------------------------------------------------
97 sub initialize {
98         $sclient = OpenSRF::Utils::SettingsClient->new();
99         $default_service = $sclient->config_value("z3950", "default" );
100         my $servs = $sclient->config_value("z3950", "services" );
101         $services{$_} = $$servs{$_} for keys %$servs;
102 }
103
104
105 # -------------------------------------------------------------------
106 # High-level class based search. 
107 # -------------------------------------------------------------------
108 sub do_class_search {
109
110         my $self                        = shift;
111         my $conn                        = shift;
112         my $auth                        = shift;
113         my $args                        = shift;
114
115         $$args{query} = 
116                 compile_query('and', $$args{service}, $$args{search});
117
118         return $self->do_service_search( $conn, $auth, $args );
119 }
120
121
122 # -------------------------------------------------------------------
123 # This handles the host settings, but expects a fully formed z query
124 # -------------------------------------------------------------------
125 sub do_service_search {
126
127         my $self                        = shift;
128         my $conn                        = shift;
129         my $auth                        = shift;
130         my $args                        = shift;
131         
132         my $info = $services{$$args{service}};
133
134         $$args{host}    = $$info{host},
135         $$args{port}    = $$info{port},
136         $$args{db}              = $$info{db},
137
138         return $self->do_search( $conn, $auth, $args );
139 }
140
141
142
143 # -------------------------------------------------------------------
144 # This is the low level search method.  All config and query
145 # data must be provided to this method
146 # -------------------------------------------------------------------
147 sub do_search {
148
149         my $self        = shift;
150         my $conn        = shift;
151         my $auth = shift;
152         my $args = shift;
153
154         my $host                = $$args{host} or return undef;
155         my $port                = $$args{port} or return undef;
156         my $db          = $$args{db}    or return undef;
157         my $query       = $$args{query} or return undef;
158
159         my $limit       = $$args{limit} || 10;
160         my $offset      = $$args{offset} || 0;
161
162         my $username = $$args{username} || "";
163         my $password = $$args{password} || "";
164
165         my $editor = new_editor(authtoken => $auth);
166         return $editor->event unless $editor->checkauth;
167         return $editor->event unless $editor->allowed('REMOTE_Z3950_QUERY');
168
169         my $connection = new Net::Z3950::Connection(
170                 $host, $port,
171                 databaseName                            => $db, 
172                 user                                                    => $username,
173                 password                                                => $password,
174                 preferredRecordSyntax   => $output, 
175         );
176
177         if( ! $connection ) {
178                 $logger->error("z3950: Unable to connect to Z server: ".
179                         "$host:$port:$db:$username:$password");
180                 return OpenILS::Event->new('Z3950_LOGIN_FAILED') unless $connection;
181         }
182
183         my $start = time;
184         my $results = $connection->search( $query );
185         $logger->info("z3950: search [$query] took ".(time - $start)." seconds");
186
187         return OpenILS::Event->new('Z3950_SEARCH_FAILED') unless $results;
188
189         return process_results($results, $limit, $offset);
190 }
191
192
193 # -------------------------------------------------------------------
194 # Takes a result batch and returns the hitcount and a list of xml
195 # and mvr objects
196 # -------------------------------------------------------------------
197 sub process_results {
198         my $results     = shift;
199         my $limit       = shift;
200         my $offset      = shift;
201
202         $results->option(elementSetName => "FI"); # full records with no holdings
203
204         my @records;
205         my $res = {};
206         my $count = $$res{count} = $results->size;
207
208         $logger->info("z3950: search returned $count hits");
209
210         my $tend = $limit + $offset;
211         $offset++; # records start at 1
212
213         my $end = ($tend <= $count) ? $tend : $count;
214
215         for($offset..$end) {
216
217                 my $err;
218                 my $mods;
219                 my $marcxml;
220
221                 $logger->info("z3950: fetching record $_");
222
223                 try {
224
225                         my $rec = $results->record($_);
226                         my $marc = MARC::Record->new_from_usmarc($rec->rawdata());
227                         my $doc = XML::LibXML->new->parse_string($marc->as_xml_record);
228                         $marcxml = entityize( $doc->documentElement->toString );
229         
230                         my $u = OpenILS::Utils::ModsParser->new();
231                         $u->start_mods_batch( $marcxml );
232                         $mods = $u->finish_mods_batch();
233         
234
235                 } catch Error with { $err = shift; };
236
237                 push @records, { 'mvr' => $mods, 'marcxml' => $marcxml } unless $err;
238                 $logger->error("z3950: bad XML : $err") if $err;
239         }
240         
241         $res->{records} = \@records;
242         return $res;
243 }
244
245
246
247 # -------------------------------------------------------------------
248 # Compiles the class based search query
249 # -------------------------------------------------------------------
250 sub compile_query {
251
252         my $seperator   = shift;
253         my $service             = shift;
254         my $hash                        = shift;
255
256         my $count = scalar(keys %$hash);
257
258         my $str = "";
259         $str .= "\@$seperator " for (1..$count-1);
260         
261         for( keys %$hash ) {
262                 $str .= '@attr 1=' . $services{$service}->{attrs}->{$_} . " \"" . $$hash{$_} . "\" ";           
263         }
264         return $str;
265 }
266
267
268
269 # -------------------------------------------------------------------
270 # Handles the unicode
271 # -------------------------------------------------------------------
272 sub entityize {
273         my $stuff = shift;
274         my $form = shift || "";
275         
276         if ($form eq 'D') {
277                 $stuff = NFD($stuff);
278         } else {
279                 $stuff = NFC($stuff);
280         }
281         
282         $stuff =~ s/([\x{0080}-\x{fffd}])/sprintf('&#x%X;',ord($1))/sgoe;
283         return $stuff;
284 }
285
286
287 1;