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