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