Bug 10096 - Add a Z39.50 interface for authority searching
[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 TODO description
461
462 =cut
463
464 sub ImportBreedingAuth {
465     my ($marcrecords,$overwrite_auth,$filename,$encoding,$z3950random,$batch_type) = @_;
466     my @marcarray = split /\x1D/, $marcrecords;
467
468     my $dbh = C4::Context->dbh;
469
470     my $batch_id = GetZ3950BatchId($filename);
471     my $searchbreeding = $dbh->prepare("select import_record_id from import_auths where control_number=? and authorized_heading=?");
472
473 #     $encoding = C4::Context->preference("marcflavour") unless $encoding;
474     # fields used for import results
475     my $imported=0;
476     my $alreadyindb = 0;
477     my $alreadyinfarm = 0;
478     my $notmarcrecord = 0;
479     my $breedingid;
480     for (my $i=0;$i<=$#marcarray;$i++) {
481         my ($marcrecord, $charset_result, $charset_errors);
482         ($marcrecord, $charset_result, $charset_errors) =
483             MarcToUTF8Record($marcarray[$i]."\x1D", C4::Context->preference("marcflavour"), $encoding);
484
485         # Normalize the record so it doesn't have separated diacritics
486         SetUTF8Flag($marcrecord);
487
488 #         warn "$i : $marcarray[$i]";
489         # FIXME - currently this does nothing
490         my @warnings = $marcrecord->warnings();
491
492         if (scalar($marcrecord->fields()) == 0) {
493             $notmarcrecord++;
494         } else {
495             my $heading;
496             $heading = C4::AuthoritiesMarc::GetAuthorizedHeading({ record => $marcrecord });
497
498             my $heading_authtype_code;
499             $heading_authtype_code = GuessAuthTypeCode($marcrecord);
500
501             my $controlnumber;
502             $controlnumber = $marcrecord->field('001')->data;
503
504             #Check if the authority record already exists in the database...
505             my ($duplicateauthid,$duplicateauthvalue);
506             if ($marcrecord && $heading_authtype_code) {
507                 ($duplicateauthid,$duplicateauthvalue) = FindDuplicateAuthority( $marcrecord, $heading_authtype_code);
508             }
509
510             if ($duplicateauthid && $overwrite_auth ne 2) {
511                 #If the authority record exists and $overwrite_auth doesn't equal 2, then mark it as already in the DB
512                 #FIXME: What does $overwrite_auth = 2 even mean?
513
514                 #FIXME: Should we bother with $overwrite_auth values? Currently, the hard-coded $overwrite_auth value is 2, which means the database gets filled with import_records...
515                 #^^ of course, we might not want to reject records if their control number/heading exist in the db or breeding/import pool...as we might be wanting to update existing authority records...
516                 $alreadyindb++;
517             } else {
518                 if ($controlnumber && $heading) {
519                     $searchbreeding->execute($controlnumber,$heading);
520                     ($breedingid) = $searchbreeding->fetchrow;
521                 }
522                 if ($breedingid && $overwrite_auth eq '0') {
523                     #FIXME: What does $overwrite_auth = 0 even mean?
524                     $alreadyinfarm++;
525                 } else {
526                     if ($breedingid && $overwrite_auth eq '1') {
527                         #FIXME: What does $overwrite_auth = 1 even mean?
528                         ModAuthorityInBatch($breedingid, $marcrecord);
529                     } else {
530                         my $import_id = AddAuthToBatch($batch_id, $imported, $marcrecord, $encoding, $z3950random);
531                         $breedingid = $import_id;
532                     }
533                     $imported++;
534                 }
535             }
536         }
537     }
538     return ($notmarcrecord,$alreadyindb,$alreadyinfarm,$imported,$breedingid);
539 }
540
541 =head2 Z3950SearchAuth
542
543 Z3950SearchAuth($pars, $template);
544
545 Parameters for Z3950 search are all passed via the $pars hash. It may contain nameany, namepersonal, namecorp, namemeetingcon,
546 title, uniform title, subject, subjectsubdiv, srchany.
547 Also it should contain an arrayref id that points to a list of IDs of the z3950 targets to be queried (see z3950servers table).
548 This code is used in cataloging/z3950_auth_search.
549 The second parameter $template is a Template object. The routine uses this parameter to store the found values into the template.
550
551 =cut
552
553 sub Z3950SearchAuth {
554     my ($pars, $template)= @_;
555
556     my $dbh   = C4::Context->dbh;
557     my @id= @{$pars->{id}};
558     my $random= $pars->{random};
559     my $page= $pars->{page};
560
561     my $nameany= $pars->{nameany};
562     my $authorany= $pars->{authorany};
563     my $authorpersonal= $pars->{authorpersonal};
564     my $authorcorp= $pars->{authorcorp};
565     my $authormeetingcon= $pars->{authormeetingcon};
566     my $title= $pars->{title};
567     my $uniformtitle= $pars->{uniformtitle};
568     my $subject= $pars->{subject};
569     my $subjectsubdiv= $pars->{subjectsubdiv};
570     my $srchany= $pars->{srchany};
571
572     my $show_next       = 0;
573     my $total_pages     = 0;
574     my $attr = '';
575     my $host;
576     my $server;
577     my $database;
578     my $port;
579     my $marcdata;
580     my @encoding;
581     my @results;
582     my $count;
583     my $record;
584     my @serverhost;
585     my @servername;
586     my @breeding_loop = ();
587
588     my @oConnection;
589     my @oResult;
590     my @errconn;
591     my $s = 0;
592     my $query;
593     my $nterms=0;
594
595     if ($nameany) {
596         $query .= " \@attr 1=1002 \"$nameany\" "; #Any name (this includes personal, corporate, meeting/conference authors, and author names in subject headings)
597         #This attribute is supported by both the Library of Congress and Libraries Australia 08/05/2013
598         $nterms++;
599     }
600
601     if ($authorany) {
602         $query .= " \@attr 1=1003 \"$authorany\" "; #Author-name (this includes personal, corporate, meeting/conference authors, but not author names in subject headings)
603         #This attribute is not supported by the Library of Congress, but is supported by Libraries Australia 08/05/2013
604         $nterms++;
605     }
606
607     if ($authorcorp) {
608         $query .= " \@attr 1=2 \"$authorcorp\" "; #1005 is another valid corporate author attribute...
609         $nterms++;
610     }
611
612     if ($authorpersonal) {
613         $query .= " \@attr 1=1 \"$authorpersonal\" "; #1004 is another valid personal name attribute...
614         $nterms++;
615     }
616
617     if ($authormeetingcon) {
618         $query .= " \@attr 1=3 \"$authormeetingcon\" "; #1006 is another valid meeting/conference name attribute...
619         $nterms++;
620     }
621
622     if ($subject) {
623         $query .= " \@attr 1=21 \"$subject\" ";
624         $nterms++;
625     }
626
627     if ($subjectsubdiv) {
628         $query .= " \@attr 1=47 \"$subjectsubdiv\" ";
629         $nterms++;
630     }
631
632     if ($title) {
633         $query .= " \@attr 1=4 \"$title\" "; #This is a regular title search. 1=6 will give just uniform titles
634         $nterms++;
635     }
636
637      if ($uniformtitle) {
638         $query .= " \@attr 1=6 \"$uniformtitle\" "; #This is the uniform title search
639         $nterms++;
640     }
641
642     if($srchany) {
643         $query .= " \@attr 1=1016 \"$srchany\" ";
644         $nterms++;
645     }
646
647     for my $i (1..$nterms-1) {
648         $query = "\@and " . $query;
649     }
650
651     foreach my $servid (@id) {
652         my $sth = $dbh->prepare("select * from z3950servers where id=?");
653         $sth->execute($servid);
654         while ( $server = $sth->fetchrow_hashref ) {
655             my $option1      = new ZOOM::Options();
656             $option1->option( 'async' => 1 );
657             $option1->option( 'elementSetName', 'F' );
658             $option1->option( 'databaseName',   $server->{db} );
659             $option1->option( 'user', $server->{userid} ) if $server->{userid};
660             $option1->option( 'password', $server->{password} ) if $server->{password};
661             $option1->option( 'preferredRecordSyntax', $server->{syntax} );
662             $option1->option( 'timeout', $server->{timeout} ) if $server->{timeout};
663             $oConnection[$s] = create ZOOM::Connection($option1);
664             $oConnection[$s]->connect( $server->{host}, $server->{port} );
665             $serverhost[$s] = $server->{host};
666             $servername[$s] = $server->{name};
667             $encoding[$s]   = ($server->{encoding}?$server->{encoding}:"iso-5426");
668             $s++;
669         }    ## while fetch
670     }    # foreach
671     my $nremaining  = $s;
672
673     for ( my $z = 0 ; $z < $s ; $z++ ) {
674         $oResult[$z] = $oConnection[$z]->search_pqf($query);
675     }
676
677     while ( $nremaining-- ) {
678         my $k;
679         my $event;
680         while ( ( $k = ZOOM::event( \@oConnection ) ) != 0 ) {
681             $event = $oConnection[ $k - 1 ]->last_event();
682             last if $event == ZOOM::Event::ZEND;
683         }
684
685         if ( $k != 0 ) {
686             $k--;
687             my ($error, $errmsg, $addinfo, $diagset)= $oConnection[$k]->error_x();
688             if ($error) {
689                 if ($error =~ m/^(10000|10007)$/ ) {
690                     push(@errconn, {'server' => $serverhost[$k]});
691                 }
692             }
693             else {
694                 my $numresults = $oResult[$k]->size();
695                 my $i;
696                 my $result = '';
697                 if ( $numresults > 0  and $numresults >= (($page-1)*20)) {
698                     $show_next = 1 if $numresults >= ($page*20);
699                     $total_pages = int($numresults/20)+1 if $total_pages < ($numresults/20);
700                     for ($i = ($page-1)*20; $i < (($numresults < ($page*20)) ? $numresults : ($page*20)); $i++) {
701                         my $rec = $oResult[$k]->record($i);
702                         if ($rec) {
703                             my $marcrecord;
704                             my $marcdata;
705                             $marcdata   = $rec->raw();
706
707                             my ($charset_result, $charset_errors);
708                             ($marcrecord, $charset_result, $charset_errors)= MarcToUTF8Record($marcdata, C4::Context->preference('marcflavour'), $encoding[$k]);
709
710                             my $heading;
711                             my $heading_authtype_code;
712                             $heading_authtype_code = GuessAuthTypeCode($marcrecord);
713                             $heading = C4::AuthoritiesMarc::GetAuthorizedHeading({ record => $marcrecord });
714
715                             my ($notmarcrecord, $alreadyindb, $alreadyinfarm, $imported, $breedingid)= ImportBreedingAuth( $marcdata, 2, $serverhost[$k], $encoding[$k], $random, 'z3950' );
716                             my %row_data;
717                             $row_data{server}       = $servername[$k];
718                             $row_data{breedingid}   = $breedingid;
719                             $row_data{heading}      = $heading;
720                             $row_data{heading_code}      = $heading_authtype_code;
721                             push( @breeding_loop, \%row_data );
722                         }
723                         else {
724                             push(@breeding_loop,{'server'=>$servername[$k],'title'=>join(': ',$oConnection[$k]->error_x()),'breedingid'=>-1});
725                         }
726                     }
727                 }    #if $numresults
728             }
729         }    # if $k !=0
730
731         $template->param(
732             numberpending => $nremaining,
733             current_page => $page,
734             total_pages => $total_pages,
735             show_nextbutton => $show_next?1:0,
736             show_prevbutton => $page!=1,
737         );
738     } # while nremaining
739
740     #close result sets and connections
741     foreach(0..$s-1) {
742         $oResult[$_]->destroy();
743         $oConnection[$_]->destroy();
744     }
745
746     my @servers = ();
747     foreach my $id (@id) {
748         push @servers, {id => $id};
749     }
750     $template->param(
751         breeding_loop => \@breeding_loop,
752         servers => \@servers,
753         errconn       => \@errconn
754     );
755 }
756
757 1;
758 __END__
759