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