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