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