1 package C4::SearchMarc;
3 # Copyright 2000-2002 Katipo Communications
5 # This file is part of Koha.
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
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.
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
29 use vars qw($VERSION @ISA @EXPORT @EXPORT_OK %EXPORT_TAGS);
31 # set the version for version checking
36 C4::Search - Functions for searching the Koha MARC catalog
40 This module provides the searching facilities for the Koha MARC catalog
45 @EXPORT = qw(&catalogsearch &findseealso &findsuggestion &getMARCnotes &getMARCsubjects);
47 =head1 findsuggestion($dbh,$values);
49 =head2 $dbh is a link to the DB handler.
52 my $dbh =C4::Context->dbh;
54 =head2 $values is a word
56 Searches words with the same soundex, ordered by frequency of use.
57 Useful to suggest other searches to the users.
62 my ($dbh,$values) = @_;
63 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");
65 for(my $i = 0 ; $i <= $#{$values} ; $i++) {
66 if (length(@$values[$i]) >=5) {
67 $sth->execute(@$values[$i],@$values[$i]);
70 while ((my ($count,$word) = $sth->fetchrow) and $resfound <=10) {
71 push @results, "@$values[$i]|$word|$count";
72 # $results{@$values[$i]} = \@resline;
80 =head1 findseealso($dbh,$fields);
82 =head2 $dbh is a link to the DB handler.
85 my $dbh =C4::Context->dbh;
87 =head2 $fields is a reference to the fields array
89 This function modify the @$fields array and add related fields to search on.
94 my ($dbh, $fields) = @_;
95 my $tagslib = MARCgettagslib ($dbh,1);
96 for (my $i=0;$i<=$#{$fields};$i++) {
97 next unless @$fields[$i];
98 my ($tag) =substr(@$fields[$i],1,3);
99 my ($subfield) =substr(@$fields[$i],4,1);
100 @$fields[$i].=','.$tagslib->{$tag}->{$subfield}->{seealso} if ($tagslib->{$tag}->{$subfield}->{seealso});
104 =head1 my ($count, @results) = catalogsearch($dbh, $tags, $and_or, $excluding, $operator, $value, $offset,$length,$orderby,$sqlstring);
106 =head2 $dbh is a link to the DB handler.
109 my $dbh =C4::Context->dbh;
111 $tags,$and_or, $excluding, $operator, $value are references to array
115 contains the list of tags+subfields (for example : $@tags[0] = '200a')
116 A field can be a list of fields : '200f','700a','700b','701a','701b'
122 contains a list of strings containing and or or. The 1st value is useless.
126 contains 0 or 1. If 1, then the request is negated.
130 contains contains,=,start,>,>=,<,<= the = and start work on the complete subfield. The contains operator works on every word in the subfield.
133 contains home, search home anywhere.
134 = home, search a string being home.
138 contains the value to search
139 If it contains a * or a %, then the search is partial.
141 =head2 $offset and $length
143 returns $length results, beginning at $offset
147 define the field used to order the request. Any field in the biblio/biblioitem tables can be used. DESC is possible too
149 (for example title, title DESC,...)
153 optional argument containing an sql string to be used in the 'where' statement. see usage in opac-search.pl.
157 optional argument containing extra tables to search. Used in conjunction with $sqlstring. See usage in opac-search.pl.
158 String... so ',items,issues,reserves' allows the items, issues and reserves tables to be used.in a where.
162 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.
165 =head2 my $marcurlsarray = &getMARCurls($dbh,$bibid,$marcflavour);
167 Returns a reference to an array containing all the URLS stored in the MARC database for the given bibid.
168 $marcflavour ("MARC21" or "UNIMARC") isn't used in this version because both flavours of MARC use the same subfield for URLS (but eventually when we get the lables working we'll need to change this.
172 my ($dbh, $tags, $and_or, $excluding, $operator, $value, $offset,$length,$orderby,$desc_or_asc,$sqlstring, $extratables) = @_;
174 # the item.notforloan contains an integer. Every value <>0 means "book unavailable for loan".
175 # but each library can have it's own table of meaning for each value. Get them
176 # 1st search if there is a list of authorised values connected to items.notforloan
177 my $sth = $dbh->prepare('select authorised_value from marc_subfield_structure where kohafield="items.notforloan"');
179 my %notforloanstatus;
180 my ($authorised_valuecode) = $sth->fetchrow;
181 if ($authorised_valuecode) {
182 $sth = $dbh->prepare("select authorised_value,lib from authorised_values where category=?");
183 $sth->execute($authorised_valuecode);
184 while (my ($authorised_value,$lib) = $sth->fetchrow) {
185 $notforloanstatus{$authorised_value} = $lib?$lib:$authorised_value;
188 my $subtitle; # Added by JF for Subtitles
190 # prepare the query to find item status
192 if (C4::Context->preference('hidelostitem')) {
193 $sth_itemCN = $dbh->prepare("select items.* from items where biblionumber=? and (itemlost = 0 or itemlost is NULL)");
195 $sth_itemCN = $dbh->prepare("select items.* from items where biblionumber=?");
197 # prepare the query to find date_due where applicable
198 my $sth_issue = $dbh->prepare("select date_due,returndate from issues where itemnumber=?");
199 my $sth_itemtype = $dbh->prepare("select itemtypes.description,itemtypes.notforloan,itemtypes.imageurl from itemtypes where itemtype=?");
201 # prepare the query to find subtitles
202 my $sth_subtitle = $dbh->prepare("SELECT subtitle FROM bibliosubtitle WHERE biblionumber=?"); # Added BY JF for Subtitles
205 # now, do stupid things, that have to be modified for 3.0 :
206 # retrieve the 1st MARC tag.
207 # find the matching non-MARC field
208 # find bib1 attribute. This way, we will be MARC-independant (as title is in 200$a in UNIMARC and 245ùa in MARC21, we use "title" !)
209 # the best method to do this would probably to add a "bib1 attribute" column to marc_subfield_structure
210 # (or a CQL attribute name if we don't want to build bib1 requests)
211 # for instance, we manage only author / title / isbn. Any other field is considered as a keyword/anywhere search
213 my $tagslib = MARCgettagslib($dbh,$1,'');
215 for(my $i = 0 ; $i <= $#{$value} ; $i++){
216 # 1st split on , then remove ' in the 1st, the find koha field
217 my @x = split /,/, @$tags[$i];
218 $x[0] =~ s/'//g if $x[0];
219 $x[0] =~ /(...)(.)/ if $x[0];
220 my ($tag,$subfield) = ($1,$2);
221 if (@$value[$i]) { # if there is something to search, build the request
222 # if $query already contains something, add @and
223 $query .= " and " if ($query);
224 my $field = $tagslib->{$tag}->{$subfield}->{kohafield};
225 if ($field eq 'biblio.author') {
226 $query .= "Author all \"".@$value[$i]."\"";
227 } elsif ($field eq 'biblio.title') {
228 $query .= "Title all \"".@$value[$i]."\"";
229 } elsif ($field eq 'biblioitems.isbn') {
230 $query .= "Isbn= ".@$value[$i];
231 } elsif ($field eq 'bibliosubject.subject'){
232 $query.="Subject all \"@$value[$i]\"";
233 } elsif ($field eq 'biblioitems.itemtype'){
234 $query="Itemtype=@$value[$i]";
235 } elsif ($field eq 'items.homebranch'){
236 $query="Branch=@$value[$i]";
237 } elsif ($field eq 'items.barcode'){
238 $query="Barcode=@$value[$i]";
241 my @spacedout=split(/ /,@$value[$i]);
242 my $text = join(" and ",@spacedout);
246 # warn "$i : ".@$tags[$i]. "=> $tag / $subfield = ".$tagslib->{$tag}->{$subfield}->{kohafield};
248 # $query.= " ordered title";
249 warn "QUERY : $query";
250 my $Zconn = C4::Context->Zconn or die "unable to set Zconn";
251 my $q = new ZOOM::Query::CQL2RPN( $query, $Zconn);
252 my $rs = $Zconn->search($q);
253 my $numresults=$rs->size();
254 if ($numresults eq 0) {
255 warn "no records found\n";
257 warn "$numresults records found, retrieving them (max 80)\n";
260 # in theory this should sort by title
262 if ($orderby eq 'biblio.title'){
265 elsif ($orderby eq 'biblio.author'){
268 elsif ($orderby eq 'biblioitems.dewey'){
271 elsif ($orderby eq 'biblioitems.publicationyear'){
274 elsif ($orderby eq 'biblioitems.publishercode'){
277 if ($desc_or_asc eq 'ASC'){
284 if ($rs->sort("yaz", $sort) < 0) {
291 my $scantimerstart=time();
292 my @finalresult = ();
295 $offset=1 unless $offset;
296 # calculate max offset
297 my $maxrecordnum = $offset+$length<$numresults?$offset+$length:($numresults);
298 for (my $i=$offset-1; $i <= $maxrecordnum-1; $i++) {
299 # get the MARC record (in XML)...
300 # warn "REC $i = ".$rs->record($i)->raw();
301 # FIXME : it's a silly way to do things : XML => MARC::Record => hash. We had better developping a XML=> hash (in biblio.pm)
302 my $record = MARC::Record->new_from_xml($rs->record($i)->raw(), 'UTF-8');
303 # transform it into a meaningul hash
304 my $line = MARCmarc2koha($dbh,$record);
305 my $biblionumber=$line->{biblionumber};
306 # Return subtitles first ADDED BY JF
307 # $sth_subtitle->execute($biblionumber);
308 # my $subtitle_here.= $sth_subtitle->fetchrow." ";
309 # chop $subtitle_here;
310 # $subtitle = $subtitle_here;
311 # warn "Here's the Biblionumber ".$biblionumber;
312 # warn "and here's the subtitle: ".$subtitle_here;
315 # search itemtype information
316 $sth_itemtype->execute($line->{itemtype});
317 my ($itemtype_description,$itemtype_notforloan,$itemtype_imageurl) = $sth_itemtype->fetchrow;
318 $line->{description} = $itemtype_description;
319 $line->{imageurl} = $itemtype_imageurl;
320 $line->{notforloan} = $itemtype_notforloan;
321 $sth_itemCN->execute($biblionumber);
323 my $notforloan=1; # to see if there is at least 1 item that can be issued
324 while (my $item = $sth_itemCN->fetchrow_hashref) {
325 # parse the result, putting holdingbranch & itemcallnumber in separate array
326 # then all other fields in the main array
328 # search if item is on loan
330 $sth_issue->execute($item->{itemnumber});
331 while (my $loan = $sth_issue->fetchrow_hashref) {
332 if ($loan->{date_due} and !$loan->{returndate}) {
333 $date_due = $loan->{date_due};
338 $lineCN{holdingbranch} = $item->{holdingbranch};
339 $lineCN{itemcallnumber} = $item->{itemcallnumber};
340 $lineCN{location} = $item->{location};
341 $lineCN{date_due} = format_date($date_due);
342 $lineCN{notforloan} = $notforloanstatus{$line->{notforloan}} if ($line->{notforloan}); # setting not forloan if itemtype is not for loan
343 $lineCN{notforloan} = $notforloanstatus{$item->{notforloan}} if ($item->{notforloan}); # setting not forloan it this item is not for loan
344 $notforloan=0 unless ($item->{notforloan} or $item->{wthdrawn} or $item->{itemlost});
345 push @CNresults,\%lineCN;
348 # save the biblio in the final array, with item and item issue status
351 $newline{totitem} = $totalitems;
352 # if $totalitems == 0, check if it's being ordered.
353 if ($totalitems == 0) {
354 my $sth = $dbh->prepare("select count(*) from aqorders where biblionumber=? and datecancellationprinted is NULL");
355 $sth->execute($biblionumber);
356 my ($ordered) = $sth->fetchrow;
357 $newline{onorder} = 1 if $ordered;
359 $newline{biblionumber} = $biblionumber;
360 $newline{norequests} = 0;
361 $newline{norequests} = 1 if ($line->{notforloan}); # itemtype not issuable
362 $newline{norequests} = 1 if (!$line->{notforloan} && $notforloan); # itemtype issuable but all items not issuable for instance
363 $newline{subtitle} = $subtitle; # put the subtitle in ADDED BY JF
365 my @CNresults2= @CNresults;
366 $newline{CN} = \@CNresults2;
367 $newline{'even'} = 1 if $#finalresult % 2 == 0;
368 $newline{'odd'} = 1 if $#finalresult % 2 == 1;
369 $newline{'timestamp'} = format_date($newline{timestamp});
371 push @finalresult, \%newline;
374 my $nbresults = $#finalresult+1;
375 return (\@finalresult, $numresults);
378 =head2 my $marcnotesarray = &getMARCnotes($dbh,$bibid,$marcflavour);
380 Returns a reference to an array containing all the notes stored in the MARC database for the given bibid.
381 $marcflavour ("MARC21" or "UNIMARC") determines which tags are used for retrieving subjects.
386 my ($dbh, $bibid, $marcflavour) = @_;
387 my ($mintag, $maxtag);
388 if ($marcflavour eq "MARC21") {
391 } else { # assume unimarc if not marc21
396 my $sth=$dbh->prepare("SELECT subfieldvalue,tag FROM marc_subfield_table WHERE bibid=? AND tag BETWEEN ? AND ? ORDER BY tagorder");
398 $sth->execute($bibid,$mintag,$maxtag);
405 while (my $data=$sth->fetchrow_arrayref) {
406 my $value=$data->[0];
407 my $thistag=$data->[1];
411 if ($thistag ne $tag && $note ne "") {
412 $marcnote = {marcnote => $note,};
413 push @marcnotes, $marcnote;
417 if ($note ne $value) {
418 $note = $note." ".$value;
423 $marcnote = {marcnote => $note};
424 push @marcnotes, $marcnote; #load last tag into array
429 my $marcnotesarray=\@marcnotes;
430 return $marcnotesarray;
434 =head2 my $marcsubjctsarray = &getMARCsubjects($dbh,$bibid,$marcflavour);
436 Returns a reference to an array containing all the subjects stored in the MARC database for the given bibid.
437 $marcflavour ("MARC21" or "UNIMARC") determines which tags are used for retrieving subjects.
441 sub getMARCsubjects {
442 my ($dbh, $bibid, $marcflavour) = @_;
443 my ($mintag, $maxtag);
444 if ($marcflavour eq "MARC21") {
447 } else { # assume unimarc if not marc21
451 my $sth=$dbh->prepare("SELECT `subfieldvalue`,`subfieldcode`,`tagorder`,`tag` FROM `marc_subfield_table` WHERE `bibid`= ? AND `subfieldcode` NOT IN ('2','4','6','8') AND `tag` BETWEEN ? AND ? ORDER BY `tagorder`,`subfieldorder`");
452 # Subfield exclusion for $2, $4, $6, $8 protects against searching for
453 # variant data in otherwise invariant authorised subject headings when all
454 # returned subfields are used to form a query for matching subjects. One
455 # example is the use of $2 in MARC 21 where the value of $2 changes for
456 # different editions of the thesaurus used, even where the subject heading
457 # is otherwise the same. There is certainly a better fix for many cases
458 # where the value of the subfield may be parsed for the invariant data.
459 # More complete display values may also be separated from query values
460 # containing only the actual invariant authorised subject headings. More
461 # coding is required for careful value parsing, or display and query
462 # separation; instead of blanket subfield exclusion.
464 # As implemented, $3 is passed and might still pose a problem. Passing $3
465 # could have benefits for some proper use of $3 for UNIMARC, however, might
466 # restrict query usage to a given material type. -- thd
468 $sth->execute($bibid,$mintag,$maxtag);
474 my $activetagorder=0;
476 my ($subfieldvalue,$subfieldcode,$tagorder,$tag);
477 while (($subfieldvalue,$subfieldcode,$tagorder,$tag)=$sth->fetchrow) {
478 $lasttag=$tag if $tag;
479 if ($activetagorder && $tagorder != $activetagorder) {
480 $subject=~ s/ -- $//;
481 $marcsubjct = {MARCSUBJCT => $subject,
483 linkvalue => $field9,
485 push @marcsubjcts, $marcsubjct;
490 if ($subfieldcode eq 9) {
491 $field9=$subfieldvalue;
492 } elsif ($subfieldcode eq (3 || 5)) {
493 $subject .= $subfieldvalue . " ";
495 $subject .= $subfieldvalue . " -- ";
497 $activetagorder=$tagorder;
499 $subject=~ s/ -- $//;
500 $marcsubjct = {MARCSUBJCT => $subject,
501 link => $lasttag."9",
502 linkvalue => $field9,
504 push @marcsubjcts, $marcsubjct;
508 my $marcsubjctsarray=\@marcsubjcts;
509 return $marcsubjctsarray;
510 } #end getMARCsubjects
512 END { } # module clean-up code here (global destructor)
521 Koha Developement team <info@koha.org>