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