Bug 6536: Include SRU searching in Breeding.pm
[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 under the
9 # terms of the GNU General Public License as published by the Free Software
10 # Foundation; either version 2 of the License, or (at your option) any later
11 # version.
12 #
13 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
14 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
15 # A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
16 #
17 # You should have received a copy of the GNU General Public License along
18 # with Koha; if not, write to the Free Software Foundation, Inc.,
19 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
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 Koha::Database;
31
32 use vars qw($VERSION @ISA @EXPORT @EXPORT_OK %EXPORT_TAGS);
33
34 BEGIN {
35         # set the version for version checking
36     $VERSION = 3.07.00.049;
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 ) = _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
168     my $nremaining = $s;
169     while ( $nremaining-- ) {
170         my $k;
171         my $event;
172         while ( ( $k = ZOOM::event( \@oConnection ) ) != 0 ) {
173             $event = $oConnection[ $k - 1 ]->last_event();
174             last if $event == ZOOM::Event::ZEND;
175         }
176
177         if ( $k != 0 ) {
178             $k--;
179             my ($error)= $oConnection[$k]->error_x(); #ignores errmsg, addinfo, diagset
180             if ($error) {
181                 if ($error =~ m/^(10000|10007)$/ ) {
182                     push(@errconn, { server => $servers[$k]->{host}, error => $error } );
183                 }
184             }
185             else {
186                 my $numresults = $oResult[$k]->size();
187                 my $i;
188                 my $result = '';
189                 if ( $numresults > 0  and $numresults >= (($page-1)*20)) {
190                     $show_next = 1 if $numresults >= ($page*20);
191                     $total_pages = int($numresults/20)+1 if $total_pages < ($numresults/20);
192                     for ($i = ($page-1)*20; $i < (($numresults < ($page*20)) ? $numresults : ($page*20)); $i++) {
193                         if($oResult[$k]->record($i)) {
194                             my $res=_handle_one_result($oResult[$k]->record($i), $servers[$k], ++$imported, $biblionumber); #ignores error in sequence numbering
195                             push @breeding_loop, $res if $res;
196                         }
197                         else {
198                             push(@breeding_loop,{'server'=>$servers[$k]->{servername},'title'=>join(': ',$oConnection[$k]->error_x()),'breedingid'=>-1,'biblionumber'=>-1});
199                         }
200                     }
201                 }    #if $numresults
202             }
203         }    # if $k !=0
204
205         $template->param(
206             numberpending => $nremaining,
207             current_page => $page,
208             total_pages => $total_pages,
209             show_nextbutton => $show_next?1:0,
210             show_prevbutton => $page!=1,
211         );
212     } # while nremaining
213
214     #close result sets and connections
215     foreach(0..$s-1) {
216         $oResult[$_]->destroy();
217         $oConnection[$_]->destroy();
218     }
219
220     $template->param(
221         breeding_loop => \@breeding_loop,
222         servers => \@servers,
223         errconn       => \@errconn
224     );
225 }
226
227 sub _build_query {
228     my ( $pars ) = @_;
229
230     my $qry_build = {
231         isbn    => '@attr 1=7 @attr 5=1 "#term" ',
232         issn    => '@attr 1=8 @attr 5=1 "#term" ',
233         title   => '@attr 1=4 #term ',
234         author  => '@attr 1=1003 "#term" ',
235         dewey   => '@attr 1=16 "#term" ',
236         subject => '@attr 1=21 "#term" ',
237         lccall  => '@attr 1=16 @attr 2=3 @attr 3=1 @attr 4=1 @attr 5=1 '.
238                    '@attr 6=1 "#term" ',
239         controlnumber => '@attr 1=12 "#term" ',
240         srchany => '@attr 1=1016 "#term" ',
241         stdid   => '@attr 1=1007 "#term" ',
242     };
243
244     my $zquery='';
245     my $squery='';
246     my $nterms=0;
247     foreach my $k ( keys %$pars ) {
248         if( ( my $val=$pars->{$k} ) && $qry_build->{$k} ) {
249             $qry_build->{$k} =~ s/#term/$val/g;
250             $zquery .= $qry_build->{$k};
251             $squery .= "[$k]=\"$val\" and ";
252             $nterms++;
253         }
254     }
255     $zquery = "\@and " . $zquery for 2..$nterms;
256     $squery =~ s/ and $//;
257     return ( $zquery, $squery );
258 }
259
260 sub _handle_one_result {
261     my ($zoomrec, $servhref, $seq, $bib)= @_;
262
263     my $raw= $zoomrec->raw();
264     my $marcrecord;
265     if( $servhref->{servertype} eq 'sru' ) {
266         $marcrecord= MARC::Record->new_from_xml( $raw, 'UTF-8',
267             $servhref->{syntax} );
268     } else {
269         ($marcrecord) = MarcToUTF8Record($raw, C4::Context->preference('marcflavour'), $servhref->{encoding} // "iso-5426" ); #ignores charset return values
270     }
271     SetUTF8Flag($marcrecord);
272
273     my $batch_id = GetZ3950BatchId($servhref->{servername});
274     my $breedingid = AddBiblioToBatch($batch_id, $seq, $marcrecord, 'UTF-8', 0, 0);
275         #FIXME passing 0 for z3950random
276         #Will eliminate this unused field in a followup report
277         #Last zero indicates: no update for batch record counts
278
279
280     #call to TransformMarcToKoha replaced by next call
281     #we only need six fields from the marc record
282     return _add_rowdata(
283         {
284             biblionumber => $bib,
285             server       => $servhref->{servername},
286             breedingid   => $breedingid,
287         }, $marcrecord) if $breedingid;
288 }
289
290 sub _add_rowdata {
291     my ($row, $record)=@_;
292     my %fetch= (
293         title => 'biblio.title',
294         author => 'biblio.author',
295         isbn =>'biblioitems.isbn',
296         lccn =>'biblioitems.lccn', #LC control number (not call number)
297         edition =>'biblioitems.editionstatement',
298         date => 'biblio.copyrightdate', #MARC21
299         date2 => 'biblioitems.publicationyear', #UNIMARC
300     );
301     foreach my $k (keys %fetch) {
302         my ($t, $f)= split '\.', $fetch{$k};
303         $row= C4::Biblio::TransformMarcToKohaOneField($t, $f, $record, $row);
304         $row->{$k}= $row->{$f} if $k ne $f;
305     }
306     $row->{date}//= $row->{date2};
307     $row->{isbn}=_isbn_replace($row->{isbn});
308     return $row;
309 }
310
311 sub _isbn_replace {
312     my ($isbn) = @_;
313     return unless defined $isbn;
314     $isbn =~ s/ |-|\.//g;
315     $isbn =~ s/\|/ \| /g;
316     $isbn =~ s/\(/ \(/g;
317     return $isbn;
318 }
319
320 sub _create_connection {
321     my ( $server ) = @_;
322     my $option1= new ZOOM::Options();
323     $option1->option( 'async' => 1 );
324     $option1->option( 'elementSetName', 'F' );
325     $option1->option( 'preferredRecordSyntax', $server->{syntax} );
326     $option1->option( 'timeout', $server->{timeout} ) if $server->{timeout};
327
328     if( $server->{servertype} eq 'sru' ) {
329         foreach( split ',', $server->{sru_options}//'' ) {
330             my @temp= split '=';
331             $option1->option( $temp[0] => $temp[1] ) if @temp;
332         }
333     } elsif( $server->{servertype} eq 'zed' ) {
334         $option1->option( 'databaseName',   $server->{db} );
335         $option1->option( 'user', $server->{userid} ) if $server->{userid};
336         $option1->option( 'password', $server->{password} ) if $server->{password};
337     }
338
339     my $obj= ZOOM::Connection->create($option1);
340     if( $server->{servertype} eq 'sru' ) {
341         my $host= $server->{host};
342         if( $host !~ /^https?:\/\// ) {
343             #Normally, host will not be prefixed by protocol.
344             #In that case we can (safely) assume http.
345             #In case someone prefixed with https, give it a try..
346             $host = 'http://' . $host;
347         }
348         $obj->connect( $host.':'.$server->{port}.'/'.$server->{db} );
349     } else {
350         $obj->connect( $server->{host}, $server->{port} );
351     }
352     return $obj;
353 }
354
355 sub _translate_query { #SRU query adjusted per server cf. srufields column
356     my ($server, $query) = @_;
357
358     #sru_fields is in format title=field,isbn=field,...
359     #if a field doesn't exist, try anywhere or remove [field]=
360     my @parts= split(',', $server->{sru_fields} );
361     my %trans= map { if( /=/ ) { ( $`,$' ) } else { () } } @parts;
362     my $any= $trans{srchany}?$trans{srchany}.'=':'';
363
364     my $q=$query;
365     foreach my $key (keys %trans) {
366         my $f=$trans{$key};
367         if( $f ) {
368             $q=~s/\[$key\]/$f/g;
369         } else {
370             $q=~s/\[$key\]=/$any/g;
371         }
372     }
373     $q=~s/\[\w+\]=/$any/g; # remove remaining fields (not found in field list)
374     return $q;
375 }
376
377 =head2 ImportBreedingAuth
378
379 ImportBreedingAuth($marcrecords,$overwrite_auth,$filename,$encoding,$z3950random,$batch_type);
380
381     ImportBreedingAuth imports MARC records in the reservoir (import_records table).
382     ImportBreedingAuth is based on the ImportBreeding subroutine.
383
384 =cut
385
386 sub ImportBreedingAuth {
387     my ($marcrecords,$overwrite_auth,$filename,$encoding,$z3950random,$batch_type) = @_;
388     my @marcarray = split /\x1D/, $marcrecords;
389
390     my $dbh = C4::Context->dbh;
391
392     my $batch_id = GetZ3950BatchId($filename);
393     my $searchbreeding = $dbh->prepare("select import_record_id from import_auths where control_number=? and authorized_heading=?");
394
395 #     $encoding = C4::Context->preference("marcflavour") unless $encoding;
396     # fields used for import results
397     my $imported=0;
398     my $alreadyindb = 0;
399     my $alreadyinfarm = 0;
400     my $notmarcrecord = 0;
401     my $breedingid;
402     for (my $i=0;$i<=$#marcarray;$i++) {
403         my ($marcrecord, $charset_result, $charset_errors);
404         ($marcrecord, $charset_result, $charset_errors) =
405             MarcToUTF8Record($marcarray[$i]."\x1D", C4::Context->preference("marcflavour"), $encoding);
406
407         # Normalize the record so it doesn't have separated diacritics
408         SetUTF8Flag($marcrecord);
409
410         if (scalar($marcrecord->fields()) == 0) {
411             $notmarcrecord++;
412         } else {
413             my $heading;
414             $heading = C4::AuthoritiesMarc::GetAuthorizedHeading({ record => $marcrecord });
415
416             my $heading_authtype_code;
417             $heading_authtype_code = GuessAuthTypeCode($marcrecord);
418
419             my $controlnumber;
420             $controlnumber = $marcrecord->field('001')->data;
421
422             #Check if the authority record already exists in the database...
423             my ($duplicateauthid,$duplicateauthvalue);
424             if ($marcrecord && $heading_authtype_code) {
425                 ($duplicateauthid,$duplicateauthvalue) = FindDuplicateAuthority( $marcrecord, $heading_authtype_code);
426             }
427
428             if ($duplicateauthid && $overwrite_auth ne 2) {
429                 #If the authority record exists and $overwrite_auth doesn't equal 2, then mark it as already in the DB
430                 $alreadyindb++;
431             } else {
432                 if ($controlnumber && $heading) {
433                     $searchbreeding->execute($controlnumber,$heading);
434                     ($breedingid) = $searchbreeding->fetchrow;
435                 }
436                 if ($breedingid && $overwrite_auth eq '0') {
437                     $alreadyinfarm++;
438                 } else {
439                     if ($breedingid && $overwrite_auth eq '1') {
440                         ModAuthorityInBatch($breedingid, $marcrecord);
441                     } else {
442                         my $import_id = AddAuthToBatch($batch_id, $imported, $marcrecord, $encoding, $z3950random);
443                         $breedingid = $import_id;
444                     }
445                     $imported++;
446                 }
447             }
448         }
449     }
450     return ($notmarcrecord,$alreadyindb,$alreadyinfarm,$imported,$breedingid);
451 }
452
453 =head2 Z3950SearchAuth
454
455 Z3950SearchAuth($pars, $template);
456
457 Parameters for Z3950 search are all passed via the $pars hash. It may contain nameany, namepersonal, namecorp, namemeetingcon,
458 title, uniform title, subject, subjectsubdiv, srchany.
459 Also it should contain an arrayref id that points to a list of IDs of the z3950 targets to be queried (see z3950servers table).
460 This code is used in cataloging/z3950_auth_search.
461 The second parameter $template is a Template object. The routine uses this parameter to store the found values into the template.
462
463 =cut
464
465 sub Z3950SearchAuth {
466     my ($pars, $template)= @_;
467
468     my $dbh   = C4::Context->dbh;
469     my @id= @{$pars->{id}};
470     my $random= $pars->{random};
471     my $page= $pars->{page};
472
473     my $nameany= $pars->{nameany};
474     my $authorany= $pars->{authorany};
475     my $authorpersonal= $pars->{authorpersonal};
476     my $authorcorp= $pars->{authorcorp};
477     my $authormeetingcon= $pars->{authormeetingcon};
478     my $title= $pars->{title};
479     my $uniformtitle= $pars->{uniformtitle};
480     my $subject= $pars->{subject};
481     my $subjectsubdiv= $pars->{subjectsubdiv};
482     my $srchany= $pars->{srchany};
483
484     my $show_next       = 0;
485     my $total_pages     = 0;
486     my $attr = '';
487     my $host;
488     my $server;
489     my $database;
490     my $port;
491     my $marcdata;
492     my @encoding;
493     my @results;
494     my $count;
495     my $record;
496     my @serverhost;
497     my @servername;
498     my @breeding_loop = ();
499
500     my @oConnection;
501     my @oResult;
502     my @errconn;
503     my $s = 0;
504     my $query;
505     my $nterms=0;
506
507     if ($nameany) {
508         $query .= " \@attr 1=1002 \"$nameany\" "; #Any name (this includes personal, corporate, meeting/conference authors, and author names in subject headings)
509         #This attribute is supported by both the Library of Congress and Libraries Australia 08/05/2013
510         $nterms++;
511     }
512
513     if ($authorany) {
514         $query .= " \@attr 1=1003 \"$authorany\" "; #Author-name (this includes personal, corporate, meeting/conference authors, but not author names in subject headings)
515         #This attribute is not supported by the Library of Congress, but is supported by Libraries Australia 08/05/2013
516         $nterms++;
517     }
518
519     if ($authorcorp) {
520         $query .= " \@attr 1=2 \"$authorcorp\" "; #1005 is another valid corporate author attribute...
521         $nterms++;
522     }
523
524     if ($authorpersonal) {
525         $query .= " \@attr 1=1 \"$authorpersonal\" "; #1004 is another valid personal name attribute...
526         $nterms++;
527     }
528
529     if ($authormeetingcon) {
530         $query .= " \@attr 1=3 \"$authormeetingcon\" "; #1006 is another valid meeting/conference name attribute...
531         $nterms++;
532     }
533
534     if ($subject) {
535         $query .= " \@attr 1=21 \"$subject\" ";
536         $nterms++;
537     }
538
539     if ($subjectsubdiv) {
540         $query .= " \@attr 1=47 \"$subjectsubdiv\" ";
541         $nterms++;
542     }
543
544     if ($title) {
545         $query .= " \@attr 1=4 \"$title\" "; #This is a regular title search. 1=6 will give just uniform titles
546         $nterms++;
547     }
548
549      if ($uniformtitle) {
550         $query .= " \@attr 1=6 \"$uniformtitle\" "; #This is the uniform title search
551         $nterms++;
552     }
553
554     if($srchany) {
555         $query .= " \@attr 1=1016 \"$srchany\" ";
556         $nterms++;
557     }
558
559     for my $i (1..$nterms-1) {
560         $query = "\@and " . $query;
561     }
562
563     foreach my $servid (@id) {
564         my $sth = $dbh->prepare("select * from z3950servers where id=?");
565         $sth->execute($servid);
566         while ( $server = $sth->fetchrow_hashref ) {
567             my $option1      = new ZOOM::Options();
568             $option1->option( 'async' => 1 );
569             $option1->option( 'elementSetName', 'F' );
570             $option1->option( 'databaseName',   $server->{db} );
571             $option1->option( 'user', $server->{userid} ) if $server->{userid};
572             $option1->option( 'password', $server->{password} ) if $server->{password};
573             $option1->option( 'preferredRecordSyntax', $server->{syntax} );
574             $option1->option( 'timeout', $server->{timeout} ) if $server->{timeout};
575             $oConnection[$s] = create ZOOM::Connection($option1);
576             $oConnection[$s]->connect( $server->{host}, $server->{port} );
577             $serverhost[$s] = $server->{host};
578             $servername[$s] = $server->{name};
579             $encoding[$s]   = ($server->{encoding}?$server->{encoding}:"iso-5426");
580             $s++;
581         }    ## while fetch
582     }    # foreach
583     my $nremaining  = $s;
584
585     for ( my $z = 0 ; $z < $s ; $z++ ) {
586         $oResult[$z] = $oConnection[$z]->search_pqf($query);
587     }
588
589     while ( $nremaining-- ) {
590         my $k;
591         my $event;
592         while ( ( $k = ZOOM::event( \@oConnection ) ) != 0 ) {
593             $event = $oConnection[ $k - 1 ]->last_event();
594             last if $event == ZOOM::Event::ZEND;
595         }
596
597         if ( $k != 0 ) {
598             $k--;
599             my ($error, $errmsg, $addinfo, $diagset)= $oConnection[$k]->error_x();
600             if ($error) {
601                 if ($error =~ m/^(10000|10007)$/ ) {
602                     push(@errconn, {'server' => $serverhost[$k]});
603                 }
604             }
605             else {
606                 my $numresults = $oResult[$k]->size();
607                 my $i;
608                 my $result = '';
609                 if ( $numresults > 0  and $numresults >= (($page-1)*20)) {
610                     $show_next = 1 if $numresults >= ($page*20);
611                     $total_pages = int($numresults/20)+1 if $total_pages < ($numresults/20);
612                     for ($i = ($page-1)*20; $i < (($numresults < ($page*20)) ? $numresults : ($page*20)); $i++) {
613                         my $rec = $oResult[$k]->record($i);
614                         if ($rec) {
615                             my $marcrecord;
616                             my $marcdata;
617                             $marcdata   = $rec->raw();
618
619                             my ($charset_result, $charset_errors);
620                             ($marcrecord, $charset_result, $charset_errors)= MarcToUTF8Record($marcdata, C4::Context->preference('marcflavour'), $encoding[$k]);
621
622                             my $heading;
623                             my $heading_authtype_code;
624                             $heading_authtype_code = GuessAuthTypeCode($marcrecord);
625                             $heading = C4::AuthoritiesMarc::GetAuthorizedHeading({ record => $marcrecord });
626
627                             my ($notmarcrecord, $alreadyindb, $alreadyinfarm, $imported, $breedingid)= ImportBreedingAuth( $marcdata, 2, $serverhost[$k], $encoding[$k], $random, 'z3950' );
628                             my %row_data;
629                             $row_data{server}       = $servername[$k];
630                             $row_data{breedingid}   = $breedingid;
631                             $row_data{heading}      = $heading;
632                             $row_data{heading_code}      = $heading_authtype_code;
633                             push( @breeding_loop, \%row_data );
634                         }
635                         else {
636                             push(@breeding_loop,{'server'=>$servername[$k],'title'=>join(': ',$oConnection[$k]->error_x()),'breedingid'=>-1});
637                         }
638                     }
639                 }    #if $numresults
640             }
641         }    # if $k !=0
642
643         $template->param(
644             numberpending => $nremaining,
645             current_page => $page,
646             total_pages => $total_pages,
647             show_nextbutton => $show_next?1:0,
648             show_prevbutton => $page!=1,
649         );
650     } # while nremaining
651
652     #close result sets and connections
653     foreach(0..$s-1) {
654         $oResult[$_]->destroy();
655         $oConnection[$_]->destroy();
656     }
657
658     my @servers = ();
659     foreach my $id (@id) {
660         push @servers, {id => $id};
661     }
662     $template->param(
663         breeding_loop => \@breeding_loop,
664         servers => \@servers,
665         errconn       => \@errconn
666     );
667 }
668
669 1;
670 __END__
671