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