Bug 30813: Remove TransformMarcToKohaOneField
[koha.git] / Koha / MetaSearcher.pm
1 package Koha::MetaSearcher;
2
3 # Copyright 2014 ByWater Solutions
4 #
5 # This file is part of Koha.
6 #
7 # Koha is free software; you can redistribute it and/or modify it
8 # under the terms of the GNU General Public License as published by
9 # the Free Software Foundation; either version 3 of the License, or
10 # (at your option) any later version.
11 #
12 # Koha is distributed in the hope that it will be useful, but
13 # WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 # GNU General Public License for more details.
16 #
17 # You should have received a copy of the GNU General Public License
18 # along with Koha; if not, see <http://www.gnu.org/licenses>.
19
20 use Modern::Perl;
21
22 use base 'Class::Accessor';
23
24 use C4::Charset qw( MarcToUTF8Record SetUTF8Flag );
25 use C4::Search qw( new_record_from_zebra );
26 use DBIx::Class::ResultClass::HashRefInflator;
27 use IO::Select;
28 use Koha::Caches;
29 use Koha::Database;
30 use Koha::MetadataRecord;
31 use MARC::File::XML;
32 use Storable qw( fd_retrieve store_fd );
33 use Time::HiRes qw( clock_gettime CLOCK_MONOTONIC );
34 use UUID;
35 use ZOOM;
36
37 use sort 'stable';
38
39 __PACKAGE__->mk_accessors( qw( fetch offset on_error resultset ) );
40
41 sub new {
42     my ( $class, $options ) = @_;
43
44     my ( $uuid, $uuidstring );
45     UUID::generate($uuid);
46     UUID::unparse( $uuid, $uuidstring );
47
48     return bless {
49         offset => 0,
50         fetch => 100,
51         on_error => sub {},
52         results => [],
53         resultset => $uuidstring,
54         %{ $options || {} }
55     }, $class;
56 }
57
58 sub handle_hit {
59     my ( $self, $index, $server, $marcrecord ) = @_;
60
61     my @kohafields = ('biblio.title','biblio.subtitle','biblio.seriestitle','biblio.author',
62             'biblioitems.isbn','biblioitems.issn','biblioitems.lccn','biblioitems.editionstatement',
63             'biblio.copyrightdate','biblioitems.publicationyear');
64     my $metadata =  C4::Biblio::TransformMarcToKoha({ kohafields => \@kohafields, record => $marcrecord});
65     $metadata->{edition} = delete $metadata->{editionstatement};
66     $metadata->{date} = delete $metadata->{copyrightdate};
67     $metadata->{date} //= delete $metadata->{publicationyear};
68
69     push @{ $self->{results} }, {
70         server => $server,
71         index => $index,
72         record => $marcrecord,
73         metadata => $metadata,
74     };
75 }
76
77 sub search {
78     my ( $self, $server_ids, $query ) = @_;
79
80     my $resultset_expiry = 300;
81
82     my $cache = Koha::Caches->get_instance();
83     my $schema = Koha::Database->new->schema;
84     my $stats = {
85         num_fetched => {
86             map { $_ => 0 } @$server_ids
87         },
88         num_hits => {
89             map { $_ => 0 } @$server_ids
90         },
91         total_fetched => 0,
92         total_hits => 0,
93     };
94     my $start = clock_gettime( CLOCK_MONOTONIC );
95     my $select = IO::Select->new;
96
97     my @cached_sets;
98     my @servers;
99
100     foreach my $server_id ( @$server_ids ) {
101         if ( $server_id =~ /^\d+$/ ) {
102             # Z39.50 server
103             my $server = $schema->resultset('Z3950server')->find(
104                 { id => $server_id },
105                 { result_class => 'DBIx::Class::ResultClass::HashRefInflator' },
106             );
107             $server->{type} = 'z3950';
108
109             push @servers, $server;
110         } elsif ( $server_id =~ /(\w+)(?::(\w+))?/ ) {
111             # Special server
112             push @servers, {
113                 type => $1,
114                 extra => $2,
115                 id => $server_id,
116                 host => $server_id,
117                 servername => $server_id,
118             };
119         }
120     }
121
122     # HashRefInflator is used so that the information will survive into the fork
123     foreach my $server ( @servers ) {
124         if ( $cache ) {
125             my $set = $cache->get_from_cache( 'z3950-resultset-' . $self->resultset . '-' . $server->{id} );
126             if ( ref($set) eq 'HASH' ) {
127                 $set->{server} = $server;
128                 push @cached_sets, $set;
129                 next;
130             }
131         }
132
133         $select->add( $self->_start_worker( $server, $query ) );
134     }
135
136     # Handle these while the servers are searching
137     foreach my $set ( @cached_sets ) {
138         $self->_handle_hits( $stats, $set );
139     }
140
141     while ( $select->count ) {
142         foreach my $readfh ( $select->can_read() ) {
143             my $result = fd_retrieve( $readfh );
144
145             $select->remove( $readfh );
146             close $readfh;
147             wait;
148
149             next if ( ref $result ne 'HASH' );
150
151             if ( $result->{error} ) {
152                 $self->{on_error}->( $result->{server}, $result->{error} );
153                 next;
154             }
155
156             $self->_handle_hits( $stats, $result );
157
158             if ( $cache ) {
159                 $cache->set_in_cache( 'z3950-resultset-' . $self->resultset . '-' . $result->{server}->{id}, {
160                     hits => $result->{hits},
161                     num_fetched => $result->{num_fetched},
162                     num_hits => $result->{num_hits},
163                 }, { expiry => $resultset_expiry } );
164             }
165         }
166     }
167
168     $stats->{time} = clock_gettime( CLOCK_MONOTONIC ) - $start;
169
170     return $stats;
171 }
172
173 sub _start_worker {
174     my ( $self, $server, $query ) = @_;
175     pipe my $readfh, my $writefh;
176
177     # Accessing the cache or Koha database after the fork is risky, so get any resources we need
178     # here.
179     my $pid;
180     my $marcflavour = C4::Context->preference('marcflavour');
181
182     if ( ( $pid = fork ) ) {
183         # Parent process
184         close $writefh;
185
186         return $readfh;
187     } elsif ( !defined $pid ) {
188         # Error
189
190         $self->{on_error}->( $server, 'Failed to fork' );
191         return;
192     }
193
194     close $readfh;
195     my $connection;
196     my ( $num_hits, $num_fetched, $hits, $results );
197
198     eval {
199         if ( $server->{type} eq 'z3950' ) {
200             my $zoptions = ZOOM::Options->new();
201             $zoptions->option( 'elementSetName', 'F' );
202             $zoptions->option( 'databaseName',   $server->{db} );
203             $zoptions->option( 'user', $server->{userid} ) if $server->{userid};
204             $zoptions->option( 'password', $server->{password} ) if $server->{password};
205             $zoptions->option( 'preferredRecordSyntax', $server->{syntax} );
206             $zoptions->option( 'timeout', $server->{timeout} ) if $server->{timeout};
207
208             $connection = ZOOM::Connection->create($zoptions);
209
210             $connection->connect( $server->{host}, $server->{port} );
211             $results = $connection->search_pqf( $query ); # Starts the search
212         } elsif ( $server->{type} eq 'koha' ) {
213             $connection = C4::Context->Zconn( $server->{extra} );
214             $results = $connection->search_pqf( $query ); # Starts the search
215         } elsif ( $server->{type} eq 'batch' )  {
216             $server->{encoding} = 'utf-8';
217         }
218     };
219     if ($@) {
220         store_fd {
221             error => $connection ? $connection->exception() : $@,
222             server => $server,
223         }, $writefh;
224         exit;
225     }
226
227     if ( $server->{type} eq 'batch' ) {
228         # TODO: actually handle PQF
229         $query =~ s/@\w+ (?:\d+=\d+ )?//g;
230         $query =~ s/"//g;
231
232         my $schema = Koha::Database->new->schema;
233         $schema->storage->debug(1);
234         my $match_condition = [ map +{ -like => '%' . $_ . '%' }, split( /\s+/, $query ) ];
235         $hits = [ $schema->resultset('ImportRecord')->search(
236             {
237                 import_batch_id => $server->{extra},
238                 -or => [
239                     { 'import_biblios.title' => $match_condition },
240                     { 'import_biblios.author' => $match_condition },
241                     { 'import_biblios.isbn' => $match_condition },
242                     { 'import_biblios.issn' => $match_condition },
243                 ],
244             },
245             {
246                 join => [ qw( import_biblios ) ],
247                 rows => $self->{fetch},
248             }
249         )->get_column( 'marc' )->all ];
250
251         $num_hits = $num_fetched = scalar @$hits;
252     } else {
253         $num_hits = $results->size;
254         $num_fetched = ( $self->{offset} + $self->{fetch} ) < $num_hits ? $self->{fetch} : $num_hits;
255
256         $hits = [ map { $_->raw() } @{ $results->records( $self->{offset}, $num_fetched, 1 ) } ];
257     }
258
259     if ( !@$hits && $connection && $connection->exception() ) {
260         store_fd {
261             error => $connection->exception(),
262             server => $server,
263         }, $writefh;
264         exit;
265     }
266
267     if ( $server->{type} eq 'koha' ) {
268         $hits = [ map { C4::Search::new_record_from_zebra( $server->{extra}, $_ ) } @$hits ];
269     } else {
270         $hits = [ map { $self->_import_record( $_, $marcflavour, $server->{encoding} ? $server->{encoding} : "iso-5426" ) } @$hits ];
271     }
272
273     store_fd {
274         hits => $hits,
275         num_fetched => $num_fetched,
276         num_hits => $num_hits,
277         server => $server,
278     }, $writefh;
279
280     exit;
281 }
282
283 sub _import_record {
284     my ( $self, $raw, $marcflavour, $encoding ) = @_;
285
286     my ( $marcrecord ) = MarcToUTF8Record( $raw, $marcflavour, $encoding ); #ignores charset return values
287
288     SetUTF8Flag($marcrecord);
289     return $marcrecord;
290 }
291
292 sub _handle_hits {
293     my ( $self, $stats, $set ) = @_;
294
295     my $server = $set->{server};
296
297     my $num_hits = $stats->{num_hits}->{ $server->{id} } = $set->{num_hits};
298     my $num_fetched = $stats->{num_fetched}->{ $server->{id} } = $set->{num_fetched};
299
300     $stats->{total_hits} += $num_hits;
301     $stats->{total_fetched} += $num_fetched;
302
303     foreach my $j ( 0..$#{ $set->{hits} } ) {
304         $self->handle_hit( $self->{offset} + $j, $server, $set->{hits}->[$j] );
305     }
306 }
307
308 sub sort {
309     my ( $self, $key, $direction ) = @_;
310
311     my $empty_flip = -1; # Determines the flip of ordering for records with empty sort keys.
312
313     foreach my $hit ( @{ $self->{results} } ) {
314         ( $hit->{sort_key} = $hit->{metadata}->{$key} || '' ) =~ s/\W//g;
315     }
316
317     $self->{results} = [ sort {
318         # Sort empty records at the end
319         return -$empty_flip unless $a->{sort_key};
320         return $empty_flip unless $b->{sort_key};
321
322         $direction * ( $a->{sort_key} cmp $b->{sort_key} );
323     } @{ $self->{results} } ];
324 }
325
326 sub results {
327     my ( $self, $offset, $length ) = @_;
328
329     my @subset;
330
331     foreach my $i ( $offset..( $offset + $length - 1 ) ) {
332         push @subset, $self->{results}->[$i] if $self->{results}->[$i];
333     }
334
335     return @subset;
336 }
337
338 1;