Bug 9105: Move Z3950 search code to Breeding module
[koha.git] / C4 / Breeding.pm
1 package C4::Breeding;
2
3 # Copyright 2000-2002 Katipo Communications
4 #
5 # This file is part of Koha.
6 #
7 # Koha is free software; you can redistribute it and/or modify it under the
8 # terms of the GNU General Public License as published by the Free Software
9 # Foundation; either version 2 of the License, or (at your option) any later
10 # version.
11 #
12 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
13 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
14 # A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
15 #
16 # You should have received a copy of the GNU General Public License along
17 # with Koha; if not, write to the Free Software Foundation, Inc.,
18 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
19
20 use strict;
21 use warnings;
22
23 use C4::Biblio;
24 use C4::Koha;
25 use C4::Charset;
26 use MARC::File::USMARC;
27 use C4::ImportBatch;
28
29 use vars qw($VERSION @ISA @EXPORT @EXPORT_OK %EXPORT_TAGS);
30
31 BEGIN {
32         # set the version for version checking
33     $VERSION = 3.07.00.049;
34         require Exporter;
35         @ISA = qw(Exporter);
36     @EXPORT = qw(&ImportBreeding &BreedingSearch &Z3950Search);
37 }
38
39 =head1 NAME
40
41 C4::Breeding : module to add biblios to import_records via
42                the breeding/reservoir API.
43
44 =head1 SYNOPSIS
45
46     use C4::Scan;
47     &ImportBreeding($marcrecords,$overwrite_biblio,$filename,$z3950random,$batch_type);
48
49     C<$marcrecord> => the MARC::Record
50     C<$overwrite_biblio> => if set to 1 a biblio with the same ISBN will be overwritted.
51                                 if set to 0 a biblio with the same isbn will be ignored (the previous will be kept)
52                                 if set to -1 the biblio will be added anyway (more than 1 biblio with the same ISBN 
53                                 possible in the breeding
54     C<$encoding> => USMARC
55                         or UNIMARC. used for char_decoding.
56                         If not present, the parameter marcflavour is used instead
57     C<$z3950random> => the random value created during a z3950 search result.
58
59 =head1 DESCRIPTION
60
61     ImportBreeding import MARC records in the reservoir (import_records/import_batches tables).
62     the records can be properly encoded or not, we try to reencode them in utf-8 if needed.
63     works perfectly with BNF server, that sends UNIMARC latin1 records. Should work with other servers too.
64
65 =head2 ImportBreeding
66
67         ImportBreeding($marcrecords,$overwrite_biblio,$filename,$encoding,$z3950random,$batch_type);
68
69         TODO description
70
71 =cut
72
73 sub ImportBreeding {
74     my ($marcrecords,$overwrite_biblio,$filename,$encoding,$z3950random,$batch_type) = @_;
75     my @marcarray = split /\x1D/, $marcrecords;
76     
77     my $dbh = C4::Context->dbh;
78     
79     my $batch_id = GetZ3950BatchId($filename);
80     my $searchisbn = $dbh->prepare("select biblioitemnumber from biblioitems where isbn=?");
81     my $searchissn = $dbh->prepare("select biblioitemnumber from biblioitems where issn=?");
82     # FIXME -- not sure that this kind of checking is actually needed
83     my $searchbreeding = $dbh->prepare("select import_record_id from import_biblios where isbn=? and title=?");
84     
85 #     $encoding = C4::Context->preference("marcflavour") unless $encoding;
86     # fields used for import results
87     my $imported=0;
88     my $alreadyindb = 0;
89     my $alreadyinfarm = 0;
90     my $notmarcrecord = 0;
91     my $breedingid;
92     for (my $i=0;$i<=$#marcarray;$i++) {
93         my ($marcrecord, $charset_result, $charset_errors);
94         ($marcrecord, $charset_result, $charset_errors) = 
95             MarcToUTF8Record($marcarray[$i]."\x1D", C4::Context->preference("marcflavour"), $encoding);
96         
97         # Normalize the record so it doesn't have separated diacritics
98         SetUTF8Flag($marcrecord);
99
100 #         warn "$i : $marcarray[$i]";
101         # FIXME - currently this does nothing 
102         my @warnings = $marcrecord->warnings();
103         
104         if (scalar($marcrecord->fields()) == 0) {
105             $notmarcrecord++;
106         } else {
107             my $oldbiblio = TransformMarcToKoha($dbh,$marcrecord,'');
108             # if isbn found and biblio does not exist, add it. If isbn found and biblio exists, 
109             # overwrite or ignore depending on user choice
110             # drop every "special" char : spaces, - ...
111             $oldbiblio->{isbn} = C4::Koha::_isbn_cleanup($oldbiblio->{isbn}); # FIXME C4::Koha::_isbn_cleanup should be public
112             # search if biblio exists
113             my $biblioitemnumber;
114             if ($oldbiblio->{isbn}) {
115                 $searchisbn->execute($oldbiblio->{isbn});
116                 ($biblioitemnumber) = $searchisbn->fetchrow;
117             } else {
118                 if ($oldbiblio->{issn}) {
119                     $searchissn->execute($oldbiblio->{issn});
120                         ($biblioitemnumber) = $searchissn->fetchrow;
121                 }
122             }
123             if ($biblioitemnumber && $overwrite_biblio ne 2) {
124                 $alreadyindb++;
125             } else {
126                 # FIXME - in context of batch load,
127                 # rejecting records because already present in the reservoir
128                 # not correct in every case.
129                 # search in breeding farm
130                 if ($oldbiblio->{isbn}) {
131                     $searchbreeding->execute($oldbiblio->{isbn},$oldbiblio->{title});
132                     ($breedingid) = $searchbreeding->fetchrow;
133                 } elsif ($oldbiblio->{issn}){
134                     $searchbreeding->execute($oldbiblio->{issn},$oldbiblio->{title});
135                     ($breedingid) = $searchbreeding->fetchrow;
136                 }
137                 if ($breedingid && $overwrite_biblio eq '0') {
138                     $alreadyinfarm++;
139                 } else {
140                     if ($breedingid && $overwrite_biblio eq '1') {
141                         ModBiblioInBatch($breedingid, $marcrecord);
142                     } else {
143                         my $import_id = AddBiblioToBatch($batch_id, $imported, $marcrecord, $encoding, $z3950random);
144                         $breedingid = $import_id;
145                     }
146                     $imported++;
147                 }
148             }
149         }
150     }
151     return ($notmarcrecord,$alreadyindb,$alreadyinfarm,$imported,$breedingid);
152 }
153
154
155 =head2 BreedingSearch
156
157 ($count, @results) = &BreedingSearch($title,$isbn,$random);
158 C<$title> contains the title,
159 C<$isbn> contains isbn or issn,
160 C<$random> contains the random seed from a z3950 search.
161
162 C<$count> is the number of items in C<@results>. C<@results> is an
163 array of references-to-hash; the keys are the items from the C<import_records> and
164 C<import_biblios> tables of the Koha database.
165
166 =cut
167
168 sub BreedingSearch {
169     my ($search,$isbn,$z3950random) = @_;
170     my $dbh   = C4::Context->dbh;
171     my $count = 0;
172     my ($query,@bind);
173     my $sth;
174     my @results;
175
176     $query = "SELECT import_record_id, file_name, isbn, title, author
177               FROM  import_biblios 
178               JOIN import_records USING (import_record_id)
179               JOIN import_batches USING (import_batch_id)
180               WHERE ";
181     if ($z3950random) {
182         $query .= "z3950random = ?";
183         @bind=($z3950random);
184     } else {
185         @bind=();
186         if (defined($search) && length($search)>0) {
187             $search =~ s/(\s+)/\%/g;
188             $query .= "title like ? OR author like ?";
189             push(@bind,"%$search%", "%$search%");
190         }
191         if ($#bind!=-1 && defined($isbn) && length($isbn)>0) {
192             $query .= " and ";
193         }
194         if (defined($isbn) && length($isbn)>0) {
195             $query .= "isbn like ?";
196             push(@bind,"$isbn%");
197         }
198     }
199     $sth   = $dbh->prepare($query);
200     $sth->execute(@bind);
201     while (my $data = $sth->fetchrow_hashref) {
202             $results[$count] = $data;
203             # FIXME - hack to reflect difference in name 
204             # of columns in old marc_breeding and import_records
205             # There needs to be more separation between column names and 
206             # field names used in the templates </soapbox>
207             $data->{'file'} = $data->{'file_name'};
208             $data->{'id'} = $data->{'import_record_id'};
209             $count++;
210     } # while
211
212     $sth->finish;
213     return($count, @results);
214 } # sub breedingsearch
215
216
217 =head2 Z3950Search
218
219 Z3950Search($pars, $template);
220
221 Parameters for Z3950 search are all passed via the $pars hash. It may contain isbn, title, author, dewey, subject, lccall, controlnumber, stdid, srchany.
222 Also it should contain an arrayref id that points to a list of id's of the z3950 targets to be queried (see z3950servers table).
223 This code is used in acqui/z3950_search and cataloging/z3950_search.
224 The second parameter $template is a Template object. The routine uses this parameter to store the found values into the template.
225
226 =cut
227
228 sub Z3950Search {
229     my ($pars, $template)= @_;
230
231     my $dbh   = C4::Context->dbh;
232     my @id= @{$pars->{id}};
233     my $random= $pars->{random};
234     my $page= $pars->{page};
235     my $biblionumber= $pars->{biblionumber};
236
237     my $isbn= $pars->{isbn};
238     my $issn= $pars->{issn};
239     my $title= $pars->{title};
240     my $author= $pars->{author};
241     my $dewey= $pars->{dewey};
242     my $subject= $pars->{subject};
243     my $lccn= $pars->{lccn};
244     my $lccall= $pars->{lccall};
245     my $controlnumber= $pars->{controlnumber};
246
247
248 my $show_next       = 0;
249 my $total_pages     = 0;
250
251 my $noconnection;
252 my $attr = '';
253 my $term;
254 my $host;
255 my $server;
256 my $database;
257 my $port;
258 my $marcdata;
259 my @encoding;
260 my @results;
261 my $count;
262 my $toggle;
263 my $record;
264 my $oldbiblio;
265 my $errmsg;
266 my @serverhost;
267 my @servername;
268 my @breeding_loop = ();
269
270
271     my @oConnection;
272     my @oResult;
273     my @errconn;
274     my $s = 0;
275     my $query;
276     my $nterms=0;
277     if ($isbn) {
278         $term=$isbn;
279         $query .= " \@attr 1=7 \@attr 5=1 \"$term\" ";
280         $nterms++;
281     }
282     if ($issn) {
283         $term=$issn;
284         $query .= " \@attr 1=8 \@attr 5=1 \"$term\" ";
285         $nterms++;
286     }
287     if ($title) {
288         utf8::decode($title);
289         $query .= " \@attr 1=4 \"$title\" ";
290         $nterms++;
291     }
292     if ($author) {
293         utf8::decode($author);
294         $query .= " \@attr 1=1003 \"$author\" ";
295         $nterms++;
296     }
297     if ($dewey) {
298         $query .= " \@attr 1=16 \"$dewey\" ";
299         $nterms++;
300     }
301     if ($subject) {
302         utf8::decode($subject);
303         $query .= " \@attr 1=21 \"$subject\" ";
304         $nterms++;
305     }
306     if ($lccn) {
307         $query .= " \@attr 1=9 $lccn ";
308         $nterms++;
309     }
310     if ($lccall) {
311         $query .= " \@attr 1=16 \@attr 2=3 \@attr 3=1 \@attr 4=1 \@attr 5=1 \@attr 6=1 \"$lccall\" ";
312         $nterms++;
313     }
314     if ($controlnumber) {
315         $query .= " \@attr 1=12 \"$controlnumber\" ";
316         $nterms++;
317     }
318 for my $i (1..$nterms-1) {
319     $query = "\@and " . $query;
320 }
321 warn "query ".$query  if $DEBUG;
322
323     foreach my $servid (@id) {
324         my $sth = $dbh->prepare("select * from z3950servers where id=?");
325         $sth->execute($servid);
326         while ( $server = $sth->fetchrow_hashref ) {
327             warn "serverinfo ".join(':',%$server) if $DEBUG;
328             my $option1      = new ZOOM::Options();
329             $option1->option( 'async' => 1 );
330             $option1->option( 'elementSetName', 'F' );
331             $option1->option( 'databaseName',   $server->{db} );
332             $option1->option( 'user', $server->{userid} ) if $server->{userid};
333             $option1->option( 'password', $server->{password} )
334               if $server->{password};
335             $option1->option( 'preferredRecordSyntax', $server->{syntax} );
336             $oConnection[$s] = create ZOOM::Connection($option1)
337               || $DEBUG
338               && warn( "" . $oConnection[$s]->errmsg() );
339             warn( "server data", $server->{name}, $server->{port} ) if $DEBUG;
340             $oConnection[$s]->connect( $server->{host}, $server->{port} )
341               || $DEBUG
342               && warn( "" . $oConnection[$s]->errmsg() );
343             $serverhost[$s] = $server->{host};
344             $servername[$s] = $server->{name};
345             $encoding[$s]   = ($server->{encoding}?$server->{encoding}:"iso-5426");
346             $s++;
347         }    ## while fetch
348     }    # foreach
349     my $nremaining  = $s;
350     my $firstresult = 1;
351
352     for ( my $z = 0 ; $z < $s ; $z++ ) {
353         warn "doing the search" if $DEBUG;
354         $oResult[$z] = $oConnection[$z]->search_pqf($query)
355           || $DEBUG
356           && warn( "somthing went wrong: " . $oConnection[$s]->errmsg() );
357
358         # $oResult[$z] = $oConnection[$z]->search_pqf($query);
359     }
360
361   warn "# nremaining = $nremaining\n" if $DEBUG;
362
363   while ( $nremaining-- ) {
364
365     my $k;
366     my $event;
367     while ( ( $k = ZOOM::event( \@oConnection ) ) != 0 ) {
368         $event = $oConnection[ $k - 1 ]->last_event();
369         warn( "connection ", $k - 1, ": event $event (",
370             ZOOM::event_str($event), ")\n" )
371           if $DEBUG;
372         last if $event == ZOOM::Event::ZEND;
373     }
374
375     if ( $k != 0 ) {
376         $k--;
377         warn "event from $k server = ",$serverhost[$k] if $DEBUG;
378         my ( $error, $errmsg, $addinfo, $diagset ) =
379           $oConnection[$k]->error_x();
380         if ($error) {
381             if ($error =~ m/^(10000|10007)$/ ) {
382                 push(@errconn, {'server' => $serverhost[$k]});
383             }
384             $DEBUG and warn "$k $serverhost[$k] error $query: $errmsg ($error) $addinfo\n";
385         }
386         else {
387             my $numresults = $oResult[$k]->size();
388             warn "numresults = $numresults" if $DEBUG;
389             my $i;
390             my $result = '';
391             if ( $numresults > 0  and $numresults >= (($page-1)*20)) {
392                 $show_next = 1 if $numresults >= ($page*20);
393                 $total_pages = int($numresults/20)+1 if $total_pages < ($numresults/20);
394                 for ($i = ($page-1)*20; $i < (($numresults < ($page*20)) ? $numresults : ($page*20)); $i++) {
395                     my $rec = $oResult[$k]->record($i);
396                     if ($rec) {
397                         my $marcrecord;
398                         $marcdata   = $rec->raw();
399
400                         my ($charset_result, $charset_errors);
401                         ($marcrecord, $charset_result, $charset_errors) =
402                           MarcToUTF8Record($marcdata, C4::Context->preference('marcflavour'), $encoding[$k]);
403 ####WARNING records coming from Z3950 clients are in various character sets MARC8,UTF8,UNIMARC etc
404 ## In HEAD i change everything to UTF-8
405 # In rel2_2 i am not sure what encoding is so no character conversion is done here
406 ##Add necessary encoding changes to here -TG
407
408                         # Normalize the record so it doesn't have separated diacritics
409                         SetUTF8Flag($marcrecord);
410
411                         my $oldbiblio = TransformMarcToKoha( $dbh, $marcrecord, "" );
412                         $oldbiblio->{isbn}   =~ s/ |-|\.//g if $oldbiblio->{isbn};
413                         # pad | and ( with spaces to allow line breaks in the HTML
414                         $oldbiblio->{isbn} =~ s/\|/ \| /g if $oldbiblio->{isbn};
415                         $oldbiblio->{isbn} =~ s/\(/ \(/g if $oldbiblio->{isbn};
416
417                         $oldbiblio->{issn} =~ s/ |-|\.//g if $oldbiblio->{issn};
418                         # pad | and ( with spaces to allow line breaks in the HTML
419                         $oldbiblio->{issn} =~ s/\|/ \| /g if $oldbiblio->{issn};
420                         $oldbiblio->{issn} =~ s/\(/ \(/g if $oldbiblio->{issn};
421                           my (
422                             $notmarcrecord, $alreadyindb, $alreadyinfarm,
423                             $imported,      $breedingid
424                           )
425                           = ImportBreeding( $marcdata, 2, $serverhost[$k], $encoding[$k], $random, 'z3950' );
426                         my %row_data;
427                         $row_data{server}       = $servername[$k];
428                         $row_data{isbn}         = $oldbiblio->{isbn};
429                         $row_data{lccn}         = $oldbiblio->{lccn};
430                         $row_data{title}        = $oldbiblio->{title};
431                         $row_data{author}       = $oldbiblio->{author};
432                         $row_data{breedingid}   = $breedingid;
433                         $row_data{biblionumber} = $biblionumber;
434                         push( @breeding_loop, \%row_data );
435
436                     } else {
437                         push(@breeding_loop,{'server'=>$servername[$k],'title'=>join(': ',$oConnection[$k]->error_x()),'breedingid'=>-1,'biblionumber'=>-1});
438                     } # $rec
439                 }    # upto 5 results
440             }    #$numresults
441         }
442     }    # if $k !=0
443     my $numberpending = $nremaining - 1;
444
445     my @servers = ();
446     foreach my $id (@id) {
447         push(@servers,{id => $id});
448     }
449
450     $template->param(
451         breeding_loop => \@breeding_loop,
452         server        => $servername[$k],
453         numberpending => $numberpending,
454         current_page => $page,
455         servers => \@servers,
456         total_pages => $total_pages,
457     );
458     $template->param(show_nextbutton=>1) if $show_next;
459     $template->param(show_prevbutton=>1) if $page != 1;
460
461     #  print  $template->output  if $firstresult !=1;
462     $firstresult++;
463
464   } # while nremaining
465
466     $template->param(
467         breeding_loop => \@breeding_loop,
468         #server        => $servername[$k],
469         numberpending => $nremaining > 0 ? $nremaining : 0,
470         errconn       => \@errconn
471     );
472
473 }
474
475 1;
476 __END__
477