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