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