Bug 19436: Add SRU support for authorities
[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
9 # under the terms of the GNU General Public License as published by
10 # the Free Software Foundation; either version 3 of the License, or
11 # (at your option) any later version.
12 #
13 # Koha is distributed in the hope that it will be useful, but
14 # WITHOUT ANY WARRANTY; without even the implied warranty of
15 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 # GNU General Public License for more details.
17 #
18 # You should have received a copy of the GNU General Public License
19 # along with Koha; if not, see <http://www.gnu.org/licenses>.
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 use C4::Languages;
31 use Koha::Database;
32 use Koha::XSLT_Handler;
33
34 use vars qw(@ISA @EXPORT @EXPORT_OK %EXPORT_TAGS);
35
36 BEGIN {
37         require Exporter;
38         @ISA = qw(Exporter);
39     @EXPORT = qw(&BreedingSearch &Z3950Search &Z3950SearchAuth);
40 }
41
42 =head1 NAME
43
44 C4::Breeding : module to add biblios to import_records via
45                the breeding/reservoir API.
46
47 =head1 SYNOPSIS
48
49     Z3950Search($pars, $template);
50     ($count, @results) = &BreedingSearch($title,$isbn,$random);
51
52 =head1 DESCRIPTION
53
54 This module contains routines related to Koha's Z39.50 search into
55 cataloguing reservoir features.
56
57 =head2 BreedingSearch
58
59 ($count, @results) = &BreedingSearch($title,$isbn,$random);
60 C<$title> contains the title,
61 C<$isbn> contains isbn or issn,
62 C<$random> contains the random seed from a z3950 search.
63
64 C<$count> is the number of items in C<@results>. C<@results> is an
65 array of references-to-hash; the keys are the items from the C<import_records> and
66 C<import_biblios> tables of the Koha database.
67
68 =cut
69
70 sub BreedingSearch {
71     my ($search,$isbn,$z3950random) = @_;
72     my $dbh   = C4::Context->dbh;
73     my $count = 0;
74     my ($query,@bind);
75     my $sth;
76     my @results;
77
78     # normalise ISBN like at import
79     $isbn = C4::Koha::GetNormalizedISBN($isbn);
80
81     $query = "SELECT import_record_id, file_name, isbn, title, author
82               FROM  import_biblios 
83               JOIN import_records USING (import_record_id)
84               JOIN import_batches USING (import_batch_id)
85               WHERE ";
86     if ($z3950random) {
87         $query .= "z3950random = ?";
88         @bind=($z3950random);
89     } else {
90         @bind=();
91         if (defined($search) && length($search)>0) {
92             $search =~ s/(\s+)/\%/g;
93             $query .= "title like ? OR author like ?";
94             push(@bind,"%$search%", "%$search%");
95         }
96         if ($#bind!=-1 && defined($isbn) && length($isbn)>0) {
97             $query .= " and ";
98         }
99         if (defined($isbn) && length($isbn)>0) {
100             $query .= "isbn like ?";
101             push(@bind,"$isbn%");
102         }
103     }
104     $sth   = $dbh->prepare($query);
105     $sth->execute(@bind);
106     while (my $data = $sth->fetchrow_hashref) {
107             $results[$count] = $data;
108             # FIXME - hack to reflect difference in name 
109             # of columns in old marc_breeding and import_records
110             # There needs to be more separation between column names and 
111             # field names used in the templates </soapbox>
112             $data->{'file'} = $data->{'file_name'};
113             $data->{'id'} = $data->{'import_record_id'};
114             $count++;
115     } # while
116
117     $sth->finish;
118     return($count, @results);
119 } # sub breedingsearch
120
121
122 =head2 Z3950Search
123
124 Z3950Search($pars, $template);
125
126 Parameters for Z3950 search are all passed via the $pars hash. It may contain isbn, title, author, dewey, subject, lccall, controlnumber, stdid, srchany.
127 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).
128 This code is used in acqui/z3950_search and cataloging/z3950_search.
129 The second parameter $template is a Template object. The routine uses this parameter to store the found values into the template.
130
131 =cut
132
133 sub Z3950Search {
134     my ($pars, $template)= @_;
135
136     my @id= @{$pars->{id}};
137     my $page= $pars->{page};
138     my $biblionumber= $pars->{biblionumber};
139
140     my $show_next       = 0;
141     my $total_pages     = 0;
142     my @results;
143     my @breeding_loop = ();
144     my @oConnection;
145     my @oResult;
146     my @errconn;
147     my $s = 0;
148     my $imported=0;
149
150     my ( $zquery, $squery ) = _build_query( $pars );
151
152     my $schema = Koha::Database->new()->schema();
153     my $rs = $schema->resultset('Z3950server')->search(
154         { id => [ @id ] },
155         { result_class => 'DBIx::Class::ResultClass::HashRefInflator' },
156     );
157     my @servers = $rs->all;
158     foreach my $server ( @servers ) {
159         $oConnection[$s] = _create_connection( $server );
160         $oResult[$s] =
161             $server->{servertype} eq 'zed'?
162                 $oConnection[$s]->search_pqf( $zquery ):
163                 $oConnection[$s]->search(new ZOOM::Query::CQL(
164                     _translate_query( $server, $squery )));
165         $s++;
166     }
167     my $xslh = Koha::XSLT_Handler->new;
168
169     my $nremaining = $s;
170     while ( $nremaining-- ) {
171         my $k;
172         my $event;
173         while ( ( $k = ZOOM::event( \@oConnection ) ) != 0 ) {
174             $event = $oConnection[ $k - 1 ]->last_event();
175             last if $event == ZOOM::Event::ZEND;
176         }
177
178         if ( $k != 0 ) {
179             $k--;
180             my ($error)= $oConnection[$k]->error_x(); #ignores errmsg, addinfo, diagset
181             if ($error) {
182                 if ($error =~ m/^(10000|10007)$/ ) {
183                     push(@errconn, { server => $servers[$k]->{host}, error => $error } );
184                 }
185             }
186             else {
187                 my $numresults = $oResult[$k]->size();
188                 my $i;
189                 my $res;
190                 if ( $numresults > 0  and $numresults >= (($page-1)*20)) {
191                     $show_next = 1 if $numresults >= ($page*20);
192                     $total_pages = int($numresults/20)+1 if $total_pages < ($numresults/20);
193                     for ($i = ($page-1)*20; $i < (($numresults < ($page*20)) ? $numresults : ($page*20)); $i++) {
194                         if ( $oResult[$k]->record($i) ) {
195                             undef $error;
196                             ( $res, $error ) = _handle_one_result( $oResult[$k]->record($i), $servers[$k], ++$imported, $biblionumber, $xslh ); #ignores error in sequence numbering
197                             push @breeding_loop, $res if $res;
198                             push @errconn, { server => $servers[$k]->{servername}, error => $error, seq => $i+1 } if $error;
199                         }
200                         else {
201                             push @errconn, { 'server' => $servers[$k]->{servername}, error => ( ( $oConnection[$k]->error_x() )[0] ), seq => $i+1 };
202                         }
203                     }
204                 }    #if $numresults
205             }
206         }    # if $k !=0
207
208         $template->param(
209             numberpending => $nremaining,
210             current_page => $page,
211             total_pages => $total_pages,
212             show_nextbutton => $show_next?1:0,
213             show_prevbutton => $page!=1,
214         );
215     } # while nremaining
216
217     #close result sets and connections
218     foreach(0..$s-1) {
219         $oResult[$_]->destroy();
220         $oConnection[$_]->destroy();
221     }
222
223     $template->param(
224         breeding_loop => \@breeding_loop,
225         servers => \@servers,
226         errconn       => \@errconn
227     );
228 }
229
230 sub _auth_build_query {
231     my ( $pars ) = @_;
232
233     my $nameany= $pars->{nameany};
234     my $authorany= $pars->{authorany};
235     my $authorpersonal= $pars->{authorpersonal};
236     my $authorcorp= $pars->{authorcorp};
237     my $authormeetingcon= $pars->{authormeetingcon};
238     my $title= $pars->{title};
239     my $uniformtitle= $pars->{uniformtitle};
240     my $subject= $pars->{subject};
241     my $subjectsubdiv= $pars->{subjectsubdiv};
242     my $srchany= $pars->{srchany};
243     my $authid= $pars->{authid};
244
245     my $qry_build = {
246         nameany           => '@attr 1=1002 "#term" ',
247         authorany         => '@attr 1=1003 "#term" ',
248         authorcorp        => '@attr 1=2 "#term" ',
249         authorpersonal    => '@attr 1=1 "#term" ',
250         authormeetingcon  => '@attr 1=3 "#term" ',
251         subject           => '@attr 1=21 "#term" ',
252         subjectsubdiv     => '@attr 1=47 "#term" ',
253         title             => '@attr 1=4 "#term" ',
254         uniformtitle      => '@attr 1=6 "#term" ',
255         srchany           => '@attr 1=1016 "#term" ',
256     };
257
258     my $zquery='';
259     my $squery='';
260     my $nterms=0;
261     foreach my $k ( sort keys %$pars ) {
262     #note that the sort keys forces an identical result under Perl 5.18
263     #one of the unit tests is based on that assumption
264         if( ( my $val=$pars->{$k} ) && $qry_build->{$k} ) {
265             $qry_build->{$k} =~ s/#term/$val/g;
266             $zquery .= $qry_build->{$k};
267             $squery .= "[$k]=\"$val\" and ";
268             $nterms++;
269         }
270     }
271     $zquery = "\@and " . $zquery for 2..$nterms;
272     $squery =~ s/ and $//;
273     return ( $zquery, $squery );
274
275 }
276
277 sub _build_query {
278     my ( $pars ) = @_;
279
280     my $qry_build = {
281         isbn    => '@attr 1=7 @attr 5=1 "#term" ',
282         issn    => '@attr 1=8 @attr 5=1 "#term" ',
283         title   => '@attr 1=4 "#term" ',
284         author  => '@attr 1=1003 "#term" ',
285         dewey   => '@attr 1=16 "#term" ',
286         subject => '@attr 1=21 "#term" ',
287         lccall  => '@attr 1=16 @attr 2=3 @attr 3=1 @attr 4=1 @attr 5=1 '.
288                    '@attr 6=1 "#term" ',
289         controlnumber => '@attr 1=12 "#term" ',
290         srchany => '@attr 1=1016 "#term" ',
291         stdid   => '@attr 1=1007 "#term" ',
292     };
293
294     my $zquery='';
295     my $squery='';
296     my $nterms=0;
297     foreach my $k ( sort keys %$pars ) {
298     #note that the sort keys forces an identical result under Perl 5.18
299     #one of the unit tests is based on that assumption
300         if( ( my $val=$pars->{$k} ) && $qry_build->{$k} ) {
301             $qry_build->{$k} =~ s/#term/$val/g;
302             $zquery .= $qry_build->{$k};
303             $squery .= "[$k]=\"$val\" and ";
304             $nterms++;
305         }
306     }
307     $zquery = "\@and " . $zquery for 2..$nterms;
308     $squery =~ s/ and $//;
309     return ( $zquery, $squery );
310 }
311
312 sub _handle_one_result {
313     my ( $zoomrec, $servhref, $seq, $bib, $xslh )= @_;
314
315     my $raw= $zoomrec->raw();
316     my $marcrecord;
317     if( $servhref->{servertype} eq 'sru' ) {
318         $raw= MARC::Record->new_from_xml( $raw, $servhref->{encoding}, $servhref->{syntax} );
319     }
320     ($marcrecord) = MarcToUTF8Record($raw, C4::Context->preference('marcflavour'), $servhref->{encoding} // "iso-5426" ); #ignores charset return values
321     SetUTF8Flag($marcrecord);
322     my $error;
323     ( $marcrecord, $error ) = _do_xslt_proc($marcrecord, $servhref, $xslh);
324
325     my $batch_id = GetZ3950BatchId($servhref->{servername});
326     my $breedingid = AddBiblioToBatch($batch_id, $seq, $marcrecord, 'UTF-8', 0, 0);
327         #FIXME passing 0 for z3950random
328         #Will eliminate this unused field in a followup report
329         #Last zero indicates: no update for batch record counts
330
331
332     #call to TransformMarcToKoha replaced by next call
333     #we only need six fields from the marc record
334     my $row;
335     $row = _add_rowdata(
336         {
337             biblionumber => $bib,
338             server       => $servhref->{servername},
339             breedingid   => $breedingid,
340         }, $marcrecord) if $breedingid;
341     return ( $row, $error );
342 }
343
344 sub _do_xslt_proc {
345     my ( $marc, $server, $xslh ) = @_;
346     return $marc if !$server->{add_xslt};
347
348     my $htdocs = C4::Context->config('intrahtdocs');
349     my $theme = C4::Context->preference("template"); #staff
350     my $lang = C4::Languages::getlanguage() || 'en';
351
352     my @files= split ',', $server->{add_xslt};
353     my $xml = $marc->as_xml;
354     foreach my $f ( @files ) {
355         $f =~ s/^\s+//; $f =~ s/\s+$//; next if !$f;
356         $f = C4::XSLT::_get_best_default_xslt_filename(
357             $htdocs, $theme, $lang, $f ) unless $f =~ /^\//;
358         $xml = $xslh->transform( $xml, $f );
359         last if $xslh->err; #skip other files
360     }
361     if( !$xslh->err ) {
362         return MARC::Record->new_from_xml($xml, 'UTF-8');
363     } else {
364         return ( $marc, $xslh->err ); #original record in case of errors
365     }
366 }
367
368 sub _add_rowdata {
369     my ($row, $record)=@_;
370     my %fetch= (
371         title => 'biblio.title',
372         author => 'biblio.author',
373         isbn =>'biblioitems.isbn',
374         lccn =>'biblioitems.lccn', #LC control number (not call number)
375         edition =>'biblioitems.editionstatement',
376         date => 'biblio.copyrightdate', #MARC21
377         date2 => 'biblioitems.publicationyear', #UNIMARC
378     );
379     foreach my $k (keys %fetch) {
380         $row->{$k} = C4::Biblio::TransformMarcToKohaOneField( $fetch{$k}, $record );
381     }
382     $row->{date}//= $row->{date2};
383     $row->{isbn}=_isbn_replace($row->{isbn});
384     return $row;
385 }
386
387 sub _isbn_replace {
388     my ($isbn) = @_;
389     return unless defined $isbn;
390     $isbn =~ s/ |-|\.//g;
391     $isbn =~ s/\|/ \| /g;
392     $isbn =~ s/\(/ \(/g;
393     return $isbn;
394 }
395
396 sub _create_connection {
397     my ( $server ) = @_;
398     my $option1= new ZOOM::Options();
399     $option1->option( 'async' => 1 );
400     $option1->option( 'elementSetName', 'F' );
401     $option1->option( 'preferredRecordSyntax', $server->{syntax} );
402     $option1->option( 'timeout', $server->{timeout} ) if $server->{timeout};
403
404     if( $server->{servertype} eq 'sru' ) {
405         foreach( split ',', $server->{sru_options}//'' ) {
406             #first remove surrounding spaces at comma and equals-sign
407             s/^\s+|\s+$//g;
408             my @temp= split '=', $_, 2;
409             @temp= map { my $c=$_; $c=~s/^\s+|\s+$//g; $c; } @temp;
410             $option1->option( $temp[0] => $temp[1] ) if @temp;
411         }
412     } elsif( $server->{servertype} eq 'zed' ) {
413         $option1->option( 'databaseName',   $server->{db} );
414         $option1->option( 'user', $server->{userid} ) if $server->{userid};
415         $option1->option( 'password', $server->{password} ) if $server->{password};
416     }
417     my $obj= ZOOM::Connection->create($option1);
418     if( $server->{servertype} eq 'sru' ) {
419         my $host= $server->{host};
420         if( $host !~ /^https?:\/\// ) {
421             #Normally, host will not be prefixed by protocol.
422             #In that case we can (safely) assume http.
423             #In case someone prefixed with https, give it a try..
424             $host = 'http://' . $host;
425         }
426         $obj->connect( $host.':'.$server->{port}.'/'.$server->{db} );
427     } else {
428         $obj->connect( $server->{host}, $server->{port} );
429     }
430     return $obj;
431 }
432
433 sub _translate_query { #SRU query adjusted per server cf. srufields column
434     my ($server, $query) = @_;
435
436     #sru_fields is in format title=field,isbn=field,...
437     #if a field doesn't exist, try anywhere or remove [field]=
438     my @parts= split(',', $server->{sru_fields} );
439     my %trans= map { if( /=/ ) { ( $`,$' ) } else { () } } @parts;
440     my $any= $trans{srchany}?$trans{srchany}.'=':'';
441
442     my $q=$query;
443     foreach my $key (keys %trans) {
444         my $f=$trans{$key};
445         if( $f ) {
446             $q=~s/\[$key\]/$f/g;
447         } else {
448             $q=~s/\[$key\]=/$any/g;
449         }
450     }
451     $q=~s/\[\w+\]=/$any/g; # remove remaining fields (not found in field list)
452     return $q;
453 }
454
455 =head2 ImportBreedingAuth
456
457 ImportBreedingAuth($marcrecords,$overwrite_auth,$filename,$encoding,$z3950random);
458
459     ImportBreedingAuth imports MARC records in the reservoir (import_records table).
460     ImportBreedingAuth is based on the ImportBreeding subroutine.
461
462 =cut
463
464 sub ImportBreedingAuth {
465     my ($marcrecord,$overwrite_auth,$filename,$encoding,$z3950random) = @_;
466     my $dbh = C4::Context->dbh;
467
468     my $batch_id = GetZ3950BatchId($filename);
469     my $searchbreeding = $dbh->prepare("select import_record_id from import_auths where control_number=? and authorized_heading=?");
470
471     my $marcflavour = C4::Context->preference('marcflavour');
472     my $marc_type = $marcflavour eq 'UNIMARC' ? 'UNIMARCAUTH' : $marcflavour;
473
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
481         # Normalize the record so it doesn't have separated diacritics
482         SetUTF8Flag($marcrecord);
483
484         if (scalar($marcrecord->fields()) == 0) {
485             $notmarcrecord++;
486         } else {
487             my $heading;
488             $heading = C4::AuthoritiesMarc::GetAuthorizedHeading({ record => $marcrecord });
489
490             my $heading_authtype_code;
491             $heading_authtype_code = GuessAuthTypeCode($marcrecord);
492
493             my $controlnumber;
494             $controlnumber = $marcrecord->field('001')->data;
495
496             #Check if the authority record already exists in the database...
497             my ($duplicateauthid,$duplicateauthvalue);
498             if ($marcrecord && $heading_authtype_code) {
499                 ($duplicateauthid,$duplicateauthvalue) = FindDuplicateAuthority( $marcrecord, $heading_authtype_code);
500             }
501
502             if ($duplicateauthid && $overwrite_auth ne 2) {
503                 #If the authority record exists and $overwrite_auth doesn't equal 2, then mark it as already in the DB
504                 $alreadyindb++;
505             } else {
506                 if ($controlnumber && $heading) {
507                     $searchbreeding->execute($controlnumber,$heading);
508                     ($breedingid) = $searchbreeding->fetchrow;
509                 }
510                 if ($breedingid && $overwrite_auth eq '0') {
511                     $alreadyinfarm++;
512                 } else {
513                     if ($breedingid && $overwrite_auth eq '1') {
514                         ModAuthorityInBatch($breedingid, $marcrecord);
515                     } else {
516                         my $import_id = AddAuthToBatch($batch_id, $imported, $marcrecord, $encoding, $z3950random);
517                         $breedingid = $import_id;
518                     }
519                     $imported++;
520                 }
521             }
522         }
523     return ($notmarcrecord,$alreadyindb,$alreadyinfarm,$imported,$breedingid);
524 }
525
526 =head2 Z3950SearchAuth
527
528 Z3950SearchAuth($pars, $template);
529
530 Parameters for Z3950 search are all passed via the $pars hash. It may contain nameany, namepersonal, namecorp, namemeetingcon,
531 title, uniform title, subject, subjectsubdiv, srchany.
532 Also it should contain an arrayref id that points to a list of IDs of the z3950 targets to be queried (see z3950servers table).
533 This code is used in cataloging/z3950_auth_search.
534 The second parameter $template is a Template object. The routine uses this parameter to store the found values into the template.
535
536 =cut
537
538 sub Z3950SearchAuth {
539     my ($pars, $template)= @_;
540
541     my $dbh   = C4::Context->dbh;
542     my @id= @{$pars->{id}};
543     my $random= $pars->{random};
544     my $page= $pars->{page};
545
546
547     my $show_next       = 0;
548     my $total_pages     = 0;
549     my $attr = '';
550     my $host;
551     my $server;
552     my $database;
553     my $port;
554     my $marcdata;
555     my @encoding;
556     my @results;
557     my $count;
558     my $record;
559     my @serverhost;
560     my @breeding_loop = ();
561
562     my @oConnection;
563     my @oResult;
564     my @errconn;
565     my @servers;
566     my $s = 0;
567     my $query;
568     my $nterms=0;
569
570     my $marcflavour = C4::Context->preference('marcflavour');
571     my $marc_type = $marcflavour eq 'UNIMARC' ? 'UNIMARCAUTH' : $marcflavour;
572     my $authid= $pars->{authid};
573     my ( $zquery, $squery ) = _auth_build_query( $pars );
574     foreach my $servid (@id) {
575         my $sth = $dbh->prepare("select * from z3950servers where id=?");
576         $sth->execute($servid);
577         while ( $server = $sth->fetchrow_hashref ) {
578             $oConnection[$s] = _create_connection( $server );
579
580             $oResult[$s] =
581             $server->{servertype} eq 'zed'?
582                 $oConnection[$s]->search_pqf( $zquery ):
583                 $oConnection[$s]->search(new ZOOM::Query::CQL(
584                     _translate_query( $server, $squery )));
585             $encoding[$s]   = ($server->{encoding}?$server->{encoding}:"iso-5426");
586             $servers[$s] = $server;
587             $s++;
588         }   ## while fetch
589     }    # foreach
590     my $nremaining  = $s;
591
592     while ( $nremaining-- ) {
593         my $k;
594         my $event;
595         while ( ( $k = ZOOM::event( \@oConnection ) ) != 0 ) {
596             $event = $oConnection[ $k - 1 ]->last_event();
597             last if $event == ZOOM::Event::ZEND;
598         }
599
600         if ( $k != 0 ) {
601             $k--;
602             my ($error, $errmsg, $addinfo, $diagset)= $oConnection[$k]->error_x();
603             if ($error) {
604                 if ($error =~ m/^(10000|10007)$/ ) {
605                     push(@errconn, {'server' => $serverhost[$k]});
606                 }
607             }
608             else {
609                 my $numresults = $oResult[$k]->size();
610                 my $i;
611                 my $result = '';
612                 if ( $numresults > 0  and $numresults >= (($page-1)*20)) {
613                     $show_next = 1 if $numresults >= ($page*20);
614                     $total_pages = int($numresults/20)+1 if $total_pages < ($numresults/20);
615                     for ($i = ($page-1)*20; $i < (($numresults < ($page*20)) ? $numresults : ($page*20)); $i++) {
616                         my $rec = $oResult[$k]->record($i);
617                         if ($rec) {
618                             my $marcrecord;
619                             my $marcdata;
620                             $marcdata   = $rec->raw();
621
622                             my ($charset_result, $charset_errors);
623                             if( $servers[$k]->{servertype} eq 'sru' ) {
624                                 $marcdata = MARC::Record->new_from_xml( $marcdata, $encoding[$k], $servers[$k]->{syntax} );
625                             }
626                             ($marcrecord, $charset_result, $charset_errors)= MarcToUTF8Record($marcdata, $marc_type, $encoding[$k]);
627                             my $heading;
628                             my $heading_authtype_code;
629                             $heading_authtype_code = GuessAuthTypeCode($marcrecord);
630                             $heading = C4::AuthoritiesMarc::GetAuthorizedHeading({ record => $marcrecord });
631
632                             my ($notmarcrecord, $alreadyindb, $alreadyinfarm, $imported, $breedingid)= ImportBreedingAuth( $marcrecord, 2, $serverhost[$k], $encoding[$k], $random);
633                             my %row_data;
634                             $row_data{server}       = $servers[$k]->{'servername'};
635                             $row_data{breedingid}   = $breedingid;
636                             $row_data{heading}      = $heading;
637                             $row_data{authid}       = $authid;
638                             $row_data{heading_code}      = $heading_authtype_code;
639                             push( @breeding_loop, \%row_data );
640                         }
641                         else {
642                             push(@breeding_loop,{'server'=>$servers[$k]->{'servername'},'title'=>join(': ',$oConnection[$k]->error_x()),'breedingid'=>-1,'authid'=>-1});
643                         }
644                     }
645                 }    #if $numresults
646             }
647         }    # if $k !=0
648
649         $template->param(
650             numberpending => $nremaining,
651             current_page => $page,
652             total_pages => $total_pages,
653             show_nextbutton => $show_next?1:0,
654             show_prevbutton => $page!=1,
655         );
656     } # while nremaining
657
658     #close result sets and connections
659     foreach(0..$s-1) {
660         $oResult[$_]->destroy();
661         $oConnection[$_]->destroy();
662     }
663
664     @servers = ();
665     foreach my $id (@id) {
666         push @servers, {id => $id};
667     }
668     $template->param(
669         breeding_loop => \@breeding_loop,
670         servers => \@servers,
671         errconn       => \@errconn
672     );
673 }
674
675 1;
676 __END__
677