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