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