wr72054 fixing the z3950 search for acquisitions
[koha.git] / acqui / z3950_search.pl
1 #!/usr/bin/perl
2
3 # This is a completely new Z3950 clients search using async ZOOM -TG 02/11/06
4 # Copyright 2000-2002 Katipo Communications
5 # Copyright 2010 Catalyst IT
6 #
7 # This file is part of Koha.
8 #
9 # Koha is free software; you can redistribute it and/or modify it under the
10 # terms of the GNU General Public License as published by the Free Software
11 # Foundation; either version 2 of the License, or (at your option) any later
12 # version.
13 #
14 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
15 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
16 # A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
17 #
18 # You should have received a copy of the GNU General Public License along
19 # with Koha; if not, write to the Free Software Foundation, Inc.,
20 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
21
22 use warnings;
23 use strict;
24 use CGI;
25
26 use C4::Auth;
27 use C4::Output;
28 use C4::Biblio;
29 use C4::Context;
30 use C4::Breeding;
31 use C4::Koha;
32 use C4::Charset;
33 use ZOOM;
34
35 my $input        = new CGI;
36 my ( $template, $loggedinuser, $cookie ) = get_template_and_user(
37     {
38         template_name   => "acqui/z3950_search.tmpl",
39         query           => $input,
40         type            => "intranet",
41         authnotrequired => 1,
42         flagsrequired   => { acquisition => 'order_manage' },
43         debug           => 1,
44     }
45 );
46
47 my $dbh          = C4::Context->dbh;
48 my $error        = $input->param('error');
49 my $biblionumber = $input->param('biblionumber');
50 $biblionumber = 0 unless $biblionumber;
51 my $frameworkcode = $input->param('frameworkcode');
52 my $title         = $input->param('title');
53 my $author        = $input->param('author');
54 my $isbn          = $input->param('isbn');
55 my $issn          = $input->param('issn');
56 my $lccn          = $input->param('lccn');
57 my $subject= $input->param('subject');
58 my $dewey = $input->param('dewey');
59 my $op            = $input->param('op');
60 my $booksellerid = $input->param('booksellerid');
61 my $basketno = $input->param('basketno');
62 my $noconnection;
63 my $numberpending;
64 my $attr = '';
65 my $term;
66 my $host;
67 my $server;
68 my $database;
69 my $port;
70 my $marcdata;
71 my @encoding;
72 my @results;
73 my $count;
74 my $toggle;
75 my $record;
76 my $oldbiblio;
77 my $errmsg;
78 my @serverhost;
79 my @servername;
80 my @breeding_loop = ();
81 my $random        = $input->param('random');
82 unless ($random)
83 {    # this var is not useful anymore just kept to keep rel2_2 compatibility
84     $random = rand(1000000000);
85 }
86
87 my $DEBUG = 0;    # if set to 1, many debug message are send on syslog.
88
89 # get framework list
90 my $frameworks = getframeworks;
91 my @frameworkcodeloop;
92 foreach my $thisframeworkcode ( keys %$frameworks ) {
93     my %row = (
94         value         => $thisframeworkcode,
95         frameworktext => $frameworks->{$thisframeworkcode}->{'frameworktext'},
96     );
97     if ( $row{'value'} eq $frameworkcode){
98         $row{'active'} = 'true';
99     }
100     push @frameworkcodeloop, $row;
101 }
102
103 $template->param( frameworkcode => $frameworkcode, 
104                                     frameworkcodeloop => \@frameworkcodeloop,
105                                     booksellerid => $booksellerid,
106                                     basketno => $basketno);
107
108
109 if ( $op ne "do_search" ) {
110     my $sth = $dbh->prepare("select id,host,name,checked from z3950servers  order by host");
111     $sth->execute();
112     my $serverloop = $sth->fetchall_arrayref( {} );
113     $template->param(
114         isbn         => $isbn,
115         issn         => $issn,
116         lccn         => $lccn,
117         title        => $title,
118         author       => $author,
119         serverloop   => $serverloop,
120         opsearch     => "search",
121         biblionumber => $biblionumber,
122     );
123     output_html_with_http_headers $input, $cookie, $template->output;
124 }
125 else {
126     my @id = $input->param('id');
127     my @oConnection;
128     my @oResult;
129     my $s = 0;
130     my $query;
131     my $nterms;
132     if ($isbn || $issn) {
133         $term=$isbn if ($isbn);
134         $term=$issn if ($issn);
135         $query .= " \@or \@attr 1=8 \"$term\" \@attr 1=7 \"$term\" ";
136         $nterms++;
137     }
138     if ($title) {
139         utf8::decode($title);
140         $query .= " \@attr 1=4 \"$title\" ";
141         $nterms++;
142     }
143     if ($author) {
144         utf8::decode($author);
145         $query .= " \@attr 1=1003 \"$author\" ";
146         $nterms++;
147     }
148     if ($dewey) {
149         $query .= " \@attr 1=16 \"$dewey\" ";
150         $nterms++;
151     }
152     if ($subject) {
153         utf8::decode($subject);
154         $query .= " \@attr 1=21 \"$subject\" ";
155         $nterms++;
156     }
157         if ($lccn) {    
158         $query .= " \@attr 1=9 $lccn ";
159         $nterms++;
160     }
161 for my $i (1..$nterms-1) {
162     $query = "\@and " . $query;
163 }
164 warn "query ".$query  if $DEBUG;
165
166     foreach my $servid (@id) {
167         my $sth = $dbh->prepare("select * from z3950servers where id=?");
168         $sth->execute($servid);
169         while ( $server = $sth->fetchrow_hashref ) {
170             warn "serverinfo ".join(':',%$server) if $DEBUG;
171             my $noconnection = 0;
172             my $option1      = new ZOOM::Options();
173             $option1->option( 'async' => 1 );
174             $option1->option( 'elementSetName', 'F' );
175             $option1->option( 'databaseName',   $server->{db} );
176             $option1->option( 'user', $server->{userid} ) if $server->{userid};
177             $option1->option( 'password', $server->{password} )
178               if $server->{password};
179             $option1->option( 'preferredRecordSyntax', $server->{syntax} );
180             $oConnection[$s] = create ZOOM::Connection($option1)
181               || $DEBUG
182               && warn( "" . $oConnection[$s]->errmsg() );
183             warn( "server data", $server->{name}, $server->{port} ) if $DEBUG;
184             $oConnection[$s]->connect( $server->{host}, $server->{port} )
185               || $DEBUG
186               && warn( "" . $oConnection[$s]->errmsg() );
187             $serverhost[$s] = $server->{host};
188             $servername[$s] = $server->{name};
189             $encoding[$s]   = ($server->{encoding}?$server->{encoding}:"iso-5426");
190             $s++;
191         }    ## while fetch
192     }    # foreach
193     my $nremaining  = $s;
194     my $firstresult = 1;
195
196     for ( my $z = 0 ; $z < $s ; $z++ ) {
197         warn "doing the search" if $DEBUG;
198         $oResult[$z] = $oConnection[$z]->search_pqf($query)
199           || $DEBUG
200           && warn( "somthing went wrong: " . $oConnection[$s]->errmsg() );
201
202         # $oResult[$z] = $oConnection[$z]->search_pqf($query);
203     }
204
205 sub displayresults {
206     my $k;
207     my $event;
208     while ( ( $k = ZOOM::event( \@oConnection ) ) != 0 ) {
209         $event = $oConnection[ $k - 1 ]->last_event();
210         warn( "connection ", $k - 1, ": event $event (",
211             ZOOM::event_str($event), ")\n" )
212           if $DEBUG;
213         last if $event == ZOOM::Event::ZEND;
214     }
215
216     if ( $k != 0 ) {
217         $k--;
218         warn $serverhost[$k] if $DEBUG;
219         my ( $error, $errmsg, $addinfo, $diagset ) =
220           $oConnection[$k]->error_x();
221         if ($error) {
222             warn "$k $serverhost[$k] error $query: $errmsg ($error) $addinfo\n"
223               if $DEBUG;
224
225         }
226         else {
227             my $numresults = $oResult[$k]->size();
228             my $i;
229             my $result = '';
230             if ( $numresults > 0 ) {
231                 for (
232                     $i = 0 ;
233                     $i < ( ( $numresults < 20 ) ? ($numresults) : (20) ) ;
234                     $i++
235                   )
236                 {
237                     my $rec = $oResult[$k]->record($i);
238                     if ($rec) {
239                         my $marcrecord;
240                         $marcdata   = $rec->raw();
241
242                         my ($charset_result, $charset_errors);
243                         ($marcrecord, $charset_result, $charset_errors) = 
244                           MarcToUTF8Record($marcdata, C4::Context->preference('marcflavour'), $encoding[$k]);
245 ####WARNING records coming from Z3950 clients are in various character sets MARC8,UTF8,UNIMARC etc
246 ## In HEAD i change everything to UTF-8
247 # In rel2_2 i am not sure what encoding is so no character conversion is done here
248 ##Add necessary encoding changes to here -TG
249                         my $oldbiblio = TransformMarcToKoha( $dbh, $marcrecord, "" );
250                         $oldbiblio->{isbn}   =~ s/ |-|\.//g if $oldbiblio->{isbn};
251                          $oldbiblio->{issn} =~ s/ |-|\.//g if $oldbiblio->{issn};
252                           my (
253                             $notmarcrecord, $alreadyindb, $alreadyinfarm,
254                             $imported,      $breedingid
255                           )
256                           = ImportBreeding( $marcdata, 2, $serverhost[$k], $encoding[$k], $random, 'z3950' );
257                         my %row_data;
258                         if ( $i % 2 ) {
259                             $toggle = 1;
260                         }
261                         else {
262                             $toggle = 0;
263                         }
264                         $row_data{toggle}       = $toggle;
265                         $row_data{server}       = $servername[$k];
266                         $row_data{isbn}         = $oldbiblio->{isbn};
267                         $row_data{lccn}         = $oldbiblio->{lccn};
268                         $row_data{title}        = $oldbiblio->{title};
269                         $row_data{author}       = $oldbiblio->{author};
270                         $row_data{breedingid}   = $breedingid;
271                         $row_data{biblionumber} = $biblionumber;
272                         push( @breeding_loop, \%row_data );
273                             
274                     } else {
275                         push(@breeding_loop,{'toggle'=>($i % 2)?1:0,'server'=>$servername[$k],'title'=>join(': ',$oConnection[$k]->error_x()),'breedingid'=>-1,'biblionumber'=>-1});
276                     } # $rec
277                 }    # upto 5 results
278             }    #$numresults
279         }
280     }    # if $k !=0
281     $numberpending = $nremaining - 1;
282     $template->param(
283         breeding_loop => \@breeding_loop,
284         server        => $servername[$k],
285         numberpending => $numberpending,
286     );
287     output_html_with_http_headers $input, $cookie, $template->output if $numberpending == 0;
288
289     #   print  $template->output  if $firstresult !=1;
290     $firstresult++;
291 }
292 displayresults();
293 while ( --$nremaining > 0 ) {
294         displayresults();
295     }
296 }    ## if op=search