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