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