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