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