Added some FIXME comments.
[koha.git] / C4 / Search.pm
1 package C4::Search;
2
3 # Copyright 2000-2002 Katipo Communications
4 #
5 # This file is part of Koha.
6 #
7 # Koha is free software; you can redistribute it and/or modify it under the
8 # terms of the GNU General Public License as published by the Free Software
9 # Foundation; either version 2 of the License, or (at your option) any later
10 # version.
11 #
12 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
13 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
14 # A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
15 #
16 # You should have received a copy of the GNU General Public License along with
17 # Koha; if not, write to the Free Software Foundation, Inc., 59 Temple Place,
18 # Suite 330, Boston, MA  02111-1307 USA
19
20 use strict;
21 require Exporter;
22 use DBI;
23 use C4::Context;
24 use C4::Reserves2;
25         # FIXME - C4::Search uses C4::Reserves2, which uses C4::Search.
26         # So Perl complains that all of the functions here get redefined.
27
28 use vars qw($VERSION @ISA @EXPORT @EXPORT_OK %EXPORT_TAGS);
29
30 # set the version for version checking
31 $VERSION = 0.02;
32
33 =head1 NAME
34
35 C4::Search - Functions for searching the Koha catalog and other databases
36
37 =head1 SYNOPSIS
38
39   use C4::Search;
40
41   my ($count, @results) = catalogsearch($env, $type, $search, $num, $offset);
42
43 =head1 DESCRIPTION
44
45 This module provides the searching facilities for the Koha catalog and
46 other databases.
47
48 C<&catalogsearch> is a front end to all the other searches. Depending
49 on what is passed to it, it calls the appropriate search function.
50
51 =head1 FUNCTIONS
52
53 =over 2
54
55 =cut
56
57 @ISA = qw(Exporter);
58 @EXPORT = qw(&CatSearch &BornameSearch &ItemInfo &KeywordSearch &subsearch
59 &itemdata &bibdata &GetItems &borrdata &itemnodata &itemcount
60 &borrdata2 &NewBorrowerNumber &bibitemdata &borrissues
61 &getboracctrecord &ItemType &itemissues &subject &subtitle
62 &addauthor &bibitems &barcodes &findguarantees &allissues
63 &findguarantor &getwebsites &getwebbiblioitems &catalogsearch &itemcount2);
64 # make all your functions, whether exported or not;
65
66 =item findguarantees
67
68   ($num_children, $children_arrayref) = &findguarantees($parent_borrno);
69   $child0_cardno = $children_arrayref->[0]{"cardnumber"};
70   $child0_borrno = $children_arrayref->[0]{"borrowernumber"};
71
72 C<&findguarantees> takes a borrower number (e.g., that of a patron
73 with children) and looks up the borrowers who are guaranteed by that
74 borrower (i.e., the patron's children).
75
76 C<&findguarantees> returns two values: an integer giving the number of
77 borrowers guaranteed by C<$parent_borrno>, and a reference to an array
78 of references to hash, which gives the actual results.
79
80 =cut
81 #'
82 sub findguarantees{
83   my ($bornum)=@_;
84   my $dbh = C4::Context->dbh;
85   my $query="select cardnumber,borrowernumber from borrowers where
86   guarantor='$bornum'";
87   my $sth=$dbh->prepare($query);
88   $sth->execute;
89
90   my @dat;
91   while (my $data = $sth->fetchrow_hashref)
92   {
93     push @dat, $data;
94   }
95   $sth->finish;
96   return (scalar(@dat), \@dat);
97 }
98
99 =item findguarantor
100
101   $guarantor = &findguarantor($borrower_no);
102   $guarantor_cardno = $guarantor->{"cardnumber"};
103   $guarantor_surname = $guarantor->{"surname"};
104   ...
105
106 C<&findguarantor> takes a borrower number (presumably that of a child
107 patron), finds the guarantor for C<$borrower_no> (the child's parent),
108 and returns the record for the guarantor.
109
110 C<&findguarantor> returns a reference-to-hash. Its keys are the fields
111 from the C<borrowers> database table;
112
113 =cut
114 #'
115 sub findguarantor{
116   my ($bornum)=@_;
117   my $dbh = C4::Context->dbh;
118   my $query="select guarantor from borrowers where
119   borrowernumber='$bornum'";
120   my $sth=$dbh->prepare($query);
121   $sth->execute;
122   my $data=$sth->fetchrow_hashref;
123   $sth->finish;
124   $query="Select * from borrowers where
125   borrowernumber='$data->{'guarantor'}'";
126   $sth=$dbh->prepare($query);
127   $sth->execute;
128   $data=$sth->fetchrow_hashref;
129   $sth->finish;
130   return($data);
131 }
132
133 =item NewBorrowerNumber
134
135   $num = &NewBorrowerNumber();
136
137 Allocates a new, unused borrower number, and returns it.
138
139 =cut
140 #'
141 # FIXME - This is identical to C4::Circulation::Borrower::NewBorrowerNumber.
142 # Pick one and stick with it. Preferably use the other one. This function
143 # doesn't belong in C4::Search.
144 sub NewBorrowerNumber {
145   my $dbh = C4::Context->dbh;
146   my $sth=$dbh->prepare("Select max(borrowernumber) from borrowers");
147   $sth->execute;
148   my $data=$sth->fetchrow_hashref;
149   $sth->finish;
150   $data->{'max(borrowernumber)'}++;
151   return($data->{'max(borrowernumber)'});
152 }
153
154 =item catalogsearch
155
156   ($count, @results) = &catalogsearch($env, $type, $search, $num, $offset);
157
158 This is primarily a front-end to other, more specialized catalog
159 search functions: if C<$search-E<gt>{itemnumber}> or
160 C<$search-E<gt>{isbn}> is given, C<&catalogsearch> uses a precise
161 C<&CatSearch>. If $search->{subject} is given, it runs a subject
162 C<&CatSearch>. If C<$search-E<gt>{keyword}> is given, it runs a
163 C<&KeywordSearch>. Otherwise, it runs a loose C<&CatSearch>.
164
165 If C<$env-E<gt>{itemcount}> is 1, then C<&catalogsearch> also counts
166 the items for each result, and adds several keys:
167
168 =over 4
169
170 =item C<itemcount>
171
172 The total number of copies of this book.
173
174 =item C<locationhash>
175
176 This is a reference-to-hash; the keys are the names of branches where
177 this book may be found, and the values are the number of copies at
178 that branch.
179
180 =item C<location>
181
182 A descriptive string saying where the book is located, and how many
183 copies there are, if greater than 1.
184
185 =item C<subject2>
186
187 The book's subject, with spaces replaced with C<%20>, presumably for
188 HTML.
189
190 =back
191
192 =cut
193 #'
194 sub catalogsearch {
195   my ($env,$type,$search,$num,$offset)=@_;
196   my $dbh = C4::Context->dbh;
197 #  foreach my $key (%$search){
198 #    $search->{$key}=$dbh->quote($search->{$key});
199 #  }
200   my ($count,@results);
201 #  print STDERR "Doing a search \n";
202   # FIXME - Use "elsif" to avoid this sort of deep nesting
203   if ($search->{'itemnumber'} ne '' || $search->{'isbn'} ne ''){
204         print STDERR "Doing a precise search\n";
205     ($count,@results)=CatSearch($env,'precise',$search,$num,$offset);
206
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=$query." and (title like '$key[$i]%' or title like '% $key[$i]%')";
571                                 # FIXME - .=
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=$query."))";           # FIXME - .=
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=$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                                 # FIXME - .= <<EOT
894            $i++;
895          }
896          $query=$query.")";     # FIXME - .=
897          if ($search->{'title'} ne ''){
898            my @key=split(' ',$search->{'title'});
899            my $count=@key;
900            my $i=0;
901            $query.= " and (((title like '$key[0]%' or title like '% $key[0]%' or title like '% $key[0]')";
902             while ($i<$count){
903               $query=$query." and (title like '$key[$i]%' or title like '% $key[$i]%' or title like '% $key[$i]')";
904                                 # FIXME - .=
905               $i++;
906             }
907 #           $query.=") or ((subtitle like '$key[0]%' or subtitle like '% $key[0] %' or subtitle like '% $key[0]')";
908 #            for ($i=1;$i<$count;$i++){
909 #             $query.=" and (subtitle like '$key[$i]%' or subtitle like '% $key[$i] %' or subtitle like '% $key[$i]')";
910 #            }
911             $query.=") or ((seriestitle like '$key[0]%' or seriestitle like '% $key[0]%' or seriestitle like '% $key[0]')";
912             for ($i=1;$i<$count;$i++){
913                 $query.=" and (seriestitle like '$key[$i]%' or seriestitle like '% $key[$i]%')";
914             }
915             $query.=") or ((unititle like '$key[0]%' or unititle like '% $key[0]%' or unititle like '% $key[0]')";
916             for ($i=1;$i<$count;$i++){
917                 $query.=" and (unititle like '$key[$i]%' or unititle like '% $key[$i]%')";
918             }
919             $query=$query."))";         # FIXME - .=
920            #$query=$query. " and (title like '%$search->{'title'}%'
921            #or seriestitle like '%$search->{'title'}%')";
922          }
923          if ($search->{'abstract'} ne ''){
924             $query.= " and (abstract like '%$search->{'abstract'}%')";
925          }
926          if ($search->{'date-before'} ne ''){
927             $query.= " and (copyrightdate like '%$search->{'date-before'}%')";
928            }
929
930          $query.=" group by biblio.biblionumber";
931       } else {
932           if ($search->{'title'} ne '') {
933            if ($search->{'ttype'} eq 'exact'){
934              $query="select * from biblio
935              where
936              (biblio.title='$search->{'title'}' or (biblio.unititle = '$search->{'title'}'
937              or biblio.unititle like '$search->{'title'} |%' or
938              biblio.unititle like '%| $search->{'title'} |%' or
939              biblio.unititle like '%| $search->{'title'}') or
940              (biblio.seriestitle = '$search->{'title'}' or
941              biblio.seriestitle like '$search->{'title'} |%' or
942              biblio.seriestitle like '%| $search->{'title'} |%' or
943              biblio.seriestitle like '%| $search->{'title'}')
944              )";
945            } else {
946             my @key=split(' ',$search->{'title'});
947             my $count=@key;
948             my $i=1;
949             $query="select * from biblio
950             left join bibliosubtitle on
951             biblio.biblionumber=bibliosubtitle.biblionumber
952             where
953             (((title like '$key[0]%' or title like '% $key[0]%' or title like '% $key[0]')";
954             while ($i<$count){
955               $query=$query." and (title like '$key[$i]%' or title like '% $key[$i]%' or title like '% $key[$i]')";
956                                         # FIXME - .=
957               $i++;
958             }
959             $query.=") or ((subtitle like '$key[0]%' or subtitle like '% $key[0]%' or subtitle like '% $key[0]')";
960             for ($i=1;$i<$count;$i++){
961               $query.=" and (subtitle like '$key[$i]%' or subtitle like '% $key[$i]%' or subtitle like '% $key[$i]')";
962             }
963             $query.=") or ((seriestitle like '$key[0]%' or seriestitle like '% $key[0]%' or seriestitle like '% $key[0]')";
964             for ($i=1;$i<$count;$i++){
965               $query.=" and (seriestitle like '$key[$i]%' or seriestitle like '% $key[$i]%')";
966             }
967             $query.=") or ((unititle like '$key[0]%' or unititle like '% $key[0]%' or unititle like '% $key[0]')";
968             for ($i=1;$i<$count;$i++){
969               $query.=" and (unititle like '$key[$i]%' or unititle like '% $key[$i]%')";
970             }
971             $query=$query."))";         # FIXME - .=
972            }
973            if ($search->{'abstract'} ne ''){
974             $query.= " and (abstract like '%$search->{'abstract'}%')";
975            }
976            if ($search->{'date-before'} ne ''){
977             $query.= " and (copyrightdate like '%$search->{'date-before'}%')";
978            }
979           } elsif ($search->{'class'} ne ''){
980              $query="select * from biblioitems,biblio where biblio.biblionumber=biblioitems.biblionumber";
981              my @temp=split(/\|/,$search->{'class'});
982               my $count=@temp;
983               $query.= " and ( itemtype='$temp[0]'";
984               for (my $i=1;$i<$count;$i++){
985                $query.=" or itemtype='$temp[$i]'";
986               }
987               $query.=")";
988               if ($search->{'illustrator'} ne ''){
989                 $query.=" and illus like '%".$search->{'illustrator'}."%' ";
990               }
991               if ($search->{'dewey'} ne ''){
992                 $query.=" and biblioitems.dewey like '$search->{'dewey'}%'";
993               }
994           } elsif ($search->{'dewey'} ne ''){
995              $query="select * from biblioitems,biblio
996              where biblio.biblionumber=biblioitems.biblionumber
997              and biblioitems.dewey like '$search->{'dewey'}%'";
998           } elsif ($search->{'illustrator'} ne '') {
999              $query="select * from biblioitems,biblio
1000              where biblio.biblionumber=biblioitems.biblionumber
1001              and biblioitems.illus like '%".$search->{'illustrator'}."%'";
1002           } elsif ($search->{'publisher'} ne ''){
1003             $query.= "Select * from biblio,biblioitems where biblio.biblionumber
1004             =biblioitems.biblionumber and (publishercode like '%$search->{'publisher'}%')";
1005           } elsif ($search->{'abstract'} ne ''){
1006             $query.= "Select * from biblio where abstract like '%$search->{'abstract'}%'";
1007
1008           } elsif ($search->{'date-before'} ne ''){
1009             $query.= "Select * from biblio where copyrightdate like '%$search->{'date-before'}%'";
1010           }
1011           $query .=" group by biblio.biblionumber";
1012       }
1013   }
1014   if ($type eq 'subject'){
1015     # FIXME - Subject search is badly broken. The query defined by
1016     # $query returns a single item (the subject), but later code
1017     # expects a ref-to-hash with all sorts of stuff in it.
1018     # Also, the count of items (biblios?) with the given subject is
1019     # wrong.
1020
1021     my @key=split(' ',$search->{'subject'});
1022     my $count=@key;
1023     my $i=1;
1024     $query="select distinct(subject) from bibliosubject where( subject like
1025     '$key[0]%' or subject like '% $key[0]%' or subject like '% $key[0]' or subject like '%($key[0])%')";
1026     while ($i<$count){
1027       $query.=" and (subject like '$key[$i]%' or subject like '% $key[$i]%'
1028       or subject like '% $key[$i]'
1029       or subject like '%($key[$i])%')";
1030       $i++;
1031     }
1032
1033     # FIXME - Wouldn't it be better to fix the database so that if a
1034     # book has a subject "NZ", then it also gets added the subject
1035     # "New Zealand"?
1036     # This can also be generalized by adding a table of subject
1037     # synonyms to the database: just declare "NZ" to be a synonym for
1038     # "New Zealand", "SF" a synonym for both "Science fiction" and
1039     # "Fantastic fiction", etc.
1040
1041     # FIXME - This can be rewritten as
1042     #   if (lc($search->{"subject"}) eq "nz") {
1043     if ($search->{'subject'} eq 'NZ' || $search->{'subject'} eq 'nz'){
1044       $query.= " or (subject like 'NEW ZEALAND %' or subject like '% NEW ZEALAND %'
1045       or subject like '% NEW ZEALAND' or subject like '%(NEW ZEALAND)%' ) ";
1046     } elsif ( $search->{'subject'} =~ /^nz /i || $search->{'subject'} =~ / nz /i || $search->{'subject'} =~ / nz$/i){
1047       $query=~ s/ nz/ NEW ZEALAND/ig;
1048       $query=~ s/nz /NEW ZEALAND /ig;
1049       $query=~ s/\(nz\)/\(NEW ZEALAND\)/gi;
1050     }
1051   }
1052   if ($type eq 'precise'){
1053
1054       if ($search->{'item'} ne ''){
1055         $query="select * from items,biblio ";
1056         my $search2=uc $search->{'item'};
1057         $query=$query." where
1058         items.biblionumber=biblio.biblionumber
1059         and barcode='$search2'";
1060                         # FIXME - .= <<EOT;
1061       }
1062       if ($search->{'isbn'} ne ''){
1063         my $search2=uc $search->{'isbn'};
1064         my $query1 = "select * from biblioitems where isbn='$search2'";
1065         my $sth1=$dbh->prepare($query1);
1066 #       print STDERR "$query1\n";
1067         $sth1->execute;
1068         my $i2=0;
1069         while (my $data=$sth1->fetchrow_hashref) {
1070            $query="select * from biblioitems,biblio where
1071            biblio.biblionumber = $data->{'biblionumber'}
1072            and biblioitems.biblionumber = biblio.biblionumber";
1073            my $sth=$dbh->prepare($query);
1074            $sth->execute;
1075            # FIXME - There's already a $data in this scope.
1076            my $data=$sth->fetchrow_hashref;
1077            my ($dewey, $subclass) = ($data->{'dewey'}, $data->{'subclass'});
1078            # FIXME - The following assumes that the Dewey code is a
1079            # floating-point number. It isn't: it's a string.
1080            $dewey=~s/\.*0*$//;
1081            ($dewey == 0) && ($dewey='');
1082            ($dewey) && ($dewey.=" $subclass");
1083            $data->{'dewey'}=$dewey;
1084            $results[$i2]=$data;
1085 #           $results[$i2]="$data->{'author'}\t$data->{'title'}\t$data->{'biblionumber'}\t$data->{'copyrightdate'}\t$dewey\t$data->{'isbn'}\t$data->{'itemtype'}";
1086            $i2++;
1087            $sth->finish;
1088         }
1089         $sth1->finish;
1090       }
1091   }
1092 #print $query;
1093 if ($type ne 'precise' && $type ne 'subject'){
1094   if ($search->{'author'} ne ''){
1095       $query=$query." order by biblio.author,title";    # FIXME - .=
1096   } else {
1097       $query=$query." order by title";                  # FIXME - .=
1098   }
1099 } else {
1100   if ($type eq 'subject'){
1101       $query=$query." order by subject";                # FIXME - .=
1102   }
1103 }
1104 #print STDERR "$query\n";
1105 my $sth=$dbh->prepare($query);
1106 $sth->execute;
1107 my $count=1;
1108 my $i=0;
1109 my $limit= $num+$offset;
1110 while (my $data=$sth->fetchrow_hashref){
1111   my $query="select dewey,subclass,publishercode from biblioitems where biblionumber=$data->{'biblionumber'}";
1112             if ($search->{'class'} ne ''){
1113               my @temp=split(/\|/,$search->{'class'});
1114               my $count=@temp;
1115               $query.= " and ( itemtype='$temp[0]'";
1116               for (my $i=1;$i<$count;$i++){
1117                $query.=" or itemtype='$temp[$i]'";
1118               }
1119               $query.=")";
1120             }
1121             if ($search->{'dewey'} ne ''){
1122               $query.=" and dewey='$search->{'dewey'}' ";
1123             }
1124             if ($search->{'illustrator'} ne ''){
1125               $query.=" and illus like '%".$search->{'illustrator'}."%' ";
1126             }
1127             if ($search->{'publisher'} ne ''){
1128             $query.= " and (publishercode like '%$search->{'publisher'}%')";
1129             }
1130
1131   my $sti=$dbh->prepare($query);
1132   $sti->execute;
1133   my $dewey;
1134   my $subclass;
1135   my $true=0;
1136   my $publishercode;
1137   my $bibitemdata;
1138   if ($bibitemdata = $sti->fetchrow_hashref() || $type eq 'subject'){
1139     $true=1;
1140     $dewey=$bibitemdata->{'dewey'};
1141     $subclass=$bibitemdata->{'subclass'};
1142     $publishercode=$bibitemdata->{'publishercode'};
1143   }
1144 #  print STDERR "$dewey $subclass $publishercode\n";
1145   # FIXME - The Dewey code is a string, not a number.
1146   $dewey=~s/\.*0*$//;
1147   ($dewey == 0) && ($dewey='');
1148   ($dewey) && ($dewey.=" $subclass");
1149   $data->{'dewey'}=$dewey;
1150   $data->{'publishercode'}=$publishercode;
1151   $sti->finish;
1152   if ($true == 1){
1153     if ($count > $offset && $count <= $limit){
1154       $results[$i]=$data;
1155       $i++;
1156     }
1157     $count++;
1158   }
1159 }
1160 $sth->finish;
1161 #if ($type ne 'precise'){
1162   $count--;
1163 #}
1164 #$count--;
1165 return($count,@results);
1166 }
1167
1168 sub updatesearchstats{
1169   my ($dbh,$query)=@_;
1170
1171 }
1172
1173 =item subsearch
1174
1175   @results = &subsearch($env, $subject);
1176
1177 Searches for books that have a subject that exactly matches
1178 C<$subject>.
1179
1180 C<&subsearch> returns an array of results. Each element of this array
1181 is a string, containing the book's title, author, and biblionumber,
1182 separated by tabs.
1183
1184 C<$env> is ignored.
1185
1186 =cut
1187 #'
1188 sub subsearch {
1189   my ($env,$subject)=@_;
1190   my $dbh = C4::Context->dbh;
1191   $subject=$dbh->quote($subject);
1192   my $query="Select * from biblio,bibliosubject where
1193   biblio.biblionumber=bibliosubject.biblionumber and
1194   bibliosubject.subject=$subject group by biblio.biblionumber
1195   order by biblio.title";
1196   my $sth=$dbh->prepare($query);
1197   $sth->execute;
1198   my $i=0;
1199 #  print $query;
1200   my @results;
1201   while (my $data=$sth->fetchrow_hashref){
1202     $results[$i]="$data->{'title'}\t$data->{'author'}\t$data->{'biblionumber'}";
1203     $i++;
1204   }
1205   $sth->finish;
1206   return(@results);
1207 }
1208
1209 =item ItemInfo
1210
1211   @results = &ItemInfo($env, $biblionumber, $type);
1212
1213 Returns information about books with the given biblionumber.
1214
1215 C<$type> may be either C<intra> or anything else. If it is not set to
1216 C<intra>, then the search will exclude lost, very overdue, and
1217 withdrawn items.
1218
1219 C<$env> is ignored.
1220
1221 C<&ItemInfo> returns a list of references-to-hash. Each element
1222 contains a number of keys. Most of them are table items from the
1223 C<biblio>, C<biblioitems>, C<items>, and C<itemtypes> tables in the
1224 Koha database. Other keys include:
1225
1226 =over 4
1227
1228 =item C<$data-E<gt>{branchname}>
1229
1230 The name (not the code) of the branch to which the book belongs.
1231
1232 =item C<$data-E<gt>{datelastseen}>
1233
1234 This is simply C<items.datelastseen>, except that while the date is
1235 stored in YYYY-MM-DD format in the database, here it is converted to
1236 DD/MM/YYYY format. A NULL date is returned as C<//>.
1237
1238 =item C<$data-E<gt>{datedue}>
1239
1240 =item C<$data-E<gt>{class}>
1241
1242 This is the concatenation of C<biblioitems.classification>, the book's
1243 Dewey code, and C<biblioitems.subclass>.
1244
1245 =item C<$data-E<gt>{ocount}>
1246
1247 I think this is the number of copies of the book available.
1248
1249 =item C<$data-E<gt>{order}>
1250
1251 If this is set, it is set to C<One Order>.
1252
1253 =back
1254
1255 =cut
1256 #'
1257 sub ItemInfo {
1258     my ($env,$biblionumber,$type) = @_;
1259     my $dbh   = C4::Context->dbh;
1260     my $query = "SELECT * FROM items, biblio, biblioitems, itemtypes
1261                   WHERE items.biblionumber = ?
1262                     AND biblioitems.biblioitemnumber = items.biblioitemnumber
1263                     AND biblioitems.itemtype = itemtypes.itemtype
1264                     AND biblio.biblionumber = items.biblionumber";
1265   if ($type ne 'intra'){
1266     $query .= " and ((items.itemlost<>1 and items.itemlost <> 2)
1267     or items.itemlost is NULL)
1268     and (wthdrawn <> 1 or wthdrawn is NULL)";
1269   }
1270   $query .= " order by items.dateaccessioned desc";
1271     #warn $query;
1272   my $sth=$dbh->prepare($query);
1273   $sth->execute($biblionumber);
1274   my $i=0;
1275   my @results;
1276 #  print $query;
1277   while (my $data=$sth->fetchrow_hashref){
1278     my $iquery = "Select * from issues
1279     where itemnumber = '$data->{'itemnumber'}'
1280     and returndate is null";
1281     my $datedue = '';
1282     my $isth=$dbh->prepare($iquery);
1283     $isth->execute;
1284     if (my $idata=$isth->fetchrow_hashref){
1285       # FIXME - The date ought to be properly parsed, and printed
1286       # according to local convention.
1287       my @temp=split('-',$idata->{'date_due'});
1288       $datedue = "$temp[2]/$temp[1]/$temp[0]";
1289     }
1290     if ($data->{'itemlost'} eq '2'){
1291         $datedue='Very Overdue';
1292     }
1293     if ($data->{'itemlost'} eq '1'){
1294         $datedue='Lost';
1295     }
1296     if ($data->{'wthdrawn'} eq '1'){
1297         $datedue="Cancelled";
1298     }
1299     if ($datedue eq ''){
1300         $datedue="Available";
1301         my ($restype,$reserves)=CheckReserves($data->{'itemnumber'});
1302         if ($restype){
1303             $datedue=$restype;
1304         }
1305     }
1306     $isth->finish;
1307 #get branch information.....
1308     my $bquery = "SELECT * FROM branches
1309                           WHERE branchcode = '$data->{'holdingbranch'}'";
1310     my $bsth=$dbh->prepare($bquery);
1311     $bsth->execute;
1312     if (my $bdata=$bsth->fetchrow_hashref){
1313         $data->{'branchname'} = $bdata->{'branchname'};
1314     }
1315
1316     my $class = $data->{'classification'};
1317     my $dewey = $data->{'dewey'};
1318     $dewey =~ s/0+$//;
1319     if ($dewey eq "000.") { $dewey = "";};      # FIXME - "000" is general
1320                                                 # books about computer science
1321     if ($dewey < 10){$dewey='00'.$dewey;}
1322     if ($dewey < 100 && $dewey > 10){$dewey='0'.$dewey;}
1323     if ($dewey <= 0){
1324       $dewey='';
1325     }
1326     $dewey=~ s/\.$//;
1327     $class = $class.$dewey;                     # FIXME - .=
1328     if ($dewey ne ''){
1329       $class = $class.$data->{'subclass'};      # FIXME - .=
1330     }
1331  #   $results[$i]="$data->{'title'}\t$data->{'barcode'}\t$datedue\t$data->{'branchname'}\t$data->{'dewey'}";
1332     # FIXME - If $data->{'datelastseen'} is NULL, perhaps it'd be prettier
1333     # to leave it empty, rather than convert it to "//".
1334     # Also ideally this should use the local format for displaying dates.
1335     my @temp=split('-',$data->{'datelastseen'});
1336     my $date="$temp[2]/$temp[1]/$temp[0]";
1337     $data->{'datelastseen'}=$date;
1338     $data->{'datedue'}=$datedue;
1339     $data->{'class'}=$class;
1340     $results[$i]=$data;
1341     $i++;
1342   }
1343  $sth->finish;
1344   my $query2="Select * from aqorders where biblionumber=$biblionumber";
1345   my $sth2=$dbh->prepare($query2);
1346   $sth2->execute;
1347   my $data;
1348   my $ocount;
1349   if ($data=$sth2->fetchrow_hashref){
1350     $ocount=$data->{'quantity'} - $data->{'quantityreceived'};
1351     if ($ocount > 0){
1352       $data->{'ocount'}=$ocount;
1353       $data->{'order'}="One Order";
1354       $results[$i]=$data;
1355     }
1356   }
1357   $sth2->finish;
1358
1359   return(@results);
1360 }
1361
1362 =item GetItems
1363
1364   @results = &GetItems($env, $biblionumber);
1365
1366 Returns information about books with the given biblionumber.
1367
1368 C<$env> is ignored.
1369
1370 C<&GetItems> returns an array of strings. Each element is a
1371 tab-separated list of values: biblioitemnumber, itemtype,
1372 classification, Dewey number, subclass, ISBN, volume, number, and
1373 itemdata.
1374
1375 Itemdata, in turn, is a string of the form
1376 "I<barcode>C<[>I<holdingbranch>C<[>I<flags>" where I<flags> contains
1377 the string C<NFL> if the item is not for loan, and C<LOST> if the item
1378 is lost.
1379
1380 =cut
1381 #'
1382 sub GetItems {
1383    my ($env,$biblionumber)=@_;
1384    #debug_msg($env,"GetItems");
1385    my $dbh = C4::Context->dbh;
1386    my $query = "Select * from biblioitems where (biblionumber = $biblionumber)";
1387    #debug_msg($env,$query);
1388    my $sth=$dbh->prepare($query);
1389    $sth->execute;
1390    #debug_msg($env,"executed query");
1391    my $i=0;
1392    my @results;
1393    while (my $data=$sth->fetchrow_hashref) {
1394       #debug_msg($env,$data->{'biblioitemnumber'});
1395       my $dewey = $data->{'dewey'};
1396       $dewey =~ s/0+$//;
1397       my $line = $data->{'biblioitemnumber'}."\t".$data->{'itemtype'};
1398       $line = $line."\t$data->{'classification'}\t$dewey";      # FIXME - .=
1399       $line = $line."\t$data->{'subclass'}\t$data->{isbn}";     # FIXME - .=
1400       $line = $line."\t$data->{'volume'}\t$data->{number}";     # FIXME - .=
1401       my $isth= $dbh->prepare("select * from items where biblioitemnumber = $data->{'biblioitemnumber'}");
1402       $isth->execute;
1403       while (my $idata = $isth->fetchrow_hashref) {
1404         my $iline = $idata->{'barcode'}."[".$idata->{'holdingbranch'}."[";
1405         if ($idata->{'notforloan'} == 1) {
1406           $iline = $iline."NFL ";                               # FIXME - .=
1407         }
1408         if ($idata->{'itemlost'} == 1) {
1409           $iline = $iline."LOST ";                              # FIXME - .=
1410         }
1411         $line = $line."\t$iline";                               # FIXME - .=
1412       }
1413       $isth->finish;
1414       $results[$i] = $line;
1415       $i++;
1416    }
1417    $sth->finish;
1418    return(@results);
1419 }
1420
1421 =item itemdata
1422
1423   $item = &itemdata($barcode);
1424
1425 Looks up the item with the given barcode, and returns a
1426 reference-to-hash containing information about that item. The keys of
1427 the hash are the fields from the C<items> and C<biblioitems> tables in
1428 the Koha database.
1429
1430 =cut
1431 #'
1432 sub itemdata {
1433   my ($barcode)=@_;
1434   my $dbh = C4::Context->dbh;
1435   my $query="Select * from items,biblioitems where barcode='$barcode'
1436   and items.biblioitemnumber=biblioitems.biblioitemnumber";
1437 #  print $query;
1438   my $sth=$dbh->prepare($query);
1439   $sth->execute;
1440   my $data=$sth->fetchrow_hashref;
1441   $sth->finish;
1442   return($data);
1443 }
1444
1445 =item bibdata
1446
1447   $data = &bibdata($biblionumber, $type);
1448
1449 Returns information about the book with the given biblionumber.
1450
1451 C<$type> is ignored.
1452
1453 C<&bibdata> returns a reference-to-hash. The keys are the fields in
1454 the C<biblio>, C<biblioitems>, and C<bibliosubtitle> tables in the
1455 Koha database.
1456
1457 In addition, C<$data-E<gt>{subject}> is the list of the book's
1458 subjects, separated by C<" , "> (space, comma, space).
1459
1460 If there are multiple biblioitems with the given biblionumber, only
1461 the first one is considered.
1462
1463 =cut
1464 #'
1465 sub bibdata {
1466     my ($bibnum, $type) = @_;
1467     my $dbh   = C4::Context->dbh;
1468     my $query = "Select *, biblio.notes
1469     from biblio, biblioitems
1470     left join bibliosubtitle on
1471     biblio.biblionumber = bibliosubtitle.biblionumber
1472     where biblio.biblionumber = $bibnum
1473     and biblioitems.biblionumber = $bibnum";
1474     my $sth   = $dbh->prepare($query);
1475     my $data;
1476
1477     $sth->execute;
1478     $data  = $sth->fetchrow_hashref;
1479     $sth->finish;
1480
1481     $query = "Select * from bibliosubject where biblionumber = '$bibnum'";
1482     $sth   = $dbh->prepare($query);
1483     $sth->execute;
1484     while (my $dat = $sth->fetchrow_hashref){
1485         $data->{'subject'} .= " , $dat->{'subject'}";
1486     } # while
1487
1488     $sth->finish;
1489     return($data);
1490 } # sub bibdata
1491
1492 =item bibitemdata
1493
1494   $itemdata = &bibitemdata($biblioitemnumber);
1495
1496 Looks up the biblioitem with the given biblioitemnumber. Returns a
1497 reference-to-hash. The keys are the fields from the C<biblio>,
1498 C<biblioitems>, and C<itemtypes> tables in the Koha database, except
1499 that C<biblioitems.notes> is given as C<$itemdata-E<gt>{bnotes}>.
1500
1501 =cut
1502 #'
1503 sub bibitemdata {
1504     my ($bibitem) = @_;
1505     my $dbh   = C4::Context->dbh;
1506     my $query = "Select *,biblioitems.notes as bnotes from biblio, biblioitems,itemtypes
1507 where biblio.biblionumber = biblioitems.biblionumber
1508 and biblioitemnumber = $bibitem
1509 and biblioitems.itemtype = itemtypes.itemtype";
1510     my $sth   = $dbh->prepare($query);
1511     my $data;
1512
1513     $sth->execute;
1514
1515     $data = $sth->fetchrow_hashref;
1516
1517     $sth->finish;
1518     return($data);
1519 } # sub bibitemdata
1520
1521 =item subject
1522
1523   ($count, $subjects) = &subject($biblionumber);
1524
1525 Looks up the subjects of the book with the given biblionumber. Returns
1526 a two-element list. C<$subjects> is a reference-to-array, where each
1527 element is a subject of the book, and C<$count> is the number of
1528 elements in C<$subjects>.
1529
1530 =cut
1531 #'
1532 sub subject {
1533   my ($bibnum)=@_;
1534   my $dbh = C4::Context->dbh;
1535   my $query="Select * from bibliosubject where biblionumber=$bibnum";
1536   my $sth=$dbh->prepare($query);
1537   $sth->execute;
1538   my @results;
1539   my $i=0;
1540   while (my $data=$sth->fetchrow_hashref){
1541     $results[$i]=$data;
1542     $i++;
1543   }
1544   $sth->finish;
1545   return($i,\@results);
1546 }
1547
1548 =item addauthor
1549
1550   ($count, $authors) = &addauthors($biblionumber);
1551
1552 Looks up the additional authors for the book with the given
1553 biblionumber.
1554
1555 Returns a two-element list. C<$authors> is a reference-to-array, where
1556 each element is an additional author, and C<$count> is the number of
1557 elements in C<$authors>.
1558
1559 =cut
1560 #'
1561 sub addauthor {
1562   my ($bibnum)=@_;
1563   my $dbh = C4::Context->dbh;
1564   my $query="Select * from additionalauthors where biblionumber=$bibnum";
1565   my $sth=$dbh->prepare($query);
1566   $sth->execute;
1567   my @results;
1568   my $i=0;
1569   while (my $data=$sth->fetchrow_hashref){
1570     $results[$i]=$data;
1571     $i++;
1572   }
1573   $sth->finish;
1574   return($i,\@results);
1575 }
1576
1577 =item subtitle
1578
1579   ($count, $subtitles) = &subtitle($biblionumber);
1580
1581 Looks up the subtitles for the book with the given biblionumber.
1582
1583 Returns a two-element list. C<$subtitles> is a reference-to-array,
1584 where each element is a subtitle, and C<$count> is the number of
1585 elements in C<$subtitles>.
1586
1587 =cut
1588 #'
1589 sub subtitle {
1590   my ($bibnum)=@_;
1591   my $dbh = C4::Context->dbh;
1592   my $query="Select * from bibliosubtitle where biblionumber=$bibnum";
1593   my $sth=$dbh->prepare($query);
1594   $sth->execute;
1595   my @results;
1596   my $i=0;
1597   while (my $data=$sth->fetchrow_hashref){
1598     $results[$i]=$data;
1599     $i++;
1600   }
1601   $sth->finish;
1602   return($i,\@results);
1603 }
1604
1605 =item itemissues
1606
1607   @issues = &itemissues($biblioitemnumber, $biblio);
1608
1609 Looks up information about who has borrowed the bookZ<>(s) with the
1610 given biblioitemnumber.
1611
1612 C<$biblio> is ignored.
1613
1614 C<&itemissues> returns an array of references-to-hash. The keys
1615 include the fields from the C<items> table in the Koha database.
1616 Additional keys include:
1617
1618 =over 4
1619
1620 =item C<date_due>
1621
1622 If the item is currently on loan, this gives the due date.
1623
1624 If the item is not on loan, then this is either "Available" or
1625 "Cancelled", if the item has been withdrawn.
1626
1627 =item C<card>
1628
1629 If the item is currently on loan, this gives the card number of the
1630 patron who currently has the item.
1631
1632 =item C<timestamp0>, C<timestamp1>, C<timestamp2>
1633
1634 These give the timestamp for the last three times the item was
1635 borrowed.
1636
1637 =item C<card0>, C<card1>, C<card2>
1638
1639 The card number of the last three patrons who borrowed this item.
1640
1641 =item C<borrower0>, C<borrower1>, C<borrower2>
1642
1643 The borrower number of the last three patrons who borrowed this item.
1644
1645 =back
1646
1647 =cut
1648 #'
1649 sub itemissues {
1650     my ($bibitem, $biblio)=@_;
1651     my $dbh   = C4::Context->dbh;
1652     my $query = "Select * from items where
1653 items.biblioitemnumber = '$bibitem'";
1654     # FIXME - If this function die()s, the script will abort, and the
1655     # user won't get anything; depending on how far the script has
1656     # gotten, the user might get a blank page. It would be much better
1657     # to at least print an error message. The easiest way to do this
1658     # is to set $SIG{__DIE__}.
1659     my $sth   = $dbh->prepare($query)
1660       || die $dbh->errstr;
1661     my $i     = 0;
1662     my @results;
1663
1664     $sth->execute
1665       || die $sth->errstr;
1666
1667     while (my $data = $sth->fetchrow_hashref) {
1668         # Find out who currently has this item.
1669         # FIXME - Wouldn't it be better to do this as a left join of
1670         # some sort? Currently, this code assumes that if
1671         # fetchrow_hashref() fails, then the book is on the shelf.
1672         # fetchrow_hashref() can fail for any number of reasons (e.g.,
1673         # database server crash), not just because no items match the
1674         # search criteria.
1675         my $query2 = "select * from issues,borrowers
1676 where itemnumber = $data->{'itemnumber'}
1677 and returndate is NULL
1678 and issues.borrowernumber = borrowers.borrowernumber";
1679         my $sth2   = $dbh->prepare($query2);
1680
1681         $sth2->execute;
1682         if (my $data2 = $sth2->fetchrow_hashref) {
1683             $data->{'date_due'} = $data2->{'date_due'};
1684             $data->{'card'}     = $data2->{'cardnumber'};
1685         } else {
1686             if ($data->{'wthdrawn'} eq '1') {
1687                 $data->{'date_due'} = 'Cancelled';
1688             } else {
1689                 $data->{'date_due'} = 'Available';
1690             } # else
1691         } # else
1692
1693         $sth2->finish;
1694
1695         # Find the last 3 people who borrowed this item.
1696         $query2 = "select * from issues, borrowers
1697 where itemnumber = '$data->{'itemnumber'}'
1698 and issues.borrowernumber = borrowers.borrowernumber
1699 and returndate is not NULL
1700 order by returndate desc,timestamp desc";
1701         $sth2 = $dbh->prepare($query2)
1702           || die $dbh->errstr;
1703         $sth2->execute
1704           || die $sth2->errstr;
1705
1706         for (my $i2 = 0; $i2 < 2; $i2++) {
1707             if (my $data2 = $sth2->fetchrow_hashref) {
1708                 $data->{"timestamp$i2"} = $data2->{'timestamp'};
1709                 $data->{"card$i2"}      = $data2->{'cardnumber'};
1710                 $data->{"borrower$i2"}  = $data2->{'borrowernumber'};
1711             } # if
1712         } # for
1713
1714         $sth2->finish;
1715         $results[$i] = $data;
1716         $i++;
1717     }
1718
1719     $sth->finish;
1720     return(@results);
1721 }
1722
1723 =item itemnodata
1724
1725   $item = &itemnodata($env, $dbh, $biblioitemnumber);
1726
1727 Looks up the item with the given biblioitemnumber.
1728
1729 C<$env> and C<$dbh> are ignored.
1730
1731 C<&itemnodata> returns a reference-to-hash whose keys are the fields
1732 from the C<biblio>, C<biblioitems>, and C<items> tables in the Koha
1733 database.
1734
1735 =cut
1736 #'
1737 sub itemnodata {
1738   my ($env,$dbh,$itemnumber) = @_;
1739   $dbh = C4::Context->dbh;
1740   my $query="Select * from biblio,items,biblioitems
1741     where items.itemnumber = '$itemnumber'
1742     and biblio.biblionumber = items.biblionumber
1743     and biblioitems.biblioitemnumber = items.biblioitemnumber";
1744   my $sth=$dbh->prepare($query);
1745 #  print $query;
1746   $sth->execute;
1747   my $data=$sth->fetchrow_hashref;
1748   $sth->finish;
1749   return($data);
1750 }
1751
1752 =item BornameSearch
1753
1754   ($count, $borrowers) = &BornameSearch($env, $searchstring, $type);
1755
1756 Looks up patrons (borrowers) by name.
1757
1758 C<$env> and C<$type> are ignored.
1759
1760 C<$searchstring> is a space-separated list of search terms. Each term
1761 must match the beginning a borrower's surname, first name, or other
1762 name.
1763
1764 C<&BornameSearch> returns a two-element list. C<$borrowers> is a
1765 reference-to-array; each element is a reference-to-hash, whose keys
1766 are the fields of the C<borrowers> table in the Koha database.
1767 C<$count> is the number of elements in C<$borrowers>.
1768
1769 =cut
1770 #'
1771 #used by member enquiries from the intranet
1772 #called by member.pl
1773 sub BornameSearch  {
1774   my ($env,$searchstring,$type)=@_;
1775   my $dbh = C4::Context->dbh;
1776   $searchstring=~ s/\'/\\\'/g;
1777   my @data=split(' ',$searchstring);
1778   my $count=@data;
1779   my $query="Select * from borrowers
1780   where ((surname like \"$data[0]%\" or surname like \"% $data[0]%\"
1781   or firstname  like \"$data[0]%\" or firstname like \"% $data[0]%\"
1782   or othernames like \"$data[0]%\" or othernames like \"% $data[0]%\")
1783   ";
1784   for (my $i=1;$i<$count;$i++){
1785     $query=$query." and (surname like \"$data[$i]%\" or surname like \"% $data[$i]%\"
1786     or firstname  like \"$data[$i]%\" or firstname like \"% $data[$i]%\"
1787     or othernames like \"$data[$i]%\" or othernames like \"% $data[$i]%\")";
1788                         # FIXME - .= <<EOT;
1789   }
1790   $query=$query.") or cardnumber = \"$searchstring\"
1791   order by surname,firstname";
1792                         # FIXME - .= <<EOT;
1793 #  print $query,"\n";
1794   my $sth=$dbh->prepare($query);
1795   $sth->execute;
1796   my @results;
1797   my $cnt=0;
1798   while (my $data=$sth->fetchrow_hashref){
1799     push(@results,$data);
1800     $cnt ++;
1801   }
1802 #  $sth->execute;
1803   $sth->finish;
1804   return ($cnt,\@results);
1805 }
1806
1807 =item borrdata
1808
1809   $borrower = &borrdata($cardnumber, $borrowernumber);
1810
1811 Looks up information about a patron (borrower) by either card number
1812 or borrower number. If $borrowernumber is specified, C<&borrdata>
1813 searches by borrower number; otherwise, it searches by card number.
1814
1815 C<&borrdata> returns a reference-to-hash whose keys are the fields of
1816 the C<borrowers> table in the Koha database.
1817
1818 =cut
1819 #'
1820 sub borrdata {
1821   my ($cardnumber,$bornum)=@_;
1822   $cardnumber = uc $cardnumber;
1823   my $dbh = C4::Context->dbh;
1824   my $query;
1825   if ($bornum eq ''){
1826     $query="Select * from borrowers where cardnumber='$cardnumber'";
1827   } else {
1828       $query="Select * from borrowers where borrowernumber='$bornum'";
1829   }
1830   #print $query;
1831   my $sth=$dbh->prepare($query);
1832   $sth->execute;
1833   my $data=$sth->fetchrow_hashref;
1834   $sth->finish;
1835   return($data);
1836 }
1837
1838 =item borrissues
1839
1840   ($count, $issues) = &borrissues($borrowernumber);
1841
1842 Looks up what the patron with the given borrowernumber has borrowed.
1843
1844 C<&borrissues> returns a two-element array. C<$issues> is a
1845 reference-to-array, where each element is a reference-to-hash; the
1846 keys are the fields from the C<issues>, C<biblio>, and C<items> tables
1847 in the Koha database. C<$count> is the number of elements in
1848 C<$issues>.
1849
1850 =cut
1851 #'
1852 sub borrissues {
1853   my ($bornum)=@_;
1854   my $dbh = C4::Context->dbh;
1855   my $query;
1856   $query="Select * from issues,biblio,items where borrowernumber='$bornum' and
1857 items.itemnumber=issues.itemnumber and
1858 items.biblionumber=biblio.biblionumber and issues.returndate is NULL order
1859 by date_due";
1860   #print $query;
1861   my $sth=$dbh->prepare($query);
1862     $sth->execute;
1863   my @result;
1864   while (my $data = $sth->fetchrow_hashref) {
1865     push @result, $data;
1866   }
1867   $sth->finish;
1868   return(scalar(@result), \@result);
1869 }
1870
1871 =item allissues
1872
1873   ($count, $issues) = &allissues($borrowernumber, $sortkey, $limit);
1874
1875 Looks up what the patron with the given borrowernumber has borrowed,
1876 and sorts the results.
1877
1878 C<$sortkey> is the name of a field on which to sort the results. This
1879 should be the name of a field in the C<issues>, C<biblio>,
1880 C<biblioitems>, or C<items> table in the Koha database.
1881
1882 C<$limit> is the maximum number of results to return.
1883
1884 C<&allissues> returns a two-element array. C<$issues> is a
1885 reference-to-array, where each element is a reference-to-hash; the
1886 keys are the fields from the C<issues>, C<biblio>, C<biblioitems>, and
1887 C<items> tables of the Koha database. C<$count> is the number of
1888 elements in C<$issues>
1889
1890 =cut
1891 #'
1892 sub allissues {
1893   my ($bornum,$order,$limit)=@_;
1894   my $dbh = C4::Context->dbh;
1895   my $query;
1896   $query="Select * from issues,biblio,items,biblioitems
1897   where borrowernumber='$bornum' and
1898   items.biblioitemnumber=biblioitems.biblioitemnumber and
1899   items.itemnumber=issues.itemnumber and
1900   items.biblionumber=biblio.biblionumber";
1901   $query.=" order by $order";
1902   if ($limit !=0){
1903     $query.=" limit $limit";
1904   }
1905   #print $query;
1906   my $sth=$dbh->prepare($query);
1907   $sth->execute;
1908   my @result;
1909   my $i=0;
1910   while (my $data=$sth->fetchrow_hashref){
1911     $result[$i]=$data;;
1912     $i++;
1913   }
1914   $sth->finish;
1915   return($i,\@result);
1916 }
1917
1918 =item borrdata2
1919
1920   ($borrowed, $due, $fine) = &borrdata2($env, $borrowernumber);
1921
1922 Returns aggregate data about items borrowed by the patron with the
1923 given borrowernumber.
1924
1925 C<$env> is ignored.
1926
1927 C<&borrdata2> returns a three-element array. C<$borrowed> is the
1928 number of books the patron currently has borrowed. C<$due> is the
1929 number of overdue items the patron currently has borrowed. C<$fine> is
1930 the total fine currently due by the borrower.
1931
1932 =cut
1933 #'
1934 sub borrdata2 {
1935   my ($env,$bornum)=@_;
1936   my $dbh = C4::Context->dbh;
1937   my $query="Select count(*) from issues where borrowernumber='$bornum' and
1938     returndate is NULL";
1939     # print $query;
1940   my $sth=$dbh->prepare($query);
1941   $sth->execute;
1942   my $data=$sth->fetchrow_hashref;
1943   $sth->finish;
1944   $sth=$dbh->prepare("Select count(*) from issues where
1945     borrowernumber='$bornum' and date_due < now() and returndate is NULL");
1946   $sth->execute;
1947   my $data2=$sth->fetchrow_hashref;
1948   $sth->finish;
1949   $sth=$dbh->prepare("Select sum(amountoutstanding) from accountlines where
1950     borrowernumber='$bornum'");
1951   $sth->execute;
1952   my $data3=$sth->fetchrow_hashref;
1953   $sth->finish;
1954
1955 return($data2->{'count(*)'},$data->{'count(*)'},$data3->{'sum(amountoutstanding)'});
1956 }
1957
1958 =item getboracctrecord
1959
1960   ($count, $acctlines, $total) = &getboracctrecord($env, $borrowernumber);
1961
1962 Looks up accounting data for the patron with the given borrowernumber.
1963
1964 C<$env> is ignored.
1965
1966 (FIXME - I'm not at all sure what this is about.)
1967
1968 C<&getboracctrecord> returns a three-element array. C<$acctlines> is a
1969 reference-to-array, where each element is a reference-to-hash; the
1970 keys are the fields of the C<accountlines> table in the Koha database.
1971 C<$count> is the number of elements in C<$acctlines>. C<$total> is the
1972 total amount outstanding for all of the account lines.
1973
1974 =cut
1975 #'
1976 sub getboracctrecord {
1977    my ($env,$params) = @_;
1978    my $dbh = C4::Context->dbh;
1979    my @acctlines;
1980    my $numlines=0;
1981    my $query= "Select * from accountlines where
1982 borrowernumber=$params->{'borrowernumber'} order by date desc,timestamp desc";
1983    my $sth=$dbh->prepare($query);
1984 #   print $query;
1985    $sth->execute;
1986    my $total=0;
1987    while (my $data=$sth->fetchrow_hashref){
1988 #      if ($data->{'itemnumber'} ne ''){
1989 #        $query="Select * from items,biblio where items.itemnumber=
1990 #       '$data->{'itemnumber'}' and biblio.biblionumber=items.biblionumber";
1991 #       my $sth2=$dbh->prepare($query);
1992 #       $sth2->execute;
1993 #       my $data2=$sth2->fetchrow_hashref;
1994 #       $sth2->finish;
1995 #       $data=$data2;
1996  #     }
1997       $acctlines[$numlines] = $data;
1998       $numlines++;
1999       $total = $total+ $data->{'amountoutstanding'};    # FIXME - +=
2000    }
2001    $sth->finish;
2002    return ($numlines,\@acctlines,$total);
2003 }
2004
2005 =item itemcount
2006
2007   ($count, $lcount, $nacount, $fcount, $scount, $lostcount,
2008   $mending, $transit,$ocount) =
2009     &itemcount($env, $biblionumber, $type);
2010
2011 Counts the number of items with the given biblionumber, broken down by
2012 category.
2013
2014 C<$env> is ignored.
2015
2016 If C<$type> is not set to C<intra>, lost, very overdue, and withdrawn
2017 items will not be counted.
2018
2019 C<&itemcount> returns a nine-element list:
2020
2021 C<$count> is the total number of items with the given biblionumber.
2022
2023 C<$lcount> is the number of items at the Levin branch.
2024
2025 C<$nacount> is the number of items that are neither borrowed, lost,
2026 nor withdrawn (and are therefore presumably on a shelf somewhere).
2027
2028 C<$fcount> is the number of items at the Foxton branch.
2029
2030 C<$scount> is the number of items at the Shannon branch.
2031
2032 C<$lostcount> is the number of lost and very overdue items.
2033
2034 C<$mending> is the number of items at the Mending branch (being
2035 mended?).
2036
2037 C<$transit> is the number of items at the Transit branch (in transit
2038 between branches?).
2039
2040 C<$ocount> is the number of items that haven't arrived yet
2041 (aqorders.quantity - aqorders.quantityreceived).
2042
2043 =cut
2044 #'
2045
2046 # FIXME - There's also a &C4::Acquisitions::itemcount and
2047 # &C4::Biblio::itemcount.
2048 # Since they're all exported, acqui/acquire.pl doesn't compile with -w.
2049 sub itemcount {
2050   my ($env,$bibnum,$type)=@_;
2051   my $dbh = C4::Context->dbh;
2052   my $query="Select * from items where
2053   biblionumber=$bibnum ";
2054   if ($type ne 'intra'){
2055     $query.=" and ((itemlost <>1 and itemlost <> 2) or itemlost is NULL) and
2056     (wthdrawn <> 1 or wthdrawn is NULL)";
2057   }
2058   my $sth=$dbh->prepare($query);
2059   #  print $query;
2060   $sth->execute;
2061   my $count=0;
2062   my $lcount=0;
2063   my $nacount=0;
2064   my $fcount=0;
2065   my $scount=0;
2066   my $lostcount=0;
2067   my $mending=0;
2068   my $transit=0;
2069   my $ocount=0;
2070   while (my $data=$sth->fetchrow_hashref){
2071     $count++;
2072     my $query2="select * from issues,items where issues.itemnumber=
2073     '$data->{'itemnumber'}' and returndate is NULL
2074     and items.itemnumber=issues.itemnumber and ((items.itemlost <>1 and
2075     items.itemlost <> 2) or items.itemlost is NULL)
2076     and (wthdrawn <> 1 or wthdrawn is NULL)";
2077
2078     my $sth2=$dbh->prepare($query2);
2079     $sth2->execute;
2080     if (my $data2=$sth2->fetchrow_hashref){
2081        $nacount++;
2082     } else {
2083       if ($data->{'holdingbranch'} eq 'C' || $data->{'holdingbranch'} eq 'LT'){
2084         $lcount++;
2085       }
2086       if ($data->{'holdingbranch'} eq 'F' || $data->{'holdingbranch'} eq 'FP'){
2087         $fcount++;
2088       }
2089       if ($data->{'holdingbranch'} eq 'S' || $data->{'holdingbranch'} eq 'SP'){
2090         $scount++;
2091       }
2092       if ($data->{'itemlost'} eq '1'){
2093         $lostcount++;
2094       }
2095       if ($data->{'itemlost'} eq '2'){
2096         $lostcount++;
2097       }
2098       if ($data->{'holdingbranch'} eq 'FM'){
2099         $mending++;
2100       }
2101       if ($data->{'holdingbranch'} eq 'TR'){
2102         $transit++;
2103       }
2104     }
2105     $sth2->finish;
2106   }
2107 #  if ($count == 0){
2108     my $query2="Select * from aqorders where biblionumber=$bibnum";
2109     my $sth2=$dbh->prepare($query2);
2110     $sth2->execute;
2111     if (my $data=$sth2->fetchrow_hashref){
2112       $ocount=$data->{'quantity'} - $data->{'quantityreceived'};
2113     }
2114 #    $count+=$ocount;
2115     $sth2->finish;
2116   $sth->finish;
2117   return ($count,$lcount,$nacount,$fcount,$scount,$lostcount,$mending,$transit,$ocount);
2118 }
2119
2120 =item itemcount2
2121
2122   $counts = &itemcount2($env, $biblionumber, $type);
2123
2124 Counts the number of items with the given biblionumber, broken down by
2125 category.
2126
2127 C<$env> is ignored.
2128
2129 C<$type> may be either C<intra> or anything else. If it is not set to
2130 C<intra>, then the search will exclude lost, very overdue, and
2131 withdrawn items.
2132
2133 C<$&itemcount2> returns a reference-to-hash, with the following fields:
2134
2135 =over 4
2136
2137 =item C<total>
2138
2139 The total number of items with this biblionumber.
2140
2141 =item C<order>
2142
2143 The number of items on order (aqorders.quantity -
2144 aqorders.quantityreceived).
2145
2146 =item I<branchname>
2147
2148 For each branch that has at least one copy of the book, C<$counts>
2149 will have a key with the branch name, giving the number of copies at
2150 that branch.
2151
2152 =back
2153
2154 =cut
2155 #'
2156 sub itemcount2 {
2157   my ($env,$bibnum,$type)=@_;
2158   my $dbh = C4::Context->dbh;
2159   my $query="Select * from items,branches where
2160   biblionumber=$bibnum and items.holdingbranch=branches.branchcode";
2161   if ($type ne 'intra'){
2162     $query.=" and ((itemlost <>1 and itemlost <> 2) or itemlost is NULL) and
2163     (wthdrawn <> 1 or wthdrawn is NULL)";
2164   }
2165   my $sth=$dbh->prepare($query);
2166   #  print $query;
2167   $sth->execute;
2168   my %counts;
2169   $counts{'total'}=0;
2170   while (my $data=$sth->fetchrow_hashref){
2171     $counts{'total'}++;
2172     my $query2="select * from issues,items where issues.itemnumber=
2173     '$data->{'itemnumber'}' and returndate is NULL
2174     and items.itemnumber=issues.itemnumber and ((items.itemlost <>1 and
2175     items.itemlost <> 2) or items.itemlost is NULL)
2176     and (wthdrawn <> 1 or wthdrawn is NULL)";
2177
2178     my $sth2=$dbh->prepare($query2);
2179     $sth2->execute;
2180     # FIXME - fetchrow_hashref() can fail for any number of reasons
2181     # (e.g., a database server crash). Perhaps use a left join of some
2182     # sort for this?
2183     if (my $data2=$sth2->fetchrow_hashref){
2184        $counts{'not available'}++;
2185     } else {
2186        $counts{$data->{'branchname'}}++;
2187     }
2188     $sth2->finish;
2189   }
2190   my $query2="Select * from aqorders where biblionumber=$bibnum and
2191   datecancellationprinted is NULL and quantity > quantityreceived";
2192   my $sth2=$dbh->prepare($query2);
2193   $sth2->execute;
2194   if (my $data=$sth2->fetchrow_hashref){
2195       $counts{'order'}=$data->{'quantity'} - $data->{'quantityreceived'};
2196   }
2197   $sth2->finish;
2198   $sth->finish;
2199   return (\%counts);
2200 }
2201
2202 =item ItemType
2203
2204   $description = &ItemType($itemtype);
2205
2206 Given an item type code, returns the description for that type.
2207
2208 =cut
2209 #'
2210
2211 # FIXME - I'm pretty sure that after the initial setup, the list of
2212 # item types doesn't change very often. Hence, it seems slow and
2213 # inefficient to make yet another database call to look up information
2214 # that'll only change every few months or years.
2215 #
2216 # Much better, I think, to automatically build a Perl file that can be
2217 # included in those scripts that require it, e.g.:
2218 #       @itemtypes = qw( ART BCD CAS CD F ... );
2219 #       %itemtypedesc = (
2220 #               ART     => "Art Prints",
2221 #               BCD     => "CD-ROM from book",
2222 #               CD      => "Compact disc (WN)",
2223 #               F       => "Free Fiction",
2224 #               ...
2225 #       );
2226 # The web server can then run a cron job to rebuild this file from the
2227 # database every hour or so.
2228 #
2229 # The same thing goes for branches, book funds, book sellers, currency
2230 # rates, printers, stopwords, and perhaps others.
2231 sub ItemType {
2232   my ($type)=@_;
2233   my $dbh = C4::Context->dbh;
2234   my $query="select description from itemtypes where itemtype='$type'";
2235   my $sth=$dbh->prepare($query);
2236   $sth->execute;
2237   my $dat=$sth->fetchrow_hashref;
2238   $sth->finish;
2239   return ($dat->{'description'});
2240 }
2241
2242 =item bibitems
2243
2244   ($count, @results) = &bibitems($biblionumber);
2245
2246 Given the biblionumber for a book, C<&bibitems> looks up that book's
2247 biblioitems (different publications of the same book, the audio book
2248 and film versions, etc.).
2249
2250 C<$count> is the number of elements in C<@results>.
2251
2252 C<@results> is an array of references-to-hash; the keys are the fields
2253 of the C<biblioitems> and C<itemtypes> tables of the Koha database. In
2254 addition, C<itemlost> indicates the availability of the item: if it is
2255 "2", then all copies of the item are long overdue; if it is "1", then
2256 all copies are lost; otherwise, there is at least one copy available.
2257
2258 =cut
2259 #'
2260 sub bibitems {
2261     my ($bibnum) = @_;
2262     my $dbh   = C4::Context->dbh;
2263     my $query = "SELECT biblioitems.*,
2264                         itemtypes.*,
2265                         MIN(items.itemlost)        as itemlost,
2266                         MIN(items.dateaccessioned) as dateaccessioned
2267                           FROM biblioitems, itemtypes, items
2268                          WHERE biblioitems.biblionumber     = ?
2269                            AND biblioitems.itemtype         = itemtypes.itemtype
2270                            AND biblioitems.biblioitemnumber = items.biblioitemnumber
2271                       GROUP BY items.biblioitemnumber";
2272     my $sth   = $dbh->prepare($query);
2273     my $count = 0;
2274     my @results;
2275     $sth->execute($bibnum);
2276     while (my $data = $sth->fetchrow_hashref) {
2277         $results[$count] = $data;
2278         $count++;
2279     } # while
2280     $sth->finish;
2281     return($count, @results);
2282 } # sub bibitems
2283
2284 =item barcodes
2285
2286   @barcodes = &barcodes($biblioitemnumber);
2287
2288 Given a biblioitemnumber, looks up the corresponding items.
2289
2290 Returns an array of references-to-hash; the keys are C<barcode> and
2291 C<itemlost>.
2292
2293 The returned items include very overdue items, but not lost ones.
2294
2295 =cut
2296 #'
2297 sub barcodes{
2298     #called from request.pl
2299     my ($biblioitemnumber)=@_;
2300     my $dbh = C4::Context->dbh;
2301     my $query="SELECT barcode, itemlost, holdingbranch FROM items
2302                            WHERE biblioitemnumber = ?
2303                              AND (wthdrawn <> 1 OR wthdrawn IS NULL)";
2304     my $sth=$dbh->prepare($query);
2305     $sth->execute($biblioitemnumber);
2306     my @barcodes;
2307     my $i=0;
2308     while (my $data=$sth->fetchrow_hashref){
2309         $barcodes[$i]=$data;
2310         $i++;
2311     }
2312     $sth->finish;
2313     return(@barcodes);
2314 }
2315
2316 =item getwebsites
2317
2318   ($count, @websites) = &getwebsites($biblionumber);
2319
2320 Looks up the web sites pertaining to the book with the given
2321 biblionumber.
2322
2323 C<$count> is the number of elements in C<@websites>.
2324
2325 C<@websites> is an array of references-to-hash; the keys are the
2326 fields from the C<websites> table in the Koha database.
2327
2328 =cut
2329 #'
2330 sub getwebsites {
2331     my ($biblionumber) = @_;
2332     my $dbh   = C4::Context->dbh;
2333     my $query = "Select * from websites where biblionumber = $biblionumber";
2334     my $sth   = $dbh->prepare($query);
2335     my $count = 0;
2336     my @results;
2337
2338     $sth->execute;
2339     while (my $data = $sth->fetchrow_hashref) {
2340         # FIXME - The URL scheme shouldn't be stripped off, at least
2341         # not here, since it's part of the URL, and will be useful in
2342         # constructing a link to the site. If you don't want the user
2343         # to see the "http://" part, strip that off when building the
2344         # HTML code.
2345         $data->{'url'} =~ s/^http:\/\///;       # FIXME - Leaning toothpick
2346                                                 # syndrome
2347         $results[$count] = $data;
2348         $count++;
2349     } # while
2350
2351     $sth->finish;
2352     return($count, @results);
2353 } # sub getwebsites
2354
2355 =item getwebbiblioitems
2356
2357   ($count, @results) = &getwebbiblioitems($biblionumber);
2358
2359 Given a book's biblionumber, looks up the web versions of the book
2360 (biblioitems with itemtype C<WEB>).
2361
2362 C<$count> is the number of items in C<@results>. C<@results> is an
2363 array of references-to-hash; the keys are the items from the
2364 C<biblioitems> table of the Koha database.
2365
2366 =cut
2367 #'
2368 sub getwebbiblioitems {
2369     my ($biblionumber) = @_;
2370     my $dbh   = C4::Context->dbh;
2371     my $query = "Select * from biblioitems where biblionumber = $biblionumber
2372 and itemtype = 'WEB'";
2373     my $sth   = $dbh->prepare($query);
2374     my $count = 0;
2375     my @results;
2376
2377     $sth->execute;
2378     while (my $data = $sth->fetchrow_hashref) {
2379         $data->{'url'} =~ s/^http:\/\///;
2380         $results[$count] = $data;
2381         $count++;
2382     } # while
2383
2384     $sth->finish;
2385     return($count, @results);
2386 } # sub getwebbiblioitems
2387
2388
2389 END { }       # module clean-up code here (global destructor)
2390
2391 1;
2392 __END__
2393
2394 =back
2395
2396 =head1 AUTHOR
2397
2398 Koha Developement team <info@koha.org>
2399
2400 =cut