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