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