minor reindentings
[koha.git] / C4 / Search.pm
1 package C4::Search;
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::Reserves2;
25         # FIXME - C4::Search uses C4::Reserves2, which uses C4::Search.
26         # So Perl complains that all of the functions here get redefined.
27 use C4::Date;
28
29 use vars qw($VERSION @ISA @EXPORT @EXPORT_OK %EXPORT_TAGS);
30
31 # set the version for version checking
32 $VERSION = 0.02;
33
34 =head1 NAME
35
36 C4::Search - Functions for searching the Koha catalog and other databases
37
38 =head1 SYNOPSIS
39
40   use C4::Search;
41
42   my ($count, @results) = catalogsearch($env, $type, $search, $num, $offset);
43
44 =head1 DESCRIPTION
45
46 This module provides the searching facilities for the Koha catalog and
47 other databases.
48
49 C<&catalogsearch> is a front end to all the other searches. Depending
50 on what is passed to it, it calls the appropriate search function.
51
52 =head1 FUNCTIONS
53
54 =over 2
55
56 =cut
57
58 @ISA = qw(Exporter);
59 @EXPORT = qw(
60 &newsearch
61 &CatSearch &BornameSearch &ItemInfo &KeywordSearch &subsearch
62 &itemdata &bibdata &GetItems &borrdata &itemnodata &itemcount
63 &borrdata2 &NewBorrowerNumber &bibitemdata &borrissues
64 &getboracctrecord &ItemType &itemissues &subject &subtitle
65 &addauthor &bibitems &barcodes &findguarantees &allissues
66 &findguarantor &getwebsites &getwebbiblioitems &catalogsearch &itemcount2
67 &isbnsearch &breedingsearch &getbranchname &getborrowercategory);
68 # make all your functions, whether exported or not;
69
70
71 =item newsearch
72         my (@results) = newsearch($itemtype,$duration,$number_of_results,$startfrom);
73 c<newsearch> find biblio acquired recently (last 30 days)
74 =cut
75 sub newsearch {
76         my ($itemtype,$duration,$num,$offset)=@_;
77
78         my $dbh = C4::Context->dbh;
79         my $sth=$dbh->prepare("SELECT to_days( now( ) ) - to_days( dateaccessioned ) AS duration,  biblio.biblionumber, barcode, title, author, classification, itemtype, dewey, dateaccessioned, price, replacementprice
80                                                 FROM items, biblio, biblioitems
81                                                 WHERE biblio.biblionumber = biblioitems.biblionumber AND
82                                                 items.biblionumber = biblio.biblionumber AND
83                                                 to_days( now( ) ) - to_days( dateaccessioned ) < ? and itemtype=?
84                                                 ORDER BY duration ASC ");
85         $sth->execute($duration,$itemtype);
86         my $i=0;
87         my @result;
88         while (my $data = $sth->fetchrow_hashref) {
89                 if ($i>=$offset && $i<$num+$offset) {
90                         my ($counts) = itemcount2("", $data->{'biblionumber'}, 'intra');
91                         my $subject2=$data->{'subject'};
92                         $subject2=~ s/ /%20/g;
93                         $data->{'itemcount'}=$counts->{'total'};
94                         my $totalitemcounts=0;
95                         foreach my $key (keys %$counts){
96                                 if ($key ne 'total'){   # FIXME - Should ignore 'order', too.
97                                         #$data->{'location'}.="$key $counts->{$key} ";
98                                         $totalitemcounts+=$counts->{$key};
99                                         $data->{'locationhash'}->{$key}=$counts->{$key};
100                                 }
101                         }
102                         my $locationtext='';
103                         my $locationtextonly='';
104                         my $notavailabletext='';
105                         foreach (sort keys %{$data->{'locationhash'}}) {
106                                 if ($_ eq 'notavailable') {
107                                         $notavailabletext="Not available";
108                                         my $c=$data->{'locationhash'}->{$_};
109                                         $data->{'not-available-p'}=$totalitemcounts;
110                                         if ($totalitemcounts>1) {
111                                         $notavailabletext.=" ($c)";
112                                         $data->{'not-available-plural-p'}=1;
113                                         }
114                                 } else {
115                                         $locationtext.="$_ ";
116                                         my $c=$data->{'locationhash'}->{$_};
117                                         if ($_ eq 'Item Lost') {
118                                         $data->{'lost-p'}=$totalitemcounts;
119                                         $data->{'lost-plural-p'}=1
120                                                         if $totalitemcounts > 1;
121                                         } elsif ($_ eq 'Withdrawn') {
122                                         $data->{'withdrawn-p'}=$totalitemcounts;
123                                         $data->{'withdrawn-plural-p'}=1
124                                                         if $totalitemcounts > 1;
125                                         } elsif ($_ eq 'On Loan') {
126                                         $data->{'on-loan-p'}=$totalitemcounts;
127                                         $data->{'on-loan-plural-p'}=1
128                                                         if $totalitemcounts > 1;
129                                         } else {
130                                         $locationtextonly.=$_;
131                                         $locationtextonly.=" ($c), "
132                                                         if $totalitemcounts>1;
133                                         }
134                                         if ($totalitemcounts>1) {
135                                         $locationtext.=" ($c), ";
136                                         }
137                                 }
138                         }
139                         if ($notavailabletext) {
140                                 $locationtext.=$notavailabletext;
141                         } else {
142                                 $locationtext=~s/, $//;
143                         }
144                         $data->{'location'}=$locationtext;
145                         $data->{'location-only'}=$locationtextonly;
146                         $data->{'subject2'}=$subject2;
147                         $data->{'use-location-flags-p'}=1; # XXX
148
149                         push @result,$data;
150                 }
151                 $i++
152         }
153         return($i,@result);
154
155 }
156
157 =item findguarantees
158
159   ($num_children, $children_arrayref) = &findguarantees($parent_borrno);
160   $child0_cardno = $children_arrayref->[0]{"cardnumber"};
161   $child0_borrno = $children_arrayref->[0]{"borrowernumber"};
162
163 C<&findguarantees> takes a borrower number (e.g., that of a patron
164 with children) and looks up the borrowers who are guaranteed by that
165 borrower (i.e., the patron's children).
166
167 C<&findguarantees> returns two values: an integer giving the number of
168 borrowers guaranteed by C<$parent_borrno>, and a reference to an array
169 of references to hash, which gives the actual results.
170
171 =cut
172 #'
173 sub findguarantees{
174   my ($bornum)=@_;
175   my $dbh = C4::Context->dbh;
176   my $sth=$dbh->prepare("select cardnumber,borrowernumber, firstname, surname from borrowers where guarantor=?");
177   $sth->execute($bornum);
178
179   my @dat;
180   while (my $data = $sth->fetchrow_hashref)
181   {
182     push @dat, $data;
183   }
184   $sth->finish;
185   return (scalar(@dat), \@dat);
186 }
187
188 =item findguarantor
189
190   $guarantor = &findguarantor($borrower_no);
191   $guarantor_cardno = $guarantor->{"cardnumber"};
192   $guarantor_surname = $guarantor->{"surname"};
193   ...
194
195 C<&findguarantor> takes a borrower number (presumably that of a child
196 patron), finds the guarantor for C<$borrower_no> (the child's parent),
197 and returns the record for the guarantor.
198
199 C<&findguarantor> returns a reference-to-hash. Its keys are the fields
200 from the C<borrowers> database table;
201
202 =cut
203 #'
204 sub findguarantor{
205   my ($bornum)=@_;
206   my $dbh = C4::Context->dbh;
207   my $sth=$dbh->prepare("select guarantor from borrowers where borrowernumber=?");
208   $sth->execute($bornum);
209   my $data=$sth->fetchrow_hashref;
210   $sth->finish;
211   $sth=$dbh->prepare("Select * from borrowers where borrowernumber=?");
212   $sth->execute($data->{'guarantor'});
213   $data=$sth->fetchrow_hashref;
214   $sth->finish;
215   return($data);
216 }
217
218 =item NewBorrowerNumber
219
220   $num = &NewBorrowerNumber();
221
222 Allocates a new, unused borrower number, and returns it.
223
224 =cut
225 #'
226 # FIXME - This is identical to C4::Circulation::Borrower::NewBorrowerNumber.
227 # Pick one and stick with it. Preferably use the other one. This function
228 # doesn't belong in C4::Search.
229 sub NewBorrowerNumber {
230   my $dbh = C4::Context->dbh;
231   my $sth=$dbh->prepare("Select max(borrowernumber) from borrowers");
232   $sth->execute;
233   my $data=$sth->fetchrow_hashref;
234   $sth->finish;
235   $data->{'max(borrowernumber)'}++;
236   return($data->{'max(borrowernumber)'});
237 }
238
239 =item catalogsearch
240
241   ($count, @results) = &catalogsearch($env, $type, $search, $num, $offset);
242
243 This is primarily a front-end to other, more specialized catalog
244 search functions: if C<$search-E<gt>{itemnumber}> or
245 C<$search-E<gt>{isbn}> is given, C<&catalogsearch> uses a precise
246 C<&CatSearch>. If $search->{subject} is given, it runs a subject
247 C<&CatSearch>. If C<$search-E<gt>{keyword}> is given, it runs a
248 C<&KeywordSearch>. Otherwise, it runs a loose C<&CatSearch>.
249
250 If C<$env-E<gt>{itemcount}> is 1, then C<&catalogsearch> also counts
251 the items for each result, and adds several keys:
252
253 =over 4
254
255 =item C<itemcount>
256
257 The total number of copies of this book.
258
259 =item C<locationhash>
260
261 This is a reference-to-hash; the keys are the names of branches where
262 this book may be found, and the values are the number of copies at
263 that branch.
264
265 =item C<location>
266
267 A descriptive string saying where the book is located, and how many
268 copies there are, if greater than 1.
269
270 =item C<subject2>
271
272 The book's subject, with spaces replaced with C<%20>, presumably for
273 HTML.
274
275 =back
276
277 =cut
278 #'
279 sub catalogsearch {
280         my ($env,$type,$search,$num,$offset)=@_;
281         my $dbh = C4::Context->dbh;
282         #  foreach my $key (%$search){
283         #    $search->{$key}=$dbh->quote($search->{$key});
284         #  }
285         my ($count,@results);
286         if ($search->{'itemnumber'} ne '' || $search->{'isbn'} ne ''){
287                 print STDERR "Doing a precise search\n";
288                 ($count,@results)=CatSearch($env,'precise',$search,$num,$offset);
289         } elsif ($search->{'subject'} ne ''){
290                 ($count,@results)=CatSearch($env,'subject',$search,$num,$offset);
291         } elsif ($search->{'keyword'} ne ''){
292                 ($count,@results)=&KeywordSearch($env,'keyword',$search,$num,$offset);
293         } else {
294                 ($count,@results)=CatSearch($env,'loose',$search,$num,$offset);
295
296         }
297         if ($env->{itemcount} eq '1') {
298                 foreach my $data (@results){
299                         my ($counts) = itemcount2($env, $data->{'biblionumber'}, 'intra');
300                         my $subject2=$data->{'subject'};
301                         $subject2=~ s/ /%20/g;
302                         $data->{'itemcount'}=$counts->{'total'};
303                         my $totalitemcounts=0;
304                         foreach my $key (keys %$counts){
305                                 if ($key ne 'total'){   # FIXME - Should ignore 'order', too.
306                                         #$data->{'location'}.="$key $counts->{$key} ";
307                                         $totalitemcounts+=$counts->{$key};
308                                         $data->{'locationhash'}->{$key}=$counts->{$key};
309                                 }
310                         }
311                         my $locationtext='';
312                         my $locationtextonly='';
313                         my $notavailabletext='';
314                         foreach (sort keys %{$data->{'locationhash'}}) {
315                                 if ($_ eq 'notavailable') {
316                                         $notavailabletext="Not available";
317                                         my $c=$data->{'locationhash'}->{$_};
318                                         $data->{'not-available-p'}=$totalitemcounts;
319                                         if ($totalitemcounts>1) {
320                                         $notavailabletext.=" ($c)";
321                                         $data->{'not-available-plural-p'}=1;
322                                         }
323                                 } else {
324                                         $locationtext.="$_";
325                                         my $c=$data->{'locationhash'}->{$_};
326                                         if ($_ eq 'Item Lost') {
327                                         $data->{'lost-p'}=$totalitemcounts;
328                                         $data->{'lost-plural-p'}=1
329                                                         if $totalitemcounts > 1;
330                                         } elsif ($_ eq 'Withdrawn') {
331                                         $data->{'withdrawn-p'}=$totalitemcounts;
332                                         $data->{'withdrawn-plural-p'}=1
333                                                         if $totalitemcounts > 1;
334                                         } elsif ($_ eq 'On Loan') {
335                                         $data->{'on-loan-p'}=$totalitemcounts;
336                                         $data->{'on-loan-plural-p'}=1
337                                                         if $totalitemcounts > 1;
338                                         } else {
339                                         $locationtextonly.=$_;
340                                         $locationtextonly.=" ($c), "
341                                                         if $totalitemcounts>1;
342                                         }
343                                         if ($totalitemcounts>1) {
344                                         $locationtext.=" ($c), ";
345                                         }
346                                 }
347                         }
348                         if ($notavailabletext) {
349                                 $locationtext.=$notavailabletext;
350                         } else {
351                                 $locationtext=~s/, $//;
352                         }
353                         $data->{'location'}=$locationtext;
354                         $data->{'location-only'}=$locationtextonly;
355                         $data->{'subject2'}=$subject2;
356                         $data->{'use-location-flags-p'}=1; # XXX
357                 }
358         }
359         return ($count,@results);
360 }
361
362 =item KeywordSearch
363
364   $search = { "keyword" => "One or more keywords",
365               "class"   => "VID|CD",    # Limit search to fiction and CDs
366               "dewey"   => "813",
367          };
368   ($count, @results) = &KeywordSearch($env, $type, $search, $num, $offset);
369
370 C<&KeywordSearch> searches the catalog by keyword: given a string
371 (C<$search-E<gt>{"keyword"}> consisting of a space-separated list of
372 keywords, it looks for books that contain any of those keywords in any
373 of a number of places.
374
375 C<&KeywordSearch> looks for keywords in the book title (and subtitle),
376 series name, notes (both C<biblio.notes> and C<biblioitems.notes>),
377 and subjects.
378
379 C<$search-E<gt>{"class"}> can be set to a C<|> (pipe)-separated list of
380 item class codes (e.g., "F" for fiction, "JNF" for junior nonfiction,
381 etc.). In this case, the search will be restricted to just those
382 classes.
383
384 If C<$search-E<gt>{"class"}> is not specified, you may specify
385 C<$search-E<gt>{"dewey"}>. This will restrict the search to that
386 particular Dewey Decimal Classification category. Setting
387 C<$search-E<gt>{"dewey"}> to "513" will return books about arithmetic,
388 whereas setting it to "5" will return all books with Dewey code 5I<xx>
389 (Science and Mathematics).
390
391 C<$env> and C<$type> are ignored.
392
393 C<$offset> and C<$num> specify the subset of results to return.
394 C<$num> specifies the number of results to return, and C<$offset> is
395 the number of the first result. Thus, setting C<$offset> to 100 and
396 C<$num> to 5 will return results 100 through 104 inclusive.
397
398 =cut
399 #'
400 sub KeywordSearch {
401   my ($env,$type,$search,$num,$offset)=@_;
402   my $dbh = C4::Context->dbh;
403   $search->{'keyword'}=~ s/ +$//;
404   my @key=split(' ',$search->{'keyword'});
405                 # FIXME - Naive users might enter comma-separated
406                 # words, e.g., "training, animal". Ought to cope with
407                 # this.
408   my $count=@key;
409   my $i=1;
410   my %biblionumbers;            # Set of biblionumbers returned by the
411                                 # various searches.
412
413   # FIXME - Ought to filter the stopwords out of the list of keywords.
414   #     @key = map { !defined($stopwords{$_}) } @key;
415
416   # FIXME - The way this code is currently set up, it looks for all of
417   # the keywords first in (title, notes, seriestitle), then in the
418   # subtitle, then in the subject. Thus, if you look for keywords
419   # "science fiction", this search won't find a book with
420   #     title    = "How to write fiction"
421   #     subtitle = "A science-based approach"
422   # Is this the desired effect? If not, then the first SQL query
423   # should look in the biblio, subtitle, and subject tables all at
424   # once. The way the first query is built can accomodate this easily.
425
426   # Look for keywords in table 'biblio'.
427
428   # Build an SQL query that finds each of the keywords in any of the
429   # title, biblio.notes, or seriestitle. To do this, we'll build up an
430   # array of clauses, one for each keyword.
431   my $query;                    # The SQL query
432   my @clauses = ();             # The search clauses
433   my @bind = ();                # The term bindings
434
435   $query = <<EOT;               # Beginning of the query
436         SELECT  biblionumber
437         FROM    biblio
438         WHERE
439 EOT
440   foreach my $keyword (@key)
441   {
442     my @subclauses = ();        # Subclauses, one for each field we're
443                                 # searching on
444
445     # For each field we're searching on, create a subclause that'll
446     # match the current keyword in the current field.
447     foreach my $field (qw(title notes seriestitle author))
448     {
449       push @subclauses,
450         "$field LIKE ? OR $field LIKE ?";
451           push(@bind,"\Q$keyword\E%","% \Q$keyword\E%");
452     }
453     # (Yes, this could have been done as
454     #   @subclauses = map {...} qw(field1 field2 ...)
455     # )but I think this way is more readable.
456
457     # Construct the current clause by joining the subclauses.
458     push @clauses, "(" . join(")\n\tOR (", @subclauses) . ")";
459   }
460   # Now join all of the clauses together and append to the query.
461   $query .= "(" . join(")\nAND (", @clauses) . ")";
462
463   # FIXME - Perhaps use $sth->bind_columns() ? Documented as the most
464   # efficient way to fetch data.
465   my $sth=$dbh->prepare($query);
466   $sth->execute(@bind);
467   while (my @res = $sth->fetchrow_array) {
468     for (@res)
469     {
470         $biblionumbers{$_} = 1;         # Add these results to the set
471     }
472   }
473   $sth->finish;
474
475   # Now look for keywords in the 'bibliosubtitle' table.
476
477   # Again, we build a list of clauses from the keywords.
478   @clauses = ();
479   @bind = ();
480   $query = "SELECT biblionumber FROM bibliosubtitle WHERE ";
481   foreach my $keyword (@key)
482   {
483     push @clauses,
484         "subtitle LIKE ? OR subtitle like ?";
485         push(@bind,"\Q$keyword\E%","% \Q$keyword\E%");
486   }
487   $query .= "(" . join(") AND (", @clauses) . ")";
488
489   $sth=$dbh->prepare($query);
490   $sth->execute(@bind);
491   while (my @res = $sth->fetchrow_array) {
492     for (@res)
493     {
494         $biblionumbers{$_} = 1;         # Add these results to the set
495     }
496   }
497   $sth->finish;
498
499   # Look for the keywords in the notes for individual items
500   # ('biblioitems.notes')
501
502   # Again, we build a list of clauses from the keywords.
503   @clauses = ();
504   @bind = ();
505   $query = "SELECT biblionumber FROM biblioitems WHERE ";
506   foreach my $keyword (@key)
507   {
508     push @clauses,
509         "notes LIKE ? OR notes like ?";
510         push(@bind,"\Q$keyword\E%","% \Q$keyword\E%");
511   }
512   $query .= "(" . join(") AND (", @clauses) . ")";
513
514   $sth=$dbh->prepare($query);
515   $sth->execute(@bind);
516   while (my @res = $sth->fetchrow_array) {
517     for (@res)
518     {
519         $biblionumbers{$_} = 1;         # Add these results to the set
520     }
521   }
522   $sth->finish;
523
524   # Look for keywords in the 'bibliosubject' table.
525
526   # FIXME - The other queries look for words in the desired field that
527   # begin with the individual keywords the user entered. This one
528   # searches for the literal string the user entered. Is this the
529   # desired effect?
530   # Note in particular that spaces are retained: if the user typed
531   #     science  fiction
532   # (with two spaces), this won't find the subject "science fiction"
533   # (one space). Likewise, a search for "%" will return absolutely
534   # everything.
535   # If this isn't the desired effect, see the previous searches for
536   # how to do it.
537
538   $sth=$dbh->prepare("Select biblionumber from bibliosubject where subject
539   like ? group by biblionumber");
540   $sth->execute("%$search->{'keyword'}%");
541
542   while (my @res = $sth->fetchrow_array) {
543     for (@res)
544     {
545         $biblionumbers{$_} = 1;         # Add these results to the set
546     }
547   }
548   $sth->finish;
549
550   my $i2=0;
551   my $i3=0;
552   my $i4=0;
553
554   my @res2;
555   my @res = keys %biblionumbers;
556   $count=@res;
557
558   $i=0;
559 #  print "count $count";
560   if ($search->{'class'} ne ''){
561     while ($i2 <$count){
562       my $query="select * from biblio,biblioitems where
563       biblio.biblionumber=? and
564       biblio.biblionumber=biblioitems.biblionumber ";
565       my @bind = ($res[$i2]);
566       if ($search->{'class'} ne ''){    # FIXME - Redundant
567       my @temp=split(/\|/,$search->{'class'});
568       my $count=@temp;
569       $query.= "and ( itemtype=?";
570       push(@bind,$temp[0]);
571       for (my $i=1;$i<$count;$i++){
572         $query.=" or itemtype=?";
573         push(@bind,$temp[$i]);
574       }
575       $query.=")";
576       }
577        my $sth=$dbh->prepare($query);
578        #    print $query;
579        $sth->execute(@bind);
580        if (my $data2=$sth->fetchrow_hashref){
581          my $dewey= $data2->{'dewey'};
582          my $subclass=$data2->{'subclass'};
583          # FIXME - This next bit is bogus, because it assumes that the
584          # Dewey code is a floating-point number. It isn't. It's
585          # actually a string that mainly consists of numbers. In
586          # particular, "4" is not a valid Dewey code, although "004"
587          # is ("Data processing; Computer science"). Likewise, zeros
588          # after the decimal are significant ("575" is not the same as
589          # "575.0"; the latter is more specific). And "000" is a
590          # perfectly good Dewey code ("General works; computer
591          # science") and should not be interpreted to mean "this
592          # database entry does not have a Dewey code". That's what
593          # NULL is for.
594          $dewey=~s/\.*0*$//;
595          ($dewey == 0) && ($dewey='');
596          ($dewey) && ($dewey.=" $subclass") ;
597           $sth->finish;
598           my $end=$offset +$num;
599           if ($i4 <= $offset){
600             $i4++;
601           }
602 #         print $i4;
603           if ($i4 <=$end && $i4 > $offset){
604             $data2->{'dewey'}=$dewey;
605             $res2[$i3]=$data2;
606
607 #           $res2[$i3]="$data2->{'author'}\t$data2->{'title'}\t$data2->{'biblionumber'}\t$data2->{'copyrightdate'}\t$dewey";
608             $i3++;
609             $i4++;
610 #           print "in here $i3<br>";
611           } else {
612 #           print $end;
613           }
614           $i++;
615         }
616      $i2++;
617      }
618      $count=$i;
619
620    } else {
621   # $search->{'class'} was not specified
622
623   # FIXME - This is bogus: it makes a separate query for each
624   # biblioitem, and returns results in apparently random order. It'd
625   # be much better to combine all of the previous queries into one big
626   # one (building it up a little at a time, of course), and have that
627   # big query select all of the desired fields, instead of just
628   # 'biblionumber'.
629
630   while ($i2 < $num && $i2 < $count){
631     my $query="select * from biblio,biblioitems where
632     biblio.biblionumber=? and
633     biblio.biblionumber=biblioitems.biblionumber ";
634     my @bind=($res[$i2+$offset]);
635
636     if ($search->{'dewey'} ne ''){
637       $query.= "and (dewey like ?)";
638       push(@bind,"$search->{'dewey'}%");
639     }
640
641     my $sth=$dbh->prepare($query);
642 #    print $query;
643     $sth->execute(@bind);
644     if (my $data2=$sth->fetchrow_hashref){
645         my $dewey= $data2->{'dewey'};
646         my $subclass=$data2->{'subclass'};
647         $dewey=~s/\.*0*$//;
648         ($dewey == 0) && ($dewey='');
649         ($dewey) && ($dewey.=" $subclass") ;
650         $sth->finish;
651         $data2->{'dewey'}=$dewey;
652
653         $res2[$i]=$data2;
654 #       $res2[$i]="$data2->{'author'}\t$data2->{'title'}\t$data2->{'biblionumber'}\t$data2->{'copyrightdate'}\t$dewey";
655         $i++;
656     }
657     $i2++;
658
659   }
660   }
661
662   #$count=$i;
663   return($count,@res2);
664 }
665
666 sub KeywordSearch2 {
667   my ($env,$type,$search,$num,$offset)=@_;
668   my $dbh = C4::Context->dbh;
669   $search->{'keyword'}=~ s/ +$//;
670   my @key=split(' ',$search->{'keyword'});
671   my $count=@key;
672   my $i=1;
673   my @results;
674   my $query ="Select * from biblio,bibliosubtitle,biblioitems where
675   biblio.biblionumber=biblioitems.biblionumber and
676   biblio.biblionumber=bibliosubtitle.biblionumber and
677   (((title like ? or title like ?)";
678   my @bind=("$key[0]%","% $key[0]%");
679   while ($i < $count){
680     $query .= " and (title like ? or title like ?)";
681     push(@bind,"$key[$i]%","% $key[$i]%");
682     $i++;
683   }
684   $query.= ") or ((subtitle like ? or subtitle like ?)";
685   push(@bind,"$key[0]%","% $key[0]%");
686   for ($i=1;$i<$count;$i++){
687     $query.= " and (subtitle like ? or subtitle like ?)";
688     push(@bind,"$key[$i]%","% $key[$i]%");
689   }
690   $query.= ") or ((seriestitle like ? or seriestitle like ?)";
691   push(@bind,"$key[0]%","% $key[0]%");
692   for ($i=1;$i<$count;$i++){
693     $query.=" and (seriestitle like ? or seriestitle like ?)";
694     push(@bind,"$key[$i]%","% $key[$i]%");
695   }
696   $query.= ") or ((biblio.notes like ? or biblio.notes like ?)";
697   push(@bind,"$key[0]%","% $key[0]%");
698   for ($i=1;$i<$count;$i++){
699     $query.=" and (biblio.notes like ? or biblio.notes like ?)";
700     push(@bind,"$key[$i]%","% $key[$i]%");
701   }
702   $query.= ") or ((biblioitems.notes like ? or biblioitems.notes like ?)";
703   push(@bind,"$key[0]%","% $key[0]%");
704   for ($i=1;$i<$count;$i++){
705     $query.=" and (biblioitems.notes like ? or biblioitems.notes like ?)";
706     push(@bind,"$key[$i]%","% $key[$i]%");
707   }
708   if ($search->{'keyword'} =~ /new zealand/i){
709     $query.= "or (title like 'nz%' or title like '% nz %' or title like '% nz' or subtitle like 'nz%'
710     or subtitle like '% nz %' or subtitle like '% nz' or author like 'nz %'
711     or author like '% nz %' or author like '% nz')"
712   }
713   if ($search->{'keyword'} eq  'nz' || $search->{'keyword'} eq 'NZ' ||
714   $search->{'keyword'} =~ /nz /i || $search->{'keyword'} =~ / nz /i ||
715   $search->{'keyword'} =~ / nz/i){
716     $query.= "or (title like 'new zealand%' or title like '% new zealand %'
717     or title like '% new zealand' or subtitle like 'new zealand%' or
718     subtitle like '% new zealand %'
719     or subtitle like '% new zealand' or author like 'new zealand%'
720     or author like '% new zealand %' or author like '% new zealand' or
721     seriestitle like 'new zealand%' or seriestitle like '% new zealand %'
722     or seriestitle like '% new zealand')"
723   }
724   $query .= "))";
725   if ($search->{'class'} ne ''){
726     my @temp=split(/\|/,$search->{'class'});
727     my $count=@temp;
728     $query.= "and ( itemtype=?";
729     push(@bind,"$temp[0]");
730     for (my $i=1;$i<$count;$i++){
731       $query.=" or itemtype=?";
732       push(@bind,"$temp[$i]");
733      }
734   $query.=")";
735   }
736   if ($search->{'dewey'} ne ''){
737     $query.= "and (dewey like '$search->{'dewey'}%') ";
738   }
739    $query.="group by biblio.biblionumber";
740    #$query.=" order by author,title";
741 #  print $query;
742   my $sth=$dbh->prepare($query);
743   $sth->execute(@bind);
744   $i=0;
745   while (my $data=$sth->fetchrow_hashref){
746 #FIXME: rewrite to use ? before uncomment
747 #    my $sti=$dbh->prepare("select dewey,subclass from biblioitems where biblionumber=$data->{'biblionumber'}
748 #    ");
749 #    $sti->execute;
750 #    my ($dewey, $subclass) = $sti->fetchrow;
751     my $dewey=$data->{'dewey'};
752     my $subclass=$data->{'subclass'};
753     $dewey=~s/\.*0*$//;
754     ($dewey == 0) && ($dewey='');
755     ($dewey) && ($dewey.=" $subclass");
756 #    $sti->finish;
757     $results[$i]="$data->{'author'}\t$data->{'title'}\t$data->{'biblionumber'}\t$data->{'copyrightdate'}\t$dewey";
758 #      print $results[$i];
759     $i++;
760   }
761   $sth->finish;
762   $sth=$dbh->prepare("Select biblionumber from bibliosubject where subject
763   like ? group by biblionumber");
764   $sth->execute("%".$search->{'keyword'}."%");
765   while (my $data=$sth->fetchrow_hashref){
766     $query="Select * from biblio,biblioitems where
767     biblio.biblionumber=? and
768     biblio.biblionumber=biblioitems.biblionumber ";
769     @bind=($data->{'biblionumber'});
770     if ($search->{'class'} ne ''){
771       my @temp=split(/\|/,$search->{'class'});
772       my $count=@temp;
773       $query.= " and ( itemtype=?";
774       push(@bind,$temp[0]);
775       for (my $i=1;$i<$count;$i++){
776         $query.=" or itemtype=?";
777         push(@bind,$temp[$i]);
778       }
779       $query.=")";
780
781     }
782     if ($search->{'dewey'} ne ''){
783       $query.= "and (dewey like ?)";
784       push(@bind,"$search->{'dewey'}%");
785     }
786     my $sth2=$dbh->prepare($query);
787     $sth2->execute(@bind);
788 #    print $query;
789     while (my $data2=$sth2->fetchrow_hashref){
790       my $dewey= $data2->{'dewey'};
791       my $subclass=$data2->{'subclass'};
792       $dewey=~s/\.*0*$//;
793       ($dewey == 0) && ($dewey='');
794       ($dewey) && ($dewey.=" $subclass") ;
795 #      $sti->finish;
796        $results[$i]="$data2->{'author'}\t$data2->{'title'}\t$data2->{'biblionumber'}\t$data2->{'copyrightdate'}\t$dewey";
797 #      print $results[$i];
798       $i++;
799     }
800     $sth2->finish;
801   }
802   my $i2=1;
803   @results=sort @results;
804   my @res;
805   $count=@results;
806   $i=1;
807   if ($count > 0){
808     $res[0]=$results[0];
809   }
810   while ($i2 < $count){
811     if ($results[$i2] ne $res[$i-1]){
812       $res[$i]=$results[$i2];
813       $i++;
814     }
815     $i2++;
816   }
817   $i2=0;
818   my @res2;
819   $count=@res;
820   while ($i2 < $num && $i2 < $count){
821     $res2[$i2]=$res[$i2+$offset];
822 #    print $res2[$i2];
823     $i2++;
824   }
825   $sth->finish;
826 #  $i--;
827 #  $i++;
828   return($i,@res2);
829 }
830
831 =item CatSearch
832
833   ($count, @results) = &CatSearch($env, $type, $search, $num, $offset);
834
835 C<&CatSearch> searches the Koha catalog. It returns a list whose first
836 element is the number of returned results, and whose subsequent
837 elements are the results themselves.
838
839 Each returned element is a reference-to-hash. Most of the keys are
840 simply the fields from the C<biblio> table in the Koha database, but
841 the following keys may also be present:
842
843 =over 4
844
845 =item C<illustrator>
846
847 The book's illustrator.
848
849 =item C<publisher>
850
851 The publisher.
852
853 =back
854
855 C<$env> is ignored.
856
857 C<$type> may be C<subject>, C<loose>, or C<precise>. This controls the
858 high-level behavior of C<&CatSearch>, as described below.
859
860 In many cases, the description below says that a certain field in the
861 database must match the search string. In these cases, it means that
862 the beginning of some word in the field must match the search string.
863 Thus, an author search for "sm" will return books whose author is
864 "John Smith" or "Mike Smalls", but not "Paul Grossman", since the "sm"
865 does not occur at the beginning of a word.
866
867 Note that within each search mode, the criteria are and-ed together.
868 That is, if you perform a loose search on the author "Jerome" and the
869 title "Boat", the search will only return books by Jerome containing
870 "Boat" in the title.
871
872 It is not possible to cross modes, e.g., set the author to "Asimov"
873 and the subject to "Math" in hopes of finding books on math by Asimov.
874
875 =head2 Loose search
876
877 If C<$type> is set to C<loose>, the following search criteria may be
878 used:
879
880 =over 4
881
882 =item C<$search-E<gt>{author}>
883
884 The search string is a space-separated list of words. Each word must
885 match either the C<author> or C<additionalauthors> field.
886
887 =item C<$search-E<gt>{title}>
888
889 Each word in the search string must match the book title. If no author
890 is specified, the book subtitle will also be searched.
891
892 =item C<$search-E<gt>{abstract}>
893
894 Searches for the given search string in the book's abstract.
895
896 =item C<$search-E<gt>{'date-before'}>
897
898 Searches for books whose copyright date matches the search string.
899 That is, setting C<$search-E<gt>{'date-before'}> to "1985" will find
900 books written in 1985, and setting it to "198" will find books written
901 between 1980 and 1989.
902
903 =item C<$search-E<gt>{title}>
904
905 Searches by title are also affected by the value of
906 C<$search-E<gt>{"ttype"}>; if it is set to C<exact>, then the book
907 title, (one of) the series titleZ<>(s), or (one of) the unititleZ<>(s) must
908 match the search string exactly (the subtitle is not searched).
909
910 If C<$search-E<gt>{"ttype"}> is set to anything other than C<exact>,
911 each word in the search string must match the title, subtitle,
912 unititle, or series title.
913
914 =item C<$search-E<gt>{class}>
915
916 Restricts the search to certain item classes. The value of
917 C<$search-E<gt>{"class"}> is a | (pipe)-separated list of item types.
918 Thus, setting it to "F" restricts the search to fiction, and setting
919 it to "CD|CAS" will only look in compact disks and cassettes.
920
921 =item C<$search-E<gt>{dewey}>
922
923 Searches for books whose Dewey Decimal Classification code matches the
924 search string. That is, setting C<$search-E<gt>{"dewey"}> to "5" will
925 search for all books in 5I<xx> (Science and mathematics), setting it
926 to "54" will search for all books in 54I<x> (Chemistry), and setting
927 it to "546" will search for books on inorganic chemistry.
928
929 =item C<$search-E<gt>{publisher}>
930
931 Searches for books whose publisher contains the search string (unlike
932 other search criteria, C<$search-E<gt>{publisher}> is a string, not a
933 set of words.
934
935 =back
936
937 =head2 Subject search
938
939 If C<$type> is set to C<subject>, the following search criterion may
940 be used:
941
942 =over 4
943
944 =item C<$search-E<gt>{subject}>
945
946 The search string is a space-separated list of words, each of which
947 must match the book's subject.
948
949 Special case: if C<$search-E<gt>{subject}> is set to C<nz>,
950 C<&CatSearch> will search for books whose subject is "New Zealand".
951 However, setting C<$search-E<gt>{subject}> to C<"nz football"> will
952 search for books on "nz" and "football", not books on "New Zealand"
953 and "football".
954
955 =back
956
957 =head2 Precise search
958
959 If C<$type> is set to C<precise>, the following search criteria may be
960 used:
961
962 =over 4
963
964 =item C<$search-E<gt>{item}>
965
966 Searches for books whose barcode exactly matches the search string.
967
968 =item C<$search-E<gt>{isbn}>
969
970 Searches for books whose ISBN exactly matches the search string.
971
972 =back
973
974 For a loose search, if an author was specified, the results are
975 ordered by author and title. If no author was specified, the results
976 are ordered by title.
977
978 For other (non-loose) searches, if a subject was specified, the
979 results are ordered alphabetically by subject.
980
981 In all other cases (e.g., loose search by keyword), the results are
982 not ordered.
983
984 =cut
985 #'
986 sub CatSearch  {
987         my ($env,$type,$search,$num,$offset)=@_;
988         my $dbh = C4::Context->dbh;
989         my $query = '';
990         my @bind = ();
991         my @results;
992
993         my $title = lc($search->{'title'});
994
995         if ($type eq 'loose') {
996                 if ($search->{'author'} ne ''){
997                         my @key=split(' ',$search->{'author'});
998                         my $count=@key;
999                         my $i=1;
1000                         $query="select *,biblio.author,biblio.biblionumber from
1001                                                         biblio
1002                                                         left join additionalauthors
1003                                                         on additionalauthors.biblionumber =biblio.biblionumber
1004                                                         where
1005                                                         ((biblio.author like ? or biblio.author like ? or
1006                                                         additionalauthors.author like ? or additionalauthors.author
1007                                                         like ?
1008                                                                 )";
1009                         @bind=("$key[0]%","% $key[0]%","$key[0]%","% $key[0]%");
1010                         while ($i < $count){
1011                                         $query .= " and (
1012                                                                         biblio.author like ? or biblio.author like ? or
1013                                                                         additionalauthors.author like ? or additionalauthors.author like ?
1014                                                                         )";
1015                                         push(@bind,"$key[$i]%","% $key[$i]%","$key[$i]%","% $key[$i]%");
1016                                 $i++;
1017                         }
1018                         $query .= ")";
1019                         if ($search->{'title'} ne ''){
1020                                 my @key=split(' ',$search->{'title'});
1021                                 my $count=@key;
1022                                 my $i=0;
1023                                 $query.= " and (((title like ? or title like ?)";
1024                                 push(@bind,"$key[0]%","% $key[0]%");
1025                                 while ($i<$count){
1026                                         $query .= " and (title like ? or title like ?)";
1027                                         push(@bind,"$key[$i]%","% $key[$i]%");
1028                                         $i++;
1029                                 }
1030                                 $query.=") or ((seriestitle like ? or seriestitle like ?)";
1031                                 push(@bind,"$key[0]%","% $key[0]%");
1032                                 for ($i=1;$i<$count;$i++){
1033                                         $query.=" and (seriestitle like ? or seriestitle like ?)";
1034                                         push(@bind,"$key[$i]%","% $key[$i]%");
1035                                         }
1036                                 $query.=") or ((unititle like ? or unititle like ?)";
1037                                 push(@bind,"$key[0]%","% $key[0]%");
1038                                 for ($i=1;$i<$count;$i++){
1039                                         $query.=" and (unititle like ? or unititle like ?)";
1040                                         push(@bind,"$key[$i]%","% $key[$i]%");
1041                                         }
1042                                 $query .= "))";
1043                         }
1044                         if ($search->{'abstract'} ne ''){
1045                                 $query.= " and (abstract like ?)";
1046                                 push(@bind,"%$search->{'abstract'}%");
1047                         }
1048                         if ($search->{'date-before'} ne ''){
1049                                 $query.= " and (copyrightdate like ?)";
1050                                 push(@bind,"%$search->{'date-before'}%");
1051                         }
1052                         $query.=" group by biblio.biblionumber";
1053                 } else {
1054                         if ($search->{'title'} ne '') {
1055                                 if ($search->{'ttype'} eq 'exact'){
1056                                         $query="select * from biblio
1057                                         where
1058                                         (biblio.title=? or (biblio.unititle = ?
1059                                         or biblio.unititle like ? or
1060                                         biblio.unititle like ? or
1061                                         biblio.unititle like ?) or
1062                                         (biblio.seriestitle = ? or
1063                                         biblio.seriestitle like ? or
1064                                         biblio.seriestitle like ? or
1065                                         biblio.seriestitle like ?)
1066                                         )";
1067                                         @bind=($search->{'title'},$search->{'title'},"$search->{'title'} |%","%| $search->{'title'} |%","%| $search->{'title'}",$search->{'title'},"$search->{'title'} |%","%| $search->{'title'} |%","%| $search->{'title'}");
1068                                 } else {
1069                                         my @key=split(' ',$search->{'title'});
1070                                         my $count=@key;
1071                                         my $i=1;
1072                                         $query="select biblio.biblionumber,author,title,unititle,notes,abstract,serial,seriestitle,copyrightdate,timestamp,subtitle from biblio
1073                                         left join bibliosubtitle on
1074                                         biblio.biblionumber=bibliosubtitle.biblionumber
1075                                         where
1076                                         (((title like ? or title like ?)";
1077                                         @bind=("$key[0]%","% $key[0]%");
1078                                         while ($i<$count){
1079                                                 $query .= " and (title like ? or title like ?)";
1080                                                 push(@bind,"$key[$i]%","% $key[$i]%");
1081                                                 $i++;
1082                                         }
1083                                         $query.=") or ((subtitle like ? or subtitle like ?)";
1084                                         push(@bind,"$key[0]%","% $key[0]%");
1085                                         for ($i=1;$i<$count;$i++){
1086                                                 $query.=" and (subtitle like ? or subtitle like ?)";
1087                                                 push(@bind,"$key[$i]%","% $key[$i]%");
1088                                         }
1089                                         $query.=") or ((seriestitle like ? or seriestitle like ?)";
1090                                         push(@bind,"$key[0]%","% $key[0]%");
1091                                         for ($i=1;$i<$count;$i++){
1092                                                 $query.=" and (seriestitle like ? or seriestitle like ?)";
1093                                                 push(@bind,"$key[$i]%","% $key[$i]%");
1094                                         }
1095                                         $query.=") or ((unititle like ? or unititle like ?)";
1096                                         push(@bind,"$key[0]%","% $key[0]%");
1097                                         for ($i=1;$i<$count;$i++){
1098                                                 $query.=" and (unititle like ? or unititle like ?)";
1099                                                 push(@bind,"$key[$i]%","% $key[$i]%");
1100                                         }
1101                                         $query .= "))";
1102                                 }
1103                                 if ($search->{'abstract'} ne ''){
1104                                         $query.= " and (abstract like ?)";
1105                                         push(@bind,"%$search->{'abstract'}%");
1106                                 }
1107                                 if ($search->{'date-before'} ne ''){
1108                                         $query.= " and (copyrightdate like ?)";
1109                                         push(@bind,"%$search->{'date-before'}%");
1110                                 }
1111                         } elsif ($search->{'class'} ne ''){
1112                                 $query="select * from biblioitems,biblio where biblio.biblionumber=biblioitems.biblionumber";
1113                                 my @temp=split(/\|/,$search->{'class'});
1114                                 my $count=@temp;
1115                                 $query.= " and ( itemtype= ?)";
1116                                 @bind=($temp[0]);
1117                                 for (my $i=1;$i<$count;$i++){
1118                                         $query.=" or itemtype=?";
1119                                         push(@bind,$temp[$i]);
1120                                 }
1121                                 $query.=")";
1122                                 if ($search->{'illustrator'} ne ''){
1123                                         $query.=" and illus like ?";
1124                                         push(@bind,"%".$search->{'illustrator'}."%");
1125                                 }
1126                                 if ($search->{'dewey'} ne ''){
1127                                         $query.=" and biblioitems.dewey like ?";
1128                                         push(@bind,"$search->{'dewey'}%");
1129                                 }
1130                         } elsif ($search->{'dewey'} ne ''){
1131                                 $query="select * from biblioitems,biblio
1132                                 where biblio.biblionumber=biblioitems.biblionumber
1133                                 and biblioitems.dewey like ?";
1134                                 @bind=("$search->{'dewey'}%");
1135                         } elsif ($search->{'illustrator'} ne '') {
1136                                         $query="select * from biblioitems,biblio
1137                                 where biblio.biblionumber=biblioitems.biblionumber
1138                                 and biblioitems.illus like ?";
1139                                         @bind=("%".$search->{'illustrator'}."%");
1140                         } elsif ($search->{'publisher'} ne ''){
1141                                 $query = "Select * from biblio,biblioitems where biblio.biblionumber
1142                                 =biblioitems.biblionumber and (publishercode like ?)";
1143                                 @bind=("%$search->{'publisher'}%");
1144                         } elsif ($search->{'abstract'} ne ''){
1145                                 $query = "Select * from biblio where abstract like ?";
1146                                 @bind=("%$search->{'abstract'}%");
1147                         } elsif ($search->{'date-before'} ne ''){
1148                                 $query = "Select * from biblio where copyrightdate like ?";
1149                                 @bind=("%$search->{'date-before'}%");
1150                         }
1151                         $query .=" group by biblio.biblionumber";
1152                 }
1153         }
1154         if ($type eq 'subject'){
1155                 my @key=split(' ',$search->{'subject'});
1156                 my $count=@key;
1157                 my $i=1;
1158                 $query="select * from bibliosubject, biblioitems where
1159 (bibliosubject.biblionumber = biblioitems.biblionumber) and ( subject like ? or subject like ? or subject like ?)";
1160                 @bind=("$key[0]%","% $key[0]%","%($key[0])%");
1161                 while ($i<$count){
1162                         $query.=" and (subject like ? or subject like ? or subject like ?)";
1163                         push(@bind,"$key[$i]%","% $key[$i]%","%($key[$i])%");
1164                         $i++;
1165                 }
1166
1167                 # FIXME - Wouldn't it be better to fix the database so that if a
1168                 # book has a subject "NZ", then it also gets added the subject
1169                 # "New Zealand"?
1170                 # This can also be generalized by adding a table of subject
1171                 # synonyms to the database: just declare "NZ" to be a synonym for
1172                 # "New Zealand", "SF" a synonym for both "Science fiction" and
1173                 # "Fantastic fiction", etc.
1174
1175                 if (lc($search->{'subject'}) eq 'nz'){
1176                         $query.= " or (subject like 'NEW ZEALAND %' or subject like '% NEW ZEALAND %'
1177                         or subject like '% NEW ZEALAND' or subject like '%(NEW ZEALAND)%' ) ";
1178                 } elsif ( $search->{'subject'} =~ /^nz /i || $search->{'subject'} =~ / nz /i || $search->{'subject'} =~ / nz$/i){
1179                         $query=~ s/ nz/ NEW ZEALAND/ig;
1180                         $query=~ s/nz /NEW ZEALAND /ig;
1181                         $query=~ s/\(nz\)/\(NEW ZEALAND\)/gi;
1182                 }
1183         }
1184         if ($type eq 'precise'){
1185                 if ($search->{'itemnumber'} ne ''){
1186                         $query="select * from items,biblio ";
1187                         my $search2=uc $search->{'itemnumber'};
1188                         $query=$query." where
1189                         items.biblionumber=biblio.biblionumber
1190                         and barcode=?";
1191                         @bind=($search2);
1192                                         # FIXME - .= <<EOT;
1193                 }
1194                 if ($search->{'isbn'} ne ''){
1195                         my $search2=uc $search->{'isbn'};
1196                         my $sth1=$dbh->prepare("select * from biblioitems where isbn=?");
1197                         $sth1->execute($search2);
1198                         my $i2=0;
1199                         while (my $data=$sth1->fetchrow_hashref) {
1200                                 my $sth=$dbh->prepare("select * from biblioitems,biblio where
1201                                         biblio.biblionumber = ?
1202                                         and biblioitems.biblionumber = biblio.biblionumber");
1203                                 $sth->execute($data->{'biblionumber'});
1204                                 # FIXME - There's already a $data in this scope.
1205                                 my $data=$sth->fetchrow_hashref;
1206                                 my ($dewey, $subclass) = ($data->{'dewey'}, $data->{'subclass'});
1207                                 # FIXME - The following assumes that the Dewey code is a
1208                                 # floating-point number. It isn't: it's a string.
1209                                 $dewey=~s/\.*0*$//;
1210                                 ($dewey == 0) && ($dewey='');
1211                                 ($dewey) && ($dewey.=" $subclass");
1212                                 $data->{'dewey'}=$dewey;
1213                                 $results[$i2]=$data;
1214                         #           $results[$i2]="$data->{'author'}\t$data->{'title'}\t$data->{'biblionumber'}\t$data->{'copyrightdate'}\t$dewey\t$data->{'isbn'}\t$data->{'itemtype'}";
1215                                 $i2++;
1216                                 $sth->finish;
1217                         }
1218                         $sth1->finish;
1219                 }
1220         }
1221         if ($type ne 'precise' && $type ne 'subject'){
1222                 if ($search->{'author'} ne ''){
1223                         $query .= " order by biblio.author,title";
1224                 } else {
1225                         $query .= " order by title";
1226                 }
1227         } else {
1228                 if ($type eq 'subject'){
1229                         $query .= " group by subject ";
1230                 }
1231         }
1232         my $sth=$dbh->prepare($query);
1233         $sth->execute(@bind);
1234         my $count=1;
1235         my $i=0;
1236         my $limit= $num+$offset;
1237         while (my $data=$sth->fetchrow_hashref){
1238                 my $query="select dewey,subclass,publishercode from biblioitems where biblionumber=?";
1239                 my @bind=($data->{'biblionumber'});
1240                 if ($search->{'class'} ne ''){
1241                         my @temp=split(/\|/,$search->{'class'});
1242                         my $count=@temp;
1243                         $query.= " and ( itemtype= ?";
1244                         push(@bind,$temp[0]);
1245                         for (my $i=1;$i<$count;$i++){
1246                         $query.=" or itemtype=?";
1247                         push(@bind,$temp[$i]);
1248                         }
1249                         $query.=")";
1250                 }
1251                 if ($search->{'dewey'} ne ''){
1252                         $query.=" and dewey=? ";
1253                         push(@bind,$search->{'dewey'});
1254                 }
1255                 if ($search->{'illustrator'} ne ''){
1256                         $query.=" and illus like ?";
1257                         push(@bind,"%$search->{'illustrator'}%");
1258                 }
1259                 if ($search->{'publisher'} ne ''){
1260                         $query.= " and (publishercode like ?)";
1261                         push(@bind,"%$search->{'publisher'}%");
1262                 }
1263                 my $sti=$dbh->prepare($query);
1264                 $sti->execute(@bind);
1265                 my $dewey;
1266                 my $subclass;
1267                 my $true=0;
1268                 my $publishercode;
1269                 my $bibitemdata;
1270                 if ($bibitemdata = $sti->fetchrow_hashref()){
1271                         $true=1;
1272                         $dewey=$bibitemdata->{'dewey'};
1273                         $subclass=$bibitemdata->{'subclass'};
1274                         $publishercode=$bibitemdata->{'publishercode'};
1275                 }
1276                 #  print STDERR "$dewey $subclass $publishercode\n";
1277                 # FIXME - The Dewey code is a string, not a number.
1278                 $dewey=~s/\.*0*$//;
1279                 ($dewey == 0) && ($dewey='');
1280                 ($dewey) && ($dewey.=" $subclass");
1281                 $data->{'dewey'}=$dewey;
1282                 $data->{'publishercode'}=$publishercode;
1283                 $sti->finish;
1284                 if ($true == 1){
1285                         if ($count > $offset && $count <= $limit){
1286                                 $results[$i]=$data;
1287                                 $i++;
1288                         }
1289                         $count++;
1290                 }
1291         }
1292         $sth->finish;
1293         $count--;
1294         return($count,@results);
1295 }
1296
1297 sub updatesearchstats{
1298   my ($dbh,$query)=@_;
1299
1300 }
1301
1302 =item subsearch
1303
1304   @results = &subsearch($env, $subject);
1305
1306 Searches for books that have a subject that exactly matches
1307 C<$subject>.
1308
1309 C<&subsearch> returns an array of results. Each element of this array
1310 is a string, containing the book's title, author, and biblionumber,
1311 separated by tabs.
1312
1313 C<$env> is ignored.
1314
1315 =cut
1316 #'
1317 sub subsearch {
1318   my ($env,$subject)=@_;
1319   my $dbh = C4::Context->dbh;
1320   my $sth=$dbh->prepare("Select * from biblio,bibliosubject where
1321   biblio.biblionumber=bibliosubject.biblionumber and
1322   bibliosubject.subject=? group by biblio.biblionumber
1323   order by biblio.title");
1324   $sth->execute($subject);
1325   my $i=0;
1326   my @results;
1327   while (my $data=$sth->fetchrow_hashref){
1328     push @results, $data;
1329     $i++;
1330   }
1331   $sth->finish;
1332   return(@results);
1333 }
1334
1335 =item ItemInfo
1336
1337   @results = &ItemInfo($env, $biblionumber, $type);
1338
1339 Returns information about books with the given biblionumber.
1340
1341 C<$type> may be either C<intra> or anything else. If it is not set to
1342 C<intra>, then the search will exclude lost, very overdue, and
1343 withdrawn items.
1344
1345 C<$env> is ignored.
1346
1347 C<&ItemInfo> returns a list of references-to-hash. Each element
1348 contains a number of keys. Most of them are table items from the
1349 C<biblio>, C<biblioitems>, C<items>, and C<itemtypes> tables in the
1350 Koha database. Other keys include:
1351
1352 =over 4
1353
1354 =item C<$data-E<gt>{branchname}>
1355
1356 The name (not the code) of the branch to which the book belongs.
1357
1358 =item C<$data-E<gt>{datelastseen}>
1359
1360 This is simply C<items.datelastseen>, except that while the date is
1361 stored in YYYY-MM-DD format in the database, here it is converted to
1362 DD/MM/YYYY format. A NULL date is returned as C<//>.
1363
1364 =item C<$data-E<gt>{datedue}>
1365
1366 =item C<$data-E<gt>{class}>
1367
1368 This is the concatenation of C<biblioitems.classification>, the book's
1369 Dewey code, and C<biblioitems.subclass>.
1370
1371 =item C<$data-E<gt>{ocount}>
1372
1373 I think this is the number of copies of the book available.
1374
1375 =item C<$data-E<gt>{order}>
1376
1377 If this is set, it is set to C<One Order>.
1378
1379 =back
1380
1381 =cut
1382 #'
1383 sub ItemInfo {
1384         my ($env,$biblionumber,$type) = @_;
1385         my $dbh   = C4::Context->dbh;
1386         my $query = "SELECT *,items.notforloan as itemnotforloan FROM items, biblio, biblioitems 
1387                                         left join itemtypes on biblioitems.itemtype = itemtypes.itemtype
1388                                         WHERE items.biblionumber = ?
1389                                         AND biblioitems.biblioitemnumber = items.biblioitemnumber
1390                                         AND biblio.biblionumber = items.biblionumber";
1391         if ($type ne 'intra'){
1392                 $query .= " and ((items.itemlost<>1 and items.itemlost <> 2)
1393                 or items.itemlost is NULL)
1394                 and (wthdrawn <> 1 or wthdrawn is NULL)";
1395         }
1396         $query .= " order by items.dateaccessioned desc";
1397         my $sth=$dbh->prepare($query);
1398         $sth->execute($biblionumber);
1399         my $i=0;
1400         my @results;
1401         while (my $data=$sth->fetchrow_hashref){
1402                 my $datedue = '';
1403                 my $isth=$dbh->prepare("Select * from issues where itemnumber = ? and returndate is null");
1404                 $isth->execute($data->{'itemnumber'});
1405                 if (my $idata=$isth->fetchrow_hashref){
1406                 $datedue = format_date($idata->{'date_due'});
1407                 }
1408                 if ($data->{'itemlost'} eq '2'){
1409                         $datedue='Very Overdue';
1410                 }
1411                 if ($data->{'itemlost'} eq '1'){
1412                         $datedue='Lost';
1413                 }
1414                 if ($data->{'wthdrawn'} eq '1'){
1415                         $datedue="Cancelled";
1416                 }
1417                 if ($datedue eq ''){
1418         #       $datedue="Available";
1419                         my ($restype,$reserves)=C4::Reserves2::CheckReserves($data->{'itemnumber'});
1420                         if ($restype) {
1421                                 $datedue=$restype;
1422                         }
1423                 }
1424                 $isth->finish;
1425         #get branch information.....
1426                 my $bsth=$dbh->prepare("SELECT * FROM branches WHERE branchcode = ?");
1427                 $bsth->execute($data->{'holdingbranch'});
1428                 if (my $bdata=$bsth->fetchrow_hashref){
1429                         $data->{'branchname'} = $bdata->{'branchname'};
1430                 }
1431         #   $results[$i]="$data->{'title'}\t$data->{'barcode'}\t$datedue\t$data->{'branchname'}\t$data->{'dewey'}";
1432                 # FIXME - If $data->{'datelastseen'} is NULL, perhaps it'd be prettier
1433                 # to leave it empty, rather than convert it to "//".
1434                 # Also ideally this should use the local format for displaying dates.
1435                 my $date=format_date($data->{'datelastseen'});
1436                 $data->{'datelastseen'}=$date;
1437                 $data->{'datedue'}=$datedue;
1438                 $results[$i]=$data;
1439                 $i++;
1440         }
1441         $sth->finish;
1442         #FIXME: ordering/indentation here looks wrong
1443         my $sth2=$dbh->prepare("Select * from aqorders where biblionumber=?");
1444         $sth2->execute($biblionumber);
1445         my $data;
1446         my $ocount;
1447         if ($data=$sth2->fetchrow_hashref){
1448                 $ocount=$data->{'quantity'} - $data->{'quantityreceived'};
1449                 if ($ocount > 0){
1450                 $data->{'ocount'}=$ocount;
1451                 $data->{'order'}="One Order";
1452                 $results[$i]=$data;
1453                 }
1454         }
1455         $sth2->finish;
1456         
1457         return(@results);
1458 }
1459
1460 =item GetItems
1461
1462   @results = &GetItems($env, $biblionumber);
1463
1464 Returns information about books with the given biblionumber.
1465
1466 C<$env> is ignored.
1467
1468 C<&GetItems> returns an array of strings. Each element is a
1469 tab-separated list of values: biblioitemnumber, itemtype,
1470 classification, Dewey number, subclass, ISBN, volume, number, and
1471 itemdata.
1472
1473 Itemdata, in turn, is a string of the form
1474 "I<barcode>C<[>I<holdingbranch>C<[>I<flags>" where I<flags> contains
1475 the string C<NFL> if the item is not for loan, and C<LOST> if the item
1476 is lost.
1477
1478 =cut
1479 #'
1480 sub GetItems {
1481    my ($env,$biblionumber)=@_;
1482    #debug_msg($env,"GetItems");
1483    my $dbh = C4::Context->dbh;
1484    my $sth=$dbh->prepare("Select * from biblioitems where (biblionumber = ?)");
1485    $sth->execute($biblionumber);
1486    #debug_msg($env,"executed query");
1487    my $i=0;
1488    my @results;
1489    while (my $data=$sth->fetchrow_hashref) {
1490       #debug_msg($env,$data->{'biblioitemnumber'});
1491       my $dewey = $data->{'dewey'};
1492       $dewey =~ s/0+$//;
1493       my $line = $data->{'biblioitemnumber'}."\t".$data->{'itemtype'};
1494       $line .= "\t$data->{'classification'}\t$dewey";
1495       $line .= "\t$data->{'subclass'}\t$data->{isbn}";
1496       $line .= "\t$data->{'volume'}\t$data->{number}";
1497       my $isth= $dbh->prepare("select * from items where biblioitemnumber = ?");
1498       $isth->execute($data->{'biblioitemnumber'});
1499       while (my $idata = $isth->fetchrow_hashref) {
1500         my $iline = $idata->{'barcode'}."[".$idata->{'holdingbranch'}."[";
1501         if ($idata->{'notforloan'} == 1) {
1502           $iline .= "NFL ";
1503         }
1504         if ($idata->{'itemlost'} == 1) {
1505           $iline .= "LOST ";
1506         }
1507         $line .= "\t$iline";
1508       }
1509       $isth->finish;
1510       $results[$i] = $line;
1511       $i++;
1512    }
1513    $sth->finish;
1514    return(@results);
1515 }
1516
1517 =item itemdata
1518
1519   $item = &itemdata($barcode);
1520
1521 Looks up the item with the given barcode, and returns a
1522 reference-to-hash containing information about that item. The keys of
1523 the hash are the fields from the C<items> and C<biblioitems> tables in
1524 the Koha database.
1525
1526 =cut
1527 #'
1528 sub itemdata {
1529   my ($barcode)=@_;
1530   my $dbh = C4::Context->dbh;
1531   my $sth=$dbh->prepare("Select * from items,biblioitems where barcode=?
1532   and items.biblioitemnumber=biblioitems.biblioitemnumber");
1533   $sth->execute($barcode);
1534   my $data=$sth->fetchrow_hashref;
1535   $sth->finish;
1536   return($data);
1537 }
1538
1539 =item bibdata
1540
1541   $data = &bibdata($biblionumber, $type);
1542
1543 Returns information about the book with the given biblionumber.
1544
1545 C<$type> is ignored.
1546
1547 C<&bibdata> returns a reference-to-hash. The keys are the fields in
1548 the C<biblio>, C<biblioitems>, and C<bibliosubtitle> tables in the
1549 Koha database.
1550
1551 In addition, C<$data-E<gt>{subject}> is the list of the book's
1552 subjects, separated by C<" , "> (space, comma, space).
1553
1554 If there are multiple biblioitems with the given biblionumber, only
1555 the first one is considered.
1556
1557 =cut
1558 #'
1559 sub bibdata {
1560         my ($bibnum, $type) = @_;
1561         my $dbh   = C4::Context->dbh;
1562         my $sth   = $dbh->prepare("Select *, biblioitems.notes AS bnotes, biblio.notes
1563                                                                 from biblio, biblioitems
1564                                                                 left join bibliosubtitle on
1565                                                                 biblio.biblionumber = bibliosubtitle.biblionumber
1566                                                                 where biblio.biblionumber = ?
1567                                                                 and biblioitems.biblionumber = biblio.biblionumber");
1568         $sth->execute($bibnum);
1569         my $data;
1570         $data  = $sth->fetchrow_hashref;
1571         $sth->finish;
1572         $sth   = $dbh->prepare("Select * from bibliosubject where biblionumber = ?");
1573         $sth->execute($bibnum);
1574         my @subjects;
1575         while (my $dat = $sth->fetchrow_hashref){
1576                 my %line;
1577                 $line{subject} = $dat->{'subject'};
1578                 push @subjects, \%line;
1579         } # while
1580         $data->{subjects} = \@subjects;
1581         $sth->finish;
1582         $sth   = $dbh->prepare("Select * from additionalauthors where biblionumber = ?");
1583         $sth->execute($bibnum);
1584         while (my $dat = $sth->fetchrow_hashref){
1585                 $data->{'additionalauthors'} .= "$dat->{'author'}, ";
1586         } # while
1587         chop $data->{'additionalauthors'};
1588         chop $data->{'additionalauthors'};
1589         $sth->finish;
1590         return($data);
1591 } # sub bibdata
1592
1593 =item bibitemdata
1594
1595   $itemdata = &bibitemdata($biblioitemnumber);
1596
1597 Looks up the biblioitem with the given biblioitemnumber. Returns a
1598 reference-to-hash. The keys are the fields from the C<biblio>,
1599 C<biblioitems>, and C<itemtypes> tables in the Koha database, except
1600 that C<biblioitems.notes> is given as C<$itemdata-E<gt>{bnotes}>.
1601
1602 =cut
1603 #'
1604 sub bibitemdata {
1605     my ($bibitem) = @_;
1606     my $dbh   = C4::Context->dbh;
1607     my $sth   = $dbh->prepare("Select *,biblioitems.notes as bnotes from biblio, biblioitems,itemtypes where biblio.biblionumber = biblioitems.biblionumber and biblioitemnumber = ? and biblioitems.itemtype = itemtypes.itemtype");
1608     my $data;
1609
1610     $sth->execute($bibitem);
1611
1612     $data = $sth->fetchrow_hashref;
1613
1614     $sth->finish;
1615     return($data);
1616 } # sub bibitemdata
1617
1618 =item subject
1619
1620   ($count, $subjects) = &subject($biblionumber);
1621
1622 Looks up the subjects of the book with the given biblionumber. Returns
1623 a two-element list. C<$subjects> is a reference-to-array, where each
1624 element is a subject of the book, and C<$count> is the number of
1625 elements in C<$subjects>.
1626
1627 =cut
1628 #'
1629 sub subject {
1630   my ($bibnum)=@_;
1631   my $dbh = C4::Context->dbh;
1632   my $sth=$dbh->prepare("Select * from bibliosubject where biblionumber=?");
1633   $sth->execute($bibnum);
1634   my @results;
1635   my $i=0;
1636   while (my $data=$sth->fetchrow_hashref){
1637     $results[$i]=$data;
1638     $i++;
1639   }
1640   $sth->finish;
1641   return($i,\@results);
1642 }
1643
1644 =item addauthor
1645
1646   ($count, $authors) = &addauthors($biblionumber);
1647
1648 Looks up the additional authors for the book with the given
1649 biblionumber.
1650
1651 Returns a two-element list. C<$authors> is a reference-to-array, where
1652 each element is an additional author, and C<$count> is the number of
1653 elements in C<$authors>.
1654
1655 =cut
1656 #'
1657 sub addauthor {
1658   my ($bibnum)=@_;
1659   my $dbh = C4::Context->dbh;
1660   my $sth=$dbh->prepare("Select * from additionalauthors where biblionumber=?");
1661   $sth->execute($bibnum);
1662   my @results;
1663   my $i=0;
1664   while (my $data=$sth->fetchrow_hashref){
1665     $results[$i]=$data;
1666     $i++;
1667   }
1668   $sth->finish;
1669   return($i,\@results);
1670 }
1671
1672 =item subtitle
1673
1674   ($count, $subtitles) = &subtitle($biblionumber);
1675
1676 Looks up the subtitles for the book with the given biblionumber.
1677
1678 Returns a two-element list. C<$subtitles> is a reference-to-array,
1679 where each element is a subtitle, and C<$count> is the number of
1680 elements in C<$subtitles>.
1681
1682 =cut
1683 #'
1684 sub subtitle {
1685   my ($bibnum)=@_;
1686   my $dbh = C4::Context->dbh;
1687   my $sth=$dbh->prepare("Select * from bibliosubtitle where biblionumber=?");
1688   $sth->execute($bibnum);
1689   my @results;
1690   my $i=0;
1691   while (my $data=$sth->fetchrow_hashref){
1692     $results[$i]=$data;
1693     $i++;
1694   }
1695   $sth->finish;
1696   return($i,\@results);
1697 }
1698
1699 =item itemissues
1700
1701   @issues = &itemissues($biblioitemnumber, $biblio);
1702
1703 Looks up information about who has borrowed the bookZ<>(s) with the
1704 given biblioitemnumber.
1705
1706 C<$biblio> is ignored.
1707
1708 C<&itemissues> returns an array of references-to-hash. The keys
1709 include the fields from the C<items> table in the Koha database.
1710 Additional keys include:
1711
1712 =over 4
1713
1714 =item C<date_due>
1715
1716 If the item is currently on loan, this gives the due date.
1717
1718 If the item is not on loan, then this is either "Available" or
1719 "Cancelled", if the item has been withdrawn.
1720
1721 =item C<card>
1722
1723 If the item is currently on loan, this gives the card number of the
1724 patron who currently has the item.
1725
1726 =item C<timestamp0>, C<timestamp1>, C<timestamp2>
1727
1728 These give the timestamp for the last three times the item was
1729 borrowed.
1730
1731 =item C<card0>, C<card1>, C<card2>
1732
1733 The card number of the last three patrons who borrowed this item.
1734
1735 =item C<borrower0>, C<borrower1>, C<borrower2>
1736
1737 The borrower number of the last three patrons who borrowed this item.
1738
1739 =back
1740
1741 =cut
1742 #'
1743 sub itemissues {
1744     my ($bibitem, $biblio)=@_;
1745     my $dbh   = C4::Context->dbh;
1746     # FIXME - If this function die()s, the script will abort, and the
1747     # user won't get anything; depending on how far the script has
1748     # gotten, the user might get a blank page. It would be much better
1749     # to at least print an error message. The easiest way to do this
1750     # is to set $SIG{__DIE__}.
1751     my $sth   = $dbh->prepare("Select * from items where
1752 items.biblioitemnumber = ?")
1753       || die $dbh->errstr;
1754     my $i     = 0;
1755     my @results;
1756
1757     $sth->execute($bibitem)
1758       || die $sth->errstr;
1759
1760     while (my $data = $sth->fetchrow_hashref) {
1761         # Find out who currently has this item.
1762         # FIXME - Wouldn't it be better to do this as a left join of
1763         # some sort? Currently, this code assumes that if
1764         # fetchrow_hashref() fails, then the book is on the shelf.
1765         # fetchrow_hashref() can fail for any number of reasons (e.g.,
1766         # database server crash), not just because no items match the
1767         # search criteria.
1768         my $sth2   = $dbh->prepare("select * from issues,borrowers
1769 where itemnumber = ?
1770 and returndate is NULL
1771 and issues.borrowernumber = borrowers.borrowernumber");
1772
1773         $sth2->execute($data->{'itemnumber'});
1774         if (my $data2 = $sth2->fetchrow_hashref) {
1775             $data->{'date_due'} = $data2->{'date_due'};
1776             $data->{'card'}     = $data2->{'cardnumber'};
1777             $data->{'borrower'}     = $data2->{'borrowernumber'};
1778         } else {
1779             if ($data->{'wthdrawn'} eq '1') {
1780                 $data->{'date_due'} = 'Cancelled';
1781             } else {
1782                 $data->{'date_due'} = 'Available';
1783             } # else
1784         } # else
1785
1786         $sth2->finish;
1787
1788         # Find the last 3 people who borrowed this item.
1789         $sth2 = $dbh->prepare("select * from issues, borrowers
1790                                                 where itemnumber = ?
1791                                                                         and issues.borrowernumber = borrowers.borrowernumber
1792                                                                         and returndate is not NULL
1793                                                                         order by returndate desc,timestamp desc") || die $dbh->errstr;
1794         $sth2->execute($data->{'itemnumber'}) || die $sth2->errstr;
1795         for (my $i2 = 0; $i2 < 2; $i2++) { # FIXME : error if there is less than 3 pple borrowing this item
1796             if (my $data2 = $sth2->fetchrow_hashref) {
1797                 $data->{"timestamp$i2"} = $data2->{'timestamp'};
1798                 $data->{"card$i2"}      = $data2->{'cardnumber'};
1799                 $data->{"borrower$i2"}  = $data2->{'borrowernumber'};
1800             } # if
1801         } # for
1802
1803         $sth2->finish;
1804         $results[$i] = $data;
1805         $i++;
1806     }
1807
1808     $sth->finish;
1809     return(@results);
1810 }
1811
1812 =item itemnodata
1813
1814   $item = &itemnodata($env, $dbh, $biblioitemnumber);
1815
1816 Looks up the item with the given biblioitemnumber.
1817
1818 C<$env> and C<$dbh> are ignored.
1819
1820 C<&itemnodata> returns a reference-to-hash whose keys are the fields
1821 from the C<biblio>, C<biblioitems>, and C<items> tables in the Koha
1822 database.
1823
1824 =cut
1825 #'
1826 sub itemnodata {
1827   my ($env,$dbh,$itemnumber) = @_;
1828   $dbh = C4::Context->dbh;
1829   my $sth=$dbh->prepare("Select * from biblio,items,biblioitems
1830     where items.itemnumber = ?
1831     and biblio.biblionumber = items.biblionumber
1832     and biblioitems.biblioitemnumber = items.biblioitemnumber");
1833 #  print $query;
1834   $sth->execute($itemnumber);
1835   my $data=$sth->fetchrow_hashref;
1836   $sth->finish;
1837   return($data);
1838 }
1839
1840 =item BornameSearch
1841
1842   ($count, $borrowers) = &BornameSearch($env, $searchstring, $type);
1843
1844 Looks up patrons (borrowers) by name.
1845
1846 C<$env> is ignored.
1847
1848 BUGFIX 499: C<$type> is now used to determine type of search.
1849 if $type is "simple", search is performed on the first letter of the
1850 surname only.
1851
1852 C<$searchstring> is a space-separated list of search terms. Each term
1853 must match the beginning a borrower's surname, first name, or other
1854 name.
1855
1856 C<&BornameSearch> returns a two-element list. C<$borrowers> is a
1857 reference-to-array; each element is a reference-to-hash, whose keys
1858 are the fields of the C<borrowers> table in the Koha database.
1859 C<$count> is the number of elements in C<$borrowers>.
1860
1861 =cut
1862 #'
1863 #used by member enquiries from the intranet
1864 #called by member.pl
1865 sub BornameSearch  {
1866         my ($env,$searchstring,$type)=@_;
1867         my $dbh = C4::Context->dbh;
1868         my $query = ""; my $count; my @data;
1869         my @bind=();
1870
1871         if($type eq "simple")   # simple search for one letter only
1872         {
1873                 $query="Select * from borrowers where surname like ? order by surname,firstname";
1874                 @bind=("$searchstring%");
1875         }
1876         else    # advanced search looking in surname, firstname and othernames
1877         {
1878                 @data=split(' ',$searchstring);
1879                 $count=@data;
1880                 $query="Select * from borrowers
1881                 where ((surname like ? or surname like ?
1882                 or firstname  like ? or firstname like ?
1883                 or othernames like ? or othernames like ?)
1884                 ";
1885                 @bind=("$data[0]%","% $data[0]%","$data[0]%","% $data[0]%","$data[0]%","% $data[0]%");
1886                 for (my $i=1;$i<$count;$i++){
1887                 $query=$query." and (".
1888                 " firstname  like ? or firstname like ?
1889                 or othernames like ? or othernames like ?)";
1890                 push(@bind,"$data[$i]%","% $data[$i]%","$data[$i]%","% $data[$i]%");
1891                                         # FIXME - .= <<EOT;
1892                 }
1893                 $query=$query.") or cardnumber = ?
1894                 order by surname,firstname";
1895                 push(@bind,$searchstring);
1896                                         # FIXME - .= <<EOT;
1897         }
1898
1899         my $sth=$dbh->prepare($query);
1900         $sth->execute(@bind);
1901         my @results;
1902         my $cnt=$sth->rows;
1903         while (my $data=$sth->fetchrow_hashref){
1904         push(@results,$data);
1905         }
1906         #  $sth->execute;
1907         $sth->finish;
1908         return ($cnt,\@results);
1909 }
1910
1911 =item borrdata
1912
1913   $borrower = &borrdata($cardnumber, $borrowernumber);
1914
1915 Looks up information about a patron (borrower) by either card number
1916 or borrower number. If $borrowernumber is specified, C<&borrdata>
1917 searches by borrower number; otherwise, it searches by card number.
1918
1919 C<&borrdata> returns a reference-to-hash whose keys are the fields of
1920 the C<borrowers> table in the Koha database.
1921
1922 =cut
1923 #'
1924 sub borrdata {
1925   my ($cardnumber,$bornum)=@_;
1926   $cardnumber = uc $cardnumber;
1927   my $dbh = C4::Context->dbh;
1928   my $sth;
1929   if ($bornum eq ''){
1930     $sth=$dbh->prepare("Select * from borrowers where cardnumber=?");
1931     $sth->execute($cardnumber);
1932   } else {
1933     $sth=$dbh->prepare("Select * from borrowers where borrowernumber=?");
1934   $sth->execute($bornum);
1935   }
1936   my $data=$sth->fetchrow_hashref;
1937   $sth->finish;
1938   if ($data) {
1939         return($data);
1940         } else { # try with firstname
1941                 if ($cardnumber) {
1942                         my $sth=$dbh->prepare("select * from borrowers where firstname=?");
1943                         $sth->execute($cardnumber);
1944                         my $data=$sth->fetchrow_hashref;
1945                         $sth->finish;
1946                         return($data);
1947                 }
1948         }
1949         return undef;
1950 }
1951
1952 =item borrissues
1953
1954   ($count, $issues) = &borrissues($borrowernumber);
1955
1956 Looks up what the patron with the given borrowernumber has borrowed.
1957
1958 C<&borrissues> returns a two-element array. C<$issues> is a
1959 reference-to-array, where each element is a reference-to-hash; the
1960 keys are the fields from the C<issues>, C<biblio>, and C<items> tables
1961 in the Koha database. C<$count> is the number of elements in
1962 C<$issues>.
1963
1964 =cut
1965 #'
1966 sub borrissues {
1967   my ($bornum)=@_;
1968   my $dbh = C4::Context->dbh;
1969   my $sth=$dbh->prepare("Select * from issues,biblio,items where borrowernumber=?
1970    and items.itemnumber=issues.itemnumber
1971         and items.biblionumber=biblio.biblionumber
1972         and issues.returndate is NULL order by date_due");
1973     $sth->execute($bornum);
1974   my @result;
1975   while (my $data = $sth->fetchrow_hashref) {
1976     push @result, $data;
1977   }
1978   $sth->finish;
1979   return(scalar(@result), \@result);
1980 }
1981
1982 =item allissues
1983
1984   ($count, $issues) = &allissues($borrowernumber, $sortkey, $limit);
1985
1986 Looks up what the patron with the given borrowernumber has borrowed,
1987 and sorts the results.
1988
1989 C<$sortkey> is the name of a field on which to sort the results. This
1990 should be the name of a field in the C<issues>, C<biblio>,
1991 C<biblioitems>, or C<items> table in the Koha database.
1992
1993 C<$limit> is the maximum number of results to return.
1994
1995 C<&allissues> returns a two-element array. C<$issues> is a
1996 reference-to-array, where each element is a reference-to-hash; the
1997 keys are the fields from the C<issues>, C<biblio>, C<biblioitems>, and
1998 C<items> tables of the Koha database. C<$count> is the number of
1999 elements in C<$issues>
2000
2001 =cut
2002 #'
2003 sub allissues {
2004   my ($bornum,$order,$limit)=@_;
2005   #FIXME: sanity-check order and limit
2006   my $dbh = C4::Context->dbh;
2007   my $query="Select * from issues,biblio,items,biblioitems
2008   where borrowernumber=? and
2009   items.biblioitemnumber=biblioitems.biblioitemnumber and
2010   items.itemnumber=issues.itemnumber and
2011   items.biblionumber=biblio.biblionumber order by $order";
2012   if ($limit !=0){
2013     $query.=" limit $limit";
2014   }
2015   #print $query;
2016   my $sth=$dbh->prepare($query);
2017   $sth->execute($bornum);
2018   my @result;
2019   my $i=0;
2020   while (my $data=$sth->fetchrow_hashref){
2021     $result[$i]=$data;;
2022     $i++;
2023   }
2024   $sth->finish;
2025   return($i,\@result);
2026 }
2027
2028 =item borrdata2
2029
2030   ($borrowed, $due, $fine) = &borrdata2($env, $borrowernumber);
2031
2032 Returns aggregate data about items borrowed by the patron with the
2033 given borrowernumber.
2034
2035 C<$env> is ignored.
2036
2037 C<&borrdata2> returns a three-element array. C<$borrowed> is the
2038 number of books the patron currently has borrowed. C<$due> is the
2039 number of overdue items the patron currently has borrowed. C<$fine> is
2040 the total fine currently due by the borrower.
2041
2042 =cut
2043 #'
2044 sub borrdata2 {
2045   my ($env,$bornum)=@_;
2046   my $dbh = C4::Context->dbh;
2047   my $query="Select count(*) from issues where borrowernumber='$bornum' and
2048     returndate is NULL";
2049     # print $query;
2050   my $sth=$dbh->prepare($query);
2051   $sth->execute;
2052   my $data=$sth->fetchrow_hashref;
2053   $sth->finish;
2054   $sth=$dbh->prepare("Select count(*) from issues where
2055     borrowernumber='$bornum' and date_due < now() and returndate is NULL");
2056   $sth->execute;
2057   my $data2=$sth->fetchrow_hashref;
2058   $sth->finish;
2059   $sth=$dbh->prepare("Select sum(amountoutstanding) from accountlines where
2060     borrowernumber='$bornum'");
2061   $sth->execute;
2062   my $data3=$sth->fetchrow_hashref;
2063   $sth->finish;
2064
2065 return($data2->{'count(*)'},$data->{'count(*)'},$data3->{'sum(amountoutstanding)'});
2066 }
2067
2068 =item getboracctrecord
2069
2070   ($count, $acctlines, $total) = &getboracctrecord($env, $borrowernumber);
2071
2072 Looks up accounting data for the patron with the given borrowernumber.
2073
2074 C<$env> is ignored.
2075
2076 (FIXME - I'm not at all sure what this is about.)
2077
2078 C<&getboracctrecord> returns a three-element array. C<$acctlines> is a
2079 reference-to-array, where each element is a reference-to-hash; the
2080 keys are the fields of the C<accountlines> table in the Koha database.
2081 C<$count> is the number of elements in C<$acctlines>. C<$total> is the
2082 total amount outstanding for all of the account lines.
2083
2084 =cut
2085 #'
2086 sub getboracctrecord {
2087    my ($env,$params) = @_;
2088    my $dbh = C4::Context->dbh;
2089    my @acctlines;
2090    my $numlines=0;
2091    my $sth=$dbh->prepare("Select * from accountlines where
2092 borrowernumber=? order by date desc,timestamp desc");
2093 #   print $query;
2094    $sth->execute($params->{'borrowernumber'});
2095    my $total=0;
2096    while (my $data=$sth->fetchrow_hashref){
2097    #FIXME before reinstating: insecure?
2098 #      if ($data->{'itemnumber'} ne ''){
2099 #        $query="Select * from items,biblio where items.itemnumber=
2100 #       '$data->{'itemnumber'}' and biblio.biblionumber=items.biblionumber";
2101 #       my $sth2=$dbh->prepare($query);
2102 #       $sth2->execute;
2103 #       my $data2=$sth2->fetchrow_hashref;
2104 #       $sth2->finish;
2105 #       $data=$data2;
2106  #     }
2107       $acctlines[$numlines] = $data;
2108       $numlines++;
2109       $total += $data->{'amountoutstanding'};
2110    }
2111    $sth->finish;
2112    return ($numlines,\@acctlines,$total);
2113 }
2114
2115 =item itemcount
2116
2117   ($count, $lcount, $nacount, $fcount, $scount, $lostcount,
2118   $mending, $transit,$ocount) =
2119     &itemcount($env, $biblionumber, $type);
2120
2121 Counts the number of items with the given biblionumber, broken down by
2122 category.
2123
2124 C<$env> is ignored.
2125
2126 If C<$type> is not set to C<intra>, lost, very overdue, and withdrawn
2127 items will not be counted.
2128
2129 C<&itemcount> returns a nine-element list:
2130
2131 C<$count> is the total number of items with the given biblionumber.
2132
2133 C<$lcount> is the number of items at the Levin branch.
2134
2135 C<$nacount> is the number of items that are neither borrowed, lost,
2136 nor withdrawn (and are therefore presumably on a shelf somewhere).
2137
2138 C<$fcount> is the number of items at the Foxton branch.
2139
2140 C<$scount> is the number of items at the Shannon branch.
2141
2142 C<$lostcount> is the number of lost and very overdue items.
2143
2144 C<$mending> is the number of items at the Mending branch (being
2145 mended?).
2146
2147 C<$transit> is the number of items at the Transit branch (in transit
2148 between branches?).
2149
2150 C<$ocount> is the number of items that haven't arrived yet
2151 (aqorders.quantity - aqorders.quantityreceived).
2152
2153 =cut
2154 #'
2155
2156 # FIXME - There's also a &C4::Biblio::itemcount.
2157 # Since they're all exported, acqui/acquire.pl doesn't compile with -w.
2158 sub itemcount {
2159   my ($env,$bibnum,$type)=@_;
2160   my $dbh = C4::Context->dbh;
2161   my $query="Select * from items where
2162   biblionumber=? ";
2163   if ($type ne 'intra'){
2164     $query.=" and ((itemlost <>1 and itemlost <> 2) or itemlost is NULL) and
2165     (wthdrawn <> 1 or wthdrawn is NULL)";
2166   }
2167   my $sth=$dbh->prepare($query);
2168   #  print $query;
2169   $sth->execute($bibnum);
2170   my $count=0;
2171   my $lcount=0;
2172   my $nacount=0;
2173   my $fcount=0;
2174   my $scount=0;
2175   my $lostcount=0;
2176   my $mending=0;
2177   my $transit=0;
2178   my $ocount=0;
2179   while (my $data=$sth->fetchrow_hashref){
2180     $count++;
2181
2182     my $sth2=$dbh->prepare("select * from issues,items where issues.itemnumber=
2183     ? and returndate is NULL
2184     and items.itemnumber=issues.itemnumber and ((items.itemlost <>1 and
2185     items.itemlost <> 2) or items.itemlost is NULL)
2186     and (wthdrawn <> 1 or wthdrawn is NULL)");
2187     $sth2->execute($data->{'itemnumber'});
2188     if (my $data2=$sth2->fetchrow_hashref){
2189        $nacount++;
2190     } else {
2191       if ($data->{'holdingbranch'} eq 'C' || $data->{'holdingbranch'} eq 'LT'){
2192         $lcount++;
2193       }
2194       if ($data->{'holdingbranch'} eq 'F' || $data->{'holdingbranch'} eq 'FP'){
2195         $fcount++;
2196       }
2197       if ($data->{'holdingbranch'} eq 'S' || $data->{'holdingbranch'} eq 'SP'){
2198         $scount++;
2199       }
2200       if ($data->{'itemlost'} eq '1'){
2201         $lostcount++;
2202       }
2203       if ($data->{'itemlost'} eq '2'){
2204         $lostcount++;
2205       }
2206       if ($data->{'holdingbranch'} eq 'FM'){
2207         $mending++;
2208       }
2209       if ($data->{'holdingbranch'} eq 'TR'){
2210         $transit++;
2211       }
2212     }
2213     $sth2->finish;
2214   }
2215 #  if ($count == 0){
2216     my $sth2=$dbh->prepare("Select * from aqorders where biblionumber=?");
2217     $sth2->execute($bibnum);
2218     if (my $data=$sth2->fetchrow_hashref){
2219       $ocount=$data->{'quantity'} - $data->{'quantityreceived'};
2220     }
2221 #    $count+=$ocount;
2222     $sth2->finish;
2223   $sth->finish;
2224   return ($count,$lcount,$nacount,$fcount,$scount,$lostcount,$mending,$transit,$ocount);
2225 }
2226
2227 =item itemcount2
2228
2229   $counts = &itemcount2($env, $biblionumber, $type);
2230
2231 Counts the number of items with the given biblionumber, broken down by
2232 category.
2233
2234 C<$env> is ignored.
2235
2236 C<$type> may be either C<intra> or anything else. If it is not set to
2237 C<intra>, then the search will exclude lost, very overdue, and
2238 withdrawn items.
2239
2240 C<$&itemcount2> returns a reference-to-hash, with the following fields:
2241
2242 =over 4
2243
2244 =item C<total>
2245
2246 The total number of items with this biblionumber.
2247
2248 =item C<order>
2249
2250 The number of items on order (aqorders.quantity -
2251 aqorders.quantityreceived).
2252
2253 =item I<branchname>
2254
2255 For each branch that has at least one copy of the book, C<$counts>
2256 will have a key with the branch name, giving the number of copies at
2257 that branch.
2258
2259 =back
2260
2261 =cut
2262 #'
2263 sub itemcount2 {
2264   my ($env,$bibnum,$type)=@_;
2265   my $dbh = C4::Context->dbh;
2266   my $query="Select * from items,branches where
2267   biblionumber=? and items.holdingbranch=branches.branchcode";
2268   if ($type ne 'intra'){
2269     $query.=" and ((itemlost <>1 and itemlost <> 2) or itemlost is NULL) and
2270     (wthdrawn <> 1 or wthdrawn is NULL)";
2271   }
2272   my $sth=$dbh->prepare($query);
2273   #  print $query;
2274   $sth->execute($bibnum);
2275   my %counts;
2276   $counts{'total'}=0;
2277   while (my $data=$sth->fetchrow_hashref){
2278     $counts{'total'}++;
2279
2280     my $status;
2281     for my $test (
2282       [
2283         'Item Lost',
2284         'select * from items
2285           where itemnumber=?
2286             and not ((items.itemlost <>1 and items.itemlost <> 2)
2287                       or items.itemlost is NULL)'
2288       ], [
2289         'Withdrawn',
2290         'select * from items
2291           where itemnumber=? and not (wthdrawn <> 1 or wthdrawn is NULL)'
2292       ], [
2293         'On Loan', "select * from issues,items
2294           where issues.itemnumber=? and returndate is NULL
2295             and items.itemnumber=issues.itemnumber"
2296       ],
2297     ) {
2298         my($testlabel, $query2) = @$test;
2299
2300         my $sth2=$dbh->prepare($query2);
2301         $sth2->execute($data->{'itemnumber'});
2302
2303         # FIXME - fetchrow_hashref() can fail for any number of reasons
2304         # (e.g., a database server crash). Perhaps use a left join of some
2305         # sort for this?
2306         $status = $testlabel if $sth2->fetchrow_hashref;
2307         $sth2->finish;
2308     last if defined $status;
2309     }
2310     $status = $data->{'branchname'} unless defined $status;
2311     $counts{$status}++;
2312   }
2313   my $sth2=$dbh->prepare("Select * from aqorders where biblionumber=? and
2314   datecancellationprinted is NULL and quantity > quantityreceived");
2315   $sth2->execute($bibnum);
2316   if (my $data=$sth2->fetchrow_hashref){
2317       $counts{'order'}=$data->{'quantity'} - $data->{'quantityreceived'};
2318   }
2319   $sth2->finish;
2320   $sth->finish;
2321   return (\%counts);
2322 }
2323
2324 =item ItemType
2325
2326   $description = &ItemType($itemtype);
2327
2328 Given an item type code, returns the description for that type.
2329
2330 =cut
2331 #'
2332
2333 # FIXME - I'm pretty sure that after the initial setup, the list of
2334 # item types doesn't change very often. Hence, it seems slow and
2335 # inefficient to make yet another database call to look up information
2336 # that'll only change every few months or years.
2337 #
2338 # Much better, I think, to automatically build a Perl file that can be
2339 # included in those scripts that require it, e.g.:
2340 #       @itemtypes = qw( ART BCD CAS CD F ... );
2341 #       %itemtypedesc = (
2342 #               ART     => "Art Prints",
2343 #               BCD     => "CD-ROM from book",
2344 #               CD      => "Compact disc (WN)",
2345 #               F       => "Free Fiction",
2346 #               ...
2347 #       );
2348 # The web server can then run a cron job to rebuild this file from the
2349 # database every hour or so.
2350 #
2351 # The same thing goes for branches, book funds, book sellers, currency
2352 # rates, printers, stopwords, and perhaps others.
2353 sub ItemType {
2354   my ($type)=@_;
2355   my $dbh = C4::Context->dbh;
2356   my $sth=$dbh->prepare("select description from itemtypes where itemtype=?");
2357   $sth->execute($type);
2358   my $dat=$sth->fetchrow_hashref;
2359   $sth->finish;
2360   return ($dat->{'description'});
2361 }
2362
2363 =item bibitems
2364
2365   ($count, @results) = &bibitems($biblionumber);
2366
2367 Given the biblionumber for a book, C<&bibitems> looks up that book's
2368 biblioitems (different publications of the same book, the audio book
2369 and film versions, etc.).
2370
2371 C<$count> is the number of elements in C<@results>.
2372
2373 C<@results> is an array of references-to-hash; the keys are the fields
2374 of the C<biblioitems> and C<itemtypes> tables of the Koha database. In
2375 addition, C<itemlost> indicates the availability of the item: if it is
2376 "2", then all copies of the item are long overdue; if it is "1", then
2377 all copies are lost; otherwise, there is at least one copy available.
2378
2379 =cut
2380 #'
2381 sub bibitems {
2382     my ($bibnum) = @_;
2383     my $dbh   = C4::Context->dbh;
2384     my $sth   = $dbh->prepare("SELECT biblioitems.*,
2385                         itemtypes.*,
2386                         MIN(items.itemlost)        as itemlost,
2387                         MIN(items.dateaccessioned) as dateaccessioned
2388                           FROM biblioitems, itemtypes, items
2389                          WHERE biblioitems.biblionumber     = ?
2390                            AND biblioitems.itemtype         = itemtypes.itemtype
2391                            AND biblioitems.biblioitemnumber = items.biblioitemnumber
2392                       GROUP BY items.biblioitemnumber");
2393     my $count = 0;
2394     my @results;
2395     $sth->execute($bibnum);
2396     while (my $data = $sth->fetchrow_hashref) {
2397         $results[$count] = $data;
2398         $count++;
2399     } # while
2400     $sth->finish;
2401     return($count, @results);
2402 } # sub bibitems
2403
2404 =item barcodes
2405
2406   @barcodes = &barcodes($biblioitemnumber);
2407
2408 Given a biblioitemnumber, looks up the corresponding items.
2409
2410 Returns an array of references-to-hash; the keys are C<barcode> and
2411 C<itemlost>.
2412
2413 The returned items include very overdue items, but not lost ones.
2414
2415 =cut
2416 #'
2417 sub barcodes{
2418     #called from request.pl
2419     my ($biblioitemnumber)=@_;
2420     my $dbh = C4::Context->dbh;
2421     my $sth=$dbh->prepare("SELECT barcode, itemlost, holdingbranch FROM items
2422                            WHERE biblioitemnumber = ?
2423                              AND (wthdrawn <> 1 OR wthdrawn IS NULL)");
2424     $sth->execute($biblioitemnumber);
2425     my @barcodes;
2426     my $i=0;
2427     while (my $data=$sth->fetchrow_hashref){
2428         $barcodes[$i]=$data;
2429         $i++;
2430     }
2431     $sth->finish;
2432     return(@barcodes);
2433 }
2434
2435 =item getwebsites
2436
2437   ($count, @websites) = &getwebsites($biblionumber);
2438
2439 Looks up the web sites pertaining to the book with the given
2440 biblionumber.
2441
2442 C<$count> is the number of elements in C<@websites>.
2443
2444 C<@websites> is an array of references-to-hash; the keys are the
2445 fields from the C<websites> table in the Koha database.
2446
2447 =cut
2448 #'
2449 sub getwebsites {
2450     my ($biblionumber) = @_;
2451     my $dbh   = C4::Context->dbh;
2452     my $sth   = $dbh->prepare("Select * from websites where biblionumber = ?");
2453     my $count = 0;
2454     my @results;
2455
2456     $sth->execute($biblionumber);
2457     while (my $data = $sth->fetchrow_hashref) {
2458         # FIXME - The URL scheme shouldn't be stripped off, at least
2459         # not here, since it's part of the URL, and will be useful in
2460         # constructing a link to the site. If you don't want the user
2461         # to see the "http://" part, strip that off when building the
2462         # HTML code.
2463         $data->{'url'} =~ s/^http:\/\///;       # FIXME - Leaning toothpick
2464                                                 # syndrome
2465         $results[$count] = $data;
2466         $count++;
2467     } # while
2468
2469     $sth->finish;
2470     return($count, @results);
2471 } # sub getwebsites
2472
2473 =item getwebbiblioitems
2474
2475   ($count, @results) = &getwebbiblioitems($biblionumber);
2476
2477 Given a book's biblionumber, looks up the web versions of the book
2478 (biblioitems with itemtype C<WEB>).
2479
2480 C<$count> is the number of items in C<@results>. C<@results> is an
2481 array of references-to-hash; the keys are the items from the
2482 C<biblioitems> table of the Koha database.
2483
2484 =cut
2485 #'
2486 sub getwebbiblioitems {
2487     my ($biblionumber) = @_;
2488     my $dbh   = C4::Context->dbh;
2489     my $sth   = $dbh->prepare("Select * from biblioitems where biblionumber = ?
2490 and itemtype = 'WEB'");
2491     my $count = 0;
2492     my @results;
2493
2494     $sth->execute($biblionumber);
2495     while (my $data = $sth->fetchrow_hashref) {
2496         $data->{'url'} =~ s/^http:\/\///;
2497         $results[$count] = $data;
2498         $count++;
2499     } # while
2500
2501     $sth->finish;
2502     return($count, @results);
2503 } # sub getwebbiblioitems
2504
2505
2506 =item breedingsearch
2507
2508   ($count, @results) = &breedingsearch($title,$isbn,$random);
2509 C<$title> contains the title,
2510 C<$isbn> contains isbn or issn,
2511 C<$random> contains the random seed from a z3950 search.
2512
2513 C<$count> is the number of items in C<@results>. C<@results> is an
2514 array of references-to-hash; the keys are the items from the C<marc_breeding> table of the Koha database.
2515
2516 =cut
2517
2518 sub breedingsearch {
2519         my ($title,$isbn,$z3950random) = @_;
2520         my $dbh   = C4::Context->dbh;
2521         my $count = 0;
2522         my ($query,@bind);
2523         my $sth;
2524         my @results;
2525
2526         $query = "Select id,file,isbn,title,author from marc_breeding where ";
2527         if ($z3950random) {
2528                 $query .= "z3950random = ?";
2529                 @bind=($z3950random);
2530         } else {
2531             @bind=();
2532                 if ($title) {
2533                         $query .= "title like ?";
2534                         push(@bind,"$title%");
2535                 }
2536                 if ($title && $isbn) {
2537                         $query .= " and ";
2538                 }
2539                 if ($isbn) {
2540                         $query .= "isbn like ?";
2541                         push(@bind,"$isbn%");
2542                 }
2543         }
2544         $sth   = $dbh->prepare($query);
2545         $sth->execute(@bind);
2546         while (my $data = $sth->fetchrow_hashref) {
2547                         $results[$count] = $data;
2548                         $count++;
2549         } # while
2550
2551         $sth->finish;
2552         return($count, @results);
2553 } # sub breedingsearch
2554
2555
2556
2557
2558
2559 =item isbnsearch
2560
2561   ($count, @results) = &isbnsearch($isbn,$title);
2562
2563 Given an isbn and/or a title, returns the biblios having it.
2564 Used in acqui.simple, isbnsearch.pl only
2565
2566 C<$count> is the number of items in C<@results>. C<@results> is an
2567 array of references-to-hash; the keys are the items from the
2568 C<biblioitems> table of the Koha database.
2569
2570 =cut
2571
2572 sub isbnsearch {
2573     my ($isbn,$title) = @_;
2574     my $dbh   = C4::Context->dbh;
2575     my $count = 0;
2576     my ($query,@bind);
2577     my $sth;
2578     my @results;
2579
2580     $query = "Select distinct biblio.* from biblio, biblioitems where
2581                                 biblio.biblionumber = biblioitems.biblionumber";
2582         @bind=();
2583         if ($isbn) {
2584                 $query .= " and isbn like ?";
2585                 @bind=(uc($isbn)."%");
2586         }
2587         if ($title) {
2588                 $query .= " and title like ?";
2589                 @bind=($title."%");
2590         }
2591     $sth   = $dbh->prepare($query);
2592
2593     $sth->execute(@bind);
2594     while (my $data = $sth->fetchrow_hashref) {
2595         $results[$count] = $data;
2596         $count++;
2597     } # while
2598
2599     $sth->finish;
2600     return($count, @results);
2601 } # sub isbnsearch
2602
2603 =item getbranchname
2604
2605   $branchname = &getbranchname($branchcode);
2606
2607 Given the branch code, the function returns the corresponding
2608 branch name for a comprehensive information display
2609
2610 =cut
2611
2612 sub getbranchname
2613 {
2614         my ($branchcode) = @_;
2615         my $dbh = C4::Context->dbh;
2616         my $sth = $dbh->prepare("SELECT branchname FROM branches WHERE branchcode = ?");
2617         $sth->execute($branchcode);
2618         my $branchname = $sth->fetchrow();
2619         $sth->finish();
2620         return $branchname;
2621 } # sub getbranchname
2622
2623 =item getborrowercategory
2624
2625   $description = &getborrowercategory($categorycode);
2626
2627 Given the borrower's category code, the function returns the corresponding
2628 description for a comprehensive information display.
2629
2630 =cut
2631
2632 sub getborrowercategory
2633 {
2634         my ($catcode) = @_;
2635         my $dbh = C4::Context->dbh;
2636         my $sth = $dbh->prepare("SELECT description FROM categories WHERE categorycode = ?");
2637         $sth->execute($catcode);
2638         my $description = $sth->fetchrow();
2639         $sth->finish();
2640         return $description;
2641 } # sub getborrowercategory
2642
2643
2644 END { }       # module clean-up code here (global destructor)
2645
2646 1;
2647 __END__
2648
2649 =back
2650
2651 =head1 AUTHOR
2652
2653 Koha Developement team <info@koha.org>
2654
2655 =cut