Passing through reviewson value, and fixing syntax error
[koha.git] / opac / opac-search-biblio.pl
1 #!/usr/bin/perl
2 use strict;
3 require Exporter;
4
5 use C4::Auth;
6 use C4::Interface::CGI::Output;
7 use C4::Context;
8 use CGI;
9 use C4::Database;
10 use HTML::Template;
11 use C4::SearchBiblio;
12 use C4::Acquisition;
13 use C4::Biblio;
14 my @spsuggest; # the array for holding suggestions
15 my $suggest;   # a flag to be set (if there are suggestions it's 1)
16 my $firstbiblionumber; # needed for directly sending user to first item
17 # use C4::Search;
18
19
20 my $itemtypelist;
21 my $brancheslist;
22 my $categorylist;
23 my $subcategorylist;
24 my $mediatypelist;
25 # added by Gavin 
26 my $totalresults;
27
28 my $dbh=C4::Context->dbh;
29 my $sth=$dbh->prepare("select description,itemtype from itemtypes order by description");
30 $sth->execute;
31 while (my ($description,$itemtype) = $sth->fetchrow) {
32     $itemtypelist.="<option value=\"$itemtype\">$description</option>\n";
33 }
34 my $sth=$dbh->prepare("select description,subcategorycode from subcategorytable order by description");
35 $sth->execute;
36 while (my ($description,$subcategorycode) = $sth->fetchrow) {
37     $subcategorylist.="<option value=\"$subcategorycode\">$description</option>\n";
38 }
39 my $sth=$dbh->prepare("select description,mediatypecode from mediatypetable order by description");
40 $sth->execute;
41 while (my ($description,$mediatypecode) = $sth->fetchrow) {
42     $mediatypelist.="<option value=\"$mediatypecode\">$description</option>\n";
43 }
44 my $sth=$dbh->prepare("select description,categorycode from categorytable order by description");
45 $sth->execute;
46 while (my ($description,$categorycode) = $sth->fetchrow) {
47     $categorylist .= '<input type="radio" name="categorylist" value="'.$categorycode.'">'.$description.'<br>';
48 }
49 my $sth=$dbh->prepare("select branchname,branchcode from branches order by branchname");
50 $sth->execute;
51
52 while (my ($branchname,$branchcode) = $sth->fetchrow) {
53     $brancheslist.="<option value=\"$branchcode\">$branchname</option>\n";
54 }
55 my $query = new CGI;
56 my $op = $query->param("op");
57 my $type=$query->param('type');
58
59 my $itemtypesstring=$query->param("itemtypesstring");
60 $itemtypesstring =~s/"//g;
61 my @itemtypes = split ( /\|/, $itemtypesstring);
62 my $branchesstring=$query->param("branchesstring");
63 $branchesstring =~s/"//g;
64 my @branches = split (/\|/, $branchesstring);
65
66 my $startfrom=$query->param('startfrom');
67 $startfrom=0 if(!defined $startfrom);
68 my ($template, $loggedinuser, $cookie);
69 my $resultsperpage;
70 my $searchdesc;
71
72 if ($op eq "do_search") {
73         my @marclist = $query->param('marclist');
74         my @and_or = $query->param('and_or');
75         my @excluding = $query->param('excluding');
76         my @operator = $query->param('operator');
77         my @value = $query->param('value');
78
79         for (my $i=0;$i<=$#marclist;$i++) {
80                 if ($searchdesc) { # don't put the and_or on the 1st search term
81                         $searchdesc .= $and_or[$i]." ".$excluding[$i]." ".($marclist[$i]?$marclist[$i]:"*")." ".$operator[$i]." ".$value[$i]." " if ($value[$i]);
82                 } else {
83                         $searchdesc = $excluding[$i]." ".($marclist[$i]?$marclist[$i]:"*")." ".$operator[$i]." ".$value[$i]." " if ($value[$i]);
84                 }
85         }
86   if ($itemtypesstring ne ''){
87     $searchdesc .= 'filtered by itemtypes ';
88     $searchdesc .= join(" ",@itemtypes)
89   }
90   if ($branchesstring ne ''){
91     $searchdesc .= ' in branches ';
92     $searchdesc .= join(" ",@branches)
93   }
94         $resultsperpage= $query->param('resultsperpage');
95         $resultsperpage = 19 if(!defined $resultsperpage);
96         my $orderby = $query->param('orderby');
97         my $desc_or_asc = $query->param('desc_or_asc');
98         # builds tag and subfield arrays
99         my @tags;
100
101         foreach my $marc (@marclist) {
102                 if ($marc) {
103                         my ($tag,$subfield) = MARCfind_marc_from_kohafield($dbh,$marc,'');
104                         if ($tag) {
105                                 push @tags,$dbh->quote("$tag$subfield");
106                         } else {
107                                 push @tags, $dbh->quote(substr($marc,0,4));
108                         }
109                 } else {
110                         push @tags, "";
111                 }
112         }
113         findseealso($dbh,\@tags);
114     my $sqlstring;
115     if ($itemtypesstring ne ''){
116         $sqlstring = 'and (biblioitems.itemtype IN (';
117         my $itemtypeloop=0;
118         foreach my $itemtype (@itemtypes){
119             if ($itemtype ne ''){
120                 if ($itemtypeloop != 0){
121                     $sqlstring .=','
122                 }
123                 $sqlstring .= '"'.$itemtype.'"';
124                 $itemtypeloop++;
125             }
126         }
127         $sqlstring .= '))'
128     }
129     if ($branchesstring ne ''){
130         $sqlstring .= 'and biblio.biblionumber=items.biblionumber and (items.holdingbranch IN (';
131         my $branchesloop=0;
132         foreach my $branch (@branches){
133             if ($branch ne ''){
134                 if ($branchesloop != 0){
135                     $sqlstring .=','
136                 }
137                 $sqlstring .= '"'.$branch.'"';
138                 $branchesloop++;
139             }
140         }
141         $sqlstring .= '))'
142     }
143
144         my ($results,$total) = catalogsearch1($dbh, \@tags,\@and_or,
145                                                                                 \@excluding, \@operator, \@value,
146                                                                                 $startfrom*$resultsperpage, $resultsperpage,$orderby,$desc_or_asc,$sqlstring);
147         if ($total ==1) {
148         if (C4::Context->preference("BiblioDefaultView") eq "normal") {
149              print $query->redirect("/cgi-bin/koha/opac-detail.pl?bib=".@$results[0]->{biblionumber});
150         } elsif (C4::Context->preference("BiblioDefaultView") eq "MARC") {
151              print $query->redirect("/cgi-bin/koha/MARCdetail.pl?bib=".@$results[0]->{biblionumber});
152         } else {
153              print $query->redirect("/cgi-bin/koha/ISBDdetail.pl?bib=".@$results[0]->{biblionumber});
154         }
155         exit;
156         }
157         ($template, $loggedinuser, $cookie)
158                 = get_template_and_user({template_name => "opac-searchresults.tmpl",
159                                 query => $query,
160                                 type => 'opac',
161                                 authnotrequired => 1,
162                                 debug => 1,
163                                 });
164
165         # multi page display gestion
166         my $displaynext=0;
167         my $displayprev=$startfrom;
168         if(($total - (($startfrom+1)*($resultsperpage))) > 0 ){
169                 $displaynext = 1;
170         }
171
172         my @field_data = ();
173
174 ### Added by JF
175 ## This next does a number of things:
176 # 1. It allows you to track all the searches made for stats, etc.
177 # 2. It fixes the 'searchdesc' variable problem by introducing
178 #         a. 'searchterms' which comes out as 'Keyword: neal stephenson'
179 #         b. 'phraseorterm' which comes out as 'neal stephenson'
180 #      both of these are useful for differen purposes ... I use searchterms
181 #      for display purposes and phraseorterm for passing the search terms
182 #      to an external source through a url (like a database search)
183 # 3. It provides the variables necessary for the spellchecking (look below for
184 #      how this is done
185 # 4.
186  
187 $totalresults = $total;
188
189 ## This formats the 'search results' string and populates
190 ## the 'OPLIN' variable as well as the 'spellcheck' variable
191 ## with appropriate values based on the user's search input
192
193 my $searchterms; #returned in place of searchdesc for 'results for search'
194                  # as a string (can format if need be)
195
196 my @spphrases;
197 my $phraseorterm;
198 my %searchtypehash = ( # used only for the searchterms string formation
199                         # and for spellcheck string
200         '0' => 'keyword',
201         '1' => 'title',
202         '2' => 'author',
203         '3' => 'subject',
204         '4' => 'series',
205         '5' => 'format',
206         );
207
208 my @searchterm = $query->param('value');
209
210 for (my $i=0; $i <= $#searchterm; $i++) {
211         my $searchtype = $searchtypehash{$i};
212         push @spphrases, $searchterm[$i];
213         if ($searchterms) { #don't put and in again
214                 if ($searchterm[$i]) {
215                 $phraseorterm.=$searchterm[$i];
216                 $searchterms.=" AND ".$searchtype." : \'".$searchterm[$i]."\'";
217                 }
218         } else {
219                 if ($searchterm[$i]) {
220                 $phraseorterm.=$searchterm[$i];
221                 $searchterms.=$searchtype.": \'".$searchterm[$i]."\'";
222                 }
223         }
224 }
225
226 # Spellchecck stuff ... needs to use above scheme but must change
227 # cgi script first
228 my $phrases = $query->param('value');
229 #my $searchterms = $query->param('value');
230 # warn "here is searchterms:".$searchterms;
231
232 # FIXME: should be obvious ;-)
233 #foreach my $phrases (@spphrases) {
234 $phrases =~ s/(\.|\?|\:|\!|\'|,|\-|\"|\(|\)|\[|\]|\{|\})/ /g;
235 $phrases =~ s/(\Athe |\Aa |\Aan |)//g;
236 my $spchkphraseorterm = $phraseorterm;
237         $spchkphraseorterm =~ tr/A-Z/a-z/;
238         $spchkphraseorterm =~ s/(\.|\?|\:|\!|\'|,|\-|\"|\(|\)|\[|\]|\{|\})/ /g;
239         $spchkphraseorterm =~s/(\Aand-or |\Aand\/or |\Aanon |\Aan |\Aa |\Abut |\Aby |\Ade |\Ader |\Adr |\Adu|et |\Afor |\Afrom |\Ain |\Ainto |\Ait |\Amy |\Anot |\Aon |\Aor |\Aper |\Apt |\Aspp |\Ato |\Avs |\Awith |\Athe )/ /g;
240         $spchkphraseorterm =~s/( and-or | and\/or | anon | an | a | but | by | de | der | dr | du|et | for | from | in | into | it | my | not | on | or | per | pt | spp | to | vs | with | the )/ /g;
241  
242         $spchkphraseorterm =~s/  / /g;
243 my $resultcount = $total;
244 my $ipaddress = $query->remote_host();
245 #
246
247 if (
248 #need to create a table to record the search info
249 #...FIXME: add the script name that creates the table
250
251 my $dbhpop=DBI->connect("DBI:mysql:demosuggest:localhost","auth","YourPass")) {
252
253 # insert the search info query
254 my $insertpop = "INSERT INTO phrase_log(phr_phrase,phr_resultcount,phr_ip) VALUES(?,?,?)";
255
256 # grab spelling suggestions query
257 my $getsugg = "SELECT display FROM spellcheck WHERE strcmp(soundex(suggestion), soundex(?)) = 0 order by soundex(suggestion) limit 0,5";
258
259 #get spelling suggestions when there are no results
260 if ($resultcount eq 0) {
261         my $sthgetsugg=$dbhpop->prepare($getsugg);
262         $sthgetsugg->execute($spchkphraseorterm);
263         while (my ($spsuggestion)=$sthgetsugg->fetchrow_array) {
264 #               warn "==>$spsuggestion";
265                 #push @spsuggest, +{ spsuggestion => $spsuggestion };
266                 my %line;
267                 $line{spsuggestion} = $spsuggestion;
268                 push @spsuggest,\%line;
269                 $suggest = 1;
270         }
271 #       warn "==>".$#spsuggest;
272         $sthgetsugg->finish;
273 }
274 # end of spelling suggestions
275
276 my $sthpop=$dbhpop->prepare($insertpop);
277
278 #$sthpop->execute($phrases,$resultcount,$ipaddress);
279 $sthpop->finish;
280 }
281 #
282 ### end of tracking stuff  --  jmf at kados dot org
283 #
284 $template->param(suggest => $suggest );
285 $template->param( SPELL_SUGGEST => \@spsuggest );
286 $template->param( searchterms => $searchterms );
287 $template->param( phraseorterm => $phraseorterm );
288 #warn "here's the search terms: ".$searchterms;
289 #
290 ### end of spelling suggestions
291 ### /Added by JF
292
293         for(my $i = 0 ; $i <= $#marclist ; $i++)
294         {
295                 push @field_data, { term => "marclist", val=>$marclist[$i] };
296                 push @field_data, { term => "and_or", val=>$and_or[$i] };
297                 push @field_data, { term => "excluding", val=>$excluding[$i] };
298                 push @field_data, { term => "operator", val=>$operator[$i] };
299                 push @field_data, { term => "value", val=>$value[$i] };
300         }
301
302         my @numbers = ();
303
304         if ($total>$resultsperpage)
305         {
306                 for (my $i=1; $i<$total/$resultsperpage+1; $i++)
307                 {
308                         if ($i<16)
309                         {
310                         my $highlight=0;
311                         ($startfrom==($i-1)) && ($highlight=1);
312                         push @numbers, { number => $i,
313                                         highlight => $highlight ,
314                                         searchdata=> \@field_data,
315                                         startfrom => ($i-1)};
316                         }
317         }
318         }
319
320         my $from = $startfrom*$resultsperpage+1;
321         my $to;
322
323         if($total < (($startfrom+1)*$resultsperpage))
324         {
325                 $to = $total;
326         } else {
327                 $to = (($startfrom+1)*$resultsperpage);
328         }
329         my $defaultview = 'BiblioDefaultView'.C4::Context->preference('BiblioDefaultView');
330         $template->param(results => $results,
331                                                         startfrom=> $startfrom,
332                                                         displaynext=> $displaynext,
333                                                         displayprev=> $displayprev,
334                                                         resultsperpage => $resultsperpage,
335                                                         orderby => $orderby,
336                                                         startfromnext => $startfrom+1,
337                                                         startfromprev => $startfrom-1,
338                                                         searchdata=>\@field_data,
339                                                         total=>$total,
340                                                         from=>$from,
341                                                         to=>$to,
342                                                         numbers=>\@numbers,
343                                                         searchdesc=> $searchdesc,
344                                                         $defaultview => 1,
345                                                         suggestion => C4::Context->preference("suggestion"),
346                                                         virtualshelves => C4::Context->preference("virtualshelves"),
347                 itemtypelist => $itemtypelist,
348               subcategorylist => $subcategorylist,
349               brancheslist => $brancheslist,
350               categorylist => $categorylist,
351               mediatypelist => $mediatypelist,
352               itemtypesstring => $itemtypesstring,
353                                                         );
354
355 } else {
356         ($template, $loggedinuser, $cookie)
357                 = get_template_and_user({template_name => "opac-search.tmpl",
358                                         query => $query,
359                                         type => "opac",
360                                         authnotrequired => 1,
361                                 });
362         
363         
364         $sth=$dbh->prepare("Select itemtype,description from itemtypes order by description");
365         $sth->execute;
366         my  @itemtype;
367         my %itemtypes;
368         push @itemtype, "";
369         $itemtypes{''} = "";
370         while (my ($value,$lib) = $sth->fetchrow_array) {
371                 push @itemtype, $value;
372                 $itemtypes{$value}=$lib;
373         }
374         
375         my $CGIitemtype=CGI::scrolling_list( -name     => 'value',
376                                 -values   => \@itemtype,
377                                 -labels   => \%itemtypes,
378                                 -size     => 1,
379                                 -multiple => 0 );
380         $sth->finish;
381         
382         my @branches;
383         my @select_branch;
384         my %select_branches;
385         my ($count2,@branches)=branches();
386         push @select_branch, "";
387         $select_branches{''} = "";
388         for (my $i=0;$i<$count2;$i++){
389                 push @select_branch, $branches[$i]->{'branchcode'};#
390                 $select_branches{$branches[$i]->{'branchcode'}} = $branches[$i]->{'branchname'};
391         }
392         my $CGIbranch=CGI::scrolling_list( -name     => 'value',
393                                 -values   => \@select_branch,
394                                 -labels   => \%select_branches,
395                                 -size     => 1,
396                                 -multiple => 0 );
397         $sth->finish;
398     
399         $template->param(itemtypelist => $itemtypelist,
400                                         CGIitemtype => $CGIitemtype,
401                                         CGIbranch => $CGIbranch,
402                                         suggestion => C4::Context->preference("suggestion"),
403                                         virtualshelves => C4::Context->preference("virtualshelves"),
404         );
405 }
406 # ADDED BY JF
407 if ($totalresults == 1){
408     # if its a barcode search by definition we will only have one result.
409     # And if we have a result
410     # lets jump straight to the detail.pl page
411     print $query->redirect("/cgi-bin/koha/opac-detail.pl?bib=$firstbiblionumber");
412 }
413 else {
414   output_html_with_http_headers $query, $cookie, $template->output;
415 }