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