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