serials : lot of bugfixes.
[koha.git] / C4 / SearchMarc.pm
1 package C4::SearchMarc;
2
3 # Copyright 2000-2002 Katipo Communications
4 #
5 # This file is part of Koha.
6 #
7 # Koha is free software; you can redistribute it and/or modify it under the
8 # terms of the GNU General Public License as published by the Free Software
9 # Foundation; either version 2 of the License, or (at your option) any later
10 # version.
11 #
12 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
13 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
14 # A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
15 #
16 # You should have received a copy of the GNU General Public License along with
17 # Koha; if not, write to the Free Software Foundation, Inc., 59 Temple Place,
18 # Suite 330, Boston, MA  02111-1307 USA
19
20 use strict;
21 require Exporter;
22 use DBI;
23 use C4::Context;
24 use C4::Biblio;
25
26 use vars qw($VERSION @ISA @EXPORT @EXPORT_OK %EXPORT_TAGS);
27
28 # set the version for version checking
29 $VERSION = 0.02;
30
31 =head1 NAME
32
33 C4::Search - Functions for searching the Koha MARC catalog
34
35 =head1 SYNOPSIS
36
37   use C4::Search;
38
39   my ($count, @results) = catalogsearch();
40
41 =head1 DESCRIPTION
42
43 This module provides the searching facilities for the Koha MARC catalog
44
45 C<&catalogsearch> is a front end to all the other searches. Depending
46 on what is passed to it, it calls the appropriate search function.
47
48 =head1 FUNCTIONS
49
50 =over 2
51
52 =cut
53
54 @ISA = qw(Exporter);
55 @EXPORT = qw(&catalogsearch &findseealso &findsuggestion);
56
57 # make all your functions, whether exported or not;
58
59 sub findsuggestion {
60         my ($dbh,$values) = @_;
61         my $sth = $dbh->prepare("SELECT count( * ) AS total, word FROM marc_word WHERE sndx_word = soundex( ? ) AND word <> ? GROUP BY word ORDER BY total DESC");
62         my @results;
63         for(my $i = 0 ; $i <= $#{$values} ; $i++) {
64                 if (length(@$values[$i]) >=5) {
65                         $sth->execute(@$values[$i],@$values[$i]);
66                         my $resfound = 1;
67                         my @resline;
68                         while ((my ($count,$word) = $sth->fetchrow) and $resfound <=10) {
69                                 push @results, "@$values[$i]|$word|$count";
70 #                               $results{@$values[$i]} = \@resline;
71                                 $resfound++;
72                         }
73                 }
74         }
75         return \@results;
76 }
77 sub findseealso {
78         my ($dbh, $fields) = @_;
79         my $tagslib = MARCgettagslib ($dbh,1);
80         for (my $i=0;$i<=$#{$fields};$i++) {
81                 my ($tag) =substr(@$fields[$i],1,3);
82                 my ($subfield) =substr(@$fields[$i],4,1);
83                 @$fields[$i].=','.$tagslib->{$tag}->{$subfield}->{seealso} if ($tagslib->{$tag}->{$subfield}->{seealso});
84         }
85 }
86
87 # marcsearch : search in the MARC biblio table.
88 # everything is choosen by the user : what to search, the conditions...
89
90 sub catalogsearch {
91         my ($dbh, $tags, $and_or, $excluding, $operator, $value, $offset,$length,$orderby) = @_;
92         # build the sql request. She will look like :
93         # select m1.bibid
94         #               from marc_subfield_table as m1, marc_subfield_table as m2
95         #               where m1.bibid=m2.bibid and
96         #               (m1.subfieldvalue like "Des%" and m2.subfieldvalue like "27%")
97
98         # last minute stripping out of stuff
99         # doesn't work @$value =~ s/\'/ /;
100         # @$value = map { $_ =~ s/\'/ /g } @$value;
101         
102         # "Normal" statements
103         my @normal_tags = ();
104         my @normal_and_or = ();
105         my @normal_operator = ();
106         my @normal_value = ();
107         # Extracts the NOT statements from the list of statements
108         my @not_tags = ();
109         my @not_and_or = ();
110         my @not_operator = ();
111         my @not_value = ();
112         my $any_not = 0;
113         $orderby = "biblio.title" unless $orderby;
114         
115         #last minute stripping out of ' and ,
116         foreach $_ (@$value) {
117         $_=~ s/\'/ /g;
118         $_=~ s/\,/ /g;
119         }
120         
121         for(my $i = 0 ; $i <= $#{$value} ; $i++)
122         {
123                 # replace * by %
124                 @$value[$i] =~ s/\*/%/g;
125                 # remove % at the beginning
126                 @$value[$i] =~ s/^%//g;
127                 if(@$excluding[$i])     # NOT statements
128                 {
129                         $any_not = 1;
130                         if(@$operator[$i] eq "contains")
131                         {
132                                 foreach my $word (split(/ /, @$value[$i]))      # if operator is contains, splits the words in separate requests
133                                 {
134                                         # remove the "%" for small word (3 letters. (note : the >4 is due to the % at the end)
135                                         warn "word : $word";
136                                         $word =~ s/%//g unless length($word)>4;
137                                         unless (C4::Context->stopwords->{uc($word)}) {  #it's NOT a stopword => use it. Otherwise, ignore
138                                                 push @not_tags, @$tags[$i];
139                                                 push @not_and_or, "or"; # as request is negated, finds "foo" or "bar" if final request is NOT "foo" and "bar"
140                                                 push @not_operator, @$operator[$i];
141                                                 push @not_value, $word;
142                                         }
143                                 }
144                         }
145                         else
146                         {
147                                 push @not_tags, @$tags[$i];
148                                 push @not_and_or, "or"; # as request is negated, finds "foo" or "bar" if final request is NOT "foo" and "bar"
149                                 push @not_operator, @$operator[$i];
150                                 push @not_value, @$value[$i];
151                         }
152                 }
153                 else    # NORMAL statements
154                 {
155                         if(@$operator[$i] eq "contains") # if operator is contains, splits the words in separate requests
156                         {
157                                 foreach my $word (split(/ /, @$value[$i]))
158                                 {
159                                         # remove the "%" for small word (3 letters. (note : the >4 is due to the % at the end)
160                                         warn "word : $word";
161                                         $word =~ s/%//g unless length($word)>4;
162                                         unless (C4::Context->stopwords->{uc($word)}) {  #it's NOT a stopword => use it. Otherwise, ignore
163                                                 my $tag = substr(@$tags[$i],0,3);
164                                                 my $subf = substr(@$tags[$i],3,1);
165                                                 push @normal_tags, @$tags[$i];
166                                                 push @normal_and_or, "and";     # assumes "foo" and "bar" if "foo bar" is entered
167                                                 push @normal_operator, @$operator[$i];
168                                                 push @normal_value, $word;
169                                         }
170                                 }
171                         }
172                         else
173                         {
174                                 push @normal_tags, @$tags[$i];
175                                 push @normal_and_or, @$and_or[$i];
176                                 push @normal_operator, @$operator[$i];
177                                 push @normal_value, @$value[$i];
178                         }
179                 }
180         }
181
182         # Finds the basic results without the NOT requests
183         my ($sql_tables, $sql_where1, $sql_where2) = create_request($dbh,\@normal_tags, \@normal_and_or, \@normal_operator, \@normal_value);
184
185         my $sth;
186         if ($sql_where2) {
187                 $sth = $dbh->prepare("select distinct m1.bibid from biblio,biblioitems,marc_biblio,$sql_tables where biblio.biblionumber=marc_biblio.biblionumber and biblio.biblionumber=biblioitems.biblionumber and m1.bibid=marc_biblio.bibid and $sql_where2 and ($sql_where1) order by $orderby");
188                 warn "Q2 : select distinct m1.bibid from biblio,biblioitems,marc_biblio,$sql_tables where biblio.biblionumber=marc_biblio.biblionumber and biblio.biblionumber=biblioitems.biblionumber and m1.bibid=marc_biblio.bibid and $sql_where2 and ($sql_where1) order by $orderby term is  @$value";
189         } else {
190                 $sth = $dbh->prepare("select distinct m1.bibid from biblio,biblioitems,marc_biblio,$sql_tables where biblio.biblionumber=marc_biblio.biblionumber and biblio.biblionumber=biblioitems.biblionumber and m1.bibid=marc_biblio.bibid and $sql_where1 order by $orderby");
191                 warn "Q : select distinct m1.bibid from biblio,biblioitems,marc_biblio,$sql_tables where biblio.biblionumber=marc_biblio.biblionumber and biblio.biblionumber=biblioitems.biblionumber and m1.bibid=marc_biblio.bibid and $sql_where1 order by $orderby";
192         }
193         $sth->execute();
194         my @result = ();
195
196         # Processes the NOT if any and there are results
197         my ($not_sql_tables, $not_sql_where1, $not_sql_where2);
198
199         if( ($sth->rows) && $any_not )  # some results to tune up and some NOT statements
200         {
201                 ($not_sql_tables, $not_sql_where1, $not_sql_where2) = create_request($dbh,\@not_tags, \@not_and_or, \@not_operator, \@not_value);
202
203                 my @tmpresult;
204
205                 while (my ($bibid) = $sth->fetchrow) {
206                         push @tmpresult,$bibid;
207                 }
208                 my $sth_not;
209                 warn "NOT : select distinct m1.bibid from $not_sql_tables where $not_sql_where2 and ($not_sql_where1)";
210                 if ($not_sql_where2) {
211                         $sth_not = $dbh->prepare("select distinct m1.bibid from $not_sql_tables where $not_sql_where2 and ($not_sql_where1)");
212                 } else {
213                         $sth_not = $dbh->prepare("select distinct m1.bibid from $not_sql_tables where $not_sql_where1");
214                 }
215                 $sth_not->execute();
216
217                 if($sth_not->rows)
218                 {
219                         my %not_bibids = ();
220                         while(my $bibid = $sth_not->fetchrow()) {
221                                 $not_bibids{$bibid} = 1;        # populates the hashtable with the bibids matching the NOT statement
222                         }
223
224                         foreach my $bibid (@tmpresult)
225                         {
226                                 if(!$not_bibids{$bibid})
227                                 {
228                                         push @result, $bibid;
229                                 }
230                         }
231                 }
232                 $sth_not->finish();
233         }
234         else    # no NOT statements
235         {
236                 while (my ($bibid) = $sth->fetchrow) {
237                         push @result,$bibid;
238                 }
239         }
240
241         # we have bibid list. Now, loads title and author from [offset] to [offset]+[length]
242         my $counter = $offset;
243         $sth = $dbh->prepare("SELECT biblio.*, biblioitems.*, items.*,marc_biblio.bibid
244                                                         FROM biblio, marc_biblio 
245                                                         LEFT JOIN items on items.biblionumber = biblio.biblionumber
246                                                         LEFT JOIN biblioitems on biblio.biblionumber = biblioitems.biblionumber
247                                                         WHERE biblio.biblionumber = marc_biblio.biblionumber AND bibid = ?
248                                                         GROUP BY items.biblionumber, items.holdingbranch, items.itemcallnumber");
249         my @finalresult = ();
250         my @CNresults=();
251         my $oldbiblionumber=0;
252         my $totalitems=0;
253         my $oldline;
254 #       my ($biblionumber,$author,$title,$holdingbranch, $itemcallnumber, $bibid);
255         my ($oldbibid, $oldauthor, $oldtitle,$oldbiblionumber);
256         while (($counter <= $#result) && ($counter <= ($offset + $length))) {
257                 $sth->execute($result[$counter]);
258                 while (my $line = $sth->fetchrow_hashref) {
259                         # parse the result, putting holdingbranch & itemcallnumber in separate array
260                         # then all other fields in the main array
261                         if ($oldbiblionumber && ($oldbiblionumber ne $line->{biblionumber})) {
262                                 my %newline;
263                                 %newline = %$oldline;
264                                 $newline{totitem} = $totalitems;
265                                 $newline{biblionumber} = $oldbiblionumber;
266                                 my @CNresults2= @CNresults;
267                                 $newline{CN} = \@CNresults2;
268                             $newline{'even'} = 1 if $#finalresult % 2 == 0;
269                                 $newline{'odd'} = 1 if $#finalresult % 2 == 1;
270                                 @CNresults = ();
271                                 push @finalresult, \%newline;
272                                 $totalitems=0;
273                         }
274                         $oldbiblionumber = $line->{biblionumber};
275                         $totalitems++ if ($line->{holdingbranch});
276                         $oldline = $line;
277                         # item callnumber & branch
278                         my %lineCN;
279                         $lineCN{holdingbranch} = $line->{holdingbranch};
280                         $lineCN{itemcallnumber} = $line->{itemcallnumber};
281                         push @CNresults,\%lineCN;
282                 }
283                 $counter++;
284         }
285 # add the last line, that is not reached byt the loop / if ($oldbiblionumber...)
286         my %newline;
287         if ($oldline) {
288                 %newline = %$oldline;
289                 $newline{totitem} = $totalitems;
290                 $newline{biblionumber} = $oldbiblionumber;
291                 my @CNresults2= @CNresults;
292                 $newline{CN} = \@CNresults2;
293                 $newline{'even'} = 1 if $counter % 2 == 0;
294                 $newline{'odd'} = 1 if $counter % 2 == 1;
295                 @CNresults = ();
296                 my @CNresults2= @CNresults;
297                 $newline{CN} = \@CNresults2;
298                 @CNresults = ();
299                 push @finalresult, \%newline;
300         }
301         my $nbresults = $#result + 1;
302         return (\@finalresult, $nbresults);
303 }
304
305 # Creates the SQL Request
306
307 sub create_request {
308         my ($dbh,$tags, $and_or, $operator, $value) = @_;
309
310         my $sql_tables; # will contain marc_subfield_table as m1,...
311         my $sql_where1; # will contain the "true" where
312         my $sql_where2 = "("; # will contain m1.bibid=m2.bibid
313         my $nb_active=0; # will contain the number of "active" entries. an entry is active if a value is provided.
314         my $nb_table=1; # will contain the number of table. ++ on each entry EXCEPT when an OR  is provided.
315
316         for(my $i=0; $i<=@$value;$i++) {
317                 if (@$value[$i]) {
318                         $nb_active++;
319                         if ($nb_active==1) {
320                                 if (@$operator[$i] eq "start") {
321                                         $sql_tables .= "marc_subfield_table as m$nb_table,";
322                                         $sql_where1 .= "(m1.subfieldvalue like ".$dbh->quote("@$value[$i]");
323                                         if (@$tags[$i]) {
324                                                 $sql_where1 .=" and m1.tag+m1.subfieldcode in (@$tags[$i])";
325                                         }
326                                         $sql_where1.=")";
327                                 } elsif (@$operator[$i] eq "contains") {
328                                         $sql_tables .= "marc_word as m$nb_table,";
329                                         $sql_where1 .= "(m1.word  like ".$dbh->quote("@$value[$i]");
330                                         if (@$tags[$i]) {
331                                                  $sql_where1 .=" and m1.tagsubfield in (@$tags[$i])";
332                                         }
333                                         $sql_where1.=")";
334                                 } else {
335                                         $sql_tables .= "marc_subfield_table as m$nb_table,";
336                                         $sql_where1 .= "(m1.subfieldvalue @$operator[$i] ".$dbh->quote("@$value[$i]");
337                                         if (@$tags[$i]) {
338                                                  $sql_where1 .=" and m1.tag+m1.subfieldcode in (@$tags[$i])";
339                                         }
340                                         $sql_where1.=")";
341                                 }
342                         } else {
343                                 if (@$operator[$i] eq "start") {
344                                         $nb_table++;
345                                         $sql_tables .= "marc_subfield_table as m$nb_table,";
346                                         $sql_where1 .= "@$and_or[$i] (m$nb_table.subfieldvalue like ".$dbh->quote("@$value[$i]");
347                                         if (@$tags[$i]) {
348                                                 $sql_where1 .=" and m$nb_table.tag+m$nb_table.subfieldcode in (@$tags[$i])";
349                                         }
350                                         $sql_where1.=")";
351                                         $sql_where2 .= "m1.bibid=m$nb_table.bibid and ";
352                                 } elsif (@$operator[$i] eq "contains") {
353                                         if (@$and_or[$i] eq 'and') {
354                                                 $nb_table++;
355                                                 $sql_tables .= "marc_word as m$nb_table,";
356                                                 $sql_where1 .= "@$and_or[$i] (m$nb_table.word like ".$dbh->quote("@$value[$i]");
357                                                 if (@$tags[$i]) {
358                                                         $sql_where1 .=" and m$nb_table.tagsubfield in(@$tags[$i])";
359                                                 }
360                                                 $sql_where1.=")";
361                                                 $sql_where2 .= "m1.bibid=m$nb_table.bibid and ";
362                                         } else {
363                                                 $sql_where1 .= "@$and_or[$i] (m$nb_table.word like ".$dbh->quote("@$value[$i]");
364                                                 if (@$tags[$i]) {
365                                                         $sql_where1 .="  and m$nb_table.tagsubfield in (@$tags[$i])";
366                                                 }
367                                                 $sql_where1.=")";
368                                                 $sql_where2 .= "m1.bibid=m$nb_table.bibid and ";
369                                         }
370                                 } else {
371                                         $nb_table++;
372                                         $sql_tables .= "marc_subfield_table as m$nb_table,";
373                                         $sql_where1 .= "@$and_or[$i] (m$nb_table.subfieldvalue @$operator[$i] ".$dbh->quote(@$value[$i]);
374                                         if (@$tags[$i]) {
375                                                 $sql_where1 .="  and m$nb_table.tag+m$nb_table.subfieldcode in (@$tags[$i])";
376                                         }
377                                         $sql_where2 .= "m1.bibid=m$nb_table.bibid and ";
378                                         $sql_where1.=")";
379                                 }
380                         }
381                 }
382         }
383
384         if($sql_where2 ne "(")  # some datas added to sql_where2, processing
385         {
386                 $sql_where2 = substr($sql_where2, 0, (length($sql_where2)-5)); # deletes the trailing ' and '
387                 $sql_where2 .= ")";
388         }
389         else    # no sql_where2 statement, deleting '('
390         {
391                 $sql_where2 = "";
392         }
393         chop $sql_tables;       # deletes the trailing ','
394         return ($sql_tables, $sql_where1, $sql_where2);
395 }
396
397
398 END { }       # module clean-up code here (global destructor)
399
400 1;
401 __END__
402
403 =back
404
405 =head1 AUTHOR
406
407 Koha Developement team <info@koha.org>
408
409 =cut