Bug 10853: All existing routing to get a CSV should return a MARC csv
[koha.git] / C4 / Breeding.pm
1 package C4::Breeding;
2
3 # Copyright 2000-2002 Katipo Communications
4 # Parts Copyright 2013 Prosentient Systems
5 #
6 # This file is part of Koha.
7 #
8 # Koha is free software; you can redistribute it and/or modify it under the
9 # terms of the GNU General Public License as published by the Free Software
10 # Foundation; either version 2 of the License, or (at your option) any later
11 # version.
12 #
13 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
14 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
15 # A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
16 #
17 # You should have received a copy of the GNU General Public License along
18 # with Koha; if not, write to the Free Software Foundation, Inc.,
19 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
20
21 use strict;
22 use warnings;
23
24 use C4::Biblio;
25 use C4::Koha;
26 use C4::Charset;
27 use MARC::File::USMARC;
28 use C4::ImportBatch;
29 use C4::AuthoritiesMarc; #GuessAuthTypeCode, FindDuplicateAuthority
30
31 use vars qw($VERSION @ISA @EXPORT @EXPORT_OK %EXPORT_TAGS);
32
33 BEGIN {
34         # set the version for version checking
35     $VERSION = 3.07.00.049;
36         require Exporter;
37         @ISA = qw(Exporter);
38     @EXPORT = qw(&ImportBreeding &BreedingSearch &Z3950Search &Z3950SearchAuth);
39 }
40
41 =head1 NAME
42
43 C4::Breeding : module to add biblios to import_records via
44                the breeding/reservoir API.
45
46 =head1 SYNOPSIS
47
48     use C4::Scan;
49     &ImportBreeding($marcrecords,$overwrite_biblio,$filename,$z3950random,$batch_type);
50
51     C<$marcrecord> => the MARC::Record
52     C<$overwrite_biblio> => if set to 1 a biblio with the same ISBN will be overwritted.
53                                 if set to 0 a biblio with the same isbn will be ignored (the previous will be kept)
54                                 if set to -1 the biblio will be added anyway (more than 1 biblio with the same ISBN 
55                                 possible in the breeding
56     C<$encoding> => USMARC
57                         or UNIMARC. used for char_decoding.
58                         If not present, the parameter marcflavour is used instead
59     C<$z3950random> => the random value created during a z3950 search result.
60
61 =head1 DESCRIPTION
62
63     ImportBreeding import MARC records in the reservoir (import_records/import_batches tables).
64     the records can be properly encoded or not, we try to reencode them in utf-8 if needed.
65     works perfectly with BNF server, that sends UNIMARC latin1 records. Should work with other servers too.
66
67 =head2 ImportBreeding
68
69         ImportBreeding($marcrecords,$overwrite_biblio,$filename,$encoding,$z3950random,$batch_type);
70
71         TODO description
72
73 =cut
74
75 sub ImportBreeding {
76     my ($marcrecords,$overwrite_biblio,$filename,$encoding,$z3950random,$batch_type) = @_;
77     my @marcarray = split /\x1D/, $marcrecords;
78     
79     my $dbh = C4::Context->dbh;
80     
81     my $batch_id = GetZ3950BatchId($filename);
82     my $searchisbn = $dbh->prepare("select biblioitemnumber from biblioitems where isbn=?");
83     my $searchissn = $dbh->prepare("select biblioitemnumber from biblioitems where issn=?");
84     # FIXME -- not sure that this kind of checking is actually needed
85     my $searchbreeding = $dbh->prepare("select import_record_id from import_biblios where isbn=? and title=?");
86     
87 #     $encoding = C4::Context->preference("marcflavour") unless $encoding;
88     # fields used for import results
89     my $imported=0;
90     my $alreadyindb = 0;
91     my $alreadyinfarm = 0;
92     my $notmarcrecord = 0;
93     my $breedingid;
94     for (my $i=0;$i<=$#marcarray;$i++) {
95         my ($marcrecord, $charset_result, $charset_errors);
96         ($marcrecord, $charset_result, $charset_errors) = 
97             MarcToUTF8Record($marcarray[$i]."\x1D", C4::Context->preference("marcflavour"), $encoding);
98         
99         # Normalize the record so it doesn't have separated diacritics
100         SetUTF8Flag($marcrecord);
101
102 #         warn "$i : $marcarray[$i]";
103         # FIXME - currently this does nothing 
104         my @warnings = $marcrecord->warnings();
105         
106         if (scalar($marcrecord->fields()) == 0) {
107             $notmarcrecord++;
108         } else {
109             my $oldbiblio = TransformMarcToKoha($dbh,$marcrecord,'');
110             # if isbn found and biblio does not exist, add it. If isbn found and biblio exists, 
111             # overwrite or ignore depending on user choice
112             # drop every "special" char : spaces, - ...
113             $oldbiblio->{isbn} = C4::Koha::_isbn_cleanup($oldbiblio->{isbn}); # FIXME C4::Koha::_isbn_cleanup should be public
114             # search if biblio exists
115             my $biblioitemnumber;
116             if ($oldbiblio->{isbn}) {
117                 $searchisbn->execute($oldbiblio->{isbn});
118                 ($biblioitemnumber) = $searchisbn->fetchrow;
119             } else {
120                 if ($oldbiblio->{issn}) {
121                     $searchissn->execute($oldbiblio->{issn});
122                         ($biblioitemnumber) = $searchissn->fetchrow;
123                 }
124             }
125             if ($biblioitemnumber && $overwrite_biblio ne 2) {
126                 $alreadyindb++;
127             } else {
128                 # FIXME - in context of batch load,
129                 # rejecting records because already present in the reservoir
130                 # not correct in every case.
131                 # search in breeding farm
132                 if ($oldbiblio->{isbn}) {
133                     $searchbreeding->execute($oldbiblio->{isbn},$oldbiblio->{title});
134                     ($breedingid) = $searchbreeding->fetchrow;
135                 } elsif ($oldbiblio->{issn}){
136                     $searchbreeding->execute($oldbiblio->{issn},$oldbiblio->{title});
137                     ($breedingid) = $searchbreeding->fetchrow;
138                 }
139                 if ($breedingid && $overwrite_biblio eq '0') {
140                     $alreadyinfarm++;
141                 } else {
142                     if ($breedingid && $overwrite_biblio eq '1') {
143                         ModBiblioInBatch($breedingid, $marcrecord);
144                     } else {
145                         my $import_id = AddBiblioToBatch($batch_id, $imported, $marcrecord, $encoding, $z3950random);
146                         $breedingid = $import_id;
147                     }
148                     $imported++;
149                 }
150             }
151         }
152     }
153     return ($notmarcrecord,$alreadyindb,$alreadyinfarm,$imported,$breedingid);
154 }
155
156
157 =head2 BreedingSearch
158
159 ($count, @results) = &BreedingSearch($title,$isbn,$random);
160 C<$title> contains the title,
161 C<$isbn> contains isbn or issn,
162 C<$random> contains the random seed from a z3950 search.
163
164 C<$count> is the number of items in C<@results>. C<@results> is an
165 array of references-to-hash; the keys are the items from the C<import_records> and
166 C<import_biblios> tables of the Koha database.
167
168 =cut
169
170 sub BreedingSearch {
171     my ($search,$isbn,$z3950random) = @_;
172     my $dbh   = C4::Context->dbh;
173     my $count = 0;
174     my ($query,@bind);
175     my $sth;
176     my @results;
177
178     $query = "SELECT import_record_id, file_name, isbn, title, author
179               FROM  import_biblios 
180               JOIN import_records USING (import_record_id)
181               JOIN import_batches USING (import_batch_id)
182               WHERE ";
183     if ($z3950random) {
184         $query .= "z3950random = ?";
185         @bind=($z3950random);
186     } else {
187         @bind=();
188         if (defined($search) && length($search)>0) {
189             $search =~ s/(\s+)/\%/g;
190             $query .= "title like ? OR author like ?";
191             push(@bind,"%$search%", "%$search%");
192         }
193         if ($#bind!=-1 && defined($isbn) && length($isbn)>0) {
194             $query .= " and ";
195         }
196         if (defined($isbn) && length($isbn)>0) {
197             $query .= "isbn like ?";
198             push(@bind,"$isbn%");
199         }
200     }
201     $sth   = $dbh->prepare($query);
202     $sth->execute(@bind);
203     while (my $data = $sth->fetchrow_hashref) {
204             $results[$count] = $data;
205             # FIXME - hack to reflect difference in name 
206             # of columns in old marc_breeding and import_records
207             # There needs to be more separation between column names and 
208             # field names used in the templates </soapbox>
209             $data->{'file'} = $data->{'file_name'};
210             $data->{'id'} = $data->{'import_record_id'};
211             $count++;
212     } # while
213
214     $sth->finish;
215     return($count, @results);
216 } # sub breedingsearch
217
218
219 =head2 Z3950Search
220
221 Z3950Search($pars, $template);
222
223 Parameters for Z3950 search are all passed via the $pars hash. It may contain isbn, title, author, dewey, subject, lccall, controlnumber, stdid, srchany.
224 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).
225 This code is used in acqui/z3950_search and cataloging/z3950_search.
226 The second parameter $template is a Template object. The routine uses this parameter to store the found values into the template.
227
228 =cut
229
230 sub Z3950Search {
231     my ($pars, $template)= @_;
232
233     my @id= @{$pars->{id}};
234     my $page= $pars->{page};
235     my $biblionumber= $pars->{biblionumber};
236     my $isbn= $pars->{isbn};
237     my $issn= $pars->{issn};
238     my $title= $pars->{title};
239     my $author= $pars->{author};
240     my $dewey= $pars->{dewey};
241     my $subject= $pars->{subject};
242     my $lccn= $pars->{lccn};
243     my $lccall= $pars->{lccall};
244     my $controlnumber= $pars->{controlnumber};
245     my $srchany= $pars->{srchany};
246     my $stdid= $pars->{stdid};
247
248     my $show_next       = 0;
249     my $total_pages     = 0;
250     my $term;
251     my @results;
252     my @breeding_loop = ();
253     my @oConnection;
254     my @oResult;
255     my @errconn;
256     my $s = 0;
257     my $query;
258     my $nterms=0;
259     my $imported=0;
260     my @serverinfo; #replaces former serverhost, servername, encoding
261
262     if ($isbn) {
263         $term=$isbn;
264         $query .= " \@attr 1=7 \@attr 5=1 \"$term\" ";
265         $nterms++;
266     }
267     if ($issn) {
268         $term=$issn;
269         $query .= " \@attr 1=8 \@attr 5=1 \"$term\" ";
270         $nterms++;
271     }
272     if ($title) {
273         $query .= " \@attr 1=4 \"$title\" ";
274         $nterms++;
275     }
276     if ($author) {
277         $query .= " \@attr 1=1003 \"$author\" ";
278         $nterms++;
279     }
280     if ($dewey) {
281         $query .= " \@attr 1=16 \"$dewey\" ";
282         $nterms++;
283     }
284     if ($subject) {
285         $query .= " \@attr 1=21 \"$subject\" ";
286         $nterms++;
287     }
288     if ($lccn) {
289         $query .= " \@attr 1=9 $lccn ";
290         $nterms++;
291     }
292     if ($lccall) {
293         $query .= " \@attr 1=16 \@attr 2=3 \@attr 3=1 \@attr 4=1 \@attr 5=1 \@attr 6=1 \"$lccall\" ";
294         $nterms++;
295     }
296     if ($controlnumber) {
297         $query .= " \@attr 1=12 \"$controlnumber\" ";
298         $nterms++;
299     }
300     if($srchany) {
301         $query .= " \@attr 1=1016 \"$srchany\" ";
302         $nterms++;
303     }
304     if($stdid) {
305         $query .= " \@attr 1=1007 \"$stdid\" ";
306         $nterms++;
307     }
308     for my $i (1..$nterms-1) {
309         $query = "\@and " . $query;
310     }
311
312     my $dbh   = C4::Context->dbh;
313     foreach my $servid (@id) {
314         my $sth = $dbh->prepare("select * from z3950servers where id=?");
315         $sth->execute($servid);
316         while (my $server = $sth->fetchrow_hashref) {
317             my $option1= new ZOOM::Options();
318             $option1->option( 'async' => 1 );
319             $option1->option( 'elementSetName', 'F' );
320             $option1->option( 'databaseName',   $server->{db} );
321             $option1->option( 'user', $server->{userid} ) if $server->{userid};
322             $option1->option( 'password', $server->{password} ) if $server->{password};
323             $option1->option( 'preferredRecordSyntax', $server->{syntax} );
324             $option1->option( 'timeout', $server->{timeout} ) if $server->{timeout};
325             $oConnection[$s]= create ZOOM::Connection($option1);
326             $oConnection[$s]->connect( $server->{host}, $server->{port} );
327             $serverinfo[$s]->{host}= $server->{host};
328             $serverinfo[$s]->{name}= $server->{name};
329             $serverinfo[$s]->{encd}= $server->{encoding} // "iso-5426";
330             $s++;
331         }    ## while fetch
332     }    # foreach
333     my $nremaining  = $s;
334
335     for ( my $z = 0 ; $z < $s ; $z++ ) {
336         $oResult[$z] = $oConnection[$z]->search_pqf($query);
337     }
338
339     while ( $nremaining-- ) {
340         my $k;
341         my $event;
342         while ( ( $k = ZOOM::event( \@oConnection ) ) != 0 ) {
343             $event = $oConnection[ $k - 1 ]->last_event();
344             last if $event == ZOOM::Event::ZEND;
345         }
346
347         if ( $k != 0 ) {
348             $k--;
349             my ($error)= $oConnection[$k]->error_x(); #ignores errmsg, addinfo, diagset
350             if ($error) {
351                 if ($error =~ m/^(10000|10007)$/ ) {
352                     push(@errconn, { 'server' => $serverinfo[$k]->{host} } );
353                 }
354             }
355             else {
356                 my $numresults = $oResult[$k]->size();
357                 my $i;
358                 my $result = '';
359                 if ( $numresults > 0  and $numresults >= (($page-1)*20)) {
360                     $show_next = 1 if $numresults >= ($page*20);
361                     $total_pages = int($numresults/20)+1 if $total_pages < ($numresults/20);
362                     for ($i = ($page-1)*20; $i < (($numresults < ($page*20)) ? $numresults : ($page*20)); $i++) {
363                         if($oResult[$k]->record($i)) {
364                             my $res=_handle_one_result($oResult[$k]->record($i), $serverinfo[$k], ++$imported, $biblionumber); #ignores error in sequence numbering
365                             push @breeding_loop, $res if $res;
366                         }
367                         else {
368                             push(@breeding_loop,{'server'=>$serverinfo[$k]->{name},'title'=>join(': ',$oConnection[$k]->error_x()),'breedingid'=>-1,'biblionumber'=>-1});
369                         }
370                     }
371                 }    #if $numresults
372             }
373         }    # if $k !=0
374
375         $template->param(
376             numberpending => $nremaining,
377             current_page => $page,
378             total_pages => $total_pages,
379             show_nextbutton => $show_next?1:0,
380             show_prevbutton => $page!=1,
381         );
382     } # while nremaining
383
384     #close result sets and connections
385     foreach(0..$s-1) {
386         $oResult[$_]->destroy();
387         $oConnection[$_]->destroy();
388     }
389
390     my @servers = ();
391     foreach my $id (@id) {
392         push @servers, {id => $id};
393     }
394     $template->param(
395         breeding_loop => \@breeding_loop,
396         servers => \@servers,
397         errconn       => \@errconn
398     );
399 }
400
401 sub _handle_one_result {
402     my ($zoomrec, $servhref, $seq, $bib)= @_;
403
404     my $raw= $zoomrec->raw();
405     my ($marcrecord) = MarcToUTF8Record($raw, C4::Context->preference('marcflavour'), $servhref->{encd}); #ignores charset return values
406     SetUTF8Flag($marcrecord);
407
408     #call to ImportBreeding replaced by next two calls for optimization
409     my $batch_id = GetZ3950BatchId($servhref->{name});
410     my $breedingid = AddBiblioToBatch($batch_id, $seq, $marcrecord, 'UTF-8', 0, 0);
411         #FIXME passing 0 for z3950random
412         #Will eliminate this unused field in a followup report
413         #Last zero indicates: no update for batch record counts
414
415
416     #call to TransformMarcToKoha replaced by next call
417     #we only need six fields from the marc record
418     return _add_rowdata(
419         {
420             biblionumber => $bib,
421             server       => $servhref->{name},
422             breedingid   => $breedingid,
423         }, $marcrecord) if $breedingid;
424 }
425
426 sub _add_rowdata {
427     my ($row, $record)=@_;
428     my %fetch= (
429         title => 'biblio.title',
430         author => 'biblio.author',
431         isbn =>'biblioitems.isbn',
432         lccn =>'biblioitems.lccn', #LC control number (not call number)
433         edition =>'biblioitems.editionstatement',
434         date => 'biblio.copyrightdate', #MARC21
435         date2 => 'biblioitems.publicationyear', #UNIMARC
436     );
437     foreach my $k (keys %fetch) {
438         my ($t, $f)= split '\.', $fetch{$k};
439         $row= C4::Biblio::TransformMarcToKohaOneField($t, $f, $record, $row);
440         $row->{$k}= $row->{$f} if $k ne $f;
441     }
442     $row->{date}//= $row->{date2};
443     $row->{isbn}=_isbn_replace($row->{isbn});
444     return $row;
445 }
446
447 sub _isbn_replace {
448     my ($isbn) = @_;
449     return unless defined $isbn;
450     $isbn =~ s/ |-|\.//g;
451     $isbn =~ s/\|/ \| /g;
452     $isbn =~ s/\(/ \(/g;
453     return $isbn;
454 }
455
456 =head2 ImportBreedingAuth
457
458 ImportBreedingAuth($marcrecords,$overwrite_auth,$filename,$encoding,$z3950random,$batch_type);
459
460     ImportBreedingAuth imports MARC records in the reservoir (import_records table).
461     ImportBreedingAuth is based on the ImportBreeding subroutine.
462
463 =cut
464
465 sub ImportBreedingAuth {
466     my ($marcrecords,$overwrite_auth,$filename,$encoding,$z3950random,$batch_type) = @_;
467     my @marcarray = split /\x1D/, $marcrecords;
468
469     my $dbh = C4::Context->dbh;
470
471     my $batch_id = GetZ3950BatchId($filename);
472     my $searchbreeding = $dbh->prepare("select import_record_id from import_auths where control_number=? and authorized_heading=?");
473
474 #     $encoding = C4::Context->preference("marcflavour") unless $encoding;
475     # fields used for import results
476     my $imported=0;
477     my $alreadyindb = 0;
478     my $alreadyinfarm = 0;
479     my $notmarcrecord = 0;
480     my $breedingid;
481     for (my $i=0;$i<=$#marcarray;$i++) {
482         my ($marcrecord, $charset_result, $charset_errors);
483         ($marcrecord, $charset_result, $charset_errors) =
484             MarcToUTF8Record($marcarray[$i]."\x1D", C4::Context->preference("marcflavour"), $encoding);
485
486         # Normalize the record so it doesn't have separated diacritics
487         SetUTF8Flag($marcrecord);
488
489         if (scalar($marcrecord->fields()) == 0) {
490             $notmarcrecord++;
491         } else {
492             my $heading;
493             $heading = C4::AuthoritiesMarc::GetAuthorizedHeading({ record => $marcrecord });
494
495             my $heading_authtype_code;
496             $heading_authtype_code = GuessAuthTypeCode($marcrecord);
497
498             my $controlnumber;
499             $controlnumber = $marcrecord->field('001')->data;
500
501             #Check if the authority record already exists in the database...
502             my ($duplicateauthid,$duplicateauthvalue);
503             if ($marcrecord && $heading_authtype_code) {
504                 ($duplicateauthid,$duplicateauthvalue) = FindDuplicateAuthority( $marcrecord, $heading_authtype_code);
505             }
506
507             if ($duplicateauthid && $overwrite_auth ne 2) {
508                 #If the authority record exists and $overwrite_auth doesn't equal 2, then mark it as already in the DB
509                 $alreadyindb++;
510             } else {
511                 if ($controlnumber && $heading) {
512                     $searchbreeding->execute($controlnumber,$heading);
513                     ($breedingid) = $searchbreeding->fetchrow;
514                 }
515                 if ($breedingid && $overwrite_auth eq '0') {
516                     $alreadyinfarm++;
517                 } else {
518                     if ($breedingid && $overwrite_auth eq '1') {
519                         ModAuthorityInBatch($breedingid, $marcrecord);
520                     } else {
521                         my $import_id = AddAuthToBatch($batch_id, $imported, $marcrecord, $encoding, $z3950random);
522                         $breedingid = $import_id;
523                     }
524                     $imported++;
525                 }
526             }
527         }
528     }
529     return ($notmarcrecord,$alreadyindb,$alreadyinfarm,$imported,$breedingid);
530 }
531
532 =head2 Z3950SearchAuth
533
534 Z3950SearchAuth($pars, $template);
535
536 Parameters for Z3950 search are all passed via the $pars hash. It may contain nameany, namepersonal, namecorp, namemeetingcon,
537 title, uniform title, subject, subjectsubdiv, srchany.
538 Also it should contain an arrayref id that points to a list of IDs of the z3950 targets to be queried (see z3950servers table).
539 This code is used in cataloging/z3950_auth_search.
540 The second parameter $template is a Template object. The routine uses this parameter to store the found values into the template.
541
542 =cut
543
544 sub Z3950SearchAuth {
545     my ($pars, $template)= @_;
546
547     my $dbh   = C4::Context->dbh;
548     my @id= @{$pars->{id}};
549     my $random= $pars->{random};
550     my $page= $pars->{page};
551
552     my $nameany= $pars->{nameany};
553     my $authorany= $pars->{authorany};
554     my $authorpersonal= $pars->{authorpersonal};
555     my $authorcorp= $pars->{authorcorp};
556     my $authormeetingcon= $pars->{authormeetingcon};
557     my $title= $pars->{title};
558     my $uniformtitle= $pars->{uniformtitle};
559     my $subject= $pars->{subject};
560     my $subjectsubdiv= $pars->{subjectsubdiv};
561     my $srchany= $pars->{srchany};
562
563     my $show_next       = 0;
564     my $total_pages     = 0;
565     my $attr = '';
566     my $host;
567     my $server;
568     my $database;
569     my $port;
570     my $marcdata;
571     my @encoding;
572     my @results;
573     my $count;
574     my $record;
575     my @serverhost;
576     my @servername;
577     my @breeding_loop = ();
578
579     my @oConnection;
580     my @oResult;
581     my @errconn;
582     my $s = 0;
583     my $query;
584     my $nterms=0;
585
586     if ($nameany) {
587         $query .= " \@attr 1=1002 \"$nameany\" "; #Any name (this includes personal, corporate, meeting/conference authors, and author names in subject headings)
588         #This attribute is supported by both the Library of Congress and Libraries Australia 08/05/2013
589         $nterms++;
590     }
591
592     if ($authorany) {
593         $query .= " \@attr 1=1003 \"$authorany\" "; #Author-name (this includes personal, corporate, meeting/conference authors, but not author names in subject headings)
594         #This attribute is not supported by the Library of Congress, but is supported by Libraries Australia 08/05/2013
595         $nterms++;
596     }
597
598     if ($authorcorp) {
599         $query .= " \@attr 1=2 \"$authorcorp\" "; #1005 is another valid corporate author attribute...
600         $nterms++;
601     }
602
603     if ($authorpersonal) {
604         $query .= " \@attr 1=1 \"$authorpersonal\" "; #1004 is another valid personal name attribute...
605         $nterms++;
606     }
607
608     if ($authormeetingcon) {
609         $query .= " \@attr 1=3 \"$authormeetingcon\" "; #1006 is another valid meeting/conference name attribute...
610         $nterms++;
611     }
612
613     if ($subject) {
614         $query .= " \@attr 1=21 \"$subject\" ";
615         $nterms++;
616     }
617
618     if ($subjectsubdiv) {
619         $query .= " \@attr 1=47 \"$subjectsubdiv\" ";
620         $nterms++;
621     }
622
623     if ($title) {
624         $query .= " \@attr 1=4 \"$title\" "; #This is a regular title search. 1=6 will give just uniform titles
625         $nterms++;
626     }
627
628      if ($uniformtitle) {
629         $query .= " \@attr 1=6 \"$uniformtitle\" "; #This is the uniform title search
630         $nterms++;
631     }
632
633     if($srchany) {
634         $query .= " \@attr 1=1016 \"$srchany\" ";
635         $nterms++;
636     }
637
638     for my $i (1..$nterms-1) {
639         $query = "\@and " . $query;
640     }
641
642     foreach my $servid (@id) {
643         my $sth = $dbh->prepare("select * from z3950servers where id=?");
644         $sth->execute($servid);
645         while ( $server = $sth->fetchrow_hashref ) {
646             my $option1      = new ZOOM::Options();
647             $option1->option( 'async' => 1 );
648             $option1->option( 'elementSetName', 'F' );
649             $option1->option( 'databaseName',   $server->{db} );
650             $option1->option( 'user', $server->{userid} ) if $server->{userid};
651             $option1->option( 'password', $server->{password} ) if $server->{password};
652             $option1->option( 'preferredRecordSyntax', $server->{syntax} );
653             $option1->option( 'timeout', $server->{timeout} ) if $server->{timeout};
654             $oConnection[$s] = create ZOOM::Connection($option1);
655             $oConnection[$s]->connect( $server->{host}, $server->{port} );
656             $serverhost[$s] = $server->{host};
657             $servername[$s] = $server->{name};
658             $encoding[$s]   = ($server->{encoding}?$server->{encoding}:"iso-5426");
659             $s++;
660         }    ## while fetch
661     }    # foreach
662     my $nremaining  = $s;
663
664     for ( my $z = 0 ; $z < $s ; $z++ ) {
665         $oResult[$z] = $oConnection[$z]->search_pqf($query);
666     }
667
668     while ( $nremaining-- ) {
669         my $k;
670         my $event;
671         while ( ( $k = ZOOM::event( \@oConnection ) ) != 0 ) {
672             $event = $oConnection[ $k - 1 ]->last_event();
673             last if $event == ZOOM::Event::ZEND;
674         }
675
676         if ( $k != 0 ) {
677             $k--;
678             my ($error, $errmsg, $addinfo, $diagset)= $oConnection[$k]->error_x();
679             if ($error) {
680                 if ($error =~ m/^(10000|10007)$/ ) {
681                     push(@errconn, {'server' => $serverhost[$k]});
682                 }
683             }
684             else {
685                 my $numresults = $oResult[$k]->size();
686                 my $i;
687                 my $result = '';
688                 if ( $numresults > 0  and $numresults >= (($page-1)*20)) {
689                     $show_next = 1 if $numresults >= ($page*20);
690                     $total_pages = int($numresults/20)+1 if $total_pages < ($numresults/20);
691                     for ($i = ($page-1)*20; $i < (($numresults < ($page*20)) ? $numresults : ($page*20)); $i++) {
692                         my $rec = $oResult[$k]->record($i);
693                         if ($rec) {
694                             my $marcrecord;
695                             my $marcdata;
696                             $marcdata   = $rec->raw();
697
698                             my ($charset_result, $charset_errors);
699                             ($marcrecord, $charset_result, $charset_errors)= MarcToUTF8Record($marcdata, C4::Context->preference('marcflavour'), $encoding[$k]);
700
701                             my $heading;
702                             my $heading_authtype_code;
703                             $heading_authtype_code = GuessAuthTypeCode($marcrecord);
704                             $heading = C4::AuthoritiesMarc::GetAuthorizedHeading({ record => $marcrecord });
705
706                             my ($notmarcrecord, $alreadyindb, $alreadyinfarm, $imported, $breedingid)= ImportBreedingAuth( $marcdata, 2, $serverhost[$k], $encoding[$k], $random, 'z3950' );
707                             my %row_data;
708                             $row_data{server}       = $servername[$k];
709                             $row_data{breedingid}   = $breedingid;
710                             $row_data{heading}      = $heading;
711                             $row_data{heading_code}      = $heading_authtype_code;
712                             push( @breeding_loop, \%row_data );
713                         }
714                         else {
715                             push(@breeding_loop,{'server'=>$servername[$k],'title'=>join(': ',$oConnection[$k]->error_x()),'breedingid'=>-1});
716                         }
717                     }
718                 }    #if $numresults
719             }
720         }    # if $k !=0
721
722         $template->param(
723             numberpending => $nremaining,
724             current_page => $page,
725             total_pages => $total_pages,
726             show_nextbutton => $show_next?1:0,
727             show_prevbutton => $page!=1,
728         );
729     } # while nremaining
730
731     #close result sets and connections
732     foreach(0..$s-1) {
733         $oResult[$_]->destroy();
734         $oConnection[$_]->destroy();
735     }
736
737     my @servers = ();
738     foreach my $id (@id) {
739         push @servers, {id => $id};
740     }
741     $template->param(
742         breeding_loop => \@breeding_loop,
743         servers => \@servers,
744         errconn       => \@errconn
745     );
746 }
747
748 1;
749 __END__
750