patron cleaning - do not delete staff borrowers
[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 ($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     { push @parameters,"$_ = ".$dbh->quote($data{$_}) if ($_ ne 'borrowernumber' and $_ ne 'flags' and $hashborrowerfields{$_}); }
633     $query .= join (',',@parameters) . "\n WHERE borrowernumber=? \n";
634     $debug and print STDERR "$query (executed w/ arg: $data{'borrowernumber'})";
635     $sth = $dbh->prepare($query);
636     $sth->execute($data{'borrowernumber'});
637     $sth->finish;
638
639 # ok if its an adult (type) it may have borrowers that depend on it as a guarantor
640 # so when we update information for an adult we should check for guarantees and update the relevant part
641 # of their records, ie addresses and phone numbers
642     my $borrowercategory= GetBorrowercategory( $data{'category_type'} );
643     if ( $borrowercategory->{'category_type'} eq ('A' || 'S') ) {
644         # is adult check guarantees;
645         UpdateGuarantees(%data);
646     }
647     logaction("MEMBERS", "MODIFY", $data{'borrowernumber'}, "$query (executed w/ arg: $data{'borrowernumber'})") 
648         if C4::Context->preference("BorrowersLog");
649 }
650
651
652 =head2
653
654 =item AddMember
655
656   $borrowernumber = &AddMember(%borrower);
657
658 insert new borrower into table
659 Returns the borrowernumber
660
661 =cut
662
663 #'
664 sub AddMember {
665     my (%data) = @_;
666     my $dbh = C4::Context->dbh;
667     $data{'userid'} = '' unless $data{'password'};
668     $data{'password'} = md5_base64( $data{'password'} ) if $data{'password'};
669     
670     # WE SHOULD NEVER PASS THIS SUBROUTINE ANYTHING OTHER THAN ISO DATES
671     # IF YOU UNCOMMENT THESE LINES YOU BETTER HAVE A DARN COMPELLING REASON
672 #    $data{'dateofbirth'}  = format_date_in_iso( $data{'dateofbirth'} );
673 #    $data{'dateenrolled'} = format_date_in_iso( $data{'dateenrolled'});
674 #    $data{'dateexpiry'}   = format_date_in_iso( $data{'dateexpiry'}  );
675     # This query should be rewritten to use "?" at execute.
676     if (!$data{'dateofbirth'}){
677         undef ($data{'dateofbirth'});
678     }
679     my $query =
680         "insert into borrowers set cardnumber=" . $dbh->quote( $data{'cardnumber'} )
681       . ",surname="     . $dbh->quote( $data{'surname'} )
682       . ",firstname="   . $dbh->quote( $data{'firstname'} )
683       . ",title="       . $dbh->quote( $data{'title'} )
684       . ",othernames="  . $dbh->quote( $data{'othernames'} )
685       . ",initials="    . $dbh->quote( $data{'initials'} )
686       . ",streetnumber=". $dbh->quote( $data{'streetnumber'} )
687       . ",streettype="  . $dbh->quote( $data{'streettype'} )
688       . ",address="     . $dbh->quote( $data{'address'} )
689       . ",address2="    . $dbh->quote( $data{'address2'} )
690       . ",zipcode="     . $dbh->quote( $data{'zipcode'} )
691       . ",city="        . $dbh->quote( $data{'city'} )
692       . ",phone="       . $dbh->quote( $data{'phone'} )
693       . ",email="       . $dbh->quote( $data{'email'} )
694       . ",mobile="      . $dbh->quote( $data{'mobile'} )
695       . ",phonepro="    . $dbh->quote( $data{'phonepro'} )
696       . ",opacnote="    . $dbh->quote( $data{'opacnote'} )
697       . ",guarantorid=" . $dbh->quote( $data{'guarantorid'} )
698       . ",dateofbirth=" . $dbh->quote( $data{'dateofbirth'} )
699       . ",branchcode="  . $dbh->quote( $data{'branchcode'} )
700       . ",categorycode=" . $dbh->quote( $data{'categorycode'} )
701       . ",dateenrolled=" . $dbh->quote( $data{'dateenrolled'} )
702       . ",contactname=" . $dbh->quote( $data{'contactname'} )
703       . ",borrowernotes=" . $dbh->quote( $data{'borrowernotes'} )
704       . ",dateexpiry="  . $dbh->quote( $data{'dateexpiry'} )
705       . ",contactnote=" . $dbh->quote( $data{'contactnote'} )
706       . ",B_address="   . $dbh->quote( $data{'B_address'} )
707       . ",B_zipcode="   . $dbh->quote( $data{'B_zipcode'} )
708       . ",B_city="      . $dbh->quote( $data{'B_city'} )
709       . ",B_phone="     . $dbh->quote( $data{'B_phone'} )
710       . ",B_email="     . $dbh->quote( $data{'B_email'} )
711       . ",password="    . $dbh->quote( $data{'password'} )
712       . ",userid="      . $dbh->quote( $data{'userid'} )
713       . ",sort1="       . $dbh->quote( $data{'sort1'} )
714       . ",sort2="       . $dbh->quote( $data{'sort2'} )
715       . ",contacttitle=" . $dbh->quote( $data{'contacttitle'} )
716       . ",emailpro="    . $dbh->quote( $data{'emailpro'} )
717       . ",contactfirstname=" . $dbh->quote( $data{'contactfirstname'} )
718       . ",sex="         . $dbh->quote( $data{'sex'} )
719       . ",fax="         . $dbh->quote( $data{'fax'} )
720       . ",relationship=" . $dbh->quote( $data{'relationship'} )
721       . ",B_streetnumber=" . $dbh->quote( $data{'B_streetnumber'} )
722       . ",B_streettype=" . $dbh->quote( $data{'B_streettype'} )
723       . ",gonenoaddress=" . $dbh->quote( $data{'gonenoaddress'} )
724       . ",lost="        . $dbh->quote( $data{'lost'} )
725       . ",debarred="    . $dbh->quote( $data{'debarred'} )
726       . ",ethnicity="   . $dbh->quote( $data{'ethnicity'} )
727       . ",ethnotes="    . $dbh->quote( $data{'ethnotes'} ) 
728       . ",altcontactsurname="   . $dbh->quote( $data{'altcontactsurname'} ) 
729       . ",altcontactfirstname="     . $dbh->quote( $data{'altcontactfirstname'} ) 
730       . ",altcontactaddress1="  . $dbh->quote( $data{'altcontactaddress1'} ) 
731       . ",altcontactaddress2="  . $dbh->quote( $data{'altcontactaddress2'} ) 
732       . ",altcontactaddress3="  . $dbh->quote( $data{'altcontactaddress3'} ) 
733       . ",altcontactzipcode="   . $dbh->quote( $data{'altcontactzipcode'} ) 
734       . ",altcontactphone="     . $dbh->quote( $data{'altcontactphone'} ) ;
735     $debug and print STDERR "AddMember SQL: ($query)\n";
736     my $sth = $dbh->prepare($query);
737     #   print "Executing SQL: $query\n";
738     $sth->execute();
739     $sth->finish;
740     $data{'borrowernumber'} = $dbh->{'mysql_insertid'};     # unneeded w/ autoincrement ?  
741     # mysql_insertid is probably bad.  not necessarily accurate and mysql-specific at best.
742     
743     logaction("MEMBERS", "CREATE", $data{'borrowernumber'}, "") if C4::Context->preference("BorrowersLog");
744     
745     # check for enrollment fee & add it if needed
746     $sth = $dbh->prepare("SELECT enrolmentfee FROM categories WHERE categorycode=?");
747     $sth->execute($data{'categorycode'});
748     my ($enrolmentfee) = $sth->fetchrow;
749     if ($enrolmentfee) {
750         # insert fee in patron debts
751         manualinvoice($data{'borrowernumber'}, '', '', 'A', $enrolmentfee);
752     }
753     return $data{'borrowernumber'};
754 }
755
756 sub Check_Userid {
757     my ($uid,$member) = @_;
758     my $dbh = C4::Context->dbh;
759     # Make sure the userid chosen is unique and not theirs if non-empty. If it is not,
760     # Then we need to tell the user and have them create a new one.
761     my $sth =
762       $dbh->prepare(
763         "SELECT * FROM borrowers WHERE userid=? AND borrowernumber != ?");
764     $sth->execute( $uid, $member );
765     if ( ( $uid ne '' ) && ( my $row = $sth->fetchrow_hashref ) ) {
766         return 0;
767     }
768     else {
769         return 1;
770     }
771 }
772
773
774 sub changepassword {
775     my ( $uid, $member, $digest ) = @_;
776     my $dbh = C4::Context->dbh;
777
778 #Make sure the userid chosen is unique and not theirs if non-empty. If it is not,
779 #Then we need to tell the user and have them create a new one.
780     my $resultcode;
781     my $sth =
782       $dbh->prepare(
783         "SELECT * FROM borrowers WHERE userid=? AND borrowernumber != ?");
784     $sth->execute( $uid, $member );
785     if ( ( $uid ne '' ) && ( my $row = $sth->fetchrow_hashref ) ) {
786         $resultcode=0;
787     }
788     else {
789         #Everything is good so we can update the information.
790         $sth =
791           $dbh->prepare(
792             "update borrowers set userid=?, password=? where borrowernumber=?");
793         $sth->execute( $uid, $digest, $member );
794         $resultcode=1;
795     }
796     
797     logaction("MEMBERS", "CHANGE PASS", $member, "") if C4::Context->preference("BorrowersLog");
798     return $resultcode;    
799 }
800
801
802
803 =item fixup_cardnumber
804
805 Warning: The caller is responsible for locking the members table in write
806 mode, to avoid database corruption.
807
808 =cut
809
810 use vars qw( @weightings );
811 my @weightings = ( 8, 4, 6, 3, 5, 2, 1 );
812
813 sub fixup_cardnumber ($) {
814     my ($cardnumber) = @_;
815     my $autonumber_members = C4::Context->boolean_preference('autoMemberNum');
816     $autonumber_members = 0 unless defined $autonumber_members;
817
818     # Find out whether member numbers should be generated
819     # automatically. Should be either "1" or something else.
820     # Defaults to "0", which is interpreted as "no".
821
822     #     if ($cardnumber !~ /\S/ && $autonumber_members) {
823     if ($autonumber_members) {
824         my $dbh = C4::Context->dbh;
825         if ( C4::Context->preference('checkdigit') eq 'katipo' ) {
826
827             # if checkdigit is selected, calculate katipo-style cardnumber.
828             # otherwise, just use the max()
829             # purpose: generate checksum'd member numbers.
830             # We'll assume we just got the max value of digits 2-8 of member #'s
831             # from the database and our job is to increment that by one,
832             # determine the 1st and 9th digits and return the full string.
833             my $sth =
834               $dbh->prepare(
835                 "select max(substring(borrowers.cardnumber,2,7)) from borrowers"
836               );
837             $sth->execute;
838
839             my $data = $sth->fetchrow_hashref;
840             $cardnumber = $data->{'max(substring(borrowers.cardnumber,2,7))'};
841             $sth->finish;
842             if ( !$cardnumber ) {    # If DB has no values,
843                 $cardnumber = 1000000;    # start at 1000000
844             }
845             else {
846                 $cardnumber += 1;
847             }
848
849             my $sum = 0;
850             for ( my $i = 0 ; $i < 8 ; $i += 1 ) {
851
852                 # read weightings, left to right, 1 char at a time
853                 my $temp1 = $weightings[$i];
854
855                 # sequence left to right, 1 char at a time
856                 my $temp2 = substr( $cardnumber, $i, 1 );
857
858                 # mult each char 1-7 by its corresponding weighting
859                 $sum += $temp1 * $temp2;
860             }
861
862             my $rem = ( $sum % 11 );
863             $rem = 'X' if $rem == 10;
864
865             $cardnumber = "V$cardnumber$rem";
866         }
867         else {
868
869      # MODIFIED BY JF: mysql4.1 allows casting as an integer, which is probably
870      # better. I'll leave the original in in case it needs to be changed for you
871             my $sth =
872               $dbh->prepare(
873                 "select max(cast(cardnumber as signed)) from borrowers");
874
875       #my $sth=$dbh->prepare("select max(borrowers.cardnumber) from borrowers");
876
877             $sth->execute;
878
879             my ($result) = $sth->fetchrow;
880             $sth->finish;
881             $cardnumber = $result + 1;
882         }
883     }
884     return $cardnumber;
885 }
886
887 =head2 GetGuarantees
888
889   ($num_children, $children_arrayref) = &GetGuarantees($parent_borrno);
890   $child0_cardno = $children_arrayref->[0]{"cardnumber"};
891   $child0_borrno = $children_arrayref->[0]{"borrowernumber"};
892
893 C<&GetGuarantees> takes a borrower number (e.g., that of a patron
894 with children) and looks up the borrowers who are guaranteed by that
895 borrower (i.e., the patron's children).
896
897 C<&GetGuarantees> returns two values: an integer giving the number of
898 borrowers guaranteed by C<$parent_borrno>, and a reference to an array
899 of references to hash, which gives the actual results.
900
901 =cut
902
903 #'
904 sub GetGuarantees {
905     my ($borrowernumber) = @_;
906     my $dbh              = C4::Context->dbh;
907     my $sth              =
908       $dbh->prepare(
909 "select cardnumber,borrowernumber, firstname, surname from borrowers where guarantorid=?"
910       );
911     $sth->execute($borrowernumber);
912
913     my @dat;
914     my $data = $sth->fetchall_arrayref({}); 
915     $sth->finish;
916     return ( scalar(@$data), $data );
917 }
918
919 =head2 UpdateGuarantees
920
921   &UpdateGuarantees($parent_borrno);
922   
923
924 C<&UpdateGuarantees> borrower data for an adulte and updates all the guarantees
925 with the modified information
926
927 =cut
928
929 #'
930 sub UpdateGuarantees {
931     my (%data) = @_;
932     my $dbh = C4::Context->dbh;
933     my ( $count, $guarantees ) = GetGuarantees( $data{'borrowernumber'} );
934     for ( my $i = 0 ; $i < $count ; $i++ ) {
935
936         # FIXME
937         # It looks like the $i is only being returned to handle walking through
938         # the array, which is probably better done as a foreach loop.
939         #
940         my $guaquery = qq|UPDATE borrowers 
941               SET address='$data{'address'}',fax='$data{'fax'}',
942                   B_city='$data{'B_city'}',mobile='$data{'mobile'}',city='$data{'city'}',phone='$data{'phone'}'
943               WHERE borrowernumber='$guarantees->[$i]->{'borrowernumber'}'
944         |;
945         my $sth3 = $dbh->prepare($guaquery);
946         $sth3->execute;
947         $sth3->finish;
948     }
949 }
950 =head2 GetPendingIssues
951
952   ($count, $issues) = &GetPendingIssues($borrowernumber);
953
954 Looks up what the patron with the given borrowernumber has borrowed.
955
956 C<&GetPendingIssues> returns a two-element array. C<$issues> is a
957 reference-to-array, where each element is a reference-to-hash; the
958 keys are the fields from the C<issues>, C<biblio>, and C<items> tables
959 in the Koha database. C<$count> is the number of elements in
960 C<$issues>.
961
962 =cut
963
964 #'
965 sub GetPendingIssues {
966     my ($borrowernumber) = @_;
967     my $dbh              = C4::Context->dbh;
968
969     my $sth              = $dbh->prepare(
970    "SELECT * FROM issues 
971       LEFT JOIN items ON issues.itemnumber=items.itemnumber
972       LEFT JOIN biblio ON     items.biblionumber=biblio.biblionumber 
973       LEFT JOIN biblioitems ON items.biblioitemnumber=biblioitems.biblioitemnumber
974     WHERE
975       borrowernumber=? 
976     ORDER BY issues.issuedate"
977     );
978     $sth->execute($borrowernumber);
979     my $data = $sth->fetchall_arrayref({});
980     my $today = POSIX::strftime("%Y%m%d", localtime);
981     foreach( @$data ) {
982         my $datedue = $_->{'date_due'};
983         $datedue =~ s/-//g;
984         if ( $datedue < $today ) {
985             $_->{'overdue'} = 1;
986         }
987     }
988     $sth->finish;
989     return ( scalar(@$data), $data );
990 }
991
992 =head2 GetAllIssues
993
994   ($count, $issues) = &GetAllIssues($borrowernumber, $sortkey, $limit);
995
996 Looks up what the patron with the given borrowernumber has borrowed,
997 and sorts the results.
998
999 C<$sortkey> is the name of a field on which to sort the results. This
1000 should be the name of a field in the C<issues>, C<biblio>,
1001 C<biblioitems>, or C<items> table in the Koha database.
1002
1003 C<$limit> is the maximum number of results to return.
1004
1005 C<&GetAllIssues> returns a two-element array. C<$issues> is a
1006 reference-to-array, where each element is a reference-to-hash; the
1007 keys are the fields from the C<issues>, C<biblio>, C<biblioitems>, and
1008 C<items> tables of the Koha database. C<$count> is the number of
1009 elements in C<$issues>
1010
1011 =cut
1012
1013 #'
1014 sub GetAllIssues {
1015     my ( $borrowernumber, $order, $limit ) = @_;
1016
1017     #FIXME: sanity-check order and limit
1018     my $dbh   = C4::Context->dbh;
1019     my $count = 0;
1020     my $query =
1021   "SELECT *,items.timestamp AS itemstimestamp 
1022   FROM issues 
1023   LEFT JOIN items on items.itemnumber=issues.itemnumber
1024   LEFT JOIN biblio ON items.biblionumber=biblio.biblionumber
1025   LEFT JOIN biblioitems ON items.biblioitemnumber=biblioitems.biblioitemnumber
1026   WHERE borrowernumber=? 
1027   UNION ALL
1028   SELECT *,items.timestamp AS itemstimestamp 
1029   FROM old_issues 
1030   LEFT JOIN items on items.itemnumber=old_issues.itemnumber
1031   LEFT JOIN biblio ON items.biblionumber=biblio.biblionumber
1032   LEFT JOIN biblioitems ON items.biblioitemnumber=biblioitems.biblioitemnumber
1033   WHERE borrowernumber=? 
1034   order by $order";
1035     if ( $limit != 0 ) {
1036         $query .= " limit $limit";
1037     }
1038
1039     #print $query;
1040     my $sth = $dbh->prepare($query);
1041     $sth->execute($borrowernumber, $borrowernumber);
1042     my @result;
1043     my $i = 0;
1044     while ( my $data = $sth->fetchrow_hashref ) {
1045         $result[$i] = $data;
1046         $i++;
1047         $count++;
1048     }
1049
1050     # get all issued items for borrowernumber from oldissues table
1051     # large chunk of older issues data put into table oldissues
1052     # to speed up db calls for issuing items
1053     if ( C4::Context->preference("ReadingHistory") ) {
1054         # FIXME oldissues (not to be confused with old_issues) is
1055         # apparently specific to HLT.  Not sure if the ReadingHistory
1056         # syspref is still required, as old_issues by design
1057         # is no longer checked with each loan.
1058         my $query2 = "SELECT * FROM oldissues
1059                       LEFT JOIN items ON items.itemnumber=oldissues.itemnumber
1060                       LEFT JOIN biblio ON items.biblionumber=biblio.biblionumber
1061                       LEFT JOIN biblioitems ON items.biblioitemnumber=biblioitems.biblioitemnumber
1062                       WHERE borrowernumber=? 
1063                       ORDER BY $order";
1064         if ( $limit != 0 ) {
1065             $limit = $limit - $count;
1066             $query2 .= " limit $limit";
1067         }
1068
1069         my $sth2 = $dbh->prepare($query2);
1070         $sth2->execute($borrowernumber);
1071
1072         while ( my $data2 = $sth2->fetchrow_hashref ) {
1073             $result[$i] = $data2;
1074             $i++;
1075         }
1076         $sth2->finish;
1077     }
1078     $sth->finish;
1079
1080     return ( $i, \@result );
1081 }
1082
1083
1084 =head2 GetMemberAccountRecords
1085
1086   ($total, $acctlines, $count) = &GetMemberAccountRecords($borrowernumber);
1087
1088 Looks up accounting data for the patron with the given borrowernumber.
1089
1090 C<&GetMemberAccountRecords> returns a three-element array. C<$acctlines> is a
1091 reference-to-array, where each element is a reference-to-hash; the
1092 keys are the fields of the C<accountlines> table in the Koha database.
1093 C<$count> is the number of elements in C<$acctlines>. C<$total> is the
1094 total amount outstanding for all of the account lines.
1095
1096 =cut
1097
1098 #'
1099 sub GetMemberAccountRecords {
1100     my ($borrowernumber,$date) = @_;
1101     my $dbh = C4::Context->dbh;
1102     my @acctlines;
1103     my $numlines = 0;
1104     my $strsth      = qq(
1105                         SELECT * 
1106                         FROM accountlines 
1107                         WHERE borrowernumber=?);
1108     my @bind = ($borrowernumber);
1109     if ($date && $date ne ''){
1110             $strsth.=" AND date < ? ";
1111             push(@bind,$date);
1112     }
1113     $strsth.=" ORDER BY date desc,timestamp DESC";
1114     my $sth= $dbh->prepare( $strsth );
1115     $sth->execute( @bind );
1116     my $total = 0;
1117     while ( my $data = $sth->fetchrow_hashref ) {
1118         $acctlines[$numlines] = $data;
1119         $numlines++;
1120         $total += $data->{'amountoutstanding'};
1121     }
1122     $sth->finish;
1123     return ( $total, \@acctlines,$numlines);
1124 }
1125
1126 =head2 GetBorNotifyAcctRecord
1127
1128   ($count, $acctlines, $total) = &GetBorNotifyAcctRecord($params,$notifyid);
1129
1130 Looks up accounting data for the patron with the given borrowernumber per file number.
1131
1132 (FIXME - I'm not at all sure what this is about.)
1133
1134 C<&GetBorNotifyAcctRecord> returns a three-element array. C<$acctlines> is a
1135 reference-to-array, where each element is a reference-to-hash; the
1136 keys are the fields of the C<accountlines> table in the Koha database.
1137 C<$count> is the number of elements in C<$acctlines>. C<$total> is the
1138 total amount outstanding for all of the account lines.
1139
1140 =cut
1141
1142 sub GetBorNotifyAcctRecord {
1143     my ( $borrowernumber, $notifyid ) = @_;
1144     my $dbh = C4::Context->dbh;
1145     my @acctlines;
1146     my $numlines = 0;
1147     my $sth = $dbh->prepare(
1148             "SELECT * 
1149                 FROM accountlines 
1150                 WHERE borrowernumber=? 
1151                     AND notify_id=? 
1152                     AND amountoutstanding != '0' 
1153                 ORDER BY notify_id,accounttype
1154                 ");
1155 #                    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')
1156
1157     $sth->execute( $borrowernumber, $notifyid );
1158     my $total = 0;
1159     while ( my $data = $sth->fetchrow_hashref ) {
1160         $acctlines[$numlines] = $data;
1161         $numlines++;
1162         $total += $data->{'amountoutstanding'};
1163     }
1164     $sth->finish;
1165     return ( $total, \@acctlines, $numlines );
1166 }
1167
1168 =head2 checkuniquemember (OUEST-PROVENCE)
1169
1170   ($result,$categorycode)  = &checkuniquemember($collectivity,$surname,$firstname,$dateofbirth);
1171
1172 Checks that a member exists or not in the database.
1173
1174 C<&result> is nonzero (=exist) or 0 (=does not exist)
1175 C<&categorycode> is from categorycode table
1176 C<&collectivity> is 1 (= we add a collectivity) or 0 (= we add a physical member)
1177 C<&surname> is the surname
1178 C<&firstname> is the firstname (only if collectivity=0)
1179 C<&dateofbirth> is the date of birth in ISO format (only if collectivity=0)
1180
1181 =cut
1182
1183 # FIXME: This function is not legitimate.  Multiple patrons might have the same first/last name and birthdate.
1184 # This is especially true since first name is not even a required field.
1185
1186 sub checkuniquemember {
1187     my ( $collectivity, $surname, $firstname, $dateofbirth ) = @_;
1188     my $dbh = C4::Context->dbh;
1189     my $request = ($collectivity) ?
1190         "SELECT borrowernumber,categorycode FROM borrowers WHERE surname=? " :
1191         "SELECT borrowernumber,categorycode FROM borrowers WHERE surname=? and firstname=? and dateofbirth=? ";
1192     my $sth = $dbh->prepare($request);
1193     if ($collectivity) {
1194         $sth->execute( uc($surname) );
1195     } else {
1196         $sth->execute( uc($surname), ucfirst($firstname), $dateofbirth );
1197     }
1198     my @data = $sth->fetchrow;
1199     $sth->finish;
1200     ( $data[0] ) and return $data[0], $data[1];
1201     return 0;
1202 }
1203
1204 sub checkcardnumber {
1205     my ($cardnumber,$borrowernumber) = @_;
1206     my $dbh = C4::Context->dbh;
1207     my $query = "SELECT * FROM borrowers WHERE cardnumber=?";
1208     $query .= " AND borrowernumber <> ?" if ($borrowernumber);
1209   my $sth = $dbh->prepare($query);
1210   if ($borrowernumber) {
1211    $sth->execute($cardnumber,$borrowernumber);
1212   } else { 
1213      $sth->execute($cardnumber);
1214   } 
1215     if (my $data= $sth->fetchrow_hashref()){
1216         return 1;
1217     }
1218     else {
1219         return 0;
1220     }
1221     $sth->finish();
1222 }  
1223
1224
1225 =head2 getzipnamecity (OUEST-PROVENCE)
1226
1227 take all info from table city for the fields city and  zip
1228 check for the name and the zip code of the city selected
1229
1230 =cut
1231
1232 sub getzipnamecity {
1233     my ($cityid) = @_;
1234     my $dbh      = C4::Context->dbh;
1235     my $sth      =
1236       $dbh->prepare(
1237         "select city_name,city_zipcode from cities where cityid=? ");
1238     $sth->execute($cityid);
1239     my @data = $sth->fetchrow;
1240     return $data[0], $data[1];
1241 }
1242
1243
1244 =head2 getdcity (OUEST-PROVENCE)
1245
1246 recover cityid  with city_name condition
1247
1248 =cut
1249
1250 sub getidcity {
1251     my ($city_name) = @_;
1252     my $dbh = C4::Context->dbh;
1253     my $sth = $dbh->prepare("select cityid from cities where city_name=? ");
1254     $sth->execute($city_name);
1255     my $data = $sth->fetchrow;
1256     return $data;
1257 }
1258
1259
1260 =head2 GetExpiryDate 
1261
1262   $expirydate = GetExpiryDate($categorycode, $dateenrolled);
1263
1264 Calculate expiry date given a categorycode and starting date.  Date argument must be in ISO format.
1265 Return date is also in ISO format.
1266
1267 =cut
1268
1269 sub GetExpiryDate {
1270     my ( $categorycode, $dateenrolled ) = @_;
1271     my $enrolmentperiod = 12;   # reasonable default
1272     if ($categorycode) {
1273         my $dbh = C4::Context->dbh;
1274         my $sth = $dbh->prepare("select enrolmentperiod from categories where categorycode=?");
1275         $sth->execute($categorycode);
1276         $enrolmentperiod = $sth->fetchrow;
1277     }
1278     # die "GetExpiryDate: for enrollmentperiod $enrolmentperiod (category '$categorycode') starting $dateenrolled.\n";
1279     my @date = split /-/,$dateenrolled;
1280     return sprintf("%04d-%02d-%02d", Add_Delta_YM(@date,0,$enrolmentperiod));
1281 }
1282
1283 =head2 checkuserpassword (OUEST-PROVENCE)
1284
1285 check for the password and login are not used
1286 return the number of record 
1287 0=> NOT USED 1=> USED
1288
1289 =cut
1290
1291 sub checkuserpassword {
1292     my ( $borrowernumber, $userid, $password ) = @_;
1293     $password = md5_base64($password);
1294     my $dbh = C4::Context->dbh;
1295     my $sth =
1296       $dbh->prepare(
1297 "Select count(*) from borrowers where borrowernumber !=? and userid =? and password=? "
1298       );
1299     $sth->execute( $borrowernumber, $userid, $password );
1300     my $number_rows = $sth->fetchrow;
1301     return $number_rows;
1302
1303 }
1304
1305 =head2 GetborCatFromCatType
1306
1307   ($codes_arrayref, $labels_hashref) = &GetborCatFromCatType();
1308
1309 Looks up the different types of borrowers in the database. Returns two
1310 elements: a reference-to-array, which lists the borrower category
1311 codes, and a reference-to-hash, which maps the borrower category codes
1312 to category descriptions.
1313
1314 =cut
1315
1316 #'
1317 sub GetborCatFromCatType {
1318     my ( $category_type, $action ) = @_;
1319     my $dbh     = C4::Context->dbh;
1320     my $request = qq|   SELECT categorycode,description 
1321             FROM categories 
1322             $action
1323             ORDER BY categorycode|;
1324     my $sth = $dbh->prepare($request);
1325     if ($action) {
1326         $sth->execute($category_type);
1327     }
1328     else {
1329         $sth->execute();
1330     }
1331
1332     my %labels;
1333     my @codes;
1334
1335     while ( my $data = $sth->fetchrow_hashref ) {
1336         push @codes, $data->{'categorycode'};
1337         $labels{ $data->{'categorycode'} } = $data->{'description'};
1338     }
1339     $sth->finish;
1340     return ( \@codes, \%labels );
1341 }
1342
1343 =head2 GetBorrowercategory
1344
1345   $hashref = &GetBorrowercategory($categorycode);
1346
1347 Given the borrower's category code, the function returns the corresponding
1348 data hashref for a comprehensive information display.
1349   
1350   $arrayref_hashref = &GetBorrowercategory;
1351 If no category code provided, the function returns all the categories.
1352
1353 =cut
1354
1355 sub GetBorrowercategory {
1356     my ($catcode) = @_;
1357     my $dbh       = C4::Context->dbh;
1358     if ($catcode){
1359         my $sth       =
1360         $dbh->prepare(
1361     "SELECT description,dateofbirthrequired,upperagelimit,category_type 
1362     FROM categories 
1363     WHERE categorycode = ?"
1364         );
1365         $sth->execute($catcode);
1366         my $data =
1367         $sth->fetchrow_hashref;
1368         $sth->finish();
1369         return $data;
1370     } 
1371     return;  
1372 }    # sub getborrowercategory
1373
1374 =head2 GetBorrowercategoryList
1375  
1376   $arrayref_hashref = &GetBorrowercategoryList;
1377 If no category code provided, the function returns all the categories.
1378
1379 =cut
1380
1381 sub GetBorrowercategoryList {
1382     my $dbh       = C4::Context->dbh;
1383     my $sth       =
1384     $dbh->prepare(
1385     "SELECT * 
1386     FROM categories 
1387     ORDER BY description"
1388         );
1389     $sth->execute;
1390     my $data =
1391     $sth->fetchall_arrayref({});
1392     $sth->finish();
1393     return $data;
1394 }    # sub getborrowercategory
1395
1396 =head2 ethnicitycategories
1397
1398   ($codes_arrayref, $labels_hashref) = &ethnicitycategories();
1399
1400 Looks up the different ethnic types in the database. Returns two
1401 elements: a reference-to-array, which lists the ethnicity codes, and a
1402 reference-to-hash, which maps the ethnicity codes to ethnicity
1403 descriptions.
1404
1405 =cut
1406
1407 #'
1408
1409 sub ethnicitycategories {
1410     my $dbh = C4::Context->dbh;
1411     my $sth = $dbh->prepare("Select code,name from ethnicity order by name");
1412     $sth->execute;
1413     my %labels;
1414     my @codes;
1415     while ( my $data = $sth->fetchrow_hashref ) {
1416         push @codes, $data->{'code'};
1417         $labels{ $data->{'code'} } = $data->{'name'};
1418     }
1419     $sth->finish;
1420     return ( \@codes, \%labels );
1421 }
1422
1423 =head2 fixEthnicity
1424
1425   $ethn_name = &fixEthnicity($ethn_code);
1426
1427 Takes an ethnicity code (e.g., "european" or "pi") and returns the
1428 corresponding descriptive name from the C<ethnicity> table in the
1429 Koha database ("European" or "Pacific Islander").
1430
1431 =cut
1432
1433 #'
1434
1435 sub fixEthnicity {
1436     my $ethnicity = shift;
1437     return unless $ethnicity;
1438     my $dbh       = C4::Context->dbh;
1439     my $sth       = $dbh->prepare("Select name from ethnicity where code = ?");
1440     $sth->execute($ethnicity);
1441     my $data = $sth->fetchrow_hashref;
1442     $sth->finish;
1443     return $data->{'name'};
1444 }    # sub fixEthnicity
1445
1446 =head2 GetAge
1447
1448   $dateofbirth,$date = &GetAge($date);
1449
1450 this function return the borrowers age with the value of dateofbirth
1451
1452 =cut
1453
1454 #'
1455 sub GetAge{
1456     my ( $date, $date_ref ) = @_;
1457
1458     if ( not defined $date_ref ) {
1459         $date_ref = sprintf( '%04d-%02d-%02d', Today() );
1460     }
1461
1462     my ( $year1, $month1, $day1 ) = split /-/, $date;
1463     my ( $year2, $month2, $day2 ) = split /-/, $date_ref;
1464
1465     my $age = $year2 - $year1;
1466     if ( $month1 . $day1 > $month2 . $day2 ) {
1467         $age--;
1468     }
1469
1470     return $age;
1471 }    # sub get_age
1472
1473 =head2 get_institutions
1474   $insitutions = get_institutions();
1475
1476 Just returns a list of all the borrowers of type I, borrownumber and name
1477
1478 =cut
1479
1480 #'
1481 sub get_institutions {
1482     my $dbh = C4::Context->dbh();
1483     my $sth =
1484       $dbh->prepare(
1485 "SELECT borrowernumber,surname FROM borrowers WHERE categorycode=? ORDER BY surname"
1486       );
1487     $sth->execute('I');
1488     my %orgs;
1489     while ( my $data = $sth->fetchrow_hashref() ) {
1490         $orgs{ $data->{'borrowernumber'} } = $data;
1491     }
1492     $sth->finish();
1493     return ( \%orgs );
1494
1495 }    # sub get_institutions
1496
1497 =head2 add_member_orgs
1498
1499   add_member_orgs($borrowernumber,$borrowernumbers);
1500
1501 Takes a borrowernumber and a list of other borrowernumbers and inserts them into the borrowers_to_borrowers table
1502
1503 =cut
1504
1505 #'
1506 sub add_member_orgs {
1507     my ( $borrowernumber, $otherborrowers ) = @_;
1508     my $dbh   = C4::Context->dbh();
1509     my $query =
1510       "INSERT INTO borrowers_to_borrowers (borrower1,borrower2) VALUES (?,?)";
1511     my $sth = $dbh->prepare($query);
1512     foreach my $otherborrowernumber (@$otherborrowers) {
1513         $sth->execute( $borrowernumber, $otherborrowernumber );
1514     }
1515     $sth->finish();
1516
1517 }    # sub add_member_orgs
1518
1519 =head2 GetCities (OUEST-PROVENCE)
1520
1521   ($id_cityarrayref, $city_hashref) = &GetCities();
1522
1523 Looks up the different city and zip in the database. Returns two
1524 elements: a reference-to-array, which lists the zip city
1525 codes, and a reference-to-hash, which maps the name of the city.
1526 WHERE =>OUEST PROVENCE OR EXTERIEUR
1527
1528 =cut
1529
1530 sub GetCities {
1531
1532     #my ($type_city) = @_;
1533     my $dbh   = C4::Context->dbh;
1534     my $query = qq|SELECT cityid,city_zipcode,city_name 
1535         FROM cities 
1536         ORDER BY city_name|;
1537     my $sth = $dbh->prepare($query);
1538
1539     #$sth->execute($type_city);
1540     $sth->execute();
1541     my %city;
1542     my @id;
1543     #    insert empty value to create a empty choice in cgi popup
1544     push @id, " ";
1545     $city{""} = "";
1546     while ( my $data = $sth->fetchrow_hashref ) {
1547         push @id, $data->{'city_zipcode'}."|".$data->{'city_name'};
1548         $city{ $data->{'city_zipcode'}."|".$data->{'city_name'} } = $data->{'city_name'};
1549     }
1550
1551 #test to know if the table contain some records if no the function return nothing
1552     my $id = @id;
1553     $sth->finish;
1554     if ( $id == 1 ) {
1555         # all we have is the one blank row
1556         return ();
1557     }
1558     else {
1559         unshift( @id, "" );
1560         return ( \@id, \%city );
1561     }
1562 }
1563
1564 =head2 GetSortDetails (OUEST-PROVENCE)
1565
1566   ($lib) = &GetSortDetails($category,$sortvalue);
1567
1568 Returns the authorized value  details
1569 C<&$lib>return value of authorized value details
1570 C<&$sortvalue>this is the value of authorized value 
1571 C<&$category>this is the value of authorized value category
1572
1573 =cut
1574
1575 sub GetSortDetails {
1576     my ( $category, $sortvalue ) = @_;
1577     my $dbh   = C4::Context->dbh;
1578     my $query = qq|SELECT lib 
1579         FROM authorised_values 
1580         WHERE category=?
1581         AND authorised_value=? |;
1582     my $sth = $dbh->prepare($query);
1583     $sth->execute( $category, $sortvalue );
1584     my $lib = $sth->fetchrow;
1585     return ($lib) if ($lib);
1586     return ($sortvalue) unless ($lib);
1587 }
1588
1589 =head2 DeleteBorrower 
1590
1591   () = &DeleteBorrower($member);
1592
1593 delete all data fo borrowers and add record to deletedborrowers table
1594 C<&$member>this is the borrowernumber
1595
1596 =cut
1597
1598 sub MoveMemberToDeleted {
1599     my ($member) = @_;
1600     my $dbh = C4::Context->dbh;
1601     my $query;
1602     $query = qq|SELECT * 
1603           FROM borrowers 
1604           WHERE borrowernumber=?|;
1605     my $sth = $dbh->prepare($query);
1606     $sth->execute($member);
1607     my @data = $sth->fetchrow_array;
1608     $sth->finish;
1609     $sth =
1610       $dbh->prepare( "INSERT INTO deletedborrowers VALUES ("
1611           . ( "?," x ( scalar(@data) - 1 ) )
1612           . "?)" );
1613     $sth->execute(@data);
1614     $sth->finish;
1615 }
1616
1617 =head2 DelMember
1618
1619 DelMember($borrowernumber);
1620
1621 This function remove directly a borrower whitout writing it on deleteborrower.
1622 + Deletes reserves for the borrower
1623
1624 =cut
1625
1626 sub DelMember {
1627     my $dbh            = C4::Context->dbh;
1628     my $borrowernumber = shift;
1629     #warn "in delmember with $borrowernumber";
1630     return unless $borrowernumber;    # borrowernumber is mandatory.
1631
1632     my $query = qq|DELETE 
1633           FROM  reserves 
1634           WHERE borrowernumber=?|;
1635     my $sth = $dbh->prepare($query);
1636     $sth->execute($borrowernumber);
1637     $sth->finish;
1638     $query = "
1639        DELETE
1640        FROM borrowers
1641        WHERE borrowernumber = ?
1642    ";
1643     $sth = $dbh->prepare($query);
1644     $sth->execute($borrowernumber);
1645     $sth->finish;
1646     logaction("MEMBERS", "DELETE", $borrowernumber, "") if C4::Context->preference("BorrowersLog");
1647     return $sth->rows;
1648 }
1649
1650 =head2 ExtendMemberSubscriptionTo (OUEST-PROVENCE)
1651
1652     $date = ExtendMemberSubscriptionTo($borrowerid, $date);
1653
1654 Extending the subscription to a given date or to the expiry date calculated on ISO date.
1655 Returns ISO date.
1656
1657 =cut
1658
1659 sub ExtendMemberSubscriptionTo {
1660     my ( $borrowerid,$date) = @_;
1661     my $dbh = C4::Context->dbh;
1662     my $borrower = GetMember($borrowerid,'borrowernumber');
1663     unless ($date){
1664       $date=POSIX::strftime("%Y-%m-%d",localtime());
1665       my $borrower = GetMember($borrowerid,'borrowernumber');
1666       $date = GetExpiryDate( $borrower->{'categorycode'}, $date );
1667     }
1668     my $sth = $dbh->do(<<EOF);
1669 UPDATE borrowers 
1670 SET  dateexpiry='$date' 
1671 WHERE borrowernumber='$borrowerid'
1672 EOF
1673     # add enrolmentfee if needed
1674     $sth = $dbh->prepare("SELECT enrolmentfee FROM categories WHERE categorycode=?");
1675     $sth->execute($borrower->{'categorycode'});
1676     my ($enrolmentfee) = $sth->fetchrow;
1677     if ($enrolmentfee) {
1678         # insert fee in patron debts
1679         manualinvoice($borrower->{'borrowernumber'}, '', '', 'A', $enrolmentfee);
1680     }
1681     return $date if ($sth);
1682     return 0;
1683 }
1684
1685 =head2 GetRoadTypes (OUEST-PROVENCE)
1686
1687   ($idroadtypearrayref, $roadttype_hashref) = &GetRoadTypes();
1688
1689 Looks up the different road type . Returns two
1690 elements: a reference-to-array, which lists the id_roadtype
1691 codes, and a reference-to-hash, which maps the road type of the road .
1692
1693 =cut
1694
1695 sub GetRoadTypes {
1696     my $dbh   = C4::Context->dbh;
1697     my $query = qq|
1698 SELECT roadtypeid,road_type 
1699 FROM roadtype 
1700 ORDER BY road_type|;
1701     my $sth = $dbh->prepare($query);
1702     $sth->execute();
1703     my %roadtype;
1704     my @id;
1705
1706     #    insert empty value to create a empty choice in cgi popup
1707
1708     while ( my $data = $sth->fetchrow_hashref ) {
1709
1710         push @id, $data->{'roadtypeid'};
1711         $roadtype{ $data->{'roadtypeid'} } = $data->{'road_type'};
1712     }
1713
1714 #test to know if the table contain some records if no the function return nothing
1715     my $id = @id;
1716     $sth->finish;
1717     if ( $id eq 0 ) {
1718         return ();
1719     }
1720     else {
1721         unshift( @id, "" );
1722         return ( \@id, \%roadtype );
1723     }
1724 }
1725
1726
1727
1728 =head2 GetTitles (OUEST-PROVENCE)
1729
1730   ($borrowertitle)= &GetTitles();
1731
1732 Looks up the different title . Returns array  with all borrowers title
1733
1734 =cut
1735
1736 sub GetTitles {
1737     my @borrowerTitle = split /,|\|/,C4::Context->preference('BorrowersTitles');
1738     unshift( @borrowerTitle, "" );
1739     my $count=@borrowerTitle;
1740     if ($count == 1){
1741         return ();
1742     }
1743     else {
1744         return ( \@borrowerTitle);
1745     }
1746 }
1747
1748 =head2 GetPatronImage
1749
1750     my ($imagedata, $dberror) = GetPatronImage($cardnumber);
1751
1752 Returns the mimetype and binary image data of the image for the patron with the supplied cardnumber.
1753
1754 =cut
1755
1756 sub GetPatronImage {
1757     my ($cardnumber) = @_;
1758     warn "Cardnumber passed to GetPatronImage is $cardnumber" if $debug;
1759     my $dbh = C4::Context->dbh;
1760     my $query = "SELECT mimetype, imagefile FROM patronimage WHERE cardnumber = ?;";
1761     my $sth = $dbh->prepare($query);
1762     $sth->execute($cardnumber);
1763     my $imagedata = $sth->fetchrow_hashref;
1764     my $dberror = $sth->errstr;
1765     warn "Database error!" if $sth->errstr;
1766     $sth->finish;
1767     return $imagedata, $dberror;
1768 }
1769
1770 =head2 PutPatronImage
1771
1772     PutPatronImage($cardnumber, $mimetype, $imgfile);
1773
1774 Stores patron binary image data and mimetype in database.
1775 NOTE: This function is good for updating images as well as inserting new images in the database.
1776
1777 =cut
1778
1779 sub PutPatronImage {
1780     my ($cardnumber, $mimetype, $imgfile) = @_;
1781     warn "Parameters passed in: Cardnumber=$cardnumber, Mimetype=$mimetype, " . ($imgfile ? "Imagefile" : "No Imagefile") if $debug;
1782     my $dbh = C4::Context->dbh;
1783     my $query = "INSERT INTO patronimage (cardnumber, mimetype, imagefile) VALUES (?,?,?) ON DUPLICATE KEY UPDATE imagefile = ?;";
1784     my $sth = $dbh->prepare($query);
1785     $sth->execute($cardnumber,$mimetype,$imgfile,$imgfile);
1786     warn "Error returned inserting $cardnumber.$mimetype." if $sth->errstr;
1787     my $dberror = $sth->errstr;
1788     $sth->finish;
1789     return $dberror;
1790 }
1791
1792 =head2 RmPatronImage
1793
1794     my ($dberror) = RmPatronImage($cardnumber);
1795
1796 Removes the image for the patron with the supplied cardnumber.
1797
1798 =cut
1799
1800 sub RmPatronImage {
1801     my ($cardnumber) = @_;
1802     warn "Cardnumber passed to GetPatronImage is $cardnumber" if $debug;
1803     my $dbh = C4::Context->dbh;
1804     my $query = "DELETE FROM patronimage WHERE cardnumber = ?;";
1805     my $sth = $dbh->prepare($query);
1806     $sth->execute($cardnumber);
1807     my $dberror = $sth->errstr;
1808     warn "Database error!" if $sth->errstr;
1809     $sth->finish;
1810     return $dberror;
1811 }
1812
1813 =head2 GetRoadTypeDetails (OUEST-PROVENCE)
1814
1815   ($roadtype) = &GetRoadTypeDetails($roadtypeid);
1816
1817 Returns the description of roadtype
1818 C<&$roadtype>return description of road type
1819 C<&$roadtypeid>this is the value of roadtype s
1820
1821 =cut
1822
1823 sub GetRoadTypeDetails {
1824     my ($roadtypeid) = @_;
1825     my $dbh          = C4::Context->dbh;
1826     my $query        = qq|
1827 SELECT road_type 
1828 FROM roadtype 
1829 WHERE roadtypeid=?|;
1830     my $sth = $dbh->prepare($query);
1831     $sth->execute($roadtypeid);
1832     my $roadtype = $sth->fetchrow;
1833     return ($roadtype);
1834 }
1835
1836 =head2 GetBorrowersWhoHaveNotBorrowedSince
1837
1838 &GetBorrowersWhoHaveNotBorrowedSince($date)
1839
1840 this function get all borrowers who haven't borrowed since the date given on input arg.
1841       
1842 =cut
1843
1844 sub GetBorrowersWhoHaveNotBorrowedSince {
1845 ### 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.      
1846        
1847                 my $filterdate = shift||POSIX::strftime("%Y-%m-%d",localtime());
1848     my $filterbranch = shift || 
1849                         ((C4::Context->preference('IndependantBranches') 
1850                              && C4::Context->userenv 
1851                              && C4::Context->userenv->{flags}!=1 
1852                              && C4::Context->userenv->{branch})
1853                          ? C4::Context->userenv->{branch}
1854                          : "");  
1855     my $dbh   = C4::Context->dbh;
1856     my $query = "
1857         SELECT borrowers.borrowernumber,max(issues.timestamp) as latestissue
1858         FROM   borrowers
1859         JOIN   categories USING (categorycode)
1860         LEFT JOIN issues ON borrowers.borrowernumber = issues.borrowernumber
1861         WHERE  category_type <> 'S'
1862    ";
1863     my @query_params;
1864     if ($filterbranch && $filterbranch ne ""){ 
1865         $query.=" AND borrowers.branchcode= ?";
1866         push @query_params,$filterbranch;
1867     }    
1868     $query.=" GROUP BY borrowers.borrowernumber";
1869     if ($filterdate){ 
1870         $query.=" HAVING latestissue <? OR latestissue IS NULL";
1871         push @query_params,$filterdate;
1872     }
1873     warn $query if $debug;
1874     my $sth = $dbh->prepare($query);
1875     if (scalar(@query_params)>0){  
1876         $sth->execute(@query_params);
1877     } 
1878     else {
1879         $sth->execute;
1880     }      
1881     
1882     my @results;
1883     while ( my $data = $sth->fetchrow_hashref ) {
1884         push @results, $data;
1885     }
1886     return \@results;
1887 }
1888
1889 =head2 GetBorrowersWhoHaveNeverBorrowed
1890
1891 $results = &GetBorrowersWhoHaveNeverBorrowed
1892
1893 this function get all borrowers who have never borrowed.
1894
1895 I<$result> is a ref to an array which all elements are a hasref.
1896
1897 =cut
1898
1899 sub GetBorrowersWhoHaveNeverBorrowed {
1900     my $filterbranch = shift || 
1901                         ((C4::Context->preference('IndependantBranches') 
1902                              && C4::Context->userenv 
1903                              && C4::Context->userenv->{flags}!=1 
1904                              && C4::Context->userenv->{branch})
1905                          ? C4::Context->userenv->{branch}
1906                          : "");  
1907     my $dbh   = C4::Context->dbh;
1908     my $query = "
1909         SELECT borrowers.borrowernumber,max(timestamp) as latestissue
1910         FROM   borrowers
1911           LEFT JOIN issues ON borrowers.borrowernumber = issues.borrowernumber
1912         WHERE issues.borrowernumber IS NULL
1913    ";
1914     my @query_params;
1915     if ($filterbranch && $filterbranch ne ""){ 
1916         $query.=" AND borrowers.branchcode= ?";
1917         push @query_params,$filterbranch;
1918     }
1919     warn $query if $debug;
1920   
1921     my $sth = $dbh->prepare($query);
1922     if (scalar(@query_params)>0){  
1923         $sth->execute(@query_params);
1924     } 
1925     else {
1926         $sth->execute;
1927     }      
1928     
1929     my @results;
1930     while ( my $data = $sth->fetchrow_hashref ) {
1931         push @results, $data;
1932     }
1933     return \@results;
1934 }
1935
1936 =head2 GetBorrowersWithIssuesHistoryOlderThan
1937
1938 $results = &GetBorrowersWithIssuesHistoryOlderThan($date)
1939
1940 this function get all borrowers who has an issue history older than I<$date> given on input arg.
1941
1942 I<$result> is a ref to an array which all elements are a hashref.
1943 This hashref is containt the number of time this borrowers has borrowed before I<$date> and the borrowernumber.
1944
1945 =cut
1946
1947 sub GetBorrowersWithIssuesHistoryOlderThan {
1948     my $dbh  = C4::Context->dbh;
1949     my $date = shift ||POSIX::strftime("%Y-%m-%d",localtime());
1950     my $filterbranch = shift || 
1951                         ((C4::Context->preference('IndependantBranches') 
1952                              && C4::Context->userenv 
1953                              && C4::Context->userenv->{flags}!=1 
1954                              && C4::Context->userenv->{branch})
1955                          ? C4::Context->userenv->{branch}
1956                          : "");  
1957     my $query = "
1958        SELECT count(borrowernumber) as n,borrowernumber
1959        FROM old_issues
1960        WHERE returndate < ?
1961          AND borrowernumber IS NOT NULL 
1962     "; 
1963     my @query_params;
1964     push @query_params, $date;
1965     if ($filterbranch){
1966         $query.="   AND branchcode = ?";
1967         push @query_params, $filterbranch;
1968     }    
1969     $query.=" GROUP BY borrowernumber ";
1970     warn $query if $debug;
1971     my $sth = $dbh->prepare($query);
1972     $sth->execute(@query_params);
1973     my @results;
1974
1975     while ( my $data = $sth->fetchrow_hashref ) {
1976         push @results, $data;
1977     }
1978     return \@results;
1979 }
1980
1981 =head2 GetBorrowersNamesAndLatestIssue
1982
1983 $results = &GetBorrowersNamesAndLatestIssueList(@borrowernumbers)
1984
1985 this function get borrowers Names and surnames and Issue information.
1986
1987 I<@borrowernumbers> is an array which all elements are borrowernumbers.
1988 This hashref is containt the number of time this borrowers has borrowed before I<$date> and the borrowernumber.
1989
1990 =cut
1991
1992 sub GetBorrowersNamesAndLatestIssue {
1993     my $dbh  = C4::Context->dbh;
1994     my @borrowernumbers=@_;  
1995     my $query = "
1996        SELECT surname,lastname, phone, email,max(timestamp)
1997        FROM borrowers 
1998          LEFT JOIN issues ON borrowers.borrowernumber=issues.borrowernumber
1999        GROUP BY borrowernumber
2000    ";
2001     my $sth = $dbh->prepare($query);
2002     $sth->execute;
2003     my $results = $sth->fetchall_arrayref({});
2004     return $results;
2005 }
2006 END { }    # module clean-up code here (global destructor)
2007
2008 1;
2009
2010 __END__
2011
2012 =back
2013
2014 =head1 AUTHOR
2015
2016 Koha Team
2017
2018 =cut