Sub renamed according to the coding guidelines
[koha_gimpoz] / opac / opac-search.pl
index e7c3729..00d922b 100755 (executable)
@@ -11,25 +11,65 @@ use HTML::Template;
 use C4::SearchMarc;
 use C4::Acquisition;
 use C4::Biblio;
+use C4::Koha;
 
-my $classlist='';
+my @spsuggest; # the array for holding suggestions
+my $suggest;   # a flag to be set (if there are suggestions it's 1)
+my $firstbiblionumber; # needed for directly sending user to first item
+# use C4::Search;
+my $totalresults;
+
+my $itemtypelist;
+my $brancheslist;
+my $categorylist;
+my $subcategorylist;
+my $mediatypelist;
+# added by Gavin 
+my $totalresults;
 
 my $dbh=C4::Context->dbh;
 my $sth=$dbh->prepare("select description,itemtype from itemtypes order by description");
 $sth->execute;
 while (my ($description,$itemtype) = $sth->fetchrow) {
-    $classlist.="<option value=\"$itemtype\">$description</option>\n";
+    $itemtypelist.="<option value=\"$itemtype\">$description</option>\n";
 }
+my $sth=$dbh->prepare("select description,subcategorycode from subcategorytable order by description");
+$sth->execute;
+while (my ($description,$subcategorycode) = $sth->fetchrow) {
+    $subcategorylist.="<option value=\"$subcategorycode\">$description</option>\n";
+}
+my $sth=$dbh->prepare("select description,mediatypecode from mediatypetable order by description");
+$sth->execute;
+while (my ($description,$mediatypecode) = $sth->fetchrow) {
+    $mediatypelist.="<option value=\"$mediatypecode\">$description</option>\n";
+}
+my $sth=$dbh->prepare("select description,categorycode from categorytable order by description");
+$sth->execute;
+while (my ($description,$categorycode) = $sth->fetchrow) {
+    $categorylist .= '<input type="radio" name="categorylist" value="'.$categorycode.'">'.$description.'<br>';
+}
+my $sth=$dbh->prepare("select branchname,branchcode from branches order by branchname");
+$sth->execute;
 
-
+while (my ($branchname,$branchcode) = $sth->fetchrow) {
+    $brancheslist.="<option value=\"$branchcode\">$branchname</option>\n";
+}
 my $query = new CGI;
 my $op = $query->param("op");
 my $type=$query->param('type');
+my $avail=$query->param('avail');
+my $itemtypesstring=$query->param("itemtypesstring");
+$itemtypesstring =~s/"//g;
+my @itemtypes = split ( /\|/, $itemtypesstring);
+my $branchesstring=$query->param("branchesstring");
+$branchesstring =~s/"//g;
+my @branches = split (/\|/, $branchesstring);
 
 my $startfrom=$query->param('startfrom');
 $startfrom=0 if(!defined $startfrom);
 my ($template, $loggedinuser, $cookie);
 my $resultsperpage;
+my $searchdesc;
 
 if ($op eq "do_search") {
        my @marclist = $query->param('marclist');
@@ -37,17 +77,45 @@ if ($op eq "do_search") {
        my @excluding = $query->param('excluding');
        my @operator = $query->param('operator');
        my @value = $query->param('value');
+       my $orderby = $query->param('orderby');
+       my $desc_or_asc = $query->param('desc_or_asc');
+       my $exactsearch = $query->param('exact');
+       for (my $i=0;$i<=$#marclist;$i++) {
+               if ($searchdesc) { # don't put the and_or on the 1st search term
+                       $searchdesc .= $and_or[$i].$excluding[$i]." ".($marclist[$i]?$marclist[$i]:"*").$operator[$i].$value[$i] if ($value[$i]);
+               } else {
+                       $searchdesc = $excluding[$i].($marclist[$i]?$marclist[$i]:"*").$operator[$i].$value[$i] if ($value[$i]);
+                       if ($marclist[$i] eq "biblioitems.isbn") {
+                               $value[$i] =~ s/-//g;
+                       }
+               }
+       }
+  if ($itemtypesstring ne ''){
+    $searchdesc .= 'filtered by itemtypes ';
+    $searchdesc .= join(" ",@itemtypes)
+  }
 
+  if ($branchesstring ne ''){
+    $searchdesc .= ' in branches ';
+    $searchdesc .= join(" ",@branches)
+  }
+  if ($avail ne ''){
+    $searchdesc .= '. Only available items shown.'
+  }
        $resultsperpage= $query->param('resultsperpage');
        $resultsperpage = 19 if(!defined $resultsperpage);
-       my $orderby = $query->param('orderby');
-
+       
+       if ($exactsearch) {
+               foreach (@operator) {
+                       $_='=';
+               }
+       }
        # builds tag and subfield arrays
        my @tags;
 
        foreach my $marc (@marclist) {
                if ($marc) {
-                       my ($tag,$subfield) = MARCfind_marc_from_kohafield($dbh,$marc);
+                       my ($tag,$subfield) = MARCfind_marc_from_kohafield($dbh,$marc,'');
                        if ($tag) {
                                push @tags,$dbh->quote("$tag$subfield");
                        } else {
@@ -58,10 +126,54 @@ if ($op eq "do_search") {
                }
        }
        findseealso($dbh,\@tags);
+    my $sqlstring;
+    my $extratables;
+    if ($itemtypesstring ne ''){
+        $sqlstring = 'and (biblioitems.itemtype IN (';
+        my $itemtypeloop=0;
+        foreach my $itemtype (@itemtypes){
+            if ($itemtype ne ''){
+                if ($itemtypeloop != 0){
+                    $sqlstring .=','
+                }
+                $sqlstring .= '"'.$itemtype.'"';
+                $itemtypeloop++;
+            }
+        }
+        $sqlstring .= '))'
+    }
+    if ($branchesstring ne ''){
+        $sqlstring .= 'and biblio.biblionumber=items.biblionumber and (items.holdingbranch IN (';
+        my $branchesloop=0;
+        $extratables = ',items';
+        foreach my $branch (@branches){
+            if ($branch ne ''){
+                if ($branchesloop != 0){
+                    $sqlstring .=','
+                }
+                $sqlstring .= '"'.$branch.'"';
+                $branchesloop++;
+            }
+        }
+        $sqlstring .= '))'
+    }
+  if ($avail){
+       $extratables .= ',items,issues,reserves';
+    $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) ";
+  }
        my ($results,$total) = catalogsearch($dbh, \@tags,\@and_or,
                                                                                \@excluding, \@operator, \@value,
-                                                                               $startfrom*$resultsperpage, $resultsperpage,$orderby);
-
+                                                                               $startfrom*$resultsperpage, $resultsperpage,$orderby,$desc_or_asc);
+       if ($total ==1) {
+       if (C4::Context->preference("BiblioDefaultView") eq "normal") {
+            print $query->redirect("/cgi-bin/koha/opac-detail.pl?bib=".@$results[0]->{biblionumber});
+       } elsif (C4::Context->preference("BiblioDefaultView") eq "marc") {
+            print $query->redirect("/cgi-bin/koha/opac-MARCdetail.pl?bib=".@$results[0]->{biblionumber});
+       } else {
+            print $query->redirect("/cgi-bin/koha/opac-ISBDdetail.pl?bib=".@$results[0]->{biblionumber});
+       }
+       exit;
+       }
        ($template, $loggedinuser, $cookie)
                = get_template_and_user({template_name => "opac-searchresults.tmpl",
                                query => $query,
@@ -79,6 +191,124 @@ if ($op eq "do_search") {
 
        my @field_data = ();
 
+### Added by JF
+## This next does a number of things:
+# 1. It allows you to track all the searches made for stats, etc.
+# 2. It fixes the 'searchdesc' variable problem by introducing
+#         a. 'searchterms' which comes out as 'Keyword: neal stephenson'
+#         b. 'phraseorterm' which comes out as 'neal stephenson'
+#      both of these are useful for differen purposes ... I use searchterms
+#      for display purposes and phraseorterm for passing the search terms
+#      to an external source through a url (like a database search)
+# 3. It provides the variables necessary for the spellchecking (look below for
+#      how this is done
+# 4.
+$totalresults = $total;
+
+## This formats the 'search results' string and populates
+## the 'OPLIN' variable as well as the 'spellcheck' variable
+## with appropriate values based on the user's search input
+
+my $searchterms; #returned in place of searchdesc for 'results for search'
+                 # as a string (can format if need be)
+
+my @spphrases;
+my $phraseorterm;
+my %searchtypehash = ( # used only for the searchterms string formation
+                        # and for spellcheck string
+        '0' => 'keyword',
+        '1' => 'title',
+        '2' => 'author',
+        '3' => 'subject',
+        '4' => 'series',
+        '5' => 'format',
+        );
+
+my @searchterm = $query->param('value');
+
+for (my $i=0; $i <= $#searchterm; $i++) {
+        my $searchtype = $searchtypehash{$i};
+        push @spphrases, $searchterm[$i];
+        if ($searchterms) { #don't put and in again
+                if ($searchterm[$i]) {
+                $phraseorterm.=$searchterm[$i];
+                $searchterms.=" AND ".$searchtype." : \'".$searchterm[$i]."\'";
+                }
+        } else {
+                if ($searchterm[$i]) {
+                $phraseorterm.=$searchterm[$i];
+                $searchterms.=$searchtype.": \'".$searchterm[$i]."\'";
+                }
+        }
+}
+
+# Spellchecck stuff ... needs to use above scheme but must change
+# cgi script first
+my $phrases = $query->param('value');
+#my $searchterms = $query->param('value');
+# warn "here is searchterms:".$searchterms;
+
+# FIXME: should be obvious ;-)
+#foreach my $phrases (@spphrases) {
+$phrases =~ s/(\.|\?|\:|\!|\'|,|\-|\"|\(|\)|\[|\]|\{|\})/ /g;
+$phrases =~ s/(\Athe |\Aa |\Aan |)//g;
+my $spchkphraseorterm = $phraseorterm;
+        $spchkphraseorterm =~ tr/A-Z/a-z/;
+        $spchkphraseorterm =~ s/(\.|\?|\:|\!|\'|,|\-|\"|\(|\)|\[|\]|\{|\})/ /g;
+        $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;
+        $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;
+        $spchkphraseorterm =~s/  / /g;
+my $resultcount = $total;
+my $ipaddress = $query->remote_host();
+#
+
+if (
+#need to create a table to record the search info
+#...FIXME: add the script name that creates the table
+# 
+my $dbhpop=DBI->connect("DBI:mysql:demosuggest:localhost","auth","YourPass")) {
+
+# insert the search info query
+my $insertpop = "INSERT INTO phrase_log(phr_phrase,phr_resultcount,phr_ip) VALUES(?,?,?)";
+
+# grab spelling suggestions query
+my $getsugg = "SELECT display FROM spellcheck WHERE strcmp(soundex(suggestion), soundex(?)) = 0 order by soundex(suggestion) limit 0,5";
+
+#get spelling suggestions when there are no results
+if ($resultcount eq 0) {
+        my $sthgetsugg=$dbhpop->prepare($getsugg);
+        $sthgetsugg->execute($spchkphraseorterm);
+        while (my ($spsuggestion)=$sthgetsugg->fetchrow_array) {
+#               warn "==>$spsuggestion";
+                #push @spsuggest, +{ spsuggestion => $spsuggestion };
+                my %line;
+                $line{spsuggestion} = $spsuggestion;
+                push @spsuggest,\%line;
+                $suggest = 1;
+        }
+#       warn "==>".$#spsuggest;
+        $sthgetsugg->finish;
+}
+# end of spelling suggestions
+
+my $sthpop=$dbhpop->prepare($insertpop);
+
+#$sthpop->execute($phrases,$resultcount,$ipaddress);
+$sthpop->finish;
+}
+#
+### end of tracking stuff  --  jmf at kados dot org
+#
+$template->param(suggest => $suggest );
+$template->param( SPELL_SUGGEST => \@spsuggest );
+$template->param( searchterms => $searchterms );
+$template->param( phraseorterm => $phraseorterm );
+#warn "here's the search terms: ".$searchterms;
+#
+### end of spelling suggestions
+### /Added by JF
 
        for(my $i = 0 ; $i <= $#marclist ; $i++)
        {
@@ -88,7 +318,8 @@ if ($op eq "do_search") {
                push @field_data, { term => "operator", val=>$operator[$i] };
                push @field_data, { term => "value", val=>$value[$i] };
        }
-
+       push @field_data, {term => "desc_or_asc", val => $desc_or_asc} if $desc_or_asc;
+       push @field_data, {term => "orderby", val => $orderby} if $orderby;
        my @numbers = ();
 
        if ($total>$resultsperpage)
@@ -116,6 +347,7 @@ if ($op eq "do_search") {
        } else {
                $to = (($startfrom+1)*$resultsperpage);
        }
+       my $defaultview = 'BiblioDefaultView'.C4::Context->preference('BiblioDefaultView');
        $template->param(results => $results,
                                                        startfrom=> $startfrom,
                                                        displaynext=> $displaynext,
@@ -129,6 +361,10 @@ if ($op eq "do_search") {
                                                        from=>$from,
                                                        to=>$to,
                                                        numbers=>\@numbers,
+                                                       searchdesc=> $searchdesc,
+                                                       $defaultview => 1,
+                                                       suggestion => C4::Context->preference("suggestion"),
+                                                       virtualshelves => C4::Context->preference("virtualshelves"),
                                                        );
 
 } else {
@@ -140,33 +376,43 @@ if ($op eq "do_search") {
                                });
        
        
-       $sth=$dbh->prepare("Select itemtype,description from itemtypes order by description");
+       my $query="Select itemtype,description from itemtypes order by description";
+       my $sth=$dbh->prepare($query);
        $sth->execute;
-       my  @itemtype;
+       my  @itemtypeloop;
        my %itemtypes;
-       push @itemtype, "";
-       $itemtypes{''} = "";
        while (my ($value,$lib) = $sth->fetchrow_array) {
-               push @itemtype, $value;
-               $itemtypes{$value}=$lib;
+               my %row =(      value => $value,
+                                       description => $lib,
+                               );
+               push @itemtypeloop, \%row;
        }
-       
-       my $CGIitemtype=CGI::scrolling_list( -name     => 'value',
-                               -values   => \@itemtype,
-                               -labels   => \%itemtypes,
+       $sth->finish;
+
+       my @oldbranches;
+       my @oldselect_branch;
+       my %oldselect_branches;
+       my ($oldcount2,@oldbranches)=branches();
+       push @oldselect_branch, "";
+       $oldselect_branches{''} = "";
+       for (my $i=0;$i<$oldcount2;$i++){
+               push @oldselect_branch, $oldbranches[$i]->{'branchcode'};#
+               $oldselect_branches{$oldbranches[$i]->{'branchcode'}} = $oldbranches[$i]->{'branchname'};
+       }
+       my $CGIbranch=CGI::scrolling_list( -name     => 'value',
+                               -values   => \@oldselect_branch,
+                               -labels   => \%oldselect_branches,
                                -size     => 1,
                                -multiple => 0 );
        $sth->finish;
-       
-       my @branches;
        my @select_branch;
        my %select_branches;
-       my ($count2,@branches)=branches();
+       my $branches=getbranches();
        push @select_branch, "";
        $select_branches{''} = "";
-       for (my $i=0;$i<$count2;$i++){
-               push @select_branch, $branches[$i]->{'branchcode'};#
-               $select_branches{$branches[$i]->{'branchcode'}} = $branches[$i]->{'branchname'};
+        foreach my $branch ( keys %$branches ){
+               push @select_branch, $branches->{$branch}->{'branchcode'};
+               $select_branches{$branches->{$branch}->{'branchcode'}} = $branches->{$branch}->{'branchname'};
        }
        my $CGIbranch=CGI::scrolling_list( -name     => 'value',
                                -values   => \@select_branch,
@@ -174,11 +420,31 @@ if ($op eq "do_search") {
                                -size     => 1,
                                -multiple => 0 );
        $sth->finish;
-       
-       $template->param(classlist => $classlist,
-                                       CGIitemtype => $CGIitemtype,
+    
+       $template->param('Disable_Dictionary'=>C4::Context->preference("Disable_Dictionary")) if (C4::Context->preference("Disable_Dictionary"));
+       $template->param(
+           
+# CHRIS : Whats this?      
+#          classlist => $classlist,
                                        CGIbranch => $CGIbranch,
+                                       suggestion => C4::Context->preference("suggestion"),
+                                       virtualshelves => C4::Context->preference("virtualshelves"),
+                                       LibraryName => C4::Context->preference("LibraryName"),
+                                       OpacNav => C4::Context->preference("OpacNav"),
+                                       opaccredits => C4::Context->preference("opaccredits"),
+                                       AmazonContent => C4::Context->preference("AmazonContent"),
+                               opacsmallimage => C4::Context->preference("opacsmallimage"),
+                               opaclayoutstylesheet => C4::Context->preference("opaclayoutstylesheet"),
+                               opaccolorstylesheet => C4::Context->preference("opaccolorstylesheet"),
        );
 }
-
-output_html_with_http_headers $query, $cookie, $template->output;
+# ADDED BY JF
+if ($totalresults == 1){
+    # if its a barcode search by definition we will only have one result.
+    # And if we have a result
+    # lets jump straight to the detail.pl page
+    print $query->redirect("/cgi-bin/koha/opac-detail.pl?bib=$firstbiblionumber");
+}
+else {
+  output_html_with_http_headers $query, $cookie, $template->output;
+}