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