Bug 6602 - Reports dictionary doesn't properly recognize text columns
[koha.git] / cataloguing / 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 #
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; FIXME - Bug 2505
23 use CGI;
24
25 use C4::Auth;
26 use C4::Output;
27 use C4::Biblio;
28 use C4::Context;
29 use C4::Breeding;
30 use C4::Koha;
31 use C4::Charset;
32 use ZOOM;
33
34 my $input        = new CGI;
35 my $dbh          = C4::Context->dbh;
36 my $error         = $input->param('error');
37 my $biblionumber  = $input->param('biblionumber') || 0;
38 my $frameworkcode = $input->param('frameworkcode');
39 my $title         = $input->param('title');
40 my $author        = $input->param('author');
41 my $isbn          = $input->param('isbn');
42 my $issn          = $input->param('issn');
43 my $lccn          = $input->param('lccn');
44 my $lccall        = $input->param('lccall');
45 my $subject       = $input->param('subject');
46 my $dewey         = $input->param('dewey');
47 my $controlnumber       = $input->param('controlnumber');
48 my $stdid                       = $input->param('stdid');
49 my $srchany                     = $input->param('srchany');
50 my $random        = $input->param('random') || rand(1000000000); # this var is not useful anymore just kept for rel2_2 compatibility
51 my $op            = $input->param('op');
52
53 my $page            = $input->param('current_page') || 1;
54 $page = $input->param('goto_page') if $input->param('changepage_goto');
55 my $show_next = 0;
56 my $total_pages = 0;
57
58 my $numberpending;
59 my $attr = '';
60 my $term;
61 my $host;
62 my $server;
63 my $database;
64 my $port;
65 my $marcdata;
66 my @encoding;
67 my @results;
68 my $count;
69 my $record;
70 my $oldbiblio;
71 my $errmsg;
72 my @serverloop = ();
73 my @serverhost;
74 my @servername;
75 my @breeding_loop = ();
76
77 my $DEBUG = 0;    # if set to 1, many debug message are send on syslog.
78
79 my ( $template, $loggedinuser, $cookie ) = get_template_and_user({
80         template_name   => "cataloguing/z3950_search.tmpl",
81         query           => $input,
82         type            => "intranet",
83         authnotrequired => 1,
84         flagsrequired   => { catalogue => 1 },
85         debug           => 1,
86 });
87
88 $template->param( frameworkcode => $frameworkcode, );
89 $template->param(
90     isbn         => $isbn,
91     issn         => $issn,
92     lccn         => $lccn,
93     lccall       => $lccall,
94     title        => $title,
95     author       => $author,
96     controlnumber=> $controlnumber,
97     stdid        => $stdid,
98     srchany      => $srchany,
99     biblionumber => $biblionumber,
100     dewey        => $dewey,
101     subject      => $subject,
102 );
103
104 if ( $op ne "do_search" ) {
105     my $sth = $dbh->prepare("SELECT id,host,name,checked FROM z3950servers ORDER BY rank, name");
106     $sth->execute();
107     my $serverloop = $sth->fetchall_arrayref( {} );
108     $template->param(
109         serverloop   => $serverloop,
110         opsearch     => "search",
111     );
112     output_html_with_http_headers $input, $cookie, $template->output;
113 }
114 else {
115     my @id = $input->param('id');
116
117     if ( not defined @id ) {
118         # empty server list -> report and exit
119         $template->param( emptyserverlist => 1 );
120         output_html_with_http_headers $input, $cookie, $template->output;
121         exit;
122     }
123
124     my @oConnection;
125     my @oResult;
126     my @errconn;
127     my $s = 0;
128     my $query = '';
129     my $nterms;
130     if ($isbn) {
131         $term=$isbn;
132         $query .= " \@attr 1=7 \@attr 5=1 \"$term\" ";
133         $nterms++;
134     }
135     if ($issn) {
136         $term=$issn;
137         $query .= " \@attr 1=8 \@attr 5=1 \"$term\" ";
138         $nterms++;
139     }
140     if ($title) {
141         utf8::decode($title);
142         $query .= " \@attr 1=4 \"$title\" ";
143         $nterms++;
144     }
145     if ($author) {
146         utf8::decode($author);
147         $query .= " \@attr 1=1003 \"$author\" ";
148         $nterms++;
149     }
150     if ($dewey) {
151         $query .= " \@attr 1=16 \"$dewey\" ";
152         $nterms++;
153     }
154     if ($subject) {
155         utf8::decode($subject);
156         $query .= " \@attr 1=21 \"$subject\" ";
157         $nterms++;
158     }
159         if ($lccn) {    
160         $query .= " \@attr 1=9 $lccn ";
161         $nterms++;
162     }
163     if ($lccall) {
164         $query .= " \@attr 1=16 \@attr 2=3 \@attr 3=1 \@attr 4=1 \@attr 5=1 \@attr 6=1 \"$lccall\" ";
165         $nterms++;
166     }
167     if ($controlnumber) {
168         $query .= " \@attr 1=12 \"$controlnumber\" ";
169         $nterms++;
170     }
171     if ($stdid) {
172         $query .= " \@attr 1=1007 \"$stdid\" ";
173         $nterms++;
174     }
175     if ($srchany) {
176         $query .= " \@attr 1=1016 \"$srchany\" ";
177         $nterms++;
178     }
179 for my $i (1..$nterms-1) {
180     $query = "\@and " . $query;
181 }
182 warn "query ".$query  if $DEBUG;
183
184     foreach my $servid (@id) {
185         my $sth = $dbh->prepare("SELECT * FROM z3950servers WHERE id=? ORDER BY rank, name");
186         $sth->execute($servid);
187         while ( $server = $sth->fetchrow_hashref ) {
188             warn "serverinfo ".join(':',%$server) if $DEBUG;
189             my $option1      = new ZOOM::Options();
190             $option1->option('async' => 1);
191             $option1->option('elementSetName', 'F');
192             $option1->option('databaseName', $server->{db});
193             $option1->option('user',         $server->{userid}  ) if $server->{userid};
194             $option1->option('password',     $server->{password}) if $server->{password};
195             $option1->option('preferredRecordSyntax', $server->{syntax});
196             $option1->option( 'timeout', $server->{timeout} ) if ($server->{timeout});
197             $oConnection[$s] = create ZOOM::Connection($option1)
198               || $DEBUG
199               && warn( "" . $oConnection[$s]->errmsg() );
200             warn( "server data", $server->{name}, $server->{port} ) if $DEBUG;
201             $oConnection[$s]->connect( $server->{host}, $server->{port} )
202               || $DEBUG
203               && warn( "" . $oConnection[$s]->errmsg() );
204             $serverhost[$s] = $server->{host};
205             $servername[$s] = $server->{name};
206             $encoding[$s]   = ($server->{encoding}?$server->{encoding}:"iso-5426");
207             $s++;
208         }    ## while fetch
209     }    # foreach
210     my $nremaining  = $s;
211     my $firstresult = 1;
212
213     for ( my $z = 0 ; $z < $s ; $z++ ) {
214         warn "doing the search" if $DEBUG;
215         $oResult[$z] = $oConnection[$z]->search_pqf($query)
216           || $DEBUG
217           && warn( "somthing went wrong: " . $oConnection[$s]->errmsg() );
218
219         # $oResult[$z] = $oConnection[$z]->search_pqf($query);
220     }
221
222   AGAIN:
223     my $k;
224     my $event;
225     while ( ( $k = ZOOM::event( \@oConnection ) ) != 0 ) {
226         $event = $oConnection[ $k - 1 ]->last_event();
227         warn( "connection ", $k - 1, ": event $event (",
228             ZOOM::event_str($event), ")\n" )
229           if $DEBUG;
230         last if $event == ZOOM::Event::ZEND;
231     }
232
233     if ( $k != 0 ) {
234         $k--;
235         warn $serverhost[$k] if $DEBUG;
236         my ( $error, $errmsg, $addinfo, $diagset ) =
237           $oConnection[$k]->error_x();
238         if ($error) {
239             if ($error =~ m/^(10000|10007)$/ ) {
240                 push(@errconn, {'server' => $serverhost[$k], 'error' => $error});
241             }
242             $DEBUG and warn "$k $serverhost[$k] error $query: $errmsg ($error) $addinfo\n";
243         }
244         else {
245             my $numresults = $oResult[$k]->size();
246             my $i;
247             my $result = '';
248             if ( $numresults > 0  and $numresults >= (($page-1)*20)) {
249                 $show_next = 1 if $numresults >= ($page*20);
250                 $total_pages = int($numresults/20)+1 if $total_pages < ($numresults/20);
251                 for ($i = ($page-1)*20; $i < (($numresults < ($page*20)) ? $numresults : ($page*20)); $i++) {
252                     my $rec = $oResult[$k]->record($i);
253                     if ($rec) {
254                         my $marcrecord;
255                         $marcdata   = $rec->raw();
256
257                         my ($charset_result, $charset_errors);
258                         ($marcrecord, $charset_result, $charset_errors) = 
259                           MarcToUTF8Record($marcdata, C4::Context->preference('marcflavour'), $encoding[$k]);
260 ####WARNING records coming from Z3950 clients are in various character sets MARC8,UTF8,UNIMARC etc
261 ## In HEAD i change everything to UTF-8
262 # In rel2_2 i am not sure what encoding is so no character conversion is done here
263 ##Add necessary encoding changes to here -TG
264
265                         # Normalize the record so it doesn't have separated diacritics
266                         SetUTF8Flag($marcrecord);
267
268                         my $oldbiblio = TransformMarcToKoha( $dbh, $marcrecord, "" );
269                         $oldbiblio->{isbn}   =~ s/ |-|\.//g if $oldbiblio->{isbn};
270                         # pad | and ( with spaces to allow line breaks in the HTML
271                         $oldbiblio->{isbn} =~ s/\|/ \| /g if $oldbiblio->{isbn};
272                         $oldbiblio->{isbn} =~ s/\(/ \(/g if $oldbiblio->{isbn};
273
274                         $oldbiblio->{issn} =~ s/ |-|\.//g if $oldbiblio->{issn};
275                         # pad | and ( with spaces to allow line breaks in the HTML
276                         $oldbiblio->{issn} =~ s/\|/ \| /g if $oldbiblio->{issn};
277                         $oldbiblio->{issn} =~ s/\(/ \(/g if $oldbiblio->{issn};
278                           my (
279                             $notmarcrecord, $alreadyindb, $alreadyinfarm,
280                             $imported,      $breedingid
281                           )
282                           = ImportBreeding( $marcdata, 2, $serverhost[$k], $encoding[$k], $random, 'z3950' );
283                         my %row_data;
284                         $row_data{server}       = $servername[$k];
285                         $row_data{isbn}         = $oldbiblio->{isbn};
286                         $row_data{lccn}         = $oldbiblio->{lccn};
287                         $row_data{title}        = $oldbiblio->{title};
288                         $row_data{author}       = $oldbiblio->{author};
289                         $row_data{date}         = $oldbiblio->{copyrightdate};
290                         $row_data{edition}      = $oldbiblio->{editionstatement};
291                         $row_data{breedingid}   = $breedingid;
292                         $row_data{biblionumber} = $biblionumber;
293                         push( @breeding_loop, \%row_data );
294                             
295                     } else {
296                         push(@breeding_loop,{'server'=>$servername[$k],'title'=>join(': ',$oConnection[$k]->error_x()),'breedingid'=>-1,'biblionumber'=>-1});
297                     } # $rec
298                 }
299             }    #$numresults
300         }
301     }    # if $k !=0
302     $numberpending = $nremaining - 1;
303
304     my @servers = ();
305     foreach my $id (@id) {
306         push(@servers,{id => $id});
307     }
308
309     $template->param(
310         breeding_loop => \@breeding_loop,
311         server        => $servername[$k],
312         numberpending => $numberpending,
313         biblionumber  => $biblionumber,
314         errconn       => \@errconn,
315         current_page => $page,
316         servers => \@servers,
317         total_pages => $total_pages,
318     );
319     $template->param(show_nextbutton=>1) if $show_next;
320     $template->param(show_prevbutton=>1) if $page != 1;
321     
322     output_html_with_http_headers $input, $cookie, $template->output if $numberpending == 0;
323
324     #   print  $template->output  if $firstresult !=1;
325     $firstresult++;
326
327   MAYBE_AGAIN:
328     if ( --$nremaining > 0 ) {
329         goto AGAIN;
330     }
331 }    ## if op=search