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