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