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