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