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