modifs in new acquisition option : the search is now managed through the standard...
[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 use C4::Date;
26 use Date::Manip;
27
28 use vars qw($VERSION @ISA @EXPORT @EXPORT_OK %EXPORT_TAGS);
29
30 # set the version for version checking
31 $VERSION = 0.02;
32
33 =head1 NAME
34
35 C4::Search - Functions for searching the Koha MARC catalog
36
37 =head1 SYNOPSIS
38
39   use C4::Search;
40
41   my ($count, @results) = catalogsearch();
42
43 =head1 DESCRIPTION
44
45 This module provides the searching facilities for the Koha MARC catalog
46
47 C<&catalogsearch> is a front end to all the other searches. Depending
48 on what is passed to it, it calls the appropriate search function.
49
50 =head1 FUNCTIONS
51
52 =over 2
53
54 =item my $marcnotesarray = &getMARCnotes($dbh,$bibid,$marcflavour);
55
56 Returns a reference to an array containing all the notes stored in the MARC database for the given bibid.
57 $marcflavour ("MARC21" or "UNIMARC") determines which tags are used for retrieving subjects.
58
59 =item my $marcsubjctsarray = &getMARCsubjects($dbh,$bibid,$marcflavour);
60
61 Returns a reference to an array containing all the subjects stored in the MARC database for the given bibid.
62 $marcflavour ("MARC21" or "UNIMARC") determines which tags are used for retrieving subjects.
63
64 =cut
65
66 @ISA = qw(Exporter);
67 @EXPORT = qw(&catalogsearch &findseealso &findsuggestion &getMARCnotes &getMARCsubjects);
68
69 # make all your functions, whether exported or not;
70
71 sub findsuggestion {
72         my ($dbh,$values) = @_;
73         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");
74         my @results;
75         for(my $i = 0 ; $i <= $#{$values} ; $i++) {
76                 if (length(@$values[$i]) >=5) {
77                         $sth->execute(@$values[$i],@$values[$i]);
78                         my $resfound = 1;
79                         my @resline;
80                         while ((my ($count,$word) = $sth->fetchrow) and $resfound <=10) {
81                                 push @results, "@$values[$i]|$word|$count";
82 #                               $results{@$values[$i]} = \@resline;
83                                 $resfound++;
84                         }
85                 }
86         }
87         return \@results;
88 }
89 sub findseealso {
90         my ($dbh, $fields) = @_;
91         my $tagslib = MARCgettagslib ($dbh,1);
92         for (my $i=0;$i<=$#{$fields};$i++) {
93                 my ($tag) =substr(@$fields[$i],1,3);
94                 my ($subfield) =substr(@$fields[$i],4,1);
95                 @$fields[$i].=','.$tagslib->{$tag}->{$subfield}->{seealso} if ($tagslib->{$tag}->{$subfield}->{seealso});
96         }
97 }
98
99 # marcsearch : search in the MARC biblio table.
100 # everything is choosen by the user : what to search, the conditions...
101
102 sub catalogsearch {
103         my ($dbh, $tags, $and_or, $excluding, $operator, $value, $offset,$length,$orderby) = @_;
104         # build the sql request. She will look like :
105         # select m1.bibid
106         #               from marc_subfield_table as m1, marc_subfield_table as m2
107         #               where m1.bibid=m2.bibid and
108         #               (m1.subfieldvalue like "Des%" and m2.subfieldvalue like "27%")
109
110         # last minute stripping out of stuff
111         # doesn't work @$value =~ s/\'/ /;
112         # @$value = map { $_ =~ s/\'/ /g } @$value;
113         
114         # "Normal" statements
115         my @normal_tags = ();
116         my @normal_and_or = ();
117         my @normal_operator = ();
118         my @normal_value = ();
119         # Extracts the NOT statements from the list of statements
120         my @not_tags = ();
121         my @not_and_or = ();
122         my @not_operator = ();
123         my @not_value = ();
124         my $any_not = 0;
125         $orderby = "biblio.title" unless $orderby;
126         
127         #last minute stripping out of ' and ,
128         foreach $_ (@$value) {
129         $_=~ s/\'/ /g;
130         $_=~ s/\,/ /g;
131         }
132         
133         for(my $i = 0 ; $i <= $#{$value} ; $i++)
134         {
135                 # replace * by %
136                 @$value[$i] =~ s/\*/%/g;
137                 # remove % at the beginning
138                 @$value[$i] =~ s/^%//g;
139                 if(@$excluding[$i])     # NOT statements
140                 {
141                         $any_not = 1;
142                         if(@$operator[$i] eq "contains")
143                         {
144                                 foreach my $word (split(/ /, @$value[$i]))      # if operator is contains, splits the words in separate requests
145                                 {
146                                         # remove the "%" for small word (3 letters. (note : the >4 is due to the % at the end)
147 #                                       warn "word : $word";
148                                         $word =~ s/%//g unless length($word)>4;
149                                         unless (C4::Context->stopwords->{uc($word)}) {  #it's NOT a stopword => use it. Otherwise, ignore
150                                                 push @not_tags, @$tags[$i];
151                                                 push @not_and_or, "or"; # as request is negated, finds "foo" or "bar" if final request is NOT "foo" and "bar"
152                                                 push @not_operator, @$operator[$i];
153                                                 push @not_value, $word;
154                                         }
155                                 }
156                         }
157                         else
158                         {
159                                 push @not_tags, @$tags[$i];
160                                 push @not_and_or, "or"; # as request is negated, finds "foo" or "bar" if final request is NOT "foo" and "bar"
161                                 push @not_operator, @$operator[$i];
162                                 push @not_value, @$value[$i];
163                         }
164                 }
165                 else    # NORMAL statements
166                 {
167                         if(@$operator[$i] eq "contains") # if operator is contains, splits the words in separate requests
168                         {
169                                 foreach my $word (split(/ /, @$value[$i]))
170                                 {
171                                         # remove the "%" for small word (3 letters. (note : the >4 is due to the % at the end)
172 #                                       warn "word : $word";
173                                         $word =~ s/%//g unless length($word)>4;
174                                         unless (C4::Context->stopwords->{uc($word)}) {  #it's NOT a stopword => use it. Otherwise, ignore
175                                                 my $tag = substr(@$tags[$i],0,3);
176                                                 my $subf = substr(@$tags[$i],3,1);
177                                                 push @normal_tags, @$tags[$i];
178                                                 push @normal_and_or, "and";     # assumes "foo" and "bar" if "foo bar" is entered
179                                                 push @normal_operator, @$operator[$i];
180                                                 push @normal_value, $word;
181                                         }
182                                 }
183                         }
184                         else
185                         {
186                                 push @normal_tags, @$tags[$i];
187                                 push @normal_and_or, @$and_or[$i];
188                                 push @normal_operator, @$operator[$i];
189                                 push @normal_value, @$value[$i];
190                         }
191                 }
192         }
193
194         # Finds the basic results without the NOT requests
195         my ($sql_tables, $sql_where1, $sql_where2) = create_request($dbh,\@normal_tags, \@normal_and_or, \@normal_operator, \@normal_value);
196
197         my $sth;
198         if ($sql_where2) {
199                 $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");
200                 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";
201         } else {
202                 $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");
203                 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";
204         }
205         $sth->execute();
206         my @result = ();
207
208         # Processes the NOT if any and there are results
209         my ($not_sql_tables, $not_sql_where1, $not_sql_where2);
210
211         if( ($sth->rows) && $any_not )  # some results to tune up and some NOT statements
212         {
213                 ($not_sql_tables, $not_sql_where1, $not_sql_where2) = create_request($dbh,\@not_tags, \@not_and_or, \@not_operator, \@not_value);
214
215                 my @tmpresult;
216
217                 while (my ($bibid) = $sth->fetchrow) {
218                         push @tmpresult,$bibid;
219                 }
220                 my $sth_not;
221                 warn "NOT : select distinct m1.bibid from $not_sql_tables where $not_sql_where2 and ($not_sql_where1)";
222                 if ($not_sql_where2) {
223                         $sth_not = $dbh->prepare("select distinct m1.bibid from $not_sql_tables where $not_sql_where2 and ($not_sql_where1)");
224                 } else {
225                         $sth_not = $dbh->prepare("select distinct m1.bibid from $not_sql_tables where $not_sql_where1");
226                 }
227                 $sth_not->execute();
228
229                 if($sth_not->rows)
230                 {
231                         my %not_bibids = ();
232                         while(my $bibid = $sth_not->fetchrow()) {
233                                 $not_bibids{$bibid} = 1;        # populates the hashtable with the bibids matching the NOT statement
234                         }
235
236                         foreach my $bibid (@tmpresult)
237                         {
238                                 if(!$not_bibids{$bibid})
239                                 {
240                                         push @result, $bibid;
241                                 }
242                         }
243                 }
244                 $sth_not->finish();
245         }
246         else    # no NOT statements
247         {
248                 while (my ($bibid) = $sth->fetchrow) {
249                         push @result,$bibid;
250                 }
251         }
252
253         # we have bibid list. Now, loads title and author from [offset] to [offset]+[length]
254         my $counter = $offset;
255         # HINT : biblionumber as bn is important. The hash is fills biblionumber with items.biblionumber.
256         # so if you dont' has an item, you get a not nice epty value.
257         $sth = $dbh->prepare("SELECT biblio.biblionumber as bn,count(*) as tot,biblio.*, biblioitems.*, items.*,marc_biblio.bibid
258                                                         FROM biblio, marc_biblio 
259                                                         LEFT JOIN items on items.biblionumber = biblio.biblionumber
260                                                         LEFT JOIN biblioitems on biblio.biblionumber = biblioitems.biblionumber
261                                                         WHERE biblio.biblionumber = marc_biblio.biblionumber AND bibid = ?
262                                                         GROUP BY items.biblionumber, items.holdingbranch, items.itemcallnumber");
263         my @finalresult = ();
264         my @CNresults=();
265         my $totalitems=0;
266         my $oldline;
267         my ($oldbibid, $oldauthor, $oldtitle);
268         # parse all biblios between start & end.
269         while (($counter <= $#result) && ($counter <= ($offset + $length))) {
270                 # search & parse all items & note itemcallnumber
271                 $sth->execute($result[$counter]);
272                 my $continue=1;
273                 my $line = $sth->fetchrow_hashref;
274                 my $oldbiblionumber=$line->{bn};
275                 $continue=0 unless $line->{bn};
276                 while ($continue) {
277                         # parse the result, putting holdingbranch & itemcallnumber in separate array
278                         # then all other fields in the main array
279                         if ($oldbiblionumber && ($oldbiblionumber ne $line->{bn}) && $oldline) {
280                                 my %newline;
281                                 %newline = %$oldline;
282                                 $newline{totitem} = $totalitems;
283                                 $newline{biblionumber} = $oldbiblionumber;
284                                 my @CNresults2= @CNresults;
285                                 $newline{CN} = \@CNresults2;
286                             $newline{'even'} = 1 if $#finalresult % 2 == 0;
287                                 $newline{'odd'} = 1 if $#finalresult % 2 == 1;
288                                 $newline{'timestamp'} = format_date($newline{timestamp});
289                                 @CNresults = ();
290                                 push @finalresult, \%newline;
291                                 $totalitems=0;
292                         }
293                         $continue=0 unless $line->{bn};
294                         if ($continue) {
295                                 $oldbiblionumber = $line->{bn};
296                                 $totalitems +=$line->{tot} if ($line->{holdingbranch});
297                                 $oldline = $line;
298                                 # item callnumber & branch
299                                 my %lineCN;
300                                 $lineCN{holdingbranch} = $line->{holdingbranch};
301                                 $lineCN{itemcallnumber} = $line->{itemcallnumber};
302                                 $lineCN{location} = $line->{location};
303                                 push @CNresults,\%lineCN;
304                                 $line = $sth->fetchrow_hashref;
305                         }
306                 }
307                 $counter++;
308         }
309 #add the last line, that is not reached byt the loop / if ($oldbiblionumber...)
310         my $nbresults = $#result+1;
311         return (\@finalresult, $nbresults);
312 }
313
314 # Creates the SQL Request
315
316 sub create_request {
317         my ($dbh,$tags, $and_or, $operator, $value) = @_;
318
319         my $sql_tables; # will contain marc_subfield_table as m1,...
320         my $sql_where1; # will contain the "true" where
321         my $sql_where2 = "("; # will contain m1.bibid=m2.bibid
322         my $nb_active=0; # will contain the number of "active" entries. an entry is active if a value is provided.
323         my $nb_table=1; # will contain the number of table. ++ on each entry EXCEPT when an OR  is provided.
324
325         for(my $i=0; $i<=@$value;$i++) {
326                 if (@$value[$i]) {
327                         $nb_active++;
328                         if ($nb_active==1) {
329                                 if (@$operator[$i] eq "start") {
330                                         $sql_tables .= "marc_subfield_table as m$nb_table,";
331                                         $sql_where1 .= "(m1.subfieldvalue like ".$dbh->quote("@$value[$i]");
332                                         if (@$tags[$i]) {
333                                                 $sql_where1 .=" and m1.tag+m1.subfieldcode in (@$tags[$i])";
334                                         }
335                                         $sql_where1.=")";
336                                 } elsif (@$operator[$i] eq "contains") {
337                                         $sql_tables .= "marc_word as m$nb_table,";
338                                         $sql_where1 .= "(m1.word  like ".$dbh->quote("@$value[$i]");
339                                         if (@$tags[$i]) {
340                                                  $sql_where1 .=" and m1.tagsubfield in (@$tags[$i])";
341                                         }
342                                         $sql_where1.=")";
343                                 } else {
344                                         $sql_tables .= "marc_subfield_table as m$nb_table,";
345                                         $sql_where1 .= "(m1.subfieldvalue @$operator[$i] ".$dbh->quote("@$value[$i]");
346                                         if (@$tags[$i]) {
347                                                  $sql_where1 .=" and m1.tag+m1.subfieldcode in (@$tags[$i])";
348                                         }
349                                         $sql_where1.=")";
350                                 }
351                         } else {
352                                 if (@$operator[$i] eq "start") {
353                                         $nb_table++;
354                                         $sql_tables .= "marc_subfield_table as m$nb_table,";
355                                         $sql_where1 .= "@$and_or[$i] (m$nb_table.subfieldvalue like ".$dbh->quote("@$value[$i]");
356                                         if (@$tags[$i]) {
357                                                 $sql_where1 .=" and m$nb_table.tag+m$nb_table.subfieldcode in (@$tags[$i])";
358                                         }
359                                         $sql_where1.=")";
360                                         $sql_where2 .= "m1.bibid=m$nb_table.bibid and ";
361                                 } elsif (@$operator[$i] eq "contains") {
362                                         if (@$and_or[$i] eq 'and') {
363                                                 $nb_table++;
364                                                 $sql_tables .= "marc_word as m$nb_table,";
365                                                 $sql_where1 .= "@$and_or[$i] (m$nb_table.word like ".$dbh->quote("@$value[$i]");
366                                                 if (@$tags[$i]) {
367                                                         $sql_where1 .=" and m$nb_table.tagsubfield in(@$tags[$i])";
368                                                 }
369                                                 $sql_where1.=")";
370                                                 $sql_where2 .= "m1.bibid=m$nb_table.bibid and ";
371                                         } else {
372                                                 $sql_where1 .= "@$and_or[$i] (m$nb_table.word like ".$dbh->quote("@$value[$i]");
373                                                 if (@$tags[$i]) {
374                                                         $sql_where1 .="  and m$nb_table.tagsubfield in (@$tags[$i])";
375                                                 }
376                                                 $sql_where1.=")";
377                                                 $sql_where2 .= "m1.bibid=m$nb_table.bibid and ";
378                                         }
379                                 } else {
380                                         $nb_table++;
381                                         $sql_tables .= "marc_subfield_table as m$nb_table,";
382                                         $sql_where1 .= "@$and_or[$i] (m$nb_table.subfieldvalue @$operator[$i] ".$dbh->quote(@$value[$i]);
383                                         if (@$tags[$i]) {
384                                                 $sql_where1 .="  and m$nb_table.tag+m$nb_table.subfieldcode in (@$tags[$i])";
385                                         }
386                                         $sql_where2 .= "m1.bibid=m$nb_table.bibid and ";
387                                         $sql_where1.=")";
388                                 }
389                         }
390                 }
391         }
392
393         if($sql_where2 ne "(")  # some datas added to sql_where2, processing
394         {
395                 $sql_where2 = substr($sql_where2, 0, (length($sql_where2)-5)); # deletes the trailing ' and '
396                 $sql_where2 .= ")";
397         }
398         else    # no sql_where2 statement, deleting '('
399         {
400                 $sql_where2 = "";
401         }
402         chop $sql_tables;       # deletes the trailing ','
403         return ($sql_tables, $sql_where1, $sql_where2);
404 }
405
406 sub getMARCnotes {
407         my ($dbh, $bibid, $marcflavour) = @_;
408         my ($mintag, $maxtag);
409         if ($marcflavour eq "MARC21") {
410                 $mintag = "500";
411                 $maxtag = "599";
412         } else {           # assume unimarc if not marc21
413                 $mintag = "300";
414                 $maxtag = "399";
415         }
416
417         my $sth=$dbh->prepare("SELECT subfieldvalue,tag FROM marc_subfield_table WHERE bibid=? AND tag BETWEEN ? AND ? ORDER BY tagorder");
418
419         $sth->execute($bibid,$mintag,$maxtag);
420
421         my @marcnotes;
422         my $note = "";
423         my $tag = "";
424         my $marcnote;
425
426         while (my $data=$sth->fetchrow_arrayref) {
427                 my $value=$data->[0];
428                 my $thistag=$data->[1];
429                 if ($value=~/\.$/) {
430                         $value=$value . "  ";
431                 }
432                 if ($thistag ne $tag && $note ne "") {
433                         $marcnote = {MARCNOTES => $note,};
434                         push @marcnotes, $marcnote;
435                         $note=$value;
436                         $tag=$thistag;
437                 }
438                 if ($note ne $value) {
439                         $note = $note." ".$value;
440                 }
441         }
442
443         if ($note) {
444                 $marcnote = {MARCNOTES => $note};
445                 push @marcnotes, $marcnote;   #load last tag into array
446         }
447
448         $sth->finish;
449         $dbh->disconnect;
450
451         my $marcnotesarray=\@marcnotes;
452         return $marcnotesarray;
453 }  # end getMARCnotes
454
455
456 sub getMARCsubjects {
457     my ($dbh, $bibid, $marcflavour) = @_;
458         my ($mintag, $maxtag);
459         if ($marcflavour eq "MARC21") {
460                 $mintag = "600";
461                 $maxtag = "699";
462         } else {           # assume unimarc if not marc21
463                 $mintag = "600";
464                 $maxtag = "619";
465         }
466         my $sth=$dbh->prepare("SELECT subfieldvalue,subfieldcode FROM marc_subfield_table WHERE bibid=? AND tag BETWEEN ? AND ? ORDER BY tagorder");
467
468         $sth->execute($bibid,$mintag,$maxtag);
469
470         my @marcsubjcts;
471         my $subjct = "";
472         my $subfield = "";
473         my $marcsubjct;
474
475         while (my $data=$sth->fetchrow_arrayref) {
476                 my $value = $data->[0];
477                 my $subfield = $data->[1];
478                 if ($subfield eq "a" && $value ne $subjct) {
479                         $marcsubjct = {MARCSUBJCT => $value,};
480                         push @marcsubjcts, $marcsubjct;
481                         $subjct = $value;
482                 }
483         }
484
485         $sth->finish;
486         $dbh->disconnect;
487
488         my $marcsubjctsarray=\@marcsubjcts;
489         return $marcsubjctsarray;
490 }  #end getMARCsubjects
491
492 END { }       # module clean-up code here (global destructor)
493
494 1;
495 __END__
496
497 =back
498
499 =head1 AUTHOR
500
501 Koha Developement team <info@koha.org>
502
503 =cut