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