C4::Members::SearchMember - support attributes
[koha.git] / C4 / Members.pm
1 package C4::Members;
2
3 # Copyright 2000-2003 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
21 use strict;
22 use C4::Context;
23 use C4::Dates qw(format_date_in_iso);
24 use Digest::MD5 qw(md5_base64);
25 use Date::Calc qw/Today Add_Delta_YM/;
26 use C4::Log; # logaction
27 use C4::Overdues;
28 use C4::Reserves;
29 use C4::Accounts;
30
31 our ($VERSION,@ISA,@EXPORT,@EXPORT_OK,$debug);
32
33 BEGIN {
34         $VERSION = 3.02;
35         $debug = $ENV{DEBUG} || 0;
36         require Exporter;
37         @ISA = qw(Exporter);
38         #Get data
39         push @EXPORT, qw(
40                 &SearchMember 
41                 &GetMemberDetails
42                 &GetMember
43
44                 &GetGuarantees 
45
46                 &GetMemberIssuesAndFines
47                 &GetPendingIssues
48                 &GetAllIssues
49
50                 &get_institutions 
51                 &getzipnamecity 
52                 &getidcity
53
54                 &GetAge 
55                 &GetCities 
56                 &GetRoadTypes 
57                 &GetRoadTypeDetails 
58                 &GetSortDetails
59                 &GetTitles
60
61     &GetPatronImage
62     &PutPatronImage
63     &RmPatronImage
64
65                 &GetMemberAccountRecords
66                 &GetBorNotifyAcctRecord
67
68                 &GetborCatFromCatType 
69                 &GetBorrowercategory
70
71                 &GetBorrowersWhoHaveNotBorrowedSince
72                 &GetBorrowersWhoHaveNeverBorrowed
73                 &GetBorrowersWithIssuesHistoryOlderThan
74
75                 &GetExpiryDate
76         );
77
78         #Modify data
79         push @EXPORT, qw(
80                 &ModMember
81                 &changepassword
82         );
83
84         #Delete data
85         push @EXPORT, qw(
86                 &DelMember
87         );
88
89         #Insert data
90         push @EXPORT, qw(
91                 &AddMember
92                 &add_member_orgs
93                 &MoveMemberToDeleted
94                 &ExtendMemberSubscriptionTo 
95         );
96
97         #Check data
98         push @EXPORT, qw(
99                 &checkuniquemember 
100                 &checkuserpassword
101                 &Check_Userid
102                 &fixEthnicity
103                 &ethnicitycategories 
104                 &fixup_cardnumber
105                 &checkcardnumber
106         );
107 }
108
109 =head1 NAME
110
111 C4::Members - Perl Module containing convenience functions for member handling
112
113 =head1 SYNOPSIS
114
115 use C4::Members;
116
117 =head1 DESCRIPTION
118
119 This module contains routines for adding, modifying and deleting members/patrons/borrowers 
120
121 =head1 FUNCTIONS
122
123 =over 2
124
125 =item SearchMember
126
127   ($count, $borrowers) = &SearchMember($searchstring, $type,$category_type,$filter,$showallbranches);
128
129 Looks up patrons (borrowers) by name.
130
131 BUGFIX 499: C<$type> is now used to determine type of search.
132 if $type is "simple", search is performed on the first letter of the
133 surname only.
134
135 $category_type is used to get a specified type of user. 
136 (mainly adults when creating a child.)
137
138 C<$searchstring> is a space-separated list of search terms. Each term
139 must match the beginning a borrower's surname, first name, or other
140 name.
141
142 C<$filter> is assumed to be a list of elements to filter results on
143
144 C<$showallbranches> is used in IndependantBranches Context to display all branches results.
145
146 C<&SearchMember> returns a two-element list. C<$borrowers> is a
147 reference-to-array; each element is a reference-to-hash, whose keys
148 are the fields of the C<borrowers> table in the Koha database.
149 C<$count> is the number of elements in C<$borrowers>.
150
151 =cut
152
153 #'
154 #used by member enquiries from the intranet
155 #called by member.pl and circ/circulation.pl
156 sub SearchMember {
157     my ($searchstring, $orderby, $type,$category_type,$filter,$showallbranches ) = @_;
158     my $dbh   = C4::Context->dbh;
159     my $query = "";
160     my $count;
161     my @data;
162     my @bind = ();
163     
164     # this is used by circulation everytime a new borrowers cardnumber is scanned
165     # so we can check an exact match first, if that works return, otherwise do the rest
166     $query = "SELECT * FROM borrowers
167         LEFT JOIN categories ON borrowers.categorycode=categories.categorycode
168         ";
169     my $sth = $dbh->prepare("$query WHERE cardnumber = ?");
170     $sth->execute($searchstring);
171     my $data = $sth->fetchall_arrayref({});
172     if (@$data){
173         return ( scalar(@$data), $data );
174     }
175     $sth->finish;
176
177     if ( $type eq "simple" )    # simple search for one letter only
178     {
179         $query .= ($category_type ? " AND category_type = ".$dbh->quote($category_type) : ""); 
180         $query .= " WHERE (surname LIKE ? OR cardnumber like ?) ";
181         if (C4::Context->preference("IndependantBranches") && !$showallbranches){
182           if (C4::Context->userenv && C4::Context->userenv->{flags}!=1 && C4::Context->userenv->{'branch'}){
183             $query.=" AND borrowers.branchcode =".$dbh->quote(C4::Context->userenv->{'branch'}) unless (C4::Context->userenv->{'branch'} eq "insecure");
184           }
185         }
186         $query.=" ORDER BY $orderby";
187         @bind = ("$searchstring%","$searchstring");
188     }
189     else    # advanced search looking in surname, firstname and othernames
190     {
191         @data  = split( ' ', $searchstring );
192         $count = @data;
193         $query .= " WHERE ";
194         if (C4::Context->preference("IndependantBranches") && !$showallbranches){
195           if (C4::Context->userenv && C4::Context->userenv->{flags}!=1 && C4::Context->userenv->{'branch'}){
196             $query.=" borrowers.branchcode =".$dbh->quote(C4::Context->userenv->{'branch'})." AND " unless (C4::Context->userenv->{'branch'} eq "insecure");
197           }      
198         }     
199         $query.="((surname LIKE ? OR surname LIKE ?
200                 OR firstname  LIKE ? OR firstname LIKE ?
201                 OR othernames LIKE ? OR othernames LIKE ?)
202         " .
203         ($category_type?" AND category_type = ".$dbh->quote($category_type):"");
204         @bind = (
205             "$data[0]%", "% $data[0]%", "$data[0]%", "% $data[0]%",
206             "$data[0]%", "% $data[0]%"
207         );
208         for ( my $i = 1 ; $i < $count ; $i++ ) {
209             $query = $query . " AND (" . " surname LIKE ? OR surname LIKE ?
210                 OR firstname  LIKE ? OR firstname LIKE ?
211                 OR othernames LIKE ? OR othernames LIKE ?)";
212             push( @bind,
213                 "$data[$i]%",   "% $data[$i]%", "$data[$i]%",
214                 "% $data[$i]%", "$data[$i]%",   "% $data[$i]%" );
215
216             # FIXME - .= <<EOT;
217         }
218         $query = $query . ") OR cardnumber LIKE ? ";
219         push( @bind, $searchstring );
220         if (C4::Context->preference('ExtendedPatronAttributes')) {
221             $query .= "OR borrowernumber IN (
222 SELECT borrowernumber
223 FROM borrower_attributes
224 JOIN borrower_attribute_types USING (code)
225 WHERE staff_searchable = 1
226 AND attribute like ?
227 )";
228             push (@bind, $searchstring);
229         }
230         $query .= "order by $orderby";
231
232         # FIXME - .= <<EOT;
233     }
234
235     $sth = $dbh->prepare($query);
236
237     $debug and print STDERR "Q $orderby : $query\n";
238     $sth->execute(@bind);
239     my @results;
240     $data = $sth->fetchall_arrayref({});
241
242     $sth->finish;
243     return ( scalar(@$data), $data );
244 }
245
246 =head2 GetMemberDetails
247
248 ($borrower, $flags) = &GetMemberDetails($borrowernumber, $cardnumber);
249
250 Looks up a patron and returns information about him or her. If
251 C<$borrowernumber> is true (nonzero), C<&GetMemberDetails> looks
252 up the borrower by number; otherwise, it looks up the borrower by card
253 number.
254
255 C<$borrower> is a reference-to-hash whose keys are the fields of the
256 borrowers table in the Koha database. In addition,
257 C<$borrower-E<gt>{flags}> is a hash giving more detailed information
258 about the patron. Its keys act as flags :
259
260     if $borrower->{flags}->{LOST} {
261         # Patron's card was reported lost
262     }
263
264 Each flag has a C<message> key, giving a human-readable explanation of
265 the flag. If the state of a flag means that the patron should not be
266 allowed to borrow any more books, then it will have a C<noissues> key
267 with a true value.
268
269 The possible flags are:
270
271 =head3 CHARGES
272
273 =over 4
274
275 =item Shows the patron's credit or debt, if any.
276
277 =back
278
279 =head3 GNA
280
281 =over 4
282
283 =item (Gone, no address.) Set if the patron has left without giving a
284 forwarding address.
285
286 =back
287
288 =head3 LOST
289
290 =over 4
291
292 =item Set if the patron's card has been reported as lost.
293
294 =back
295
296 =head3 DBARRED
297
298 =over 4
299
300 =item Set if the patron has been debarred.
301
302 =back
303
304 =head3 NOTES
305
306 =over 4
307
308 =item Any additional notes about the patron.
309
310 =back
311
312 =head3 ODUES
313
314 =over 4
315
316 =item Set if the patron has overdue items. This flag has several keys:
317
318 C<$flags-E<gt>{ODUES}{itemlist}> is a reference-to-array listing the
319 overdue items. Its elements are references-to-hash, each describing an
320 overdue item. The keys are selected fields from the issues, biblio,
321 biblioitems, and items tables of the Koha database.
322
323 C<$flags-E<gt>{ODUES}{itemlist}> is a string giving a text listing of
324 the overdue items, one per line.
325
326 =back
327
328 =head3 WAITING
329
330 =over 4
331
332 =item Set if any items that the patron has reserved are available.
333
334 C<$flags-E<gt>{WAITING}{itemlist}> is a reference-to-array listing the
335 available items. Each element is a reference-to-hash whose keys are
336 fields from the reserves table of the Koha database.
337
338 =back
339
340 =cut
341
342 sub GetMemberDetails {
343     my ( $borrowernumber, $cardnumber ) = @_;
344     my $dbh = C4::Context->dbh;
345     my $query;
346     my $sth;
347     if ($borrowernumber) {
348         $sth = $dbh->prepare("select borrowers.*,category_type from borrowers left join categories on borrowers.categorycode=categories.categorycode where  borrowernumber=?");
349         $sth->execute($borrowernumber);
350     }
351     elsif ($cardnumber) {
352         $sth = $dbh->prepare("select borrowers.*,category_type from borrowers left join categories on borrowers.categorycode=categories.categorycode where cardnumber=?");
353         $sth->execute($cardnumber);
354     }
355     else {
356         return undef;
357     }
358     my $borrower = $sth->fetchrow_hashref;
359     my ($amount) = GetMemberAccountRecords( $borrowernumber);
360     $borrower->{'amountoutstanding'} = $amount;
361     # FIXME - patronflags calls GetMemberAccountRecords... just have patronflags return $amount
362     my $flags = patronflags( $borrower);
363     my $accessflagshash;
364
365     $sth = $dbh->prepare("select bit,flag from userflags");
366     $sth->execute;
367     while ( my ( $bit, $flag ) = $sth->fetchrow ) {
368         if ( $borrower->{'flags'} && $borrower->{'flags'} & 2**$bit ) {
369             $accessflagshash->{$flag} = 1;
370         }
371     }
372     $sth->finish;
373     $borrower->{'flags'}     = $flags;
374     $borrower->{'authflags'} = $accessflagshash;
375
376     # find out how long the membership lasts
377     $sth =
378       $dbh->prepare(
379         "select enrolmentperiod from categories where categorycode = ?");
380     $sth->execute( $borrower->{'categorycode'} );
381     my $enrolment = $sth->fetchrow;
382     $borrower->{'enrolmentperiod'} = $enrolment;
383     return ($borrower);    #, $flags, $accessflagshash);
384 }
385
386 =head2 patronflags
387
388  Not exported
389
390  NOTE!: If you change this function, be sure to update the POD for
391  &GetMemberDetails.
392
393  $flags = &patronflags($patron);
394
395  $flags->{CHARGES}
396         {message}    Message showing patron's credit or debt
397        {noissues}    Set if patron owes >$5.00
398          {GNA}            Set if patron gone w/o address
399         {message}    "Borrower has no valid address"
400         {noissues}    Set.
401         {LOST}        Set if patron's card reported lost
402         {message}    Message to this effect
403         {noissues}    Set.
404         {DBARRED}        Set is patron is debarred
405         {message}    Message to this effect
406         {noissues}    Set.
407          {NOTES}        Set if patron has notes
408         {message}    Notes about patron
409          {ODUES}        Set if patron has overdue books
410         {message}    "Yes"
411         {itemlist}    ref-to-array: list of overdue books
412         {itemlisttext}    Text list of overdue items
413          {WAITING}        Set if there are items available that the
414                 patron reserved
415         {message}    Message to this effect
416         {itemlist}    ref-to-array: list of available items
417
418 =cut
419 # FIXME rename this function.
420 sub patronflags {
421     my %flags;
422     my ( $patroninformation) = @_;
423     my $dbh=C4::Context->dbh;
424     my ($amount) = GetMemberAccountRecords( $patroninformation->{'borrowernumber'});
425     if ( $amount > 0 ) {
426         my %flaginfo;
427         my $noissuescharge = C4::Context->preference("noissuescharge");
428         $flaginfo{'message'} = sprintf "Patron owes \$%.02f", $amount;
429         $flaginfo{'amount'} = sprintf "%.02f",$amount;
430         if ( $amount > $noissuescharge ) {
431             $flaginfo{'noissues'} = 1;
432         }
433         $flags{'CHARGES'} = \%flaginfo;
434     }
435     elsif ( $amount < 0 ) {
436         my %flaginfo;
437         $flaginfo{'message'} = sprintf "Patron has credit of \$%.02f", -$amount;
438         $flags{'CREDITS'} = \%flaginfo;
439     }
440     if (   $patroninformation->{'gonenoaddress'}
441         && $patroninformation->{'gonenoaddress'} == 1 )
442     {
443         my %flaginfo;
444         $flaginfo{'message'}  = 'Borrower has no valid address.';
445         $flaginfo{'noissues'} = 1;
446         $flags{'GNA'}         = \%flaginfo;
447     }
448     if ( $patroninformation->{'lost'} && $patroninformation->{'lost'} == 1 ) {
449         my %flaginfo;
450         $flaginfo{'message'}  = 'Borrower\'s card reported lost.';
451         $flaginfo{'noissues'} = 1;
452         $flags{'LOST'}        = \%flaginfo;
453     }
454     if (   $patroninformation->{'debarred'}
455         && $patroninformation->{'debarred'} == 1 )
456     {
457         my %flaginfo;
458         $flaginfo{'message'}  = 'Borrower is Debarred.';
459         $flaginfo{'noissues'} = 1;
460         $flags{'DBARRED'}     = \%flaginfo;
461     }
462     if (   $patroninformation->{'borrowernotes'}
463         && $patroninformation->{'borrowernotes'} )
464     {
465         my %flaginfo;
466         $flaginfo{'message'} = "$patroninformation->{'borrowernotes'}";
467         $flags{'NOTES'}      = \%flaginfo;
468     }
469     my ( $odues, $itemsoverdue ) =
470       checkoverdues( $patroninformation->{'borrowernumber'}, $dbh );
471     if ( $odues > 0 ) {
472         my %flaginfo;
473         $flaginfo{'message'}  = "Yes";
474         $flaginfo{'itemlist'} = $itemsoverdue;
475         foreach ( sort { $a->{'date_due'} cmp $b->{'date_due'} }
476             @$itemsoverdue )
477         {
478             $flaginfo{'itemlisttext'} .=
479               "$_->{'date_due'} $_->{'barcode'} $_->{'title'} \n";
480         }
481         $flags{'ODUES'} = \%flaginfo;
482     }
483     my @itemswaiting = C4::Reserves::GetReservesFromBorrowernumber( $patroninformation->{'borrowernumber'},'W' );
484     my $nowaiting = scalar @itemswaiting;
485     if ( $nowaiting > 0 ) {
486         my %flaginfo;
487         $flaginfo{'message'}  = "Reserved items available";
488         $flaginfo{'itemlist'} = \@itemswaiting;
489         $flags{'WAITING'}     = \%flaginfo;
490     }
491     return ( \%flags );
492 }
493
494
495 =item GetMember
496
497   $borrower = &GetMember($information, $type);
498
499 Looks up information about a patron (borrower) by either card number
500 ,firstname, or borrower number, depending on $type value.
501 If C<$type> == 'cardnumber', C<&GetBorrower>
502 searches by cardnumber then by firstname if not found in cardnumber; 
503 otherwise, it searches by borrowernumber.
504
505 C<&GetBorrower> returns a reference-to-hash whose keys are the fields of
506 the C<borrowers> table in the Koha database.
507
508 =cut
509
510 #'
511 sub GetMember {
512     my ( $information, $type ) = @_;
513     my $dbh = C4::Context->dbh;
514     my $sth;
515     my $select = "
516 SELECT borrowers.*, categories.category_type, categories.description
517 FROM borrowers 
518 LEFT JOIN categories on borrowers.categorycode=categories.categorycode 
519 ";
520     if ($type eq 'cardnumber' || $type eq 'firstname'|| $type eq 'userid'|| $type eq 'borrowernumber'){
521         $information = uc $information;
522         $sth = $dbh->prepare("$select WHERE $type=?");
523     } else {
524         $sth = $dbh->prepare("$select WHERE borrowernumber=?");
525     }
526     $sth->execute($information);
527     my $data = $sth->fetchrow_hashref;
528     $sth->finish;
529     ($data) and return ($data);
530
531     if ($type eq 'cardnumber' || $type eq 'firstname') {    # otherwise, try with firstname
532         $sth = $dbh->prepare("$select WHERE firstname like ?");
533         $sth->execute($information);
534         $data = $sth->fetchrow_hashref;
535         $sth->finish;
536         ($data) and return ($data);
537     }
538     return undef;        
539 }
540
541 =item GetMemberIssuesAndFines
542
543   ($overdue_count, $issue_count, $total_fines) = &GetMemberIssuesAndFines($borrowernumber);
544
545 Returns aggregate data about items borrowed by the patron with the
546 given borrowernumber.
547
548 C<&GetMemberIssuesAndFines> returns a three-element array.  C<$overdue_count> is the
549 number of overdue items the patron currently has borrowed. C<$issue_count> is the
550 number of books the patron currently has borrowed.  C<$total_fines> is
551 the total fine currently due by the borrower.
552
553 =cut
554
555 #'
556 sub GetMemberIssuesAndFines {
557     my ( $borrowernumber ) = @_;
558     my $dbh   = C4::Context->dbh;
559     my $query = "SELECT COUNT(*) FROM issues WHERE borrowernumber = ?";
560
561     $debug and warn $query."\n";
562     my $sth = $dbh->prepare($query);
563     $sth->execute($borrowernumber);
564     my $issue_count = $sth->fetchrow_arrayref->[0];
565     $sth->finish;
566
567     $sth = $dbh->prepare(
568         "SELECT COUNT(*) FROM issues 
569          WHERE borrowernumber = ? 
570          AND date_due < now()"
571     );
572     $sth->execute($borrowernumber);
573     my $overdue_count = $sth->fetchrow_arrayref->[0];
574     $sth->finish;
575
576     $sth = $dbh->prepare("SELECT SUM(amountoutstanding) FROM accountlines WHERE borrowernumber = ?");
577     $sth->execute($borrowernumber);
578     my $total_fines = $sth->fetchrow_arrayref->[0];
579     $sth->finish;
580
581     return ($overdue_count, $issue_count, $total_fines);
582 }
583
584 =head2
585
586 =item ModMember
587
588   &ModMember($borrowernumber);
589
590 Modify borrower's data.  All date fields should ALREADY be in ISO format.
591
592 =cut
593
594 #'
595 sub ModMember {
596     my (%data) = @_;
597     my $dbh = C4::Context->dbh;
598     my $iso_re = C4::Dates->new()->regexp('iso');
599     foreach (qw(dateofbirth dateexpiry dateenrolled)) {
600         if (my $tempdate = $data{$_}) {                                 # assignment, not comparison
601             ($tempdate =~ /$iso_re/) and next;                          # Congatulations, you sent a valid ISO date.
602             warn "ModMember given $_ not in ISO format ($tempdate)";
603             if (my $tempdate2 = format_date_in_iso($tempdate)) {        # assignment, not comparison
604                 $data{$_} = $tempdate2;
605             } else {
606                 warn "ModMember cannot convert '$tempdate' (from syspref)";
607             }
608         }
609     }
610     if (!$data{'dateofbirth'}){
611         undef $data{'dateofbirth'};
612     }
613     my $qborrower=$dbh->prepare("SHOW columns from borrowers");
614     $qborrower->execute;
615     my %hashborrowerfields;  
616     while (my ($field)=$qborrower->fetchrow){
617       $hashborrowerfields{$field}=1;
618     }  
619     my $query = "UPDATE borrowers SET \n";
620     my $sth;
621     my @parameters;  
622     
623     # test to know if you must update or not the borrower password
624     if ( $data{'password'} eq '****' ) {
625         delete $data{'password'};
626     } else {
627         $data{'password'} = md5_base64( $data{'password'} )  if ($data{'password'} ne "");
628         delete $data{'password'} if ($data{password} eq "");
629     }
630     foreach (keys %data)
631     { push @parameters,"$_ = ".$dbh->quote($data{$_}) if ($_ ne 'borrowernumber' and $_ ne 'flags' and $hashborrowerfields{$_}); }
632     $query .= join (',',@parameters) . "\n WHERE borrowernumber=? \n";
633     $debug and print STDERR "$query (executed w/ arg: $data{'borrowernumber'})";
634     $sth = $dbh->prepare($query);
635     $sth->execute($data{'borrowernumber'});
636     $sth->finish;
637
638 # ok if its an adult (type) it may have borrowers that depend on it as a guarantor
639 # so when we update information for an adult we should check for guarantees and update the relevant part
640 # of their records, ie addresses and phone numbers
641     my $borrowercategory= GetBorrowercategory( $data{'category_type'} );
642     if ( $borrowercategory->{'category_type'} eq ('A' || 'S') ) {
643         # is adult check guarantees;
644         UpdateGuarantees(%data);
645     }
646     logaction("MEMBERS", "MODIFY", $data{'borrowernumber'}, "$query (executed w/ arg: $data{'borrowernumber'})") 
647         if C4::Context->preference("BorrowersLog");
648 }
649
650
651 =head2
652
653 =item AddMember
654
655   $borrowernumber = &AddMember(%borrower);
656
657 insert new borrower into table
658 Returns the borrowernumber
659
660 =cut
661
662 #'
663 sub AddMember {
664     my (%data) = @_;
665     my $dbh = C4::Context->dbh;
666     $data{'userid'} = '' unless $data{'password'};
667     $data{'password'} = md5_base64( $data{'password'} ) if $data{'password'};
668     
669     # WE SHOULD NEVER PASS THIS SUBROUTINE ANYTHING OTHER THAN ISO DATES
670     # IF YOU UNCOMMENT THESE LINES YOU BETTER HAVE A DARN COMPELLING REASON
671 #    $data{'dateofbirth'}  = format_date_in_iso( $data{'dateofbirth'} );
672 #    $data{'dateenrolled'} = format_date_in_iso( $data{'dateenrolled'});
673 #    $data{'dateexpiry'}   = format_date_in_iso( $data{'dateexpiry'}  );
674     # This query should be rewritten to use "?" at execute.
675     if (!$data{'dateofbirth'}){
676         undef ($data{'dateofbirth'});
677     }
678     my $query =
679         "insert into borrowers set cardnumber=" . $dbh->quote( $data{'cardnumber'} )
680       . ",surname="     . $dbh->quote( $data{'surname'} )
681       . ",firstname="   . $dbh->quote( $data{'firstname'} )
682       . ",title="       . $dbh->quote( $data{'title'} )
683       . ",othernames="  . $dbh->quote( $data{'othernames'} )
684       . ",initials="    . $dbh->quote( $data{'initials'} )
685       . ",streetnumber=". $dbh->quote( $data{'streetnumber'} )
686       . ",streettype="  . $dbh->quote( $data{'streettype'} )
687       . ",address="     . $dbh->quote( $data{'address'} )
688       . ",address2="    . $dbh->quote( $data{'address2'} )
689       . ",zipcode="     . $dbh->quote( $data{'zipcode'} )
690       . ",city="        . $dbh->quote( $data{'city'} )
691       . ",phone="       . $dbh->quote( $data{'phone'} )
692       . ",email="       . $dbh->quote( $data{'email'} )
693       . ",mobile="      . $dbh->quote( $data{'mobile'} )
694       . ",phonepro="    . $dbh->quote( $data{'phonepro'} )
695       . ",opacnote="    . $dbh->quote( $data{'opacnote'} )
696       . ",guarantorid=" . $dbh->quote( $data{'guarantorid'} )
697       . ",dateofbirth=" . $dbh->quote( $data{'dateofbirth'} )
698       . ",branchcode="  . $dbh->quote( $data{'branchcode'} )
699       . ",categorycode=" . $dbh->quote( $data{'categorycode'} )
700       . ",dateenrolled=" . $dbh->quote( $data{'dateenrolled'} )
701       . ",contactname=" . $dbh->quote( $data{'contactname'} )
702       . ",borrowernotes=" . $dbh->quote( $data{'borrowernotes'} )
703       . ",dateexpiry="  . $dbh->quote( $data{'dateexpiry'} )
704       . ",contactnote=" . $dbh->quote( $data{'contactnote'} )
705       . ",B_address="   . $dbh->quote( $data{'B_address'} )
706       . ",B_zipcode="   . $dbh->quote( $data{'B_zipcode'} )
707       . ",B_city="      . $dbh->quote( $data{'B_city'} )
708       . ",B_phone="     . $dbh->quote( $data{'B_phone'} )
709       . ",B_email="     . $dbh->quote( $data{'B_email'} )
710       . ",password="    . $dbh->quote( $data{'password'} )
711       . ",userid="      . $dbh->quote( $data{'userid'} )
712       . ",sort1="       . $dbh->quote( $data{'sort1'} )
713       . ",sort2="       . $dbh->quote( $data{'sort2'} )
714       . ",contacttitle=" . $dbh->quote( $data{'contacttitle'} )
715       . ",emailpro="    . $dbh->quote( $data{'emailpro'} )
716       . ",contactfirstname=" . $dbh->quote( $data{'contactfirstname'} )
717       . ",sex="         . $dbh->quote( $data{'sex'} )
718       . ",fax="         . $dbh->quote( $data{'fax'} )
719       . ",relationship=" . $dbh->quote( $data{'relationship'} )
720       . ",B_streetnumber=" . $dbh->quote( $data{'B_streetnumber'} )
721       . ",B_streettype=" . $dbh->quote( $data{'B_streettype'} )
722       . ",gonenoaddress=" . $dbh->quote( $data{'gonenoaddress'} )
723       . ",lost="        . $dbh->quote( $data{'lost'} )
724       . ",debarred="    . $dbh->quote( $data{'debarred'} )
725       . ",ethnicity="   . $dbh->quote( $data{'ethnicity'} )
726       . ",ethnotes="    . $dbh->quote( $data{'ethnotes'} ) 
727       . ",altcontactsurname="   . $dbh->quote( $data{'altcontactsurname'} ) 
728       . ",altcontactfirstname="     . $dbh->quote( $data{'altcontactfirstname'} ) 
729       . ",altcontactaddress1="  . $dbh->quote( $data{'altcontactaddress1'} ) 
730       . ",altcontactaddress2="  . $dbh->quote( $data{'altcontactaddress2'} ) 
731       . ",altcontactaddress3="  . $dbh->quote( $data{'altcontactaddress3'} ) 
732       . ",altcontactzipcode="   . $dbh->quote( $data{'altcontactzipcode'} ) 
733       . ",altcontactphone="     . $dbh->quote( $data{'altcontactphone'} ) ;
734     $debug and print STDERR "AddMember SQL: ($query)\n";
735     my $sth = $dbh->prepare($query);
736     #   print "Executing SQL: $query\n";
737     $sth->execute();
738     $sth->finish;
739     $data{'borrowernumber'} = $dbh->{'mysql_insertid'};     # unneeded w/ autoincrement ?  
740     # mysql_insertid is probably bad.  not necessarily accurate and mysql-specific at best.
741     
742     logaction("MEMBERS", "CREATE", $data{'borrowernumber'}, "") if C4::Context->preference("BorrowersLog");
743     
744     # check for enrollment fee & add it if needed
745     $sth = $dbh->prepare("SELECT enrolmentfee FROM categories WHERE categorycode=?");
746     $sth->execute($data{'categorycode'});
747     my ($enrolmentfee) = $sth->fetchrow;
748     if ($enrolmentfee) {
749         # insert fee in patron debts
750         manualinvoice($data{'borrowernumber'}, '', '', 'A', $enrolmentfee);
751     }
752     return $data{'borrowernumber'};
753 }
754
755 sub Check_Userid {
756     my ($uid,$member) = @_;
757     my $dbh = C4::Context->dbh;
758     # Make sure the userid chosen is unique and not theirs if non-empty. If it is not,
759     # Then we need to tell the user and have them create a new one.
760     my $sth =
761       $dbh->prepare(
762         "SELECT * FROM borrowers WHERE userid=? AND borrowernumber != ?");
763     $sth->execute( $uid, $member );
764     if ( ( $uid ne '' ) && ( my $row = $sth->fetchrow_hashref ) ) {
765         return 0;
766     }
767     else {
768         return 1;
769     }
770 }
771
772
773 sub changepassword {
774     my ( $uid, $member, $digest ) = @_;
775     my $dbh = C4::Context->dbh;
776
777 #Make sure the userid chosen is unique and not theirs if non-empty. If it is not,
778 #Then we need to tell the user and have them create a new one.
779     my $resultcode;
780     my $sth =
781       $dbh->prepare(
782         "SELECT * FROM borrowers WHERE userid=? AND borrowernumber != ?");
783     $sth->execute( $uid, $member );
784     if ( ( $uid ne '' ) && ( my $row = $sth->fetchrow_hashref ) ) {
785         $resultcode=0;
786     }
787     else {
788         #Everything is good so we can update the information.
789         $sth =
790           $dbh->prepare(
791             "update borrowers set userid=?, password=? where borrowernumber=?");
792         $sth->execute( $uid, $digest, $member );
793         $resultcode=1;
794     }
795     
796     logaction("MEMBERS", "CHANGE PASS", $member, "") if C4::Context->preference("BorrowersLog");
797     return $resultcode;    
798 }
799
800
801
802 =item fixup_cardnumber
803
804 Warning: The caller is responsible for locking the members table in write
805 mode, to avoid database corruption.
806
807 =cut
808
809 use vars qw( @weightings );
810 my @weightings = ( 8, 4, 6, 3, 5, 2, 1 );
811
812 sub fixup_cardnumber ($) {
813     my ($cardnumber) = @_;
814     my $autonumber_members = C4::Context->boolean_preference('autoMemberNum');
815     $autonumber_members = 0 unless defined $autonumber_members;
816
817     # Find out whether member numbers should be generated
818     # automatically. Should be either "1" or something else.
819     # Defaults to "0", which is interpreted as "no".
820
821     #     if ($cardnumber !~ /\S/ && $autonumber_members) {
822     if ($autonumber_members) {
823         my $dbh = C4::Context->dbh;
824         if ( C4::Context->preference('checkdigit') eq 'katipo' ) {
825
826             # if checkdigit is selected, calculate katipo-style cardnumber.
827             # otherwise, just use the max()
828             # purpose: generate checksum'd member numbers.
829             # We'll assume we just got the max value of digits 2-8 of member #'s
830             # from the database and our job is to increment that by one,
831             # determine the 1st and 9th digits and return the full string.
832             my $sth =
833               $dbh->prepare(
834                 "select max(substring(borrowers.cardnumber,2,7)) from borrowers"
835               );
836             $sth->execute;
837
838             my $data = $sth->fetchrow_hashref;
839             $cardnumber = $data->{'max(substring(borrowers.cardnumber,2,7))'};
840             $sth->finish;
841             if ( !$cardnumber ) {    # If DB has no values,
842                 $cardnumber = 1000000;    # start at 1000000
843             }
844             else {
845                 $cardnumber += 1;
846             }
847
848             my $sum = 0;
849             for ( my $i = 0 ; $i < 8 ; $i += 1 ) {
850
851                 # read weightings, left to right, 1 char at a time
852                 my $temp1 = $weightings[$i];
853
854                 # sequence left to right, 1 char at a time
855                 my $temp2 = substr( $cardnumber, $i, 1 );
856
857                 # mult each char 1-7 by its corresponding weighting
858                 $sum += $temp1 * $temp2;
859             }
860
861             my $rem = ( $sum % 11 );
862             $rem = 'X' if $rem == 10;
863
864             $cardnumber = "V$cardnumber$rem";
865         }
866         else {
867
868      # MODIFIED BY JF: mysql4.1 allows casting as an integer, which is probably
869      # better. I'll leave the original in in case it needs to be changed for you
870             my $sth =
871               $dbh->prepare(
872                 "select max(cast(cardnumber as signed)) from borrowers");
873
874       #my $sth=$dbh->prepare("select max(borrowers.cardnumber) from borrowers");
875
876             $sth->execute;
877
878             my ($result) = $sth->fetchrow;
879             $sth->finish;
880             $cardnumber = $result + 1;
881         }
882     }
883     return $cardnumber;
884 }
885
886 =head2 GetGuarantees
887
888   ($num_children, $children_arrayref) = &GetGuarantees($parent_borrno);
889   $child0_cardno = $children_arrayref->[0]{"cardnumber"};
890   $child0_borrno = $children_arrayref->[0]{"borrowernumber"};
891
892 C<&GetGuarantees> takes a borrower number (e.g., that of a patron
893 with children) and looks up the borrowers who are guaranteed by that
894 borrower (i.e., the patron's children).
895
896 C<&GetGuarantees> returns two values: an integer giving the number of
897 borrowers guaranteed by C<$parent_borrno>, and a reference to an array
898 of references to hash, which gives the actual results.
899
900 =cut
901
902 #'
903 sub GetGuarantees {
904     my ($borrowernumber) = @_;
905     my $dbh              = C4::Context->dbh;
906     my $sth              =
907       $dbh->prepare(
908 "select cardnumber,borrowernumber, firstname, surname from borrowers where guarantorid=?"
909       );
910     $sth->execute($borrowernumber);
911
912     my @dat;
913     my $data = $sth->fetchall_arrayref({}); 
914     $sth->finish;
915     return ( scalar(@$data), $data );
916 }
917
918 =head2 UpdateGuarantees
919
920   &UpdateGuarantees($parent_borrno);
921   
922
923 C<&UpdateGuarantees> borrower data for an adulte and updates all the guarantees
924 with the modified information
925
926 =cut
927
928 #'
929 sub UpdateGuarantees {
930     my (%data) = @_;
931     my $dbh = C4::Context->dbh;
932     my ( $count, $guarantees ) = GetGuarantees( $data{'borrowernumber'} );
933     for ( my $i = 0 ; $i < $count ; $i++ ) {
934
935         # FIXME
936         # It looks like the $i is only being returned to handle walking through
937         # the array, which is probably better done as a foreach loop.
938         #
939         my $guaquery = qq|UPDATE borrowers 
940               SET address='$data{'address'}',fax='$data{'fax'}',
941                   B_city='$data{'B_city'}',mobile='$data{'mobile'}',city='$data{'city'}',phone='$data{'phone'}'
942               WHERE borrowernumber='$guarantees->[$i]->{'borrowernumber'}'
943         |;
944         my $sth3 = $dbh->prepare($guaquery);
945         $sth3->execute;
946         $sth3->finish;
947     }
948 }
949 =head2 GetPendingIssues
950
951   ($count, $issues) = &GetPendingIssues($borrowernumber);
952
953 Looks up what the patron with the given borrowernumber has borrowed.
954
955 C<&GetPendingIssues> returns a two-element array. C<$issues> is a
956 reference-to-array, where each element is a reference-to-hash; the
957 keys are the fields from the C<issues>, C<biblio>, and C<items> tables
958 in the Koha database. C<$count> is the number of elements in
959 C<$issues>.
960
961 =cut
962
963 #'
964 sub GetPendingIssues {
965     my ($borrowernumber) = @_;
966     my $dbh              = C4::Context->dbh;
967
968     my $sth              = $dbh->prepare(
969    "SELECT * FROM issues 
970       LEFT JOIN items ON issues.itemnumber=items.itemnumber
971       LEFT JOIN biblio ON     items.biblionumber=biblio.biblionumber 
972       LEFT JOIN biblioitems ON items.biblioitemnumber=biblioitems.biblioitemnumber
973     WHERE
974       borrowernumber=? 
975     ORDER BY issues.issuedate"
976     );
977     $sth->execute($borrowernumber);
978     my $data = $sth->fetchall_arrayref({});
979     my $today = POSIX::strftime("%Y%m%d", localtime);
980     foreach( @$data ) {
981         my $datedue = $_->{'date_due'};
982         $datedue =~ s/-//g;
983         if ( $datedue < $today ) {
984             $_->{'overdue'} = 1;
985         }
986     }
987     $sth->finish;
988     return ( scalar(@$data), $data );
989 }
990
991 =head2 GetAllIssues
992
993   ($count, $issues) = &GetAllIssues($borrowernumber, $sortkey, $limit);
994
995 Looks up what the patron with the given borrowernumber has borrowed,
996 and sorts the results.
997
998 C<$sortkey> is the name of a field on which to sort the results. This
999 should be the name of a field in the C<issues>, C<biblio>,
1000 C<biblioitems>, or C<items> table in the Koha database.
1001
1002 C<$limit> is the maximum number of results to return.
1003
1004 C<&GetAllIssues> returns a two-element array. C<$issues> is a
1005 reference-to-array, where each element is a reference-to-hash; the
1006 keys are the fields from the C<issues>, C<biblio>, C<biblioitems>, and
1007 C<items> tables of the Koha database. C<$count> is the number of
1008 elements in C<$issues>
1009
1010 =cut
1011
1012 #'
1013 sub GetAllIssues {
1014     my ( $borrowernumber, $order, $limit ) = @_;
1015
1016     #FIXME: sanity-check order and limit
1017     my $dbh   = C4::Context->dbh;
1018     my $count = 0;
1019     my $query =
1020   "SELECT *,items.timestamp AS itemstimestamp 
1021   FROM issues 
1022   LEFT JOIN items on items.itemnumber=issues.itemnumber
1023   LEFT JOIN biblio ON items.biblionumber=biblio.biblionumber
1024   LEFT JOIN biblioitems ON items.biblioitemnumber=biblioitems.biblioitemnumber
1025   WHERE borrowernumber=? 
1026   UNION ALL
1027   SELECT *,items.timestamp AS itemstimestamp 
1028   FROM old_issues 
1029   LEFT JOIN items on items.itemnumber=old_issues.itemnumber
1030   LEFT JOIN biblio ON items.biblionumber=biblio.biblionumber
1031   LEFT JOIN biblioitems ON items.biblioitemnumber=biblioitems.biblioitemnumber
1032   WHERE borrowernumber=? 
1033   order by $order";
1034     if ( $limit != 0 ) {
1035         $query .= " limit $limit";
1036     }
1037
1038     #print $query;
1039     my $sth = $dbh->prepare($query);
1040     $sth->execute($borrowernumber, $borrowernumber);
1041     my @result;
1042     my $i = 0;
1043     while ( my $data = $sth->fetchrow_hashref ) {
1044         $result[$i] = $data;
1045         $i++;
1046         $count++;
1047     }
1048
1049     # get all issued items for borrowernumber from oldissues table
1050     # large chunk of older issues data put into table oldissues
1051     # to speed up db calls for issuing items
1052     if ( C4::Context->preference("ReadingHistory") ) {
1053         # FIXME oldissues (not to be confused with old_issues) is
1054         # apparently specific to HLT.  Not sure if the ReadingHistory
1055         # syspref is still required, as old_issues by design
1056         # is no longer checked with each loan.
1057         my $query2 = "SELECT * FROM oldissues
1058                       LEFT JOIN items ON items.itemnumber=oldissues.itemnumber
1059                       LEFT JOIN biblio ON items.biblionumber=biblio.biblionumber
1060                       LEFT JOIN biblioitems ON items.biblioitemnumber=biblioitems.biblioitemnumber
1061                       WHERE borrowernumber=? 
1062                       ORDER BY $order";
1063         if ( $limit != 0 ) {
1064             $limit = $limit - $count;
1065             $query2 .= " limit $limit";
1066         }
1067
1068         my $sth2 = $dbh->prepare($query2);
1069         $sth2->execute($borrowernumber);
1070
1071         while ( my $data2 = $sth2->fetchrow_hashref ) {
1072             $result[$i] = $data2;
1073             $i++;
1074         }
1075         $sth2->finish;
1076     }
1077     $sth->finish;
1078
1079     return ( $i, \@result );
1080 }
1081
1082
1083 =head2 GetMemberAccountRecords
1084
1085   ($total, $acctlines, $count) = &GetMemberAccountRecords($borrowernumber);
1086
1087 Looks up accounting data for the patron with the given borrowernumber.
1088
1089 C<&GetMemberAccountRecords> returns a three-element array. C<$acctlines> is a
1090 reference-to-array, where each element is a reference-to-hash; the
1091 keys are the fields of the C<accountlines> table in the Koha database.
1092 C<$count> is the number of elements in C<$acctlines>. C<$total> is the
1093 total amount outstanding for all of the account lines.
1094
1095 =cut
1096
1097 #'
1098 sub GetMemberAccountRecords {
1099     my ($borrowernumber,$date) = @_;
1100     my $dbh = C4::Context->dbh;
1101     my @acctlines;
1102     my $numlines = 0;
1103     my $strsth      = qq(
1104                         SELECT * 
1105                         FROM accountlines 
1106                         WHERE borrowernumber=?);
1107     my @bind = ($borrowernumber);
1108     if ($date && $date ne ''){
1109             $strsth.=" AND date < ? ";
1110             push(@bind,$date);
1111     }
1112     $strsth.=" ORDER BY date desc,timestamp DESC";
1113     my $sth= $dbh->prepare( $strsth );
1114     $sth->execute( @bind );
1115     my $total = 0;
1116     while ( my $data = $sth->fetchrow_hashref ) {
1117         $acctlines[$numlines] = $data;
1118         $numlines++;
1119         $total += $data->{'amountoutstanding'};
1120     }
1121     $sth->finish;
1122     return ( $total, \@acctlines,$numlines);
1123 }
1124
1125 =head2 GetBorNotifyAcctRecord
1126
1127   ($count, $acctlines, $total) = &GetBorNotifyAcctRecord($params,$notifyid);
1128
1129 Looks up accounting data for the patron with the given borrowernumber per file number.
1130
1131 (FIXME - I'm not at all sure what this is about.)
1132
1133 C<&GetBorNotifyAcctRecord> returns a three-element array. C<$acctlines> is a
1134 reference-to-array, where each element is a reference-to-hash; the
1135 keys are the fields of the C<accountlines> table in the Koha database.
1136 C<$count> is the number of elements in C<$acctlines>. C<$total> is the
1137 total amount outstanding for all of the account lines.
1138
1139 =cut
1140
1141 sub GetBorNotifyAcctRecord {
1142     my ( $borrowernumber, $notifyid ) = @_;
1143     my $dbh = C4::Context->dbh;
1144     my @acctlines;
1145     my $numlines = 0;
1146     my $sth = $dbh->prepare(
1147             "SELECT * 
1148                 FROM accountlines 
1149                 WHERE borrowernumber=? 
1150                     AND notify_id=? 
1151                     AND amountoutstanding != '0' 
1152                 ORDER BY notify_id,accounttype
1153                 ");
1154 #                    AND (accounttype='FU' OR accounttype='N' OR accounttype='M'OR accounttype='A'OR accounttype='F'OR accounttype='L' OR accounttype='IP' OR accounttype='CH' OR accounttype='RE' OR accounttype='RL')
1155
1156     $sth->execute( $borrowernumber, $notifyid );
1157     my $total = 0;
1158     while ( my $data = $sth->fetchrow_hashref ) {
1159         $acctlines[$numlines] = $data;
1160         $numlines++;
1161         $total += $data->{'amountoutstanding'};
1162     }
1163     $sth->finish;
1164     return ( $total, \@acctlines, $numlines );
1165 }
1166
1167 =head2 checkuniquemember (OUEST-PROVENCE)
1168
1169   ($result,$categorycode)  = &checkuniquemember($collectivity,$surname,$firstname,$dateofbirth);
1170
1171 Checks that a member exists or not in the database.
1172
1173 C<&result> is nonzero (=exist) or 0 (=does not exist)
1174 C<&categorycode> is from categorycode table
1175 C<&collectivity> is 1 (= we add a collectivity) or 0 (= we add a physical member)
1176 C<&surname> is the surname
1177 C<&firstname> is the firstname (only if collectivity=0)
1178 C<&dateofbirth> is the date of birth in ISO format (only if collectivity=0)
1179
1180 =cut
1181
1182 # FIXME: This function is not legitimate.  Multiple patrons might have the same first/last name and birthdate.
1183 # This is especially true since first name is not even a required field.
1184
1185 sub checkuniquemember {
1186     my ( $collectivity, $surname, $firstname, $dateofbirth ) = @_;
1187     my $dbh = C4::Context->dbh;
1188     my $request = ($collectivity) ?
1189         "SELECT borrowernumber,categorycode FROM borrowers WHERE surname=? " :
1190         "SELECT borrowernumber,categorycode FROM borrowers WHERE surname=? and firstname=? and dateofbirth=? ";
1191     my $sth = $dbh->prepare($request);
1192     if ($collectivity) {
1193         $sth->execute( uc($surname) );
1194     } else {
1195         $sth->execute( uc($surname), ucfirst($firstname), $dateofbirth );
1196     }
1197     my @data = $sth->fetchrow;
1198     $sth->finish;
1199     ( $data[0] ) and return $data[0], $data[1];
1200     return 0;
1201 }
1202
1203 sub checkcardnumber {
1204     my ($cardnumber,$borrowernumber) = @_;
1205     my $dbh = C4::Context->dbh;
1206     my $query = "SELECT * FROM borrowers WHERE cardnumber=?";
1207     $query .= " AND borrowernumber <> ?" if ($borrowernumber);
1208   my $sth = $dbh->prepare($query);
1209   if ($borrowernumber) {
1210    $sth->execute($cardnumber,$borrowernumber);
1211   } else { 
1212      $sth->execute($cardnumber);
1213   } 
1214     if (my $data= $sth->fetchrow_hashref()){
1215         return 1;
1216     }
1217     else {
1218         return 0;
1219     }
1220     $sth->finish();
1221 }  
1222
1223
1224 =head2 getzipnamecity (OUEST-PROVENCE)
1225
1226 take all info from table city for the fields city and  zip
1227 check for the name and the zip code of the city selected
1228
1229 =cut
1230
1231 sub getzipnamecity {
1232     my ($cityid) = @_;
1233     my $dbh      = C4::Context->dbh;
1234     my $sth      =
1235       $dbh->prepare(
1236         "select city_name,city_zipcode from cities where cityid=? ");
1237     $sth->execute($cityid);
1238     my @data = $sth->fetchrow;
1239     return $data[0], $data[1];
1240 }
1241
1242
1243 =head2 getdcity (OUEST-PROVENCE)
1244
1245 recover cityid  with city_name condition
1246
1247 =cut
1248
1249 sub getidcity {
1250     my ($city_name) = @_;
1251     my $dbh = C4::Context->dbh;
1252     my $sth = $dbh->prepare("select cityid from cities where city_name=? ");
1253     $sth->execute($city_name);
1254     my $data = $sth->fetchrow;
1255     return $data;
1256 }
1257
1258
1259 =head2 GetExpiryDate 
1260
1261   $expirydate = GetExpiryDate($categorycode, $dateenrolled);
1262
1263 Calculate expiry date given a categorycode and starting date.  Date argument must be in ISO format.
1264 Return date is also in ISO format.
1265
1266 =cut
1267
1268 sub GetExpiryDate {
1269     my ( $categorycode, $dateenrolled ) = @_;
1270     my $enrolmentperiod = 12;   # reasonable default
1271     if ($categorycode) {
1272         my $dbh = C4::Context->dbh;
1273         my $sth = $dbh->prepare("select enrolmentperiod from categories where categorycode=?");
1274         $sth->execute($categorycode);
1275         $enrolmentperiod = $sth->fetchrow;
1276     }
1277     # die "GetExpiryDate: for enrollmentperiod $enrolmentperiod (category '$categorycode') starting $dateenrolled.\n";
1278     my @date = split /-/,$dateenrolled;
1279     return sprintf("%04d-%02d-%02d", Add_Delta_YM(@date,0,$enrolmentperiod));
1280 }
1281
1282 =head2 checkuserpassword (OUEST-PROVENCE)
1283
1284 check for the password and login are not used
1285 return the number of record 
1286 0=> NOT USED 1=> USED
1287
1288 =cut
1289
1290 sub checkuserpassword {
1291     my ( $borrowernumber, $userid, $password ) = @_;
1292     $password = md5_base64($password);
1293     my $dbh = C4::Context->dbh;
1294     my $sth =
1295       $dbh->prepare(
1296 "Select count(*) from borrowers where borrowernumber !=? and userid =? and password=? "
1297       );
1298     $sth->execute( $borrowernumber, $userid, $password );
1299     my $number_rows = $sth->fetchrow;
1300     return $number_rows;
1301
1302 }
1303
1304 =head2 GetborCatFromCatType
1305
1306   ($codes_arrayref, $labels_hashref) = &GetborCatFromCatType();
1307
1308 Looks up the different types of borrowers in the database. Returns two
1309 elements: a reference-to-array, which lists the borrower category
1310 codes, and a reference-to-hash, which maps the borrower category codes
1311 to category descriptions.
1312
1313 =cut
1314
1315 #'
1316 sub GetborCatFromCatType {
1317     my ( $category_type, $action ) = @_;
1318     my $dbh     = C4::Context->dbh;
1319     my $request = qq|   SELECT categorycode,description 
1320             FROM categories 
1321             $action
1322             ORDER BY categorycode|;
1323     my $sth = $dbh->prepare($request);
1324     if ($action) {
1325         $sth->execute($category_type);
1326     }
1327     else {
1328         $sth->execute();
1329     }
1330
1331     my %labels;
1332     my @codes;
1333
1334     while ( my $data = $sth->fetchrow_hashref ) {
1335         push @codes, $data->{'categorycode'};
1336         $labels{ $data->{'categorycode'} } = $data->{'description'};
1337     }
1338     $sth->finish;
1339     return ( \@codes, \%labels );
1340 }
1341
1342 =head2 GetBorrowercategory
1343
1344   $hashref = &GetBorrowercategory($categorycode);
1345
1346 Given the borrower's category code, the function returns the corresponding
1347 data hashref for a comprehensive information display.
1348   
1349   $arrayref_hashref = &GetBorrowercategory;
1350 If no category code provided, the function returns all the categories.
1351
1352 =cut
1353
1354 sub GetBorrowercategory {
1355     my ($catcode) = @_;
1356     my $dbh       = C4::Context->dbh;
1357     if ($catcode){
1358         my $sth       =
1359         $dbh->prepare(
1360     "SELECT description,dateofbirthrequired,upperagelimit,category_type 
1361     FROM categories 
1362     WHERE categorycode = ?"
1363         );
1364         $sth->execute($catcode);
1365         my $data =
1366         $sth->fetchrow_hashref;
1367         $sth->finish();
1368         return $data;
1369     } 
1370     else {
1371         my $sth       =
1372         $dbh->prepare(
1373     "SELECT *
1374     FROM categories order by description"
1375         );
1376         $sth->execute;
1377         my $data =
1378         $sth->fetchall_arrayref({});
1379         $sth->finish();
1380         return $data;
1381     }  
1382 }    # sub getborrowercategory
1383
1384 =head2 ethnicitycategories
1385
1386   ($codes_arrayref, $labels_hashref) = &ethnicitycategories();
1387
1388 Looks up the different ethnic types in the database. Returns two
1389 elements: a reference-to-array, which lists the ethnicity codes, and a
1390 reference-to-hash, which maps the ethnicity codes to ethnicity
1391 descriptions.
1392
1393 =cut
1394
1395 #'
1396
1397 sub ethnicitycategories {
1398     my $dbh = C4::Context->dbh;
1399     my $sth = $dbh->prepare("Select code,name from ethnicity order by name");
1400     $sth->execute;
1401     my %labels;
1402     my @codes;
1403     while ( my $data = $sth->fetchrow_hashref ) {
1404         push @codes, $data->{'code'};
1405         $labels{ $data->{'code'} } = $data->{'name'};
1406     }
1407     $sth->finish;
1408     return ( \@codes, \%labels );
1409 }
1410
1411 =head2 fixEthnicity
1412
1413   $ethn_name = &fixEthnicity($ethn_code);
1414
1415 Takes an ethnicity code (e.g., "european" or "pi") and returns the
1416 corresponding descriptive name from the C<ethnicity> table in the
1417 Koha database ("European" or "Pacific Islander").
1418
1419 =cut
1420
1421 #'
1422
1423 sub fixEthnicity {
1424     my $ethnicity = shift;
1425     return unless $ethnicity;
1426     my $dbh       = C4::Context->dbh;
1427     my $sth       = $dbh->prepare("Select name from ethnicity where code = ?");
1428     $sth->execute($ethnicity);
1429     my $data = $sth->fetchrow_hashref;
1430     $sth->finish;
1431     return $data->{'name'};
1432 }    # sub fixEthnicity
1433
1434 =head2 GetAge
1435
1436   $dateofbirth,$date = &GetAge($date);
1437
1438 this function return the borrowers age with the value of dateofbirth
1439
1440 =cut
1441
1442 #'
1443 sub GetAge{
1444     my ( $date, $date_ref ) = @_;
1445
1446     if ( not defined $date_ref ) {
1447         $date_ref = sprintf( '%04d-%02d-%02d', Today() );
1448     }
1449
1450     my ( $year1, $month1, $day1 ) = split /-/, $date;
1451     my ( $year2, $month2, $day2 ) = split /-/, $date_ref;
1452
1453     my $age = $year2 - $year1;
1454     if ( $month1 . $day1 > $month2 . $day2 ) {
1455         $age--;
1456     }
1457
1458     return $age;
1459 }    # sub get_age
1460
1461 =head2 get_institutions
1462   $insitutions = get_institutions();
1463
1464 Just returns a list of all the borrowers of type I, borrownumber and name
1465
1466 =cut
1467
1468 #'
1469 sub get_institutions {
1470     my $dbh = C4::Context->dbh();
1471     my $sth =
1472       $dbh->prepare(
1473 "SELECT borrowernumber,surname FROM borrowers WHERE categorycode=? ORDER BY surname"
1474       );
1475     $sth->execute('I');
1476     my %orgs;
1477     while ( my $data = $sth->fetchrow_hashref() ) {
1478         $orgs{ $data->{'borrowernumber'} } = $data;
1479     }
1480     $sth->finish();
1481     return ( \%orgs );
1482
1483 }    # sub get_institutions
1484
1485 =head2 add_member_orgs
1486
1487   add_member_orgs($borrowernumber,$borrowernumbers);
1488
1489 Takes a borrowernumber and a list of other borrowernumbers and inserts them into the borrowers_to_borrowers table
1490
1491 =cut
1492
1493 #'
1494 sub add_member_orgs {
1495     my ( $borrowernumber, $otherborrowers ) = @_;
1496     my $dbh   = C4::Context->dbh();
1497     my $query =
1498       "INSERT INTO borrowers_to_borrowers (borrower1,borrower2) VALUES (?,?)";
1499     my $sth = $dbh->prepare($query);
1500     foreach my $otherborrowernumber (@$otherborrowers) {
1501         $sth->execute( $borrowernumber, $otherborrowernumber );
1502     }
1503     $sth->finish();
1504
1505 }    # sub add_member_orgs
1506
1507 =head2 GetCities (OUEST-PROVENCE)
1508
1509   ($id_cityarrayref, $city_hashref) = &GetCities();
1510
1511 Looks up the different city and zip in the database. Returns two
1512 elements: a reference-to-array, which lists the zip city
1513 codes, and a reference-to-hash, which maps the name of the city.
1514 WHERE =>OUEST PROVENCE OR EXTERIEUR
1515
1516 =cut
1517
1518 sub GetCities {
1519
1520     #my ($type_city) = @_;
1521     my $dbh   = C4::Context->dbh;
1522     my $query = qq|SELECT cityid,city_zipcode,city_name 
1523         FROM cities 
1524         ORDER BY city_name|;
1525     my $sth = $dbh->prepare($query);
1526
1527     #$sth->execute($type_city);
1528     $sth->execute();
1529     my %city;
1530     my @id;
1531     #    insert empty value to create a empty choice in cgi popup
1532     push @id, " ";
1533     $city{""} = "";
1534     while ( my $data = $sth->fetchrow_hashref ) {
1535         push @id, $data->{'city_zipcode'}."|".$data->{'city_name'};
1536         $city{ $data->{'city_zipcode'}."|".$data->{'city_name'} } = $data->{'city_name'};
1537     }
1538
1539 #test to know if the table contain some records if no the function return nothing
1540     my $id = @id;
1541     $sth->finish;
1542     if ( $id == 1 ) {
1543         # all we have is the one blank row
1544         return ();
1545     }
1546     else {
1547         unshift( @id, "" );
1548         return ( \@id, \%city );
1549     }
1550 }
1551
1552 =head2 GetSortDetails (OUEST-PROVENCE)
1553
1554   ($lib) = &GetSortDetails($category,$sortvalue);
1555
1556 Returns the authorized value  details
1557 C<&$lib>return value of authorized value details
1558 C<&$sortvalue>this is the value of authorized value 
1559 C<&$category>this is the value of authorized value category
1560
1561 =cut
1562
1563 sub GetSortDetails {
1564     my ( $category, $sortvalue ) = @_;
1565     my $dbh   = C4::Context->dbh;
1566     my $query = qq|SELECT lib 
1567         FROM authorised_values 
1568         WHERE category=?
1569         AND authorised_value=? |;
1570     my $sth = $dbh->prepare($query);
1571     $sth->execute( $category, $sortvalue );
1572     my $lib = $sth->fetchrow;
1573     return ($lib) if ($lib);
1574     return ($sortvalue) unless ($lib);
1575 }
1576
1577 =head2 DeleteBorrower 
1578
1579   () = &DeleteBorrower($member);
1580
1581 delete all data fo borrowers and add record to deletedborrowers table
1582 C<&$member>this is the borrowernumber
1583
1584 =cut
1585
1586 sub MoveMemberToDeleted {
1587     my ($member) = @_;
1588     my $dbh = C4::Context->dbh;
1589     my $query;
1590     $query = qq|SELECT * 
1591           FROM borrowers 
1592           WHERE borrowernumber=?|;
1593     my $sth = $dbh->prepare($query);
1594     $sth->execute($member);
1595     my @data = $sth->fetchrow_array;
1596     $sth->finish;
1597     $sth =
1598       $dbh->prepare( "INSERT INTO deletedborrowers VALUES ("
1599           . ( "?," x ( scalar(@data) - 1 ) )
1600           . "?)" );
1601     $sth->execute(@data);
1602     $sth->finish;
1603 }
1604
1605 =head2 DelMember
1606
1607 DelMember($borrowernumber);
1608
1609 This function remove directly a borrower whitout writing it on deleteborrower.
1610 + Deletes reserves for the borrower
1611
1612 =cut
1613
1614 sub DelMember {
1615     my $dbh            = C4::Context->dbh;
1616     my $borrowernumber = shift;
1617     #warn "in delmember with $borrowernumber";
1618     return unless $borrowernumber;    # borrowernumber is mandatory.
1619
1620     my $query = qq|DELETE 
1621           FROM  reserves 
1622           WHERE borrowernumber=?|;
1623     my $sth = $dbh->prepare($query);
1624     $sth->execute($borrowernumber);
1625     $sth->finish;
1626     $query = "
1627        DELETE
1628        FROM borrowers
1629        WHERE borrowernumber = ?
1630    ";
1631     $sth = $dbh->prepare($query);
1632     $sth->execute($borrowernumber);
1633     $sth->finish;
1634     logaction("MEMBERS", "DELETE", $borrowernumber, "") if C4::Context->preference("BorrowersLog");
1635     return $sth->rows;
1636 }
1637
1638 =head2 ExtendMemberSubscriptionTo (OUEST-PROVENCE)
1639
1640     $date = ExtendMemberSubscriptionTo($borrowerid, $date);
1641
1642 Extending the subscription to a given date or to the expiry date calculated on ISO date.
1643 Returns ISO date.
1644
1645 =cut
1646
1647 sub ExtendMemberSubscriptionTo {
1648     my ( $borrowerid,$date) = @_;
1649     my $dbh = C4::Context->dbh;
1650     my $borrower = GetMember($borrowerid,'borrowernumber');
1651     unless ($date){
1652       $date=POSIX::strftime("%Y-%m-%d",localtime());
1653       my $borrower = GetMember($borrowerid,'borrowernumber');
1654       $date = GetExpiryDate( $borrower->{'categorycode'}, $date );
1655     }
1656     my $sth = $dbh->do(<<EOF);
1657 UPDATE borrowers 
1658 SET  dateexpiry='$date' 
1659 WHERE borrowernumber='$borrowerid'
1660 EOF
1661     # add enrolmentfee if needed
1662     $sth = $dbh->prepare("SELECT enrolmentfee FROM categories WHERE categorycode=?");
1663     $sth->execute($borrower->{'categorycode'});
1664     my ($enrolmentfee) = $sth->fetchrow;
1665     if ($enrolmentfee) {
1666         # insert fee in patron debts
1667         manualinvoice($borrower->{'borrowernumber'}, '', '', 'A', $enrolmentfee);
1668     }
1669     return $date if ($sth);
1670     return 0;
1671 }
1672
1673 =head2 GetRoadTypes (OUEST-PROVENCE)
1674
1675   ($idroadtypearrayref, $roadttype_hashref) = &GetRoadTypes();
1676
1677 Looks up the different road type . Returns two
1678 elements: a reference-to-array, which lists the id_roadtype
1679 codes, and a reference-to-hash, which maps the road type of the road .
1680
1681 =cut
1682
1683 sub GetRoadTypes {
1684     my $dbh   = C4::Context->dbh;
1685     my $query = qq|
1686 SELECT roadtypeid,road_type 
1687 FROM roadtype 
1688 ORDER BY road_type|;
1689     my $sth = $dbh->prepare($query);
1690     $sth->execute();
1691     my %roadtype;
1692     my @id;
1693
1694     #    insert empty value to create a empty choice in cgi popup
1695
1696     while ( my $data = $sth->fetchrow_hashref ) {
1697
1698         push @id, $data->{'roadtypeid'};
1699         $roadtype{ $data->{'roadtypeid'} } = $data->{'road_type'};
1700     }
1701
1702 #test to know if the table contain some records if no the function return nothing
1703     my $id = @id;
1704     $sth->finish;
1705     if ( $id eq 0 ) {
1706         return ();
1707     }
1708     else {
1709         unshift( @id, "" );
1710         return ( \@id, \%roadtype );
1711     }
1712 }
1713
1714
1715
1716 =head2 GetTitles (OUEST-PROVENCE)
1717
1718   ($borrowertitle)= &GetTitles();
1719
1720 Looks up the different title . Returns array  with all borrowers title
1721
1722 =cut
1723
1724 sub GetTitles {
1725     my @borrowerTitle = split /,|\|/,C4::Context->preference('BorrowersTitles');
1726     unshift( @borrowerTitle, "" );
1727     my $count=@borrowerTitle;
1728     if ($count == 1){
1729         return ();
1730     }
1731     else {
1732         return ( \@borrowerTitle);
1733     }
1734 }
1735
1736 =head2 GetPatronImage
1737
1738     my ($imagedata, $dberror) = GetPatronImage($cardnumber);
1739
1740 Returns the mimetype and binary image data of the image for the patron with the supplied cardnumber.
1741
1742 =cut
1743
1744 sub GetPatronImage {
1745     my ($cardnumber) = @_;
1746     warn "Cardnumber passed to GetPatronImage is $cardnumber" if $debug;
1747     my $dbh = C4::Context->dbh;
1748     my $query = "SELECT mimetype, imagefile FROM patronimage WHERE cardnumber = ?;";
1749     my $sth = $dbh->prepare($query);
1750     $sth->execute($cardnumber);
1751     my $imagedata = $sth->fetchrow_hashref;
1752     my $dberror = $sth->errstr;
1753     warn "Database error!" if $sth->errstr;
1754     $sth->finish;
1755     return $imagedata, $dberror;
1756 }
1757
1758 =head2 PutPatronImage
1759
1760     PutPatronImage($cardnumber, $mimetype, $imgfile);
1761
1762 Stores patron binary image data and mimetype in database.
1763 NOTE: This function is good for updating images as well as inserting new images in the database.
1764
1765 =cut
1766
1767 sub PutPatronImage {
1768     my ($cardnumber, $mimetype, $imgfile) = @_;
1769     warn "Parameters passed in: Cardnumber=$cardnumber, Mimetype=$mimetype, " . ($imgfile ? "Imagefile" : "No Imagefile") if $debug;
1770     my $dbh = C4::Context->dbh;
1771     my $query = "INSERT INTO patronimage (cardnumber, mimetype, imagefile) VALUES (?,?,?) ON DUPLICATE KEY UPDATE imagefile = ?;";
1772     my $sth = $dbh->prepare($query);
1773     $sth->execute($cardnumber,$mimetype,$imgfile,$imgfile);
1774     warn "Error returned inserting $cardnumber.$mimetype." if $sth->errstr;
1775     my $dberror = $sth->errstr;
1776     $sth->finish;
1777     return $dberror;
1778 }
1779
1780 =head2 RmPatronImage
1781
1782     my ($dberror) = RmPatronImage($cardnumber);
1783
1784 Removes the image for the patron with the supplied cardnumber.
1785
1786 =cut
1787
1788 sub RmPatronImage {
1789     my ($cardnumber) = @_;
1790     warn "Cardnumber passed to GetPatronImage is $cardnumber" if $debug;
1791     my $dbh = C4::Context->dbh;
1792     my $query = "DELETE FROM patronimage WHERE cardnumber = ?;";
1793     my $sth = $dbh->prepare($query);
1794     $sth->execute($cardnumber);
1795     my $dberror = $sth->errstr;
1796     warn "Database error!" if $sth->errstr;
1797     $sth->finish;
1798     return $dberror;
1799 }
1800
1801 =head2 GetRoadTypeDetails (OUEST-PROVENCE)
1802
1803   ($roadtype) = &GetRoadTypeDetails($roadtypeid);
1804
1805 Returns the description of roadtype
1806 C<&$roadtype>return description of road type
1807 C<&$roadtypeid>this is the value of roadtype s
1808
1809 =cut
1810
1811 sub GetRoadTypeDetails {
1812     my ($roadtypeid) = @_;
1813     my $dbh          = C4::Context->dbh;
1814     my $query        = qq|
1815 SELECT road_type 
1816 FROM roadtype 
1817 WHERE roadtypeid=?|;
1818     my $sth = $dbh->prepare($query);
1819     $sth->execute($roadtypeid);
1820     my $roadtype = $sth->fetchrow;
1821     return ($roadtype);
1822 }
1823
1824 =head2 GetBorrowersWhoHaveNotBorrowedSince
1825
1826 &GetBorrowersWhoHaveNotBorrowedSince($date)
1827
1828 this function get all borrowers who haven't borrowed since the date given on input arg.
1829       
1830 =cut
1831
1832 sub GetBorrowersWhoHaveNotBorrowedSince {
1833 ### TODO : It could be dangerous to delete Borrowers who have just been entered and who have not yet borrowed any book. May be good to add a dateexpiry or dateenrolled filter.      
1834        
1835                 my $filterdate = shift||POSIX::strftime("%Y-%m-%d",localtime());
1836     my $filterbranch = shift || 
1837                         ((C4::Context->preference('IndependantBranches') 
1838                              && C4::Context->userenv 
1839                              && C4::Context->userenv->{flags}!=1 
1840                              && C4::Context->userenv->{branch})
1841                          ? C4::Context->userenv->{branch}
1842                          : "");  
1843     my $dbh   = C4::Context->dbh;
1844     my $query = "
1845         SELECT borrowers.borrowernumber,max(issues.timestamp) as latestissue
1846         FROM   borrowers
1847           LEFT JOIN issues ON borrowers.borrowernumber = issues.borrowernumber
1848    ";
1849     my @query_params;
1850     if ($filterbranch && $filterbranch ne ""){ 
1851         $query.=" WHERE branchcode= ?";
1852         push @query_params,$filterbranch;
1853     }    
1854     $query.=" GROUP BY borrowers.borrowernumber";
1855     if ($filterdate){ 
1856         $query.=" HAVING latestissue <? OR latestissue IS NULL";
1857         push @query_params,$filterdate;
1858     }
1859     warn $query if $debug;
1860     my $sth = $dbh->prepare($query);
1861     if (scalar(@query_params)>0){  
1862         $sth->execute(@query_params);
1863     } 
1864     else {
1865         $sth->execute;
1866     }      
1867     
1868     my @results;
1869     while ( my $data = $sth->fetchrow_hashref ) {
1870         push @results, $data;
1871     }
1872     return \@results;
1873 }
1874
1875 =head2 GetBorrowersWhoHaveNeverBorrowed
1876
1877 $results = &GetBorrowersWhoHaveNeverBorrowed
1878
1879 this function get all borrowers who have never borrowed.
1880
1881 I<$result> is a ref to an array which all elements are a hasref.
1882
1883 =cut
1884
1885 sub GetBorrowersWhoHaveNeverBorrowed {
1886     my $filterbranch = shift || 
1887                         ((C4::Context->preference('IndependantBranches') 
1888                              && C4::Context->userenv 
1889                              && C4::Context->userenv->{flags}!=1 
1890                              && C4::Context->userenv->{branch})
1891                          ? C4::Context->userenv->{branch}
1892                          : "");  
1893     my $dbh   = C4::Context->dbh;
1894     my $query = "
1895         SELECT borrowers.borrowernumber,max(timestamp) as latestissue
1896         FROM   borrowers
1897           LEFT JOIN issues ON borrowers.borrowernumber = issues.borrowernumber
1898         WHERE issues.borrowernumber IS NULL
1899    ";
1900     my @query_params;
1901     if ($filterbranch && $filterbranch ne ""){ 
1902         $query.=" AND branchcode= ?";
1903         push @query_params,$filterbranch;
1904     }
1905     warn $query if $debug;
1906   
1907     my $sth = $dbh->prepare($query);
1908     if (scalar(@query_params)>0){  
1909         $sth->execute(@query_params);
1910     } 
1911     else {
1912         $sth->execute;
1913     }      
1914     
1915     my @results;
1916     while ( my $data = $sth->fetchrow_hashref ) {
1917         push @results, $data;
1918     }
1919     return \@results;
1920 }
1921
1922 =head2 GetBorrowersWithIssuesHistoryOlderThan
1923
1924 $results = &GetBorrowersWithIssuesHistoryOlderThan($date)
1925
1926 this function get all borrowers who has an issue history older than I<$date> given on input arg.
1927
1928 I<$result> is a ref to an array which all elements are a hashref.
1929 This hashref is containt the number of time this borrowers has borrowed before I<$date> and the borrowernumber.
1930
1931 =cut
1932
1933 sub GetBorrowersWithIssuesHistoryOlderThan {
1934     my $dbh  = C4::Context->dbh;
1935     my $date = shift ||POSIX::strftime("%Y-%m-%d",localtime());
1936     my $filterbranch = shift || 
1937                         ((C4::Context->preference('IndependantBranches') 
1938                              && C4::Context->userenv 
1939                              && C4::Context->userenv->{flags}!=1 
1940                              && C4::Context->userenv->{branch})
1941                          ? C4::Context->userenv->{branch}
1942                          : "");  
1943     my $query = "
1944        SELECT count(borrowernumber) as n,borrowernumber
1945        FROM old_issues
1946        WHERE returndate < ?
1947          AND borrowernumber IS NOT NULL 
1948     "; 
1949     my @query_params;
1950     push @query_params, $date;
1951     if ($filterbranch){
1952         $query.="   AND branchcode = ?";
1953         push @query_params, $filterbranch;
1954     }    
1955     $query.=" GROUP BY borrowernumber ";
1956     warn $query if $debug;
1957     my $sth = $dbh->prepare($query);
1958     $sth->execute(@query_params);
1959     my @results;
1960
1961     while ( my $data = $sth->fetchrow_hashref ) {
1962         push @results, $data;
1963     }
1964     return \@results;
1965 }
1966
1967 =head2 GetBorrowersNamesAndLatestIssue
1968
1969 $results = &GetBorrowersNamesAndLatestIssueList(@borrowernumbers)
1970
1971 this function get borrowers Names and surnames and Issue information.
1972
1973 I<@borrowernumbers> is an array which all elements are borrowernumbers.
1974 This hashref is containt the number of time this borrowers has borrowed before I<$date> and the borrowernumber.
1975
1976 =cut
1977
1978 sub GetBorrowersNamesAndLatestIssue {
1979     my $dbh  = C4::Context->dbh;
1980     my @borrowernumbers=@_;  
1981     my $query = "
1982        SELECT surname,lastname, phone, email,max(timestamp)
1983        FROM borrowers 
1984          LEFT JOIN issues ON borrowers.borrowernumber=issues.borrowernumber
1985        GROUP BY borrowernumber
1986    ";
1987     my $sth = $dbh->prepare($query);
1988     $sth->execute;
1989     my $results = $sth->fetchall_arrayref({});
1990     return $results;
1991 }
1992 END { }    # module clean-up code here (global destructor)
1993
1994 1;
1995
1996 __END__
1997
1998 =back
1999
2000 =head1 AUTHOR
2001
2002 Koha Team
2003
2004 =cut