all those fixes are related to translation improvement.
[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 &getbranchname &getborrowercategory);
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 author))
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         my $dbh = C4::Context->dbh;
859         my $query = '';
860         my @results;
861
862         # Why not just use quotemeta to escape all questionable characters,
863         # not just single-quotes? Because that would also escape spaces,
864         # which would cause titles/authors/illustrators with a space to
865         # become unsearchable (Bug 197)
866
867         for my $field ('title', 'author', 'illustrator') {
868             $search->{$field} =~ s/['"]/\\\1/g;
869         }
870
871         my $title = lc($search->{'title'});
872         if ($type eq 'loose') {
873                 if ($search->{'author'} ne ''){
874                         my @key=split(' ',$search->{'author'});
875                         my $count=@key;
876                         my $i=1;
877                         $query="select *,biblio.author,biblio.biblionumber from
878                                                         biblio
879                                                         left join additionalauthors
880                                                         on additionalauthors.biblionumber =biblio.biblionumber
881                                                         where
882                                                         ((biblio.author like '$key[0]%' or biblio.author like '% $key[0]%' or
883                                                         additionalauthors.author like '$key[0]%' or additionalauthors.author
884                                                         like '% $key[0]%'
885                                                                 )";
886                         while ($i < $count){
887                                         $query .= " and (
888                                                                         biblio.author like '$key[$i]%' or biblio.author like '% $key[$i]%' or
889                                                                         additionalauthors.author like '$key[$i]%' or additionalauthors.author like '% $key[$i]%'
890                                                                         )";
891                                 $i++;
892                         }
893                         $query .= ")";
894                         if ($search->{'title'} ne ''){
895                                 my @key=split(' ',$search->{'title'});
896                                 my $count=@key;
897                                 my $i=0;
898                                 $query.= " and (((title like '$key[0]%' or title like '% $key[0]%' or title like '% $key[0]')";
899                                 while ($i<$count){
900                                         $query .= " and (title like '$key[$i]%' or title like '% $key[$i]%' or title like '% $key[$i]')";
901                                         $i++;
902                                 }
903                                 $query.=") or ((seriestitle like '$key[0]%' or seriestitle like '% $key[0]%' or seriestitle like '% $key[0]')";
904                                 for ($i=1;$i<$count;$i++){
905                                         $query.=" and (seriestitle like '$key[$i]%' or seriestitle like '% $key[$i]%')";
906                                         }
907                                 $query.=") or ((unititle like '$key[0]%' or unititle like '% $key[0]%' or unititle like '% $key[0]')";
908                                 for ($i=1;$i<$count;$i++){
909                                         $query.=" and (unititle like '$key[$i]%' or unititle like '% $key[$i]%')";
910                                         }
911                                 $query .= "))";
912                                 #$query=$query. " and (title like '%$search->{'title'}%'
913                                 #or seriestitle like '%$search->{'title'}%')";
914                         }
915                         if ($search->{'abstract'} ne ''){
916                                 $query.= " and (abstract like '%$search->{'abstract'}%')";
917                         }
918                         if ($search->{'date-before'} ne ''){
919                                 $query.= " and (copyrightdate like '%$search->{'date-before'}%')";
920                         }
921                         $query.=" group by biblio.biblionumber";
922                 } else {
923                         if ($search->{'title'} ne '') {
924                                 if ($search->{'ttype'} eq 'exact'){
925                                         $query="select * from biblio
926                                         where
927                                         (biblio.title='$search->{'title'}' or (biblio.unititle = '$search->{'title'}'
928                                         or biblio.unititle like '$search->{'title'} |%' or
929                                         biblio.unititle like '%| $search->{'title'} |%' or
930                                         biblio.unititle like '%| $search->{'title'}') or
931                                         (biblio.seriestitle = '$search->{'title'}' or
932                                         biblio.seriestitle like '$search->{'title'} |%' or
933                                         biblio.seriestitle like '%| $search->{'title'} |%' or
934                                         biblio.seriestitle like '%| $search->{'title'}')
935                                         )";
936                                 } else {
937                                         my @key=split(' ',$search->{'title'});
938                                         my $count=@key;
939                                         my $i=1;
940                                         $query="select biblio.biblionumber,author,title,unititle,notes,abstract,serial,seriestitle,copyrightdate,timestamp,subtitle from biblio
941                                         left join bibliosubtitle on
942                                         biblio.biblionumber=bibliosubtitle.biblionumber
943                                         where
944                                         (((title like '$key[0]%' or title like '% $key[0]%' or title like '% $key[0]')";
945                                         while ($i<$count){
946                                                 $query .= " and (title like '$key[$i]%' or title like '% $key[$i]%' or title like '% $key[$i]')";
947                                                 $i++;
948                                         }
949                                         $query.=") or ((subtitle like '$key[0]%' or subtitle like '% $key[0]%' or subtitle like '% $key[0]')";
950                                         for ($i=1;$i<$count;$i++){
951                                                 $query.=" and (subtitle like '$key[$i]%' or subtitle like '% $key[$i]%' or subtitle like '% $key[$i]')";
952                                         }
953                                         $query.=") or ((seriestitle like '$key[0]%' or seriestitle like '% $key[0]%' or seriestitle like '% $key[0]')";
954                                         for ($i=1;$i<$count;$i++){
955                                                 $query.=" and (seriestitle like '$key[$i]%' or seriestitle like '% $key[$i]%')";
956                                         }
957                                         $query.=") or ((unititle like '$key[0]%' or unititle like '% $key[0]%' or unititle like '% $key[0]')";
958                                         for ($i=1;$i<$count;$i++){
959                                                 $query.=" and (unititle like '$key[$i]%' or unititle like '% $key[$i]%')";
960                                         }
961                                         $query .= "))";
962                                 }
963                                 if ($search->{'abstract'} ne ''){
964                                         $query.= " and (abstract like '%$search->{'abstract'}%')";
965                                 }
966                                 if ($search->{'date-before'} ne ''){
967                                         $query.= " and (copyrightdate like '%$search->{'date-before'}%')";
968                                 }
969                         } elsif ($search->{'class'} ne ''){
970                                 $query="select * from biblioitems,biblio where biblio.biblionumber=biblioitems.biblionumber";
971                                 my @temp=split(/\|/,$search->{'class'});
972                                 my $count=@temp;
973                                 $query.= " and ( itemtype='$temp[0]'";
974                                 for (my $i=1;$i<$count;$i++){
975                                         $query.=" or itemtype='$temp[$i]'";
976                                 }
977                                 $query.=")";
978                                 if ($search->{'illustrator'} ne ''){
979                                         $query.=" and illus like '%".$search->{'illustrator'}."%' ";
980                                 }
981                                 if ($search->{'dewey'} ne ''){
982                                         $query.=" and biblioitems.dewey like '$search->{'dewey'}%'";
983                                 }
984                         } elsif ($search->{'dewey'} ne ''){
985                                 $query="select * from biblioitems,biblio
986                                 where biblio.biblionumber=biblioitems.biblionumber
987                                 and biblioitems.dewey like '$search->{'dewey'}%'";
988                         } elsif ($search->{'illustrator'} ne '') {
989                                         $query="select * from biblioitems,biblio
990                                 where biblio.biblionumber=biblioitems.biblionumber
991                                 and biblioitems.illus like '%".$search->{'illustrator'}."%'";
992                         } elsif ($search->{'publisher'} ne ''){
993                                 $query.= "Select * from biblio,biblioitems where biblio.biblionumber
994                                 =biblioitems.biblionumber and (publishercode like '%$search->{'publisher'}%')";
995                         } elsif ($search->{'abstract'} ne ''){
996                                 $query.= "Select * from biblio where abstract like '%$search->{'abstract'}%'";
997                         } elsif ($search->{'date-before'} ne ''){
998                                 $query.= "Select * from biblio where copyrightdate like '%$search->{'date-before'}%'";
999                         }
1000                         $query .=" group by biblio.biblionumber";
1001                 }
1002         }
1003         if ($type eq 'subject'){
1004                 my @key=split(' ',$search->{'subject'});
1005                 my $count=@key;
1006                 my $i=1;
1007                 $query="select * from bibliosubject, biblioitems where
1008 (bibliosubject.biblionumber = biblioitems.biblionumber) and ( subject like
1009 '$key[0]%' or subject like '% $key[0]%' or subject like '% $key[0]' or subject
1010 like '%($key[0])%')";           while ($i<$count){                      $query.=" and (subject like
1011 '$key[$i]%' or subject like '% $key[$i]%'                       or subject like '% $key[$i]'
1012                         or subject like '%($key[$i])%')";
1013                         $i++;
1014                 }
1015
1016                 # FIXME - Wouldn't it be better to fix the database so that if a
1017                 # book has a subject "NZ", then it also gets added the subject
1018                 # "New Zealand"?
1019                 # This can also be generalized by adding a table of subject
1020                 # synonyms to the database: just declare "NZ" to be a synonym for
1021                 # "New Zealand", "SF" a synonym for both "Science fiction" and
1022                 # "Fantastic fiction", etc.
1023
1024                 if (lc($search->{'subject'}) eq 'nz'){
1025                         $query.= " or (subject like 'NEW ZEALAND %' or subject like '% NEW ZEALAND %'
1026                         or subject like '% NEW ZEALAND' or subject like '%(NEW ZEALAND)%' ) ";
1027                 } elsif ( $search->{'subject'} =~ /^nz /i || $search->{'subject'} =~ / nz /i || $search->{'subject'} =~ / nz$/i){
1028                         $query=~ s/ nz/ NEW ZEALAND/ig;
1029                         $query=~ s/nz /NEW ZEALAND /ig;
1030                         $query=~ s/\(nz\)/\(NEW ZEALAND\)/gi;
1031                 }
1032         }
1033         if ($type eq 'precise'){
1034                 if ($search->{'itemnumber'} ne ''){
1035                         $query="select * from items,biblio ";
1036                         my $search2=uc $search->{'itemnumber'};
1037                         $query=$query." where
1038                         items.biblionumber=biblio.biblionumber
1039                         and barcode='$search2'";
1040                                         # FIXME - .= <<EOT;
1041                 }
1042                 if ($search->{'isbn'} ne ''){
1043                         my $search2=uc $search->{'isbn'};
1044                         my $query1 = "select * from biblioitems where isbn='$search2'";
1045                         my $sth1=$dbh->prepare($query1);
1046                 #       print STDERR "$query1\n";
1047                         $sth1->execute;
1048                         my $i2=0;
1049                         while (my $data=$sth1->fetchrow_hashref) {
1050                                 $query="select * from biblioitems,biblio where
1051                                         biblio.biblionumber = $data->{'biblionumber'}
1052                                         and biblioitems.biblionumber = biblio.biblionumber";
1053                                 my $sth=$dbh->prepare($query);
1054                                 $sth->execute;
1055                                 # FIXME - There's already a $data in this scope.
1056                                 my $data=$sth->fetchrow_hashref;
1057                                 my ($dewey, $subclass) = ($data->{'dewey'}, $data->{'subclass'});
1058                                 # FIXME - The following assumes that the Dewey code is a
1059                                 # floating-point number. It isn't: it's a string.
1060                                 $dewey=~s/\.*0*$//;
1061                                 ($dewey == 0) && ($dewey='');
1062                                 ($dewey) && ($dewey.=" $subclass");
1063                                 $data->{'dewey'}=$dewey;
1064                                 $results[$i2]=$data;
1065                         #           $results[$i2]="$data->{'author'}\t$data->{'title'}\t$data->{'biblionumber'}\t$data->{'copyrightdate'}\t$dewey\t$data->{'isbn'}\t$data->{'itemtype'}";
1066                                 $i2++;
1067                                 $sth->finish;
1068                         }
1069                         $sth1->finish;
1070                 }
1071         }
1072         if ($type ne 'precise' && $type ne 'subject'){
1073                 if ($search->{'author'} ne ''){
1074                         $query .= " order by biblio.author,title";
1075                 } else {
1076                         $query .= " order by title";
1077                 }
1078         } else {
1079                 if ($type eq 'subject'){
1080                         $query .= "group by subject order by subject ";
1081                 }
1082         }
1083         my $sth=$dbh->prepare($query);
1084         $sth->execute;
1085         my $count=1;
1086         my $i=0;
1087         my $limit= $num+$offset;
1088         while (my $data=$sth->fetchrow_hashref){
1089                 my $query="select dewey,subclass,publishercode from biblioitems where biblionumber=$data->{'biblionumber'}";
1090                 if ($search->{'class'} ne ''){
1091                         my @temp=split(/\|/,$search->{'class'});
1092                         my $count=@temp;
1093                         $query.= " and ( itemtype='$temp[0]'";
1094                         for (my $i=1;$i<$count;$i++){
1095                         $query.=" or itemtype='$temp[$i]'";
1096                         }
1097                         $query.=")";
1098                 }
1099                 if ($search->{'dewey'} ne ''){
1100                         $query.=" and dewey='$search->{'dewey'}' ";
1101                 }
1102                 if ($search->{'illustrator'} ne ''){
1103                         $query.=" and illus like '%".$search->{'illustrator'}."%' ";
1104                 }
1105                 if ($search->{'publisher'} ne ''){
1106                         $query.= " and (publishercode like '%$search->{'publisher'}%')";
1107                 }
1108                 my $sti=$dbh->prepare($query);
1109                 $sti->execute;
1110                 my $dewey;
1111                 my $subclass;
1112                 my $true=0;
1113                 my $publishercode;
1114                 my $bibitemdata;
1115                 if ($bibitemdata = $sti->fetchrow_hashref()){
1116                         $true=1;
1117                         $dewey=$bibitemdata->{'dewey'};
1118                         $subclass=$bibitemdata->{'subclass'};
1119                         $publishercode=$bibitemdata->{'publishercode'};
1120                 }
1121                 #  print STDERR "$dewey $subclass $publishercode\n";
1122                 # FIXME - The Dewey code is a string, not a number.
1123                 $dewey=~s/\.*0*$//;
1124                 ($dewey == 0) && ($dewey='');
1125                 ($dewey) && ($dewey.=" $subclass");
1126                 $data->{'dewey'}=$dewey;
1127                 $data->{'publishercode'}=$publishercode;
1128                 $sti->finish;
1129                 if ($true == 1){
1130                         if ($count > $offset && $count <= $limit){
1131                                 $results[$i]=$data;
1132                                 $i++;
1133                         }
1134                         $count++;
1135                 }
1136         }
1137         $sth->finish;
1138         $count--;
1139         return($count,@results);
1140 }
1141
1142 sub updatesearchstats{
1143   my ($dbh,$query)=@_;
1144
1145 }
1146
1147 =item subsearch
1148
1149   @results = &subsearch($env, $subject);
1150
1151 Searches for books that have a subject that exactly matches
1152 C<$subject>.
1153
1154 C<&subsearch> returns an array of results. Each element of this array
1155 is a string, containing the book's title, author, and biblionumber,
1156 separated by tabs.
1157
1158 C<$env> is ignored.
1159
1160 =cut
1161 #'
1162 sub subsearch {
1163   my ($env,$subject)=@_;
1164   my $dbh = C4::Context->dbh;
1165   $subject=$dbh->quote($subject);
1166   my $query="Select * from biblio,bibliosubject where
1167   biblio.biblionumber=bibliosubject.biblionumber and
1168   bibliosubject.subject=$subject group by biblio.biblionumber
1169   order by biblio.title";
1170   my $sth=$dbh->prepare($query);
1171   $sth->execute;
1172   my $i=0;
1173 #  print $query;
1174   my @results;
1175   while (my $data=$sth->fetchrow_hashref){
1176     push @results, $data;
1177     $i++;
1178   }
1179   $sth->finish;
1180   return(@results);
1181 }
1182
1183 =item ItemInfo
1184
1185   @results = &ItemInfo($env, $biblionumber, $type);
1186
1187 Returns information about books with the given biblionumber.
1188
1189 C<$type> may be either C<intra> or anything else. If it is not set to
1190 C<intra>, then the search will exclude lost, very overdue, and
1191 withdrawn items.
1192
1193 C<$env> is ignored.
1194
1195 C<&ItemInfo> returns a list of references-to-hash. Each element
1196 contains a number of keys. Most of them are table items from the
1197 C<biblio>, C<biblioitems>, C<items>, and C<itemtypes> tables in the
1198 Koha database. Other keys include:
1199
1200 =over 4
1201
1202 =item C<$data-E<gt>{branchname}>
1203
1204 The name (not the code) of the branch to which the book belongs.
1205
1206 =item C<$data-E<gt>{datelastseen}>
1207
1208 This is simply C<items.datelastseen>, except that while the date is
1209 stored in YYYY-MM-DD format in the database, here it is converted to
1210 DD/MM/YYYY format. A NULL date is returned as C<//>.
1211
1212 =item C<$data-E<gt>{datedue}>
1213
1214 =item C<$data-E<gt>{class}>
1215
1216 This is the concatenation of C<biblioitems.classification>, the book's
1217 Dewey code, and C<biblioitems.subclass>.
1218
1219 =item C<$data-E<gt>{ocount}>
1220
1221 I think this is the number of copies of the book available.
1222
1223 =item C<$data-E<gt>{order}>
1224
1225 If this is set, it is set to C<One Order>.
1226
1227 =back
1228
1229 =cut
1230 #'
1231 sub ItemInfo {
1232     my ($env,$biblionumber,$type) = @_;
1233     my $dbh   = C4::Context->dbh;
1234     my $query = "SELECT *,items.notforloan as itemnotforloan FROM items, biblio, biblioitems left join itemtypes on biblioitems.itemtype = itemtypes.itemtype
1235                   WHERE items.biblionumber = ?
1236                     AND biblioitems.biblioitemnumber = items.biblioitemnumber
1237                     AND biblio.biblionumber = items.biblionumber";
1238   if ($type ne 'intra'){
1239     $query .= " and ((items.itemlost<>1 and items.itemlost <> 2)
1240     or items.itemlost is NULL)
1241     and (wthdrawn <> 1 or wthdrawn is NULL)";
1242   }
1243   $query .= " order by items.dateaccessioned desc";
1244     #warn $query;
1245   my $sth=$dbh->prepare($query);
1246   $sth->execute($biblionumber);
1247   my $i=0;
1248   my @results;
1249 #  print $query;
1250   while (my $data=$sth->fetchrow_hashref){
1251     my $iquery = "Select * from issues
1252     where itemnumber = '$data->{'itemnumber'}'
1253     and returndate is null";
1254     my $datedue = '';
1255     my $isth=$dbh->prepare($iquery);
1256     $isth->execute;
1257     if (my $idata=$isth->fetchrow_hashref){
1258       $datedue = format_date($idata->{'date_due'});
1259     }
1260     if ($data->{'itemlost'} eq '2'){
1261         $datedue='Very Overdue';
1262     }
1263     if ($data->{'itemlost'} eq '1'){
1264         $datedue='Lost';
1265     }
1266     if ($data->{'wthdrawn'} eq '1'){
1267         $datedue="Cancelled";
1268     }
1269     if ($datedue eq ''){
1270         $datedue="Available";
1271         my ($restype,$reserves)=CheckReserves($data->{'itemnumber'});
1272         if ($restype){
1273             $datedue=$restype;
1274         }
1275     }
1276     $isth->finish;
1277 #get branch information.....
1278     my $bquery = "SELECT * FROM branches
1279                           WHERE branchcode = '$data->{'holdingbranch'}'";
1280     my $bsth=$dbh->prepare($bquery);
1281     $bsth->execute;
1282     if (my $bdata=$bsth->fetchrow_hashref){
1283         $data->{'branchname'} = $bdata->{'branchname'};
1284     }
1285
1286     my $class = $data->{'classification'};
1287     my $dewey = $data->{'dewey'};
1288     $dewey =~ s/0+$//;
1289     if ($dewey eq "000.") { $dewey = "";};      # FIXME - "000" is general
1290                                                 # books about computer science
1291     if ($dewey < 10){$dewey='00'.$dewey;}
1292     if ($dewey < 100 && $dewey > 10){$dewey='0'.$dewey;}
1293     if ($dewey <= 0){
1294       $dewey='';
1295     }
1296     $dewey=~ s/\.$//;
1297     $class .= $dewey;
1298     if ($dewey ne ''){
1299       $class .= $data->{'subclass'};
1300     }
1301  #   $results[$i]="$data->{'title'}\t$data->{'barcode'}\t$datedue\t$data->{'branchname'}\t$data->{'dewey'}";
1302     # FIXME - If $data->{'datelastseen'} is NULL, perhaps it'd be prettier
1303     # to leave it empty, rather than convert it to "//".
1304     # Also ideally this should use the local format for displaying dates.
1305     my $date=format_date($data->{'datelastseen'});
1306     $data->{'datelastseen'}=$date;
1307     $data->{'datedue'}=$datedue;
1308     $data->{'class'}=$class;
1309     $results[$i]=$data;
1310     $i++;
1311   }
1312  $sth->finish;
1313   my $query2="Select * from aqorders where biblionumber=$biblionumber";
1314   my $sth2=$dbh->prepare($query2);
1315   $sth2->execute;
1316   my $data;
1317   my $ocount;
1318   if ($data=$sth2->fetchrow_hashref){
1319     $ocount=$data->{'quantity'} - $data->{'quantityreceived'};
1320     if ($ocount > 0){
1321       $data->{'ocount'}=$ocount;
1322       $data->{'order'}="One Order";
1323       $results[$i]=$data;
1324     }
1325   }
1326   $sth2->finish;
1327
1328   return(@results);
1329 }
1330
1331 =item GetItems
1332
1333   @results = &GetItems($env, $biblionumber);
1334
1335 Returns information about books with the given biblionumber.
1336
1337 C<$env> is ignored.
1338
1339 C<&GetItems> returns an array of strings. Each element is a
1340 tab-separated list of values: biblioitemnumber, itemtype,
1341 classification, Dewey number, subclass, ISBN, volume, number, and
1342 itemdata.
1343
1344 Itemdata, in turn, is a string of the form
1345 "I<barcode>C<[>I<holdingbranch>C<[>I<flags>" where I<flags> contains
1346 the string C<NFL> if the item is not for loan, and C<LOST> if the item
1347 is lost.
1348
1349 =cut
1350 #'
1351 sub GetItems {
1352    my ($env,$biblionumber)=@_;
1353    #debug_msg($env,"GetItems");
1354    my $dbh = C4::Context->dbh;
1355    my $query = "Select * from biblioitems where (biblionumber = $biblionumber)";
1356    #debug_msg($env,$query);
1357    my $sth=$dbh->prepare($query);
1358    $sth->execute;
1359    #debug_msg($env,"executed query");
1360    my $i=0;
1361    my @results;
1362    while (my $data=$sth->fetchrow_hashref) {
1363       #debug_msg($env,$data->{'biblioitemnumber'});
1364       my $dewey = $data->{'dewey'};
1365       $dewey =~ s/0+$//;
1366       my $line = $data->{'biblioitemnumber'}."\t".$data->{'itemtype'};
1367       $line .= "\t$data->{'classification'}\t$dewey";
1368       $line .= "\t$data->{'subclass'}\t$data->{isbn}";
1369       $line .= "\t$data->{'volume'}\t$data->{number}";
1370       my $isth= $dbh->prepare("select * from items where biblioitemnumber = $data->{'biblioitemnumber'}");
1371       $isth->execute;
1372       while (my $idata = $isth->fetchrow_hashref) {
1373         my $iline = $idata->{'barcode'}."[".$idata->{'holdingbranch'}."[";
1374         if ($idata->{'notforloan'} == 1) {
1375           $iline .= "NFL ";
1376         }
1377         if ($idata->{'itemlost'} == 1) {
1378           $iline .= "LOST ";
1379         }
1380         $line .= "\t$iline";
1381       }
1382       $isth->finish;
1383       $results[$i] = $line;
1384       $i++;
1385    }
1386    $sth->finish;
1387    return(@results);
1388 }
1389
1390 =item itemdata
1391
1392   $item = &itemdata($barcode);
1393
1394 Looks up the item with the given barcode, and returns a
1395 reference-to-hash containing information about that item. The keys of
1396 the hash are the fields from the C<items> and C<biblioitems> tables in
1397 the Koha database.
1398
1399 =cut
1400 #'
1401 sub itemdata {
1402   my ($barcode)=@_;
1403   my $dbh = C4::Context->dbh;
1404   my $query="Select * from items,biblioitems where barcode='$barcode'
1405   and items.biblioitemnumber=biblioitems.biblioitemnumber";
1406 #  print $query;
1407   my $sth=$dbh->prepare($query);
1408   $sth->execute;
1409   my $data=$sth->fetchrow_hashref;
1410   $sth->finish;
1411   return($data);
1412 }
1413
1414 =item bibdata
1415
1416   $data = &bibdata($biblionumber, $type);
1417
1418 Returns information about the book with the given biblionumber.
1419
1420 C<$type> is ignored.
1421
1422 C<&bibdata> returns a reference-to-hash. The keys are the fields in
1423 the C<biblio>, C<biblioitems>, and C<bibliosubtitle> tables in the
1424 Koha database.
1425
1426 In addition, C<$data-E<gt>{subject}> is the list of the book's
1427 subjects, separated by C<" , "> (space, comma, space).
1428
1429 If there are multiple biblioitems with the given biblionumber, only
1430 the first one is considered.
1431
1432 =cut
1433 #'
1434 sub bibdata {
1435     my ($bibnum, $type) = @_;
1436     my $dbh   = C4::Context->dbh;
1437     my $query = "Select *, biblioitems.notes AS bnotes, biblio.notes
1438     from biblio, biblioitems
1439     left join bibliosubtitle on
1440     biblio.biblionumber = bibliosubtitle.biblionumber
1441     where biblio.biblionumber = ?
1442     and biblioitems.biblionumber = biblio.biblionumber";
1443     my $sth   = $dbh->prepare($query);
1444     $sth->execute($bibnum);
1445     my $data;
1446     $data  = $sth->fetchrow_hashref;
1447     $sth->finish;
1448     $query = "Select * from bibliosubject where biblionumber = ?";
1449     $sth   = $dbh->prepare($query);
1450     $sth->execute($bibnum);
1451     while (my $dat = $sth->fetchrow_hashref){
1452         $data->{'subject'} .= "$dat->{'subject'}, ";
1453     } # while
1454         chop $data->{'subject'};
1455         chop $data->{'subject'};
1456     $sth->finish;
1457     $query = "Select * from additionalauthors where biblionumber = ?";
1458     $sth   = $dbh->prepare($query);
1459     $sth->execute($bibnum);
1460     while (my $dat = $sth->fetchrow_hashref){
1461         $data->{'additionalauthors'} .= "$dat->{'author'}, ";
1462     } # while
1463         chop $data->{'additionalauthors'};
1464         chop $data->{'additionalauthors'};
1465     $sth->finish;
1466     return($data);
1467 } # sub bibdata
1468
1469 =item bibitemdata
1470
1471   $itemdata = &bibitemdata($biblioitemnumber);
1472
1473 Looks up the biblioitem with the given biblioitemnumber. Returns a
1474 reference-to-hash. The keys are the fields from the C<biblio>,
1475 C<biblioitems>, and C<itemtypes> tables in the Koha database, except
1476 that C<biblioitems.notes> is given as C<$itemdata-E<gt>{bnotes}>.
1477
1478 =cut
1479 #'
1480 sub bibitemdata {
1481     my ($bibitem) = @_;
1482     my $dbh   = C4::Context->dbh;
1483     my $query = "Select *,biblioitems.notes as bnotes from biblio, biblioitems,itemtypes
1484 where biblio.biblionumber = biblioitems.biblionumber
1485 and biblioitemnumber = $bibitem
1486 and biblioitems.itemtype = itemtypes.itemtype";
1487     my $sth   = $dbh->prepare($query);
1488     my $data;
1489
1490     $sth->execute;
1491
1492     $data = $sth->fetchrow_hashref;
1493
1494     $sth->finish;
1495     return($data);
1496 } # sub bibitemdata
1497
1498 =item subject
1499
1500   ($count, $subjects) = &subject($biblionumber);
1501
1502 Looks up the subjects of the book with the given biblionumber. Returns
1503 a two-element list. C<$subjects> is a reference-to-array, where each
1504 element is a subject of the book, and C<$count> is the number of
1505 elements in C<$subjects>.
1506
1507 =cut
1508 #'
1509 sub subject {
1510   my ($bibnum)=@_;
1511   my $dbh = C4::Context->dbh;
1512   my $query="Select * from bibliosubject where biblionumber=?";
1513   my $sth=$dbh->prepare($query);
1514   $sth->execute($bibnum);
1515   my @results;
1516   my $i=0;
1517   while (my $data=$sth->fetchrow_hashref){
1518     $results[$i]=$data;
1519     $i++;
1520   }
1521   $sth->finish;
1522   return($i,\@results);
1523 }
1524
1525 =item addauthor
1526
1527   ($count, $authors) = &addauthors($biblionumber);
1528
1529 Looks up the additional authors for the book with the given
1530 biblionumber.
1531
1532 Returns a two-element list. C<$authors> is a reference-to-array, where
1533 each element is an additional author, and C<$count> is the number of
1534 elements in C<$authors>.
1535
1536 =cut
1537 #'
1538 sub addauthor {
1539   my ($bibnum)=@_;
1540   my $dbh = C4::Context->dbh;
1541   my $query="Select * from additionalauthors where biblionumber=$bibnum";
1542   my $sth=$dbh->prepare($query);
1543   $sth->execute;
1544   my @results;
1545   my $i=0;
1546   while (my $data=$sth->fetchrow_hashref){
1547     $results[$i]=$data;
1548     $i++;
1549   }
1550   $sth->finish;
1551   return($i,\@results);
1552 }
1553
1554 =item subtitle
1555
1556   ($count, $subtitles) = &subtitle($biblionumber);
1557
1558 Looks up the subtitles for the book with the given biblionumber.
1559
1560 Returns a two-element list. C<$subtitles> is a reference-to-array,
1561 where each element is a subtitle, and C<$count> is the number of
1562 elements in C<$subtitles>.
1563
1564 =cut
1565 #'
1566 sub subtitle {
1567   my ($bibnum)=@_;
1568   my $dbh = C4::Context->dbh;
1569   my $query="Select * from bibliosubtitle where biblionumber=$bibnum";
1570   my $sth=$dbh->prepare($query);
1571   $sth->execute;
1572   my @results;
1573   my $i=0;
1574   while (my $data=$sth->fetchrow_hashref){
1575     $results[$i]=$data;
1576     $i++;
1577   }
1578   $sth->finish;
1579   return($i,\@results);
1580 }
1581
1582 =item itemissues
1583
1584   @issues = &itemissues($biblioitemnumber, $biblio);
1585
1586 Looks up information about who has borrowed the bookZ<>(s) with the
1587 given biblioitemnumber.
1588
1589 C<$biblio> is ignored.
1590
1591 C<&itemissues> returns an array of references-to-hash. The keys
1592 include the fields from the C<items> table in the Koha database.
1593 Additional keys include:
1594
1595 =over 4
1596
1597 =item C<date_due>
1598
1599 If the item is currently on loan, this gives the due date.
1600
1601 If the item is not on loan, then this is either "Available" or
1602 "Cancelled", if the item has been withdrawn.
1603
1604 =item C<card>
1605
1606 If the item is currently on loan, this gives the card number of the
1607 patron who currently has the item.
1608
1609 =item C<timestamp0>, C<timestamp1>, C<timestamp2>
1610
1611 These give the timestamp for the last three times the item was
1612 borrowed.
1613
1614 =item C<card0>, C<card1>, C<card2>
1615
1616 The card number of the last three patrons who borrowed this item.
1617
1618 =item C<borrower0>, C<borrower1>, C<borrower2>
1619
1620 The borrower number of the last three patrons who borrowed this item.
1621
1622 =back
1623
1624 =cut
1625 #'
1626 sub itemissues {
1627     my ($bibitem, $biblio)=@_;
1628     my $dbh   = C4::Context->dbh;
1629     my $query = "Select * from items where
1630 items.biblioitemnumber = '$bibitem'";
1631     # FIXME - If this function die()s, the script will abort, and the
1632     # user won't get anything; depending on how far the script has
1633     # gotten, the user might get a blank page. It would be much better
1634     # to at least print an error message. The easiest way to do this
1635     # is to set $SIG{__DIE__}.
1636     my $sth   = $dbh->prepare($query)
1637       || die $dbh->errstr;
1638     my $i     = 0;
1639     my @results;
1640
1641     $sth->execute
1642       || die $sth->errstr;
1643
1644     while (my $data = $sth->fetchrow_hashref) {
1645         # Find out who currently has this item.
1646         # FIXME - Wouldn't it be better to do this as a left join of
1647         # some sort? Currently, this code assumes that if
1648         # fetchrow_hashref() fails, then the book is on the shelf.
1649         # fetchrow_hashref() can fail for any number of reasons (e.g.,
1650         # database server crash), not just because no items match the
1651         # search criteria.
1652         my $query2 = "select * from issues,borrowers
1653 where itemnumber = $data->{'itemnumber'}
1654 and returndate is NULL
1655 and issues.borrowernumber = borrowers.borrowernumber";
1656         my $sth2   = $dbh->prepare($query2);
1657
1658         $sth2->execute;
1659         if (my $data2 = $sth2->fetchrow_hashref) {
1660             $data->{'date_due'} = $data2->{'date_due'};
1661             $data->{'card'}     = $data2->{'cardnumber'};
1662             $data->{'borrower'}     = $data2->{'borrowernumber'};
1663         } else {
1664             if ($data->{'wthdrawn'} eq '1') {
1665                 $data->{'date_due'} = 'Cancelled';
1666             } else {
1667                 $data->{'date_due'} = 'Available';
1668             } # else
1669         } # else
1670
1671         $sth2->finish;
1672
1673         # Find the last 3 people who borrowed this item.
1674         $query2 = "select * from issues, borrowers
1675                                                 where itemnumber = ?
1676                                                                         and issues.borrowernumber = borrowers.borrowernumber
1677                                                                         and returndate is not NULL
1678                                                                         order by returndate desc,timestamp desc";
1679         $sth2 = $dbh->prepare($query2) || die $dbh->errstr;
1680         $sth2->execute($data->{'itemnumber'}) || die $sth2->errstr;
1681         for (my $i2 = 0; $i2 < 2; $i2++) { # FIXME : error if there is less than 3 pple borrowing this item
1682             if (my $data2 = $sth2->fetchrow_hashref) {
1683                 $data->{"timestamp$i2"} = $data2->{'timestamp'};
1684                 $data->{"card$i2"}      = $data2->{'cardnumber'};
1685                 $data->{"borrower$i2"}  = $data2->{'borrowernumber'};
1686             } # if
1687         } # for
1688
1689         $sth2->finish;
1690         $results[$i] = $data;
1691         $i++;
1692     }
1693
1694     $sth->finish;
1695     return(@results);
1696 }
1697
1698 =item itemnodata
1699
1700   $item = &itemnodata($env, $dbh, $biblioitemnumber);
1701
1702 Looks up the item with the given biblioitemnumber.
1703
1704 C<$env> and C<$dbh> are ignored.
1705
1706 C<&itemnodata> returns a reference-to-hash whose keys are the fields
1707 from the C<biblio>, C<biblioitems>, and C<items> tables in the Koha
1708 database.
1709
1710 =cut
1711 #'
1712 sub itemnodata {
1713   my ($env,$dbh,$itemnumber) = @_;
1714   $dbh = C4::Context->dbh;
1715   my $query="Select * from biblio,items,biblioitems
1716     where items.itemnumber = '$itemnumber'
1717     and biblio.biblionumber = items.biblionumber
1718     and biblioitems.biblioitemnumber = items.biblioitemnumber";
1719   my $sth=$dbh->prepare($query);
1720 #  print $query;
1721   $sth->execute;
1722   my $data=$sth->fetchrow_hashref;
1723   $sth->finish;
1724   return($data);
1725 }
1726
1727 =item BornameSearch
1728
1729   ($count, $borrowers) = &BornameSearch($env, $searchstring, $type);
1730
1731 Looks up patrons (borrowers) by name.
1732
1733 C<$env> is ignored.
1734
1735 BUGFIX 499: C<$type> is now used to determine type of search.
1736 if $type is "simple", search is performed on the first letter of the
1737 surname only.
1738
1739 C<$searchstring> is a space-separated list of search terms. Each term
1740 must match the beginning a borrower's surname, first name, or other
1741 name.
1742
1743 C<&BornameSearch> returns a two-element list. C<$borrowers> is a
1744 reference-to-array; each element is a reference-to-hash, whose keys
1745 are the fields of the C<borrowers> table in the Koha database.
1746 C<$count> is the number of elements in C<$borrowers>.
1747
1748 =cut
1749 #'
1750 #used by member enquiries from the intranet
1751 #called by member.pl
1752 sub BornameSearch  {
1753         my ($env,$searchstring,$type)=@_;
1754         my $dbh = C4::Context->dbh;
1755         $searchstring=~ s/\,//g;
1756         $searchstring=~ s/\'/\\\'/g;
1757         my $query = ""; my $count; my @data;
1758
1759         if($type eq "simple")   # simple search for one letter only
1760         {
1761                 $query="Select * from borrowers where surname like \"$searchstring%\" order by surname,firstname";
1762         }
1763         else    # advanced search looking in surname, firstname and othernames
1764         {
1765                 @data=split(' ',$searchstring);
1766                 $count=@data;
1767                 $query="Select * from borrowers
1768                 where ((surname like \"$data[0]%\" or surname like \"% $data[0]%\"
1769                 or firstname  like \"$data[0]%\" or firstname like \"% $data[0]%\"
1770                 or othernames like \"$data[0]%\" or othernames like \"% $data[0]%\")
1771                 ";
1772                 for (my $i=1;$i<$count;$i++){
1773                 $query=$query." and (".
1774                 " firstname  like \"$data[$i]%\" or firstname like \"% $data[$i]%\"
1775                 or othernames like \"$data[$i]%\" or othernames like \"% $data[$i]%\")";
1776                                         # FIXME - .= <<EOT;
1777                 }
1778                 $query=$query.") or cardnumber = \"$searchstring\"
1779                 order by surname,firstname";
1780                                         # FIXME - .= <<EOT;
1781         }
1782
1783         my $sth=$dbh->prepare($query);
1784         $sth->execute;
1785         my @results;
1786         my $cnt=$sth->rows;
1787         while (my $data=$sth->fetchrow_hashref){
1788         push(@results,$data);
1789         }
1790         #  $sth->execute;
1791         $sth->finish;
1792         return ($cnt,\@results);
1793 }
1794
1795 =item borrdata
1796
1797   $borrower = &borrdata($cardnumber, $borrowernumber);
1798
1799 Looks up information about a patron (borrower) by either card number
1800 or borrower number. If $borrowernumber is specified, C<&borrdata>
1801 searches by borrower number; otherwise, it searches by card number.
1802
1803 C<&borrdata> returns a reference-to-hash whose keys are the fields of
1804 the C<borrowers> table in the Koha database.
1805
1806 =cut
1807 #'
1808 sub borrdata {
1809   my ($cardnumber,$bornum)=@_;
1810   $cardnumber = uc $cardnumber;
1811   my $dbh = C4::Context->dbh;
1812   my $query;
1813   if ($bornum eq ''){
1814     $query="Select * from borrowers where cardnumber='$cardnumber'";
1815   } else {
1816       $query="Select * from borrowers where borrowernumber='$bornum'";
1817   }
1818   #print $query;
1819   my $sth=$dbh->prepare($query);
1820   $sth->execute;
1821   my $data=$sth->fetchrow_hashref;
1822   $sth->finish;
1823   if ($data) {
1824         return($data);
1825         } else { # try with firstname
1826                 if ($cardnumber) {
1827                         my $sth=$dbh->prepare("select * from borrowers where firstname='$cardnumber'");
1828                         $sth->execute;
1829                         my $data=$sth->fetchrow_hashref;
1830                         $sth->finish;
1831                         return($data);
1832                 }
1833         }
1834         return undef;
1835 }
1836
1837 =item borrissues
1838
1839   ($count, $issues) = &borrissues($borrowernumber);
1840
1841 Looks up what the patron with the given borrowernumber has borrowed.
1842
1843 C<&borrissues> returns a two-element array. C<$issues> is a
1844 reference-to-array, where each element is a reference-to-hash; the
1845 keys are the fields from the C<issues>, C<biblio>, and C<items> tables
1846 in the Koha database. C<$count> is the number of elements in
1847 C<$issues>.
1848
1849 =cut
1850 #'
1851 sub borrissues {
1852   my ($bornum)=@_;
1853   my $dbh = C4::Context->dbh;
1854   my $query;
1855   $query="Select * from issues,biblio,items where borrowernumber='$bornum'
1856    and items.itemnumber=issues.itemnumber
1857         and items.biblionumber=biblio.biblionumber
1858         and issues.returndate is NULL order by date_due";
1859   #print $query;
1860   my $sth=$dbh->prepare($query);
1861     $sth->execute;
1862   my @result;
1863   while (my $data = $sth->fetchrow_hashref) {
1864     push @result, $data;
1865   }
1866   $sth->finish;
1867   return(scalar(@result), \@result);
1868 }
1869
1870 =item allissues
1871
1872   ($count, $issues) = &allissues($borrowernumber, $sortkey, $limit);
1873
1874 Looks up what the patron with the given borrowernumber has borrowed,
1875 and sorts the results.
1876
1877 C<$sortkey> is the name of a field on which to sort the results. This
1878 should be the name of a field in the C<issues>, C<biblio>,
1879 C<biblioitems>, or C<items> table in the Koha database.
1880
1881 C<$limit> is the maximum number of results to return.
1882
1883 C<&allissues> returns a two-element array. C<$issues> is a
1884 reference-to-array, where each element is a reference-to-hash; the
1885 keys are the fields from the C<issues>, C<biblio>, C<biblioitems>, and
1886 C<items> tables of the Koha database. C<$count> is the number of
1887 elements in C<$issues>
1888
1889 =cut
1890 #'
1891 sub allissues {
1892   my ($bornum,$order,$limit)=@_;
1893   my $dbh = C4::Context->dbh;
1894   my $query;
1895   $query="Select * from issues,biblio,items,biblioitems
1896   where borrowernumber='$bornum' and
1897   items.biblioitemnumber=biblioitems.biblioitemnumber and
1898   items.itemnumber=issues.itemnumber and
1899   items.biblionumber=biblio.biblionumber";
1900   $query.=" order by $order";
1901   if ($limit !=0){
1902     $query.=" limit $limit";
1903   }
1904   #print $query;
1905   my $sth=$dbh->prepare($query);
1906   $sth->execute;
1907   my @result;
1908   my $i=0;
1909   while (my $data=$sth->fetchrow_hashref){
1910     $result[$i]=$data;;
1911     $i++;
1912   }
1913   $sth->finish;
1914   return($i,\@result);
1915 }
1916
1917 =item borrdata2
1918
1919   ($borrowed, $due, $fine) = &borrdata2($env, $borrowernumber);
1920
1921 Returns aggregate data about items borrowed by the patron with the
1922 given borrowernumber.
1923
1924 C<$env> is ignored.
1925
1926 C<&borrdata2> returns a three-element array. C<$borrowed> is the
1927 number of books the patron currently has borrowed. C<$due> is the
1928 number of overdue items the patron currently has borrowed. C<$fine> is
1929 the total fine currently due by the borrower.
1930
1931 =cut
1932 #'
1933 sub borrdata2 {
1934   my ($env,$bornum)=@_;
1935   my $dbh = C4::Context->dbh;
1936   my $query="Select count(*) from issues where borrowernumber='$bornum' and
1937     returndate is NULL";
1938     # print $query;
1939   my $sth=$dbh->prepare($query);
1940   $sth->execute;
1941   my $data=$sth->fetchrow_hashref;
1942   $sth->finish;
1943   $sth=$dbh->prepare("Select count(*) from issues where
1944     borrowernumber='$bornum' and date_due < now() and returndate is NULL");
1945   $sth->execute;
1946   my $data2=$sth->fetchrow_hashref;
1947   $sth->finish;
1948   $sth=$dbh->prepare("Select sum(amountoutstanding) from accountlines where
1949     borrowernumber='$bornum'");
1950   $sth->execute;
1951   my $data3=$sth->fetchrow_hashref;
1952   $sth->finish;
1953
1954 return($data2->{'count(*)'},$data->{'count(*)'},$data3->{'sum(amountoutstanding)'});
1955 }
1956
1957 =item getboracctrecord
1958
1959   ($count, $acctlines, $total) = &getboracctrecord($env, $borrowernumber);
1960
1961 Looks up accounting data for the patron with the given borrowernumber.
1962
1963 C<$env> is ignored.
1964
1965 (FIXME - I'm not at all sure what this is about.)
1966
1967 C<&getboracctrecord> returns a three-element array. C<$acctlines> is a
1968 reference-to-array, where each element is a reference-to-hash; the
1969 keys are the fields of the C<accountlines> table in the Koha database.
1970 C<$count> is the number of elements in C<$acctlines>. C<$total> is the
1971 total amount outstanding for all of the account lines.
1972
1973 =cut
1974 #'
1975 sub getboracctrecord {
1976    my ($env,$params) = @_;
1977    my $dbh = C4::Context->dbh;
1978    my @acctlines;
1979    my $numlines=0;
1980    my $query= "Select * from accountlines where
1981 borrowernumber=? order by date desc,timestamp desc";
1982    my $sth=$dbh->prepare($query);
1983 #   print $query;
1984    $sth->execute($params->{'borrowernumber'});
1985    my $total=0;
1986    while (my $data=$sth->fetchrow_hashref){
1987 #      if ($data->{'itemnumber'} ne ''){
1988 #        $query="Select * from items,biblio where items.itemnumber=
1989 #       '$data->{'itemnumber'}' and biblio.biblionumber=items.biblionumber";
1990 #       my $sth2=$dbh->prepare($query);
1991 #       $sth2->execute;
1992 #       my $data2=$sth2->fetchrow_hashref;
1993 #       $sth2->finish;
1994 #       $data=$data2;
1995  #     }
1996       $acctlines[$numlines] = $data;
1997       $numlines++;
1998       $total += $data->{'amountoutstanding'};
1999    }
2000    $sth->finish;
2001    return ($numlines,\@acctlines,$total);
2002 }
2003
2004 =item itemcount
2005
2006   ($count, $lcount, $nacount, $fcount, $scount, $lostcount,
2007   $mending, $transit,$ocount) =
2008     &itemcount($env, $biblionumber, $type);
2009
2010 Counts the number of items with the given biblionumber, broken down by
2011 category.
2012
2013 C<$env> is ignored.
2014
2015 If C<$type> is not set to C<intra>, lost, very overdue, and withdrawn
2016 items will not be counted.
2017
2018 C<&itemcount> returns a nine-element list:
2019
2020 C<$count> is the total number of items with the given biblionumber.
2021
2022 C<$lcount> is the number of items at the Levin branch.
2023
2024 C<$nacount> is the number of items that are neither borrowed, lost,
2025 nor withdrawn (and are therefore presumably on a shelf somewhere).
2026
2027 C<$fcount> is the number of items at the Foxton branch.
2028
2029 C<$scount> is the number of items at the Shannon branch.
2030
2031 C<$lostcount> is the number of lost and very overdue items.
2032
2033 C<$mending> is the number of items at the Mending branch (being
2034 mended?).
2035
2036 C<$transit> is the number of items at the Transit branch (in transit
2037 between branches?).
2038
2039 C<$ocount> is the number of items that haven't arrived yet
2040 (aqorders.quantity - aqorders.quantityreceived).
2041
2042 =cut
2043 #'
2044
2045 # FIXME - There's also a &C4::Biblio::itemcount.
2046 # Since they're all exported, acqui/acquire.pl doesn't compile with -w.
2047 sub itemcount {
2048   my ($env,$bibnum,$type)=@_;
2049   my $dbh = C4::Context->dbh;
2050   my $query="Select * from items where
2051   biblionumber=$bibnum ";
2052   if ($type ne 'intra'){
2053     $query.=" and ((itemlost <>1 and itemlost <> 2) or itemlost is NULL) and
2054     (wthdrawn <> 1 or wthdrawn is NULL)";
2055   }
2056   my $sth=$dbh->prepare($query);
2057   #  print $query;
2058   $sth->execute;
2059   my $count=0;
2060   my $lcount=0;
2061   my $nacount=0;
2062   my $fcount=0;
2063   my $scount=0;
2064   my $lostcount=0;
2065   my $mending=0;
2066   my $transit=0;
2067   my $ocount=0;
2068   while (my $data=$sth->fetchrow_hashref){
2069     $count++;
2070     my $query2="select * from issues,items where issues.itemnumber=
2071     '$data->{'itemnumber'}' and returndate is NULL
2072     and items.itemnumber=issues.itemnumber and ((items.itemlost <>1 and
2073     items.itemlost <> 2) or items.itemlost is NULL)
2074     and (wthdrawn <> 1 or wthdrawn is NULL)";
2075
2076     my $sth2=$dbh->prepare($query2);
2077     $sth2->execute;
2078     if (my $data2=$sth2->fetchrow_hashref){
2079        $nacount++;
2080     } else {
2081       if ($data->{'holdingbranch'} eq 'C' || $data->{'holdingbranch'} eq 'LT'){
2082         $lcount++;
2083       }
2084       if ($data->{'holdingbranch'} eq 'F' || $data->{'holdingbranch'} eq 'FP'){
2085         $fcount++;
2086       }
2087       if ($data->{'holdingbranch'} eq 'S' || $data->{'holdingbranch'} eq 'SP'){
2088         $scount++;
2089       }
2090       if ($data->{'itemlost'} eq '1'){
2091         $lostcount++;
2092       }
2093       if ($data->{'itemlost'} eq '2'){
2094         $lostcount++;
2095       }
2096       if ($data->{'holdingbranch'} eq 'FM'){
2097         $mending++;
2098       }
2099       if ($data->{'holdingbranch'} eq 'TR'){
2100         $transit++;
2101       }
2102     }
2103     $sth2->finish;
2104   }
2105 #  if ($count == 0){
2106     my $query2="Select * from aqorders where biblionumber=$bibnum";
2107     my $sth2=$dbh->prepare($query2);
2108     $sth2->execute;
2109     if (my $data=$sth2->fetchrow_hashref){
2110       $ocount=$data->{'quantity'} - $data->{'quantityreceived'};
2111     }
2112 #    $count+=$ocount;
2113     $sth2->finish;
2114   $sth->finish;
2115   return ($count,$lcount,$nacount,$fcount,$scount,$lostcount,$mending,$transit,$ocount);
2116 }
2117
2118 =item itemcount2
2119
2120   $counts = &itemcount2($env, $biblionumber, $type);
2121
2122 Counts the number of items with the given biblionumber, broken down by
2123 category.
2124
2125 C<$env> is ignored.
2126
2127 C<$type> may be either C<intra> or anything else. If it is not set to
2128 C<intra>, then the search will exclude lost, very overdue, and
2129 withdrawn items.
2130
2131 C<$&itemcount2> returns a reference-to-hash, with the following fields:
2132
2133 =over 4
2134
2135 =item C<total>
2136
2137 The total number of items with this biblionumber.
2138
2139 =item C<order>
2140
2141 The number of items on order (aqorders.quantity -
2142 aqorders.quantityreceived).
2143
2144 =item I<branchname>
2145
2146 For each branch that has at least one copy of the book, C<$counts>
2147 will have a key with the branch name, giving the number of copies at
2148 that branch.
2149
2150 =back
2151
2152 =cut
2153 #'
2154 sub itemcount2 {
2155   my ($env,$bibnum,$type)=@_;
2156   my $dbh = C4::Context->dbh;
2157   my $query="Select * from items,branches where
2158   biblionumber=? and items.holdingbranch=branches.branchcode";
2159   if ($type ne 'intra'){
2160     $query.=" and ((itemlost <>1 and itemlost <> 2) or itemlost is NULL) and
2161     (wthdrawn <> 1 or wthdrawn is NULL)";
2162   }
2163   my $sth=$dbh->prepare($query);
2164   #  print $query;
2165   $sth->execute($bibnum);
2166   my %counts;
2167   $counts{'total'}=0;
2168   while (my $data=$sth->fetchrow_hashref){
2169     $counts{'total'}++;
2170
2171     my $status;
2172     for my $test (
2173       [
2174         'Item Lost',
2175         'select * from items
2176           where itemnumber=?
2177             and not ((items.itemlost <>1 and items.itemlost <> 2)
2178                       or items.itemlost is NULL)'
2179       ], [
2180         'Withdrawn',
2181         'select * from items
2182           where itemnumber=? and not (wthdrawn <> 1 or wthdrawn is NULL)'
2183       ], [
2184         'On Loan', "select * from issues,items
2185           where issues.itemnumber=? and returndate is NULL
2186             and items.itemnumber=issues.itemnumber"
2187       ],
2188     ) {
2189         my($testlabel, $query2) = @$test;
2190
2191         my $sth2=$dbh->prepare($query2);
2192         $sth2->execute($data->{'itemnumber'});
2193
2194         # FIXME - fetchrow_hashref() can fail for any number of reasons
2195         # (e.g., a database server crash). Perhaps use a left join of some
2196         # sort for this?
2197         $status = $testlabel if $sth2->fetchrow_hashref;
2198         $sth2->finish;
2199     last if defined $status;
2200     }
2201     $status = $data->{'branchname'} unless defined $status;
2202     $counts{$status}++;
2203   }
2204   my $query2="Select * from aqorders where biblionumber=? and
2205   datecancellationprinted is NULL and quantity > quantityreceived";
2206   my $sth2=$dbh->prepare($query2);
2207   $sth2->execute($bibnum);
2208   if (my $data=$sth2->fetchrow_hashref){
2209       $counts{'order'}=$data->{'quantity'} - $data->{'quantityreceived'};
2210   }
2211   $sth2->finish;
2212   $sth->finish;
2213   return (\%counts);
2214 }
2215
2216 =item ItemType
2217
2218   $description = &ItemType($itemtype);
2219
2220 Given an item type code, returns the description for that type.
2221
2222 =cut
2223 #'
2224
2225 # FIXME - I'm pretty sure that after the initial setup, the list of
2226 # item types doesn't change very often. Hence, it seems slow and
2227 # inefficient to make yet another database call to look up information
2228 # that'll only change every few months or years.
2229 #
2230 # Much better, I think, to automatically build a Perl file that can be
2231 # included in those scripts that require it, e.g.:
2232 #       @itemtypes = qw( ART BCD CAS CD F ... );
2233 #       %itemtypedesc = (
2234 #               ART     => "Art Prints",
2235 #               BCD     => "CD-ROM from book",
2236 #               CD      => "Compact disc (WN)",
2237 #               F       => "Free Fiction",
2238 #               ...
2239 #       );
2240 # The web server can then run a cron job to rebuild this file from the
2241 # database every hour or so.
2242 #
2243 # The same thing goes for branches, book funds, book sellers, currency
2244 # rates, printers, stopwords, and perhaps others.
2245 sub ItemType {
2246   my ($type)=@_;
2247   my $dbh = C4::Context->dbh;
2248   my $query="select description from itemtypes where itemtype='$type'";
2249   my $sth=$dbh->prepare($query);
2250   $sth->execute;
2251   my $dat=$sth->fetchrow_hashref;
2252   $sth->finish;
2253   return ($dat->{'description'});
2254 }
2255
2256 =item bibitems
2257
2258   ($count, @results) = &bibitems($biblionumber);
2259
2260 Given the biblionumber for a book, C<&bibitems> looks up that book's
2261 biblioitems (different publications of the same book, the audio book
2262 and film versions, etc.).
2263
2264 C<$count> is the number of elements in C<@results>.
2265
2266 C<@results> is an array of references-to-hash; the keys are the fields
2267 of the C<biblioitems> and C<itemtypes> tables of the Koha database. In
2268 addition, C<itemlost> indicates the availability of the item: if it is
2269 "2", then all copies of the item are long overdue; if it is "1", then
2270 all copies are lost; otherwise, there is at least one copy available.
2271
2272 =cut
2273 #'
2274 sub bibitems {
2275     my ($bibnum) = @_;
2276     my $dbh   = C4::Context->dbh;
2277     my $query = "SELECT biblioitems.*,
2278                         itemtypes.*,
2279                         MIN(items.itemlost)        as itemlost,
2280                         MIN(items.dateaccessioned) as dateaccessioned
2281                           FROM biblioitems, itemtypes, items
2282                          WHERE biblioitems.biblionumber     = ?
2283                            AND biblioitems.itemtype         = itemtypes.itemtype
2284                            AND biblioitems.biblioitemnumber = items.biblioitemnumber
2285                       GROUP BY items.biblioitemnumber";
2286     my $sth   = $dbh->prepare($query);
2287     my $count = 0;
2288     my @results;
2289     $sth->execute($bibnum);
2290     while (my $data = $sth->fetchrow_hashref) {
2291         $results[$count] = $data;
2292         $count++;
2293     } # while
2294     $sth->finish;
2295     return($count, @results);
2296 } # sub bibitems
2297
2298 =item barcodes
2299
2300   @barcodes = &barcodes($biblioitemnumber);
2301
2302 Given a biblioitemnumber, looks up the corresponding items.
2303
2304 Returns an array of references-to-hash; the keys are C<barcode> and
2305 C<itemlost>.
2306
2307 The returned items include very overdue items, but not lost ones.
2308
2309 =cut
2310 #'
2311 sub barcodes{
2312     #called from request.pl
2313     my ($biblioitemnumber)=@_;
2314     my $dbh = C4::Context->dbh;
2315     my $query="SELECT barcode, itemlost, holdingbranch FROM items
2316                            WHERE biblioitemnumber = ?
2317                              AND (wthdrawn <> 1 OR wthdrawn IS NULL)";
2318     my $sth=$dbh->prepare($query);
2319     $sth->execute($biblioitemnumber);
2320     my @barcodes;
2321     my $i=0;
2322     while (my $data=$sth->fetchrow_hashref){
2323         $barcodes[$i]=$data;
2324         $i++;
2325     }
2326     $sth->finish;
2327     return(@barcodes);
2328 }
2329
2330 =item getwebsites
2331
2332   ($count, @websites) = &getwebsites($biblionumber);
2333
2334 Looks up the web sites pertaining to the book with the given
2335 biblionumber.
2336
2337 C<$count> is the number of elements in C<@websites>.
2338
2339 C<@websites> is an array of references-to-hash; the keys are the
2340 fields from the C<websites> table in the Koha database.
2341
2342 =cut
2343 #'
2344 sub getwebsites {
2345     my ($biblionumber) = @_;
2346     my $dbh   = C4::Context->dbh;
2347     my $query = "Select * from websites where biblionumber = $biblionumber";
2348     my $sth   = $dbh->prepare($query);
2349     my $count = 0;
2350     my @results;
2351
2352     $sth->execute;
2353     while (my $data = $sth->fetchrow_hashref) {
2354         # FIXME - The URL scheme shouldn't be stripped off, at least
2355         # not here, since it's part of the URL, and will be useful in
2356         # constructing a link to the site. If you don't want the user
2357         # to see the "http://" part, strip that off when building the
2358         # HTML code.
2359         $data->{'url'} =~ s/^http:\/\///;       # FIXME - Leaning toothpick
2360                                                 # syndrome
2361         $results[$count] = $data;
2362         $count++;
2363     } # while
2364
2365     $sth->finish;
2366     return($count, @results);
2367 } # sub getwebsites
2368
2369 =item getwebbiblioitems
2370
2371   ($count, @results) = &getwebbiblioitems($biblionumber);
2372
2373 Given a book's biblionumber, looks up the web versions of the book
2374 (biblioitems with itemtype C<WEB>).
2375
2376 C<$count> is the number of items in C<@results>. C<@results> is an
2377 array of references-to-hash; the keys are the items from the
2378 C<biblioitems> table of the Koha database.
2379
2380 =cut
2381 #'
2382 sub getwebbiblioitems {
2383     my ($biblionumber) = @_;
2384     my $dbh   = C4::Context->dbh;
2385     my $query = "Select * from biblioitems where biblionumber = $biblionumber
2386 and itemtype = 'WEB'";
2387     my $sth   = $dbh->prepare($query);
2388     my $count = 0;
2389     my @results;
2390
2391     $sth->execute;
2392     while (my $data = $sth->fetchrow_hashref) {
2393         $data->{'url'} =~ s/^http:\/\///;
2394         $results[$count] = $data;
2395         $count++;
2396     } # while
2397
2398     $sth->finish;
2399     return($count, @results);
2400 } # sub getwebbiblioitems
2401
2402
2403 =item breedingsearch
2404
2405   ($count, @results) = &breedingsearch($title,$isbn,$random);
2406 C<$title> contains the title,
2407 C<$isbn> contains isbn or issn,
2408 C<$random> contains the random seed from a z3950 search.
2409
2410 C<$count> is the number of items in C<@results>. C<@results> is an
2411 array of references-to-hash; the keys are the items from the C<marc_breeding> table of the Koha database.
2412
2413 =cut
2414
2415 sub breedingsearch {
2416         my ($title,$isbn,$z3950random) = @_;
2417         my $dbh   = C4::Context->dbh;
2418         my $count = 0;
2419         my $query;
2420         my $sth;
2421         my @results;
2422
2423         $query = "Select id,file,isbn,title,author from marc_breeding where ";
2424         if ($z3950random) {
2425                 $query .= "z3950random = \"$z3950random\"";
2426         } else {
2427                 if ($title) {
2428                         $query .= "title like \"$title%\"";
2429                 }
2430                 if ($title && $isbn) {
2431                         $query .= " and ";
2432                 }
2433                 if ($isbn) {
2434                         $query .= "isbn like \"$isbn%\"";
2435                 }
2436         }
2437         $sth   = $dbh->prepare($query);
2438         $sth->execute;
2439         while (my $data = $sth->fetchrow_hashref) {
2440                         $results[$count] = $data;
2441                         $count++;
2442         } # while
2443
2444         $sth->finish;
2445         return($count, @results);
2446 } # sub breedingsearch
2447
2448
2449 =item getalllanguages
2450
2451   (@languages) = &getalllanguages();
2452   (@languages) = &getalllanguages($theme);
2453
2454 Returns an array of all available languages.
2455
2456 =cut
2457
2458 sub getalllanguages {
2459     my $type=shift;
2460     my $theme=shift;
2461     my $htdocs;
2462     my @languages;
2463     if ($type eq 'opac') {
2464         $htdocs=C4::Context->config('opachtdocs');
2465         if ($theme and -d "$htdocs/$theme") {
2466             opendir D, "$htdocs/$theme";
2467             foreach my $language (readdir D) {
2468                 next if $language=~/^\./;
2469                 next if $language eq 'all';
2470                 push @languages, $language;
2471             }
2472             return sort @languages;
2473         } else {
2474             my $lang;
2475             foreach my $theme (getallthemes('opac')) {
2476                 opendir D, "$htdocs/$theme";
2477                 foreach my $language (readdir D) {
2478                     next if $language=~/^\./;
2479                     next if $language eq 'all';
2480                     $lang->{$language}=1;
2481                 }
2482             }
2483             @languages=keys %$lang;
2484             return sort @languages;
2485         }
2486     } elsif ($type eq 'intranet') {
2487         $htdocs=C4::Context->config('intrahtdocs');
2488         if ($theme and -d "$htdocs/$theme") {
2489             opendir D, "$htdocs/$theme";
2490             foreach my $language (readdir D) {
2491                 next if $language=~/^\./;
2492                 next if $language eq 'all';
2493                 push @languages, $language;
2494             }
2495             return sort @languages;
2496         } else {
2497             my $lang;
2498             foreach my $theme (getallthemes('opac')) {
2499                 opendir D, "$htdocs/$theme";
2500                 foreach my $language (readdir D) {
2501                     next if $language=~/^\./;
2502                     next if $language eq 'all';
2503                     $lang->{$language}=1;
2504                 }
2505             }
2506             @languages=keys %$lang;
2507             return sort @languages;
2508         }
2509     } else {
2510         my $lang;
2511         my $htdocs=C4::Context->config('intrahtdocs');
2512         foreach my $theme (getallthemes('intranet')) {
2513             opendir D, "$htdocs/$theme";
2514             foreach my $language (readdir D) {
2515                 next if $language=~/^\./;
2516                 next if $language eq 'all';
2517                 $lang->{$language}=1;
2518             }
2519         }
2520         my $htdocs=C4::Context->config('opachtdocs');
2521         foreach my $theme (getallthemes('opac')) {
2522             opendir D, "$htdocs/$theme";
2523             foreach my $language (readdir D) {
2524                 next if $language=~/^\./;
2525                 next if $language eq 'all';
2526                 $lang->{$language}=1;
2527             }
2528         }
2529         @languages=keys %$lang;
2530         return sort @languages;
2531     }
2532 }
2533
2534 =item getallthemes
2535
2536   (@themes) = &getallthemes('opac');
2537   (@themes) = &getallthemes('intranet');
2538
2539 Returns an array of all available themes.
2540
2541 =cut
2542
2543 sub getallthemes {
2544     my $type=shift;
2545     my $htdocs;
2546     my @themes;
2547     if ($type eq 'intranet') {
2548         $htdocs=C4::Context->config('intrahtdocs');
2549     } else {
2550         $htdocs=C4::Context->config('opachtdocs');
2551     }
2552     opendir D, "$htdocs";
2553     my @dirlist=readdir D;
2554     foreach my $directory (@dirlist) {
2555         -d "$htdocs/$directory/en" and push @themes, $directory;
2556     }
2557     return @themes;
2558 }
2559
2560
2561
2562 =item isbnsearch
2563
2564   ($count, @results) = &isbnsearch($isbn,$title);
2565
2566 Given an isbn and/or a title, returns the biblios having it.
2567 Used in acqui.simple, isbnsearch.pl only
2568
2569 C<$count> is the number of items in C<@results>. C<@results> is an
2570 array of references-to-hash; the keys are the items from the
2571 C<biblioitems> table of the Koha database.
2572
2573 =cut
2574
2575 sub isbnsearch {
2576     my ($isbn,$title) = @_;
2577     my $dbh   = C4::Context->dbh;
2578     my $count = 0;
2579     my $query;
2580     my $sth;
2581     my @results;
2582
2583     $query = "Select distinct biblio.* from biblio, biblioitems where
2584                                 biblio.biblionumber = biblioitems.biblionumber";
2585         if ($isbn) {
2586                 $query .= " and isbn=".$dbh->quote($isbn);
2587         }
2588         if ($title) {
2589                 $query .= " and title like ".$dbh->quote($title."%");
2590         }
2591     $sth   = $dbh->prepare($query);
2592
2593     $sth->execute;
2594     while (my $data = $sth->fetchrow_hashref) {
2595         $results[$count] = $data;
2596         $count++;
2597     } # while
2598
2599     $sth->finish;
2600     return($count, @results);
2601 } # sub isbnsearch
2602
2603 =item getbranchname
2604
2605   $branchname = &getbranchname($branchcode);
2606
2607 Given the branch code, the function returns the corresponding
2608 branch name for a comprehensive information display
2609
2610 =cut
2611
2612 sub getbranchname
2613 {
2614         my ($branchcode) = @_;
2615         my $dbh = C4::Context->dbh;
2616         my $query = "SELECT branchname FROM branches WHERE branchcode = '$branchcode'";
2617         my $sth = $dbh->prepare($query);
2618         $sth->execute;
2619         my $branchname = $sth->fetchrow();
2620         $sth->finish();
2621         return $branchname;
2622 } # sub getbranchname
2623
2624 =item getborrowercategory
2625
2626   $description = &getborrowercategory($categorycode);
2627
2628 Given the borrower's category code, the function returns the corresponding
2629 description for a comprehensive information display.
2630
2631 =cut
2632
2633 sub getborrowercategory
2634 {
2635         my ($catcode) = @_;
2636         my $dbh = C4::Context->dbh;
2637         my $query = "SELECT description FROM categories WHERE categorycode = '$catcode'";
2638         my $sth = $dbh->prepare($query);
2639         $sth->execute;
2640         my $description = $sth->fetchrow();
2641         $sth->finish();
2642         return $description;
2643 } # sub getborrowercategory
2644
2645
2646 END { }       # module clean-up code here (global destructor)
2647
2648 1;
2649 __END__
2650
2651 =back
2652
2653 =head1 AUTHOR
2654
2655 Koha Developement team <info@koha.org>
2656
2657 =cut