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