synch'ing 2.2 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 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
19 my $classlist='';
20
21 my $dbh=C4::Context->dbh;
22 my $sth=$dbh->prepare("select description,itemtype from itemtypes order by description");
23 $sth->execute;
24 while (my ($description,$itemtype) = $sth->fetchrow) {
25     $classlist.="<option value=\"$itemtype\">$description</option>\n";
26 }
27
28
29 my $query = new CGI;
30 my $op = $query->param("op");
31 my $type=$query->param('type');
32
33 my $startfrom=$query->param('startfrom');
34 $startfrom=0 if(!defined $startfrom);
35 my ($template, $loggedinuser, $cookie);
36 my $resultsperpage;
37 my $searchdesc;
38
39 if ($op eq "do_search") {
40         my @marclist = $query->param('marclist');
41         my @and_or = $query->param('and_or');
42         my @excluding = $query->param('excluding');
43         my @operator = $query->param('operator');
44         my @value = $query->param('value');
45
46         for (my $i=0;$i<=$#marclist;$i++) {
47                 if ($searchdesc) { # don't put the and_or on the 1st search term
48                         $searchdesc .= $and_or[$i]." ".$excluding[$i]." ".($marclist[$i]?$marclist[$i]:"*")." ".$operator[$i]." ".$value[$i]." " if ($value[$i]);
49                 } else {
50                         $searchdesc = $excluding[$i]." ".($marclist[$i]?$marclist[$i]:"*")." ".$operator[$i]." ".$value[$i]." " if ($value[$i]);
51                 }
52         }
53         $resultsperpage= $query->param('resultsperpage');
54         $resultsperpage = 19 if(!defined $resultsperpage);
55         my $orderby = $query->param('orderby');
56         my $desc_or_asc = $query->param('desc_or_asc');
57         # builds tag and subfield arrays
58         my @tags;
59
60         foreach my $marc (@marclist) {
61                 if ($marc) {
62                         my ($tag,$subfield) = MARCfind_marc_from_kohafield($dbh,$marc,'');
63                         if ($tag) {
64                                 push @tags,$dbh->quote("$tag$subfield");
65                         } else {
66                                 push @tags, $dbh->quote(substr($marc,0,4));
67                         }
68                 } else {
69                         push @tags, "";
70                 }
71         }
72         findseealso($dbh,\@tags);
73         my ($results,$total) = catalogsearch($dbh, \@tags,\@and_or,
74                                                                                 \@excluding, \@operator, \@value,
75                                                                                 $startfrom*$resultsperpage, $resultsperpage,$orderby,$desc_or_asc);
76         if ($total ==1) {
77         if (C4::Context->preference("BiblioDefaultView") eq "normal") {
78              print $query->redirect("/cgi-bin/koha/opac-detail.pl?bib=".@$results[0]->{biblionumber});
79         } elsif (C4::Context->preference("BiblioDefaultView") eq "MARC") {
80              print $query->redirect("/cgi-bin/koha/MARCdetail.pl?bib=".@$results[0]->{biblionumber});
81         } else {
82              print $query->redirect("/cgi-bin/koha/ISBDdetail.pl?bib=".@$results[0]->{biblionumber});
83         }
84         exit;
85         }
86         ($template, $loggedinuser, $cookie)
87                 = get_template_and_user({template_name => "opac-searchresults.tmpl",
88                                 query => $query,
89                                 type => 'opac',
90                                 authnotrequired => 1,
91                                 debug => 1,
92                                 });
93
94         # multi page display gestion
95         my $displaynext=0;
96         my $displayprev=$startfrom;
97         if(($total - (($startfrom+1)*($resultsperpage))) > 0 ){
98                 $displaynext = 1;
99         }
100
101         my @field_data = ();
102
103 ### Added by JF
104 ## This next does a number of things:
105 # 1. It allows you to track all the searches made for stats, etc.
106 # 2. It fixes the 'searchdesc' variable problem by introducing
107 #         a. 'searchterms' which comes out as 'Keyword: neal stephenson'
108 #         b. 'phraseorterm' which comes out as 'neal stephenson'
109 #      both of these are useful for differen purposes ... I use searchterms
110 #      for display purposes and phraseorterm for passing the search terms
111 #      to an external source through a url (like a database search)
112 # 3. It provides the variables necessary for the spellchecking (look below for
113 #      how this is done
114 # 4.
115
116 $totalresults = $total;
117 ## This formats the 'search results' string and populates
118 ## the 'OPLIN' variable as well as the 'spellcheck' variable
119 ## with appropriate values based on the user's search input
120
121 my $searchterms; #returned in place of searchdesc for 'results for search'
122                  # as a string (can format if need be)
123
124 my @spphrases;
125 my $phraseorterm;
126 my %searchtypehash = ( # used only for the searchterms string formation
127                         # and for spellcheck string
128         '0' => 'keyword',
129         '1' => 'title',
130         '2' => 'author',
131         '3' => 'subject',
132         '4' => 'series',
133         '5' => 'format',
134         );
135
136 my @searchterm = $query->param('value');
137
138 for (my $i=0; $i <= $#searchterm; $i++) {
139         my $searchtype = $searchtypehash{$i};
140         push @spphrases, $searchterm[$i];
141         if ($searchterms) { #don't put and in again
142                 if ($searchterm[$i]) {
143                 $phraseorterm.=$searchterm[$i];
144                 $searchterms.=" AND ".$searchtype." : \'".$searchterm[$i]."\'";
145                 }
146         } else {
147                 if ($searchterm[$i]) {
148                 $phraseorterm.=$searchterm[$i];
149                 $searchterms.=$searchtype.": \'".$searchterm[$i]."\'";
150                 }
151         }
152 }
153
154 # Spellchecck stuff ... needs to use above scheme but must change
155 # cgi script first
156 my $phrases = $query->param('value');
157 #my $searchterms = $query->param('value');
158 # warn "here is searchterms:".$searchterms;
159
160 # FIXME: should be obvious ;-)
161 #foreach my $phrases (@spphrases) {
162 $phrases =~ s/(\.|\?|\:|\!|\'|,|\-|\"|\(|\)|\[|\]|\{|\})/ /g;
163 $phrases =~ s/(\Athe |\Aa |\Aan |)//g;
164 my $spchkphraseorterm = $phraseorterm;
165         $spchkphraseorterm =~ tr/A-Z/a-z/;
166         $spchkphraseorterm =~ s/(\.|\?|\:|\!|\'|,|\-|\"|\(|\)|\[|\]|\{|\})/ /g;
167         $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;
168         $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;
169  
170         $spchkphraseorterm =~s/  / /g;
171 my $resultcount = $total;
172 my $ipaddress = $query->remote_host();
173 #
174
175 if (
176 #need to create a table to record the search info
177 #...FIXME: add the script name that creates the table
178
179 my $dbhpop=DBI->connect("DBI:mysql:demosuggest:localhost","auth","YourPass")) {
180
181 # insert the search info query
182 my $insertpop = "INSERT INTO phrase_log(phr_phrase,phr_resultcount,phr_ip) VALUES(?,?,?)";
183
184 # grab spelling suggestions query
185 my $getsugg = "SELECT display FROM spellcheck WHERE strcmp(soundex(suggestion), soundex(?)) = 0 order by soundex(suggestion) limit 0,5";
186
187 #get spelling suggestions when there are no results
188 if ($resultcount eq 0) {
189         my $sthgetsugg=$dbhpop->prepare($getsugg);
190         $sthgetsugg->execute($spchkphraseorterm);
191         while (my ($spsuggestion)=$sthgetsugg->fetchrow_array) {
192 #               warn "==>$spsuggestion";
193                 #push @spsuggest, +{ spsuggestion => $spsuggestion };
194                 my %line;
195                 $line{spsuggestion} = $spsuggestion;
196                 push @spsuggest,\%line;
197                 $suggest = 1;
198         }
199 #       warn "==>".$#spsuggest;
200         $sthgetsugg->finish;
201 }
202 # end of spelling suggestions
203
204 my $sthpop=$dbhpop->prepare($insertpop);
205
206 #$sthpop->execute($phrases,$resultcount,$ipaddress);
207 $sthpop->finish;
208 }
209 #
210 ### end of tracking stuff  --  jmf at kados dot org
211 #
212 $template->param(suggest => $suggest );
213 $template->param( SPELL_SUGGEST => \@spsuggest );
214 $template->param( searchterms => $searchterms );
215 $template->param( phraseorterm => $phraseorterm );
216 #warn "here's the search terms: ".$searchterms;
217 #
218 ### end of spelling suggestions
219 ### /Added by JF
220
221         for(my $i = 0 ; $i <= $#marclist ; $i++)
222         {
223                 push @field_data, { term => "marclist", val=>$marclist[$i] };
224                 push @field_data, { term => "and_or", val=>$and_or[$i] };
225                 push @field_data, { term => "excluding", val=>$excluding[$i] };
226                 push @field_data, { term => "operator", val=>$operator[$i] };
227                 push @field_data, { term => "value", val=>$value[$i] };
228         }
229
230         my @numbers = ();
231
232         if ($total>$resultsperpage)
233         {
234                 for (my $i=1; $i<$total/$resultsperpage+1; $i++)
235                 {
236                         if ($i<16)
237                         {
238                         my $highlight=0;
239                         ($startfrom==($i-1)) && ($highlight=1);
240                         push @numbers, { number => $i,
241                                         highlight => $highlight ,
242                                         searchdata=> \@field_data,
243                                         startfrom => ($i-1)};
244                         }
245         }
246         }
247
248         my $from = $startfrom*$resultsperpage+1;
249         my $to;
250
251         if($total < (($startfrom+1)*$resultsperpage))
252         {
253                 $to = $total;
254         } else {
255                 $to = (($startfrom+1)*$resultsperpage);
256         }
257         my $defaultview = 'BiblioDefaultView'.C4::Context->preference('BiblioDefaultView');
258         $template->param(results => $results,
259                                                         startfrom=> $startfrom,
260                                                         displaynext=> $displaynext,
261                                                         displayprev=> $displayprev,
262                                                         resultsperpage => $resultsperpage,
263                                                         orderby => $orderby,
264                                                         startfromnext => $startfrom+1,
265                                                         startfromprev => $startfrom-1,
266                                                         searchdata=>\@field_data,
267                                                         total=>$total,
268                                                         from=>$from,
269                                                         to=>$to,
270                                                         numbers=>\@numbers,
271                                                         searchdesc=> $searchdesc,
272                                                         $defaultview => 1,
273                                                         suggestion => C4::Context->preference("suggestion"),
274                                                         virtualshelves => C4::Context->preference("virtualshelves"),
275                                                         );
276
277 } else {
278         ($template, $loggedinuser, $cookie)
279                 = get_template_and_user({template_name => "opac-search.tmpl",
280                                         query => $query,
281                                         type => "opac",
282                                         authnotrequired => 1,
283                                 });
284         
285         
286         $sth=$dbh->prepare("Select itemtype,description from itemtypes order by description");
287         $sth->execute;
288         my  @itemtype;
289         my %itemtypes;
290         push @itemtype, "";
291         $itemtypes{''} = "";
292         while (my ($value,$lib) = $sth->fetchrow_array) {
293                 push @itemtype, $value;
294                 $itemtypes{$value}=$lib;
295         }
296         
297         my $CGIitemtype=CGI::scrolling_list( -name     => 'value',
298                                 -values   => \@itemtype,
299                                 -labels   => \%itemtypes,
300                                 -size     => 1,
301                                 -multiple => 0 );
302         $sth->finish;
303         
304         my @branches;
305         my @select_branch;
306         my %select_branches;
307         my ($count2,@branches)=branches();
308         push @select_branch, "";
309         $select_branches{''} = "";
310         for (my $i=0;$i<$count2;$i++){
311                 push @select_branch, $branches[$i]->{'branchcode'};#
312                 $select_branches{$branches[$i]->{'branchcode'}} = $branches[$i]->{'branchname'};
313         }
314         my $CGIbranch=CGI::scrolling_list( -name     => 'value',
315                                 -values   => \@select_branch,
316                                 -labels   => \%select_branches,
317                                 -size     => 1,
318                                 -multiple => 0 );
319         $sth->finish;
320     
321         $template->param(classlist => $classlist,
322                                         CGIitemtype => $CGIitemtype,
323                                         CGIbranch => $CGIbranch,
324                                         suggestion => C4::Context->preference("suggestion"),
325                                         virtualshelves => C4::Context->preference("virtualshelves"),
326         );
327 }
328 # ADDED BY JF
329 if ($totalresults == 1){
330     # if its a barcode search by definition we will only have one result.
331     # And if we have a result
332     # lets jump straight to the detail.pl page
333     print $query->redirect("/cgi-bin/koha/opac-detail.pl?bib=$firstbiblionumber");
334 }
335 else {
336 output_html_with_http_headers $query, $cookie, $template->output;