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