Bug 6739: (follow-up) fix various issues
[koha-ffzg.git] / C4 / Members.pm
1 package C4::Members;
2
3 # Copyright 2000-2003 Katipo Communications
4 # Copyright 2010 BibLibre
5 # Parts Copyright 2010 Catalyst IT
6 #
7 # This file is part of Koha.
8 #
9 # Koha is free software; you can redistribute it and/or modify it under the
10 # terms of the GNU General Public License as published by the Free Software
11 # Foundation; either version 2 of the License, or (at your option) any later
12 # version.
13 #
14 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
15 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
16 # A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
17 #
18 # You should have received a copy of the GNU General Public License along
19 # with Koha; if not, write to the Free Software Foundation, Inc.,
20 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
21
22
23 use strict;
24 #use warnings; FIXME - Bug 2505
25 use C4::Context;
26 use C4::Dates qw(format_date_in_iso format_date);
27 use String::Random qw( random_string );
28 use Date::Calc qw/Today Add_Delta_YM check_date Date_to_Days/;
29 use C4::Log; # logaction
30 use C4::Overdues;
31 use C4::Reserves;
32 use C4::Accounts;
33 use C4::Biblio;
34 use C4::Letters;
35 use C4::SQLHelper qw(InsertInTable UpdateInTable SearchInTable);
36 use C4::Members::Attributes qw(SearchIdMatchingAttribute);
37 use C4::NewsChannels; #get slip news
38 use DateTime;
39 use DateTime::Format::DateParse;
40 use Koha::DateUtils;
41 use Koha::Borrower::Debarments qw(IsDebarred);
42 use Text::Unaccent qw( unac_string );
43 use Koha::AuthUtils qw(hash_password);
44
45 our ($VERSION,@ISA,@EXPORT,@EXPORT_OK,$debug);
46
47 BEGIN {
48     $VERSION = 3.07.00.049;
49     $debug = $ENV{DEBUG} || 0;
50     require Exporter;
51     @ISA = qw(Exporter);
52     #Get data
53     push @EXPORT, qw(
54         &Search
55         &GetMemberDetails
56         &GetMemberRelatives
57         &GetMember
58
59         &GetGuarantees
60
61         &GetMemberIssuesAndFines
62         &GetPendingIssues
63         &GetAllIssues
64
65         &getzipnamecity
66         &getidcity
67
68         &GetFirstValidEmailAddress
69         &GetNoticeEmailAddress
70
71         &GetAge
72         &GetCities
73         &GetSortDetails
74         &GetTitles
75
76         &GetPatronImage
77         &PutPatronImage
78         &RmPatronImage
79
80         &GetHideLostItemsPreference
81
82         &IsMemberBlocked
83         &GetMemberAccountRecords
84         &GetBorNotifyAcctRecord
85
86         &GetborCatFromCatType
87         &GetBorrowercategory
88         GetBorrowerCategorycode
89         &GetBorrowercategoryList
90
91         &GetBorrowersToExpunge
92         &GetBorrowersWhoHaveNeverBorrowed
93         &GetBorrowersWithIssuesHistoryOlderThan
94
95         &GetExpiryDate
96
97         &AddMessage
98         &DeleteMessage
99         &GetMessages
100         &GetMessagesCount
101
102         &IssueSlip
103         GetBorrowersWithEmail
104
105         HasOverdues
106     );
107
108     #Modify data
109     push @EXPORT, qw(
110         &ModMember
111         &changepassword
112          &ModPrivacy
113     );
114
115     #Delete data
116     push @EXPORT, qw(
117         &DelMember
118     );
119
120     #Insert data
121     push @EXPORT, qw(
122         &AddMember
123         &AddMember_Opac
124         &MoveMemberToDeleted
125         &ExtendMemberSubscriptionTo
126     );
127
128     #Check data
129     push @EXPORT, qw(
130         &checkuniquemember
131         &checkuserpassword
132         &Check_Userid
133         &Generate_Userid
134         &fixEthnicity
135         &ethnicitycategories
136         &fixup_cardnumber
137         &checkcardnumber
138     );
139 }
140
141 =head1 NAME
142
143 C4::Members - Perl Module containing convenience functions for member handling
144
145 =head1 SYNOPSIS
146
147 use C4::Members;
148
149 =head1 DESCRIPTION
150
151 This module contains routines for adding, modifying and deleting members/patrons/borrowers 
152
153 =head1 FUNCTIONS
154
155 =head2 Search
156
157   $borrowers_result_array_ref = &Search($filter,$orderby, $limit, 
158                        $columns_out, $search_on_fields,$searchtype);
159
160 Looks up patrons (borrowers) on filter. A wrapper for SearchInTable('borrowers').
161
162 For C<$filter>, C<$orderby>, C<$limit>, C<&columns_out>, C<&search_on_fields> and C<&searchtype>
163 refer to C4::SQLHelper:SearchInTable().
164
165 Special C<$filter> key '' is effectively expanded to search on surname firstname othernamescw
166 and cardnumber unless C<&search_on_fields> is defined
167
168 Examples:
169
170   $borrowers = Search('abcd', 'cardnumber');
171
172   $borrowers = Search({''=>'abcd', category_type=>'I'}, 'surname');
173
174 =cut
175
176 sub _express_member_find {
177     my ($filter) = @_;
178
179     # this is used by circulation everytime a new borrowers cardnumber is scanned
180     # so we can check an exact match first, if that works return, otherwise do the rest
181     my $dbh   = C4::Context->dbh;
182     my $query = "SELECT borrowernumber FROM borrowers WHERE cardnumber = ?";
183     if ( my $borrowernumber = $dbh->selectrow_array($query, undef, $filter) ) {
184         return( {"borrowernumber"=>$borrowernumber} );
185     }
186
187     my ($search_on_fields, $searchtype);
188     if ( length($filter) == 1 ) {
189         $search_on_fields = [ qw(surname) ];
190         $searchtype = 'start_with';
191     } else {
192         $search_on_fields = [ qw(surname firstname othernames cardnumber) ];
193         $searchtype = 'contain';
194     }
195
196     return (undef, $search_on_fields, $searchtype);
197 }
198
199 sub Search {
200     my ( $filter, $orderby, $limit, $columns_out, $search_on_fields, $searchtype ) = @_;
201
202     my $search_string;
203     my $found_borrower;
204
205     if ( my $fr = ref $filter ) {
206         if ( $fr eq "HASH" ) {
207             if ( my $search_string = $filter->{''} ) {
208                 my ($member_filter, $member_search_on_fields, $member_searchtype) = _express_member_find($search_string);
209                 if ($member_filter) {
210                     $filter = $member_filter;
211                     $found_borrower = 1;
212                 } else {
213                     $search_on_fields ||= $member_search_on_fields;
214                     $searchtype ||= $member_searchtype;
215                 }
216             }
217         }
218         else {
219             $search_string = $filter;
220         }
221     }
222     else {
223         $search_string = $filter;
224         my ($member_filter, $member_search_on_fields, $member_searchtype) = _express_member_find($search_string);
225         if ($member_filter) {
226             $filter = $member_filter;
227             $found_borrower = 1;
228         } else {
229             $search_on_fields ||= $member_search_on_fields;
230             $searchtype ||= $member_searchtype;
231         }
232     }
233
234     if ( !$found_borrower && C4::Context->preference('ExtendedPatronAttributes') && $search_string ) {
235         my $matching_records = C4::Members::Attributes::SearchIdMatchingAttribute($search_string);
236         if(scalar(@$matching_records)>0) {
237             if ( my $fr = ref $filter ) {
238                 if ( $fr eq "HASH" ) {
239                     my %f = %$filter;
240                     $filter = [ $filter ];
241                     delete $f{''};
242                     push @$filter, { %f, "borrowernumber"=>$$matching_records };
243                 }
244                 else {
245                     push @$filter, {"borrowernumber"=>$matching_records};
246                 }
247             }
248             else {
249                 $filter = [ $filter ];
250                 push @$filter, {"borrowernumber"=>$matching_records};
251             }
252         }
253     }
254
255     # $showallbranches was not used at the time SearchMember() was mainstreamed into Search().
256     # Mentioning for the reference
257
258     if ( C4::Context->preference("IndependentBranches") ) { # && !$showallbranches){
259         if ( my $userenv = C4::Context->userenv ) {
260             my $branch =  $userenv->{'branch'};
261             if ( !C4::Context->IsSuperLibrarian() && $branch ){
262                 if (my $fr = ref $filter) {
263                     if ( $fr eq "HASH" ) {
264                         $filter->{branchcode} = $branch;
265                     }
266                     else {
267                         foreach (@$filter) {
268                             $_ = { '' => $_ } unless ref $_;
269                             $_->{branchcode} = $branch;
270                         }
271                     }
272                 }
273                 else {
274                     $filter = { '' => $filter, branchcode => $branch };
275                 }
276             }      
277         }
278     }
279
280     if ($found_borrower) {
281         $searchtype = "exact";
282     }
283     $searchtype ||= "start_with";
284
285     return SearchInTable( "borrowers", $filter, $orderby, $limit, $columns_out, $search_on_fields, $searchtype );
286 }
287
288 =head2 GetMemberDetails
289
290 ($borrower) = &GetMemberDetails($borrowernumber, $cardnumber);
291
292 Looks up a patron and returns information about him or her. If
293 C<$borrowernumber> is true (nonzero), C<&GetMemberDetails> looks
294 up the borrower by number; otherwise, it looks up the borrower by card
295 number.
296
297 C<$borrower> is a reference-to-hash whose keys are the fields of the
298 borrowers table in the Koha database. In addition,
299 C<$borrower-E<gt>{flags}> is a hash giving more detailed information
300 about the patron. Its keys act as flags :
301
302     if $borrower->{flags}->{LOST} {
303         # Patron's card was reported lost
304     }
305
306 If the state of a flag means that the patron should not be
307 allowed to borrow any more books, then it will have a C<noissues> key
308 with a true value.
309
310 See patronflags for more details.
311
312 C<$borrower-E<gt>{authflags}> is a hash giving more detailed information
313 about the top-level permissions flags set for the borrower.  For example,
314 if a user has the "editcatalogue" permission,
315 C<$borrower-E<gt>{authflags}-E<gt>{editcatalogue}> will exist and have
316 the value "1".
317
318 =cut
319
320 sub GetMemberDetails {
321     my ( $borrowernumber, $cardnumber ) = @_;
322     my $dbh = C4::Context->dbh;
323     my $query;
324     my $sth;
325     if ($borrowernumber) {
326         $sth = $dbh->prepare("
327             SELECT borrowers.*,
328                    category_type,
329                    categories.description,
330                    categories.BlockExpiredPatronOpacActions,
331                    reservefee,
332                    enrolmentperiod
333             FROM borrowers
334             LEFT JOIN categories ON borrowers.categorycode=categories.categorycode
335             WHERE borrowernumber = ?
336         ");
337         $sth->execute($borrowernumber);
338     }
339     elsif ($cardnumber) {
340         $sth = $dbh->prepare("
341             SELECT borrowers.*,
342                    category_type,
343                    categories.description,
344                    categories.BlockExpiredPatronOpacActions,
345                    reservefee,
346                    enrolmentperiod
347             FROM borrowers
348             LEFT JOIN categories ON borrowers.categorycode = categories.categorycode
349             WHERE cardnumber = ?
350         ");
351         $sth->execute($cardnumber);
352     }
353     else {
354         return;
355     }
356     my $borrower = $sth->fetchrow_hashref;
357     my ($amount) = GetMemberAccountRecords( $borrowernumber);
358     $borrower->{'amountoutstanding'} = $amount;
359     # FIXME - patronflags calls GetMemberAccountRecords... just have patronflags return $amount
360     my $flags = patronflags( $borrower);
361     my $accessflagshash;
362
363     $sth = $dbh->prepare("select bit,flag from userflags");
364     $sth->execute;
365     while ( my ( $bit, $flag ) = $sth->fetchrow ) {
366         if ( $borrower->{'flags'} && $borrower->{'flags'} & 2**$bit ) {
367             $accessflagshash->{$flag} = 1;
368         }
369     }
370     $borrower->{'flags'}     = $flags;
371     $borrower->{'authflags'} = $accessflagshash;
372
373     # For the purposes of making templates easier, we'll define a
374     # 'showname' which is the alternate form the user's first name if 
375     # 'other name' is defined.
376     if ($borrower->{category_type} eq 'I') {
377         $borrower->{'showname'} = $borrower->{'othernames'};
378         $borrower->{'showname'} .= " $borrower->{'firstname'}" if $borrower->{'firstname'};
379     } else {
380         $borrower->{'showname'} = $borrower->{'firstname'};
381     }
382
383     # Handle setting the true behavior for BlockExpiredPatronOpacActions
384     $borrower->{'BlockExpiredPatronOpacActions'} =
385       C4::Context->preference('BlockExpiredPatronOpacActions')
386       if ( $borrower->{'BlockExpiredPatronOpacActions'} == -1 );
387
388     $borrower->{'is_expired'} =
389       Date_to_Days( Today() ) >
390       Date_to_Days( split /-/, $borrower->{'dateexpiry'} );
391
392     return ($borrower);    #, $flags, $accessflagshash);
393 }
394
395 =head2 patronflags
396
397  $flags = &patronflags($patron);
398
399 This function is not exported.
400
401 The following will be set where applicable:
402  $flags->{CHARGES}->{amount}        Amount of debt
403  $flags->{CHARGES}->{noissues}      Set if debt amount >$5.00 (or syspref noissuescharge)
404  $flags->{CHARGES}->{message}       Message -- deprecated
405
406  $flags->{CREDITS}->{amount}        Amount of credit
407  $flags->{CREDITS}->{message}       Message -- deprecated
408
409  $flags->{  GNA  }                  Patron has no valid address
410  $flags->{  GNA  }->{noissues}      Set for each GNA
411  $flags->{  GNA  }->{message}       "Borrower has no valid address" -- deprecated
412
413  $flags->{ LOST  }                  Patron's card reported lost
414  $flags->{ LOST  }->{noissues}      Set for each LOST
415  $flags->{ LOST  }->{message}       Message -- deprecated
416
417  $flags->{DBARRED}                  Set if patron debarred, no access
418  $flags->{DBARRED}->{noissues}      Set for each DBARRED
419  $flags->{DBARRED}->{message}       Message -- deprecated
420
421  $flags->{ NOTES }
422  $flags->{ NOTES }->{message}       The note itself.  NOT deprecated
423
424  $flags->{ ODUES }                  Set if patron has overdue books.
425  $flags->{ ODUES }->{message}       "Yes"  -- deprecated
426  $flags->{ ODUES }->{itemlist}      ref-to-array: list of overdue books
427  $flags->{ ODUES }->{itemlisttext}  Text list of overdue items -- deprecated
428
429  $flags->{WAITING}                  Set if any of patron's reserves are available
430  $flags->{WAITING}->{message}       Message -- deprecated
431  $flags->{WAITING}->{itemlist}      ref-to-array: list of available items
432
433 =over 
434
435 =item C<$flags-E<gt>{ODUES}-E<gt>{itemlist}> is a reference-to-array listing the
436 overdue items. Its elements are references-to-hash, each describing an
437 overdue item. The keys are selected fields from the issues, biblio,
438 biblioitems, and items tables of the Koha database.
439
440 =item C<$flags-E<gt>{ODUES}-E<gt>{itemlisttext}> is a string giving a text listing of
441 the overdue items, one per line.  Deprecated.
442
443 =item C<$flags-E<gt>{WAITING}-E<gt>{itemlist}> is a reference-to-array listing the
444 available items. Each element is a reference-to-hash whose keys are
445 fields from the reserves table of the Koha database.
446
447 =back
448
449 All the "message" fields that include language generated in this function are deprecated, 
450 because such strings belong properly in the display layer.
451
452 The "message" field that comes from the DB is OK.
453
454 =cut
455
456 # TODO: use {anonymous => hashes} instead of a dozen %flaginfo
457 # FIXME rename this function.
458 sub patronflags {
459     my %flags;
460     my ( $patroninformation) = @_;
461     my $dbh=C4::Context->dbh;
462     my ($balance, $owing) = GetMemberAccountBalance( $patroninformation->{'borrowernumber'});
463     if ( $owing > 0 ) {
464         my %flaginfo;
465         my $noissuescharge = C4::Context->preference("noissuescharge") || 5;
466         $flaginfo{'message'} = sprintf 'Patron owes %.02f', $owing;
467         $flaginfo{'amount'}  = sprintf "%.02f", $owing;
468         if ( $owing > $noissuescharge && !C4::Context->preference("AllowFineOverride") ) {
469             $flaginfo{'noissues'} = 1;
470         }
471         $flags{'CHARGES'} = \%flaginfo;
472     }
473     elsif ( $balance < 0 ) {
474         my %flaginfo;
475         $flaginfo{'message'} = sprintf 'Patron has credit of %.02f', -$balance;
476         $flaginfo{'amount'}  = sprintf "%.02f", $balance;
477         $flags{'CREDITS'} = \%flaginfo;
478     }
479     if (   $patroninformation->{'gonenoaddress'}
480         && $patroninformation->{'gonenoaddress'} == 1 )
481     {
482         my %flaginfo;
483         $flaginfo{'message'}  = 'Borrower has no valid address.';
484         $flaginfo{'noissues'} = 1;
485         $flags{'GNA'}         = \%flaginfo;
486     }
487     if ( $patroninformation->{'lost'} && $patroninformation->{'lost'} == 1 ) {
488         my %flaginfo;
489         $flaginfo{'message'}  = 'Borrower\'s card reported lost.';
490         $flaginfo{'noissues'} = 1;
491         $flags{'LOST'}        = \%flaginfo;
492     }
493     if ( $patroninformation->{'debarred'} && check_date( split( /-/, $patroninformation->{'debarred'} ) ) ) {
494         if ( Date_to_Days(Date::Calc::Today) < Date_to_Days( split( /-/, $patroninformation->{'debarred'} ) ) ) {
495             my %flaginfo;
496             $flaginfo{'debarredcomment'} = $patroninformation->{'debarredcomment'};
497             $flaginfo{'message'}         = $patroninformation->{'debarredcomment'};
498             $flaginfo{'noissues'}        = 1;
499             $flaginfo{'dateend'}         = $patroninformation->{'debarred'};
500             $flags{'DBARRED'}           = \%flaginfo;
501         }
502     }
503     if (   $patroninformation->{'borrowernotes'}
504         && $patroninformation->{'borrowernotes'} )
505     {
506         my %flaginfo;
507         $flaginfo{'message'} = $patroninformation->{'borrowernotes'};
508         $flags{'NOTES'}      = \%flaginfo;
509     }
510     my ( $odues, $itemsoverdue ) = C4::Overdues::checkoverdues($patroninformation->{'borrowernumber'});
511     if ( $odues && $odues > 0 ) {
512         my %flaginfo;
513         $flaginfo{'message'}  = "Yes";
514         $flaginfo{'itemlist'} = $itemsoverdue;
515         foreach ( sort { $a->{'date_due'} cmp $b->{'date_due'} }
516             @$itemsoverdue )
517         {
518             $flaginfo{'itemlisttext'} .=
519               "$_->{'date_due'} $_->{'barcode'} $_->{'title'} \n";  # newline is display layer
520         }
521         $flags{'ODUES'} = \%flaginfo;
522     }
523     my @itemswaiting = C4::Reserves::GetReservesFromBorrowernumber( $patroninformation->{'borrowernumber'},'W' );
524     my $nowaiting = scalar @itemswaiting;
525     if ( $nowaiting > 0 ) {
526         my %flaginfo;
527         $flaginfo{'message'}  = "Reserved items available";
528         $flaginfo{'itemlist'} = \@itemswaiting;
529         $flags{'WAITING'}     = \%flaginfo;
530     }
531     return ( \%flags );
532 }
533
534
535 =head2 GetMember
536
537   $borrower = &GetMember(%information);
538
539 Retrieve the first patron record meeting on criteria listed in the
540 C<%information> hash, which should contain one or more
541 pairs of borrowers column names and values, e.g.,
542
543    $borrower = GetMember(borrowernumber => id);
544
545 C<&GetBorrower> returns a reference-to-hash whose keys are the fields of
546 the C<borrowers> table in the Koha database.
547
548 FIXME: GetMember() is used throughout the code as a lookup
549 on a unique key such as the borrowernumber, but this meaning is not
550 enforced in the routine itself.
551
552 =cut
553
554 #'
555 sub GetMember {
556     my ( %information ) = @_;
557     if (exists $information{borrowernumber} && !defined $information{borrowernumber}) {
558         #passing mysql's kohaadmin?? Makes no sense as a query
559         return;
560     }
561     my $dbh = C4::Context->dbh;
562     my $select =
563     q{SELECT borrowers.*, categories.category_type, categories.description
564     FROM borrowers 
565     LEFT JOIN categories on borrowers.categorycode=categories.categorycode WHERE };
566     my $more_p = 0;
567     my @values = ();
568     for (keys %information ) {
569         if ($more_p) {
570             $select .= ' AND ';
571         }
572         else {
573             $more_p++;
574         }
575
576         if (defined $information{$_}) {
577             $select .= "$_ = ?";
578             push @values, $information{$_};
579         }
580         else {
581             $select .= "$_ IS NULL";
582         }
583     }
584     $debug && warn $select, " ",values %information;
585     my $sth = $dbh->prepare("$select");
586     $sth->execute(map{$information{$_}} keys %information);
587     my $data = $sth->fetchall_arrayref({});
588     #FIXME interface to this routine now allows generation of a result set
589     #so whole array should be returned but bowhere in the current code expects this
590     if (@{$data} ) {
591         return $data->[0];
592     }
593
594     return;
595 }
596
597 =head2 GetMemberRelatives
598
599  @borrowernumbers = GetMemberRelatives($borrowernumber);
600
601  C<GetMemberRelatives> returns a borrowersnumber's list of guarantor/guarantees of the member given in parameter
602
603 =cut 
604 sub GetMemberRelatives {
605     my $borrowernumber = shift;
606     my $dbh = C4::Context->dbh;
607     my @glist;
608
609     # Getting guarantor
610     my $query = "SELECT guarantorid FROM borrowers WHERE borrowernumber=?";
611     my $sth = $dbh->prepare($query);
612     $sth->execute($borrowernumber);
613     my $data = $sth->fetchrow_arrayref();
614     push @glist, $data->[0] if $data->[0];
615     my $guarantor = $data->[0] ? $data->[0] : undef;
616
617     # Getting guarantees
618     $query = "SELECT borrowernumber FROM borrowers WHERE guarantorid=?";
619     $sth = $dbh->prepare($query);
620     $sth->execute($borrowernumber);
621     while ($data = $sth->fetchrow_arrayref()) {
622        push @glist, $data->[0];
623     }
624
625     # Getting sibling guarantees
626     if ($guarantor) {
627         $query = "SELECT borrowernumber FROM borrowers WHERE guarantorid=?";
628         $sth = $dbh->prepare($query);
629         $sth->execute($guarantor);
630         while ($data = $sth->fetchrow_arrayref()) {
631            push @glist, $data->[0] if ($data->[0] != $borrowernumber);
632         }
633     }
634
635     return @glist;
636 }
637
638 =head2 IsMemberBlocked
639
640   my ($block_status, $count) = IsMemberBlocked( $borrowernumber );
641
642 Returns whether a patron has overdue items that may result
643 in a block or whether the patron has active fine days
644 that would block circulation privileges.
645
646 C<$block_status> can have the following values:
647
648 1 if the patron has outstanding fine days, in which case C<$count> is the number of them
649
650 -1 if the patron has overdue items, in which case C<$count> is the number of them
651
652 0 if the patron has no overdue items or outstanding fine days, in which case C<$count> is 0
653
654 Outstanding fine days are checked before current overdue items
655 are.
656
657 FIXME: this needs to be split into two functions; a potential block
658 based on the number of current overdue items could be orthogonal
659 to a block based on whether the patron has any fine days accrued.
660
661 =cut
662
663 sub IsMemberBlocked {
664     my $borrowernumber = shift;
665     my $dbh            = C4::Context->dbh;
666
667     my $blockeddate = Koha::Borrower::Debarments::IsDebarred($borrowernumber);
668
669     return ( 1, $blockeddate ) if $blockeddate;
670
671     # if he have late issues
672     my $sth = $dbh->prepare(
673         "SELECT COUNT(*) as latedocs
674          FROM issues
675          WHERE borrowernumber = ?
676          AND date_due < now()"
677     );
678     $sth->execute($borrowernumber);
679     my $latedocs = $sth->fetchrow_hashref->{'latedocs'};
680
681     return ( -1, $latedocs ) if $latedocs > 0;
682
683     return ( 0, 0 );
684 }
685
686 =head2 GetMemberIssuesAndFines
687
688   ($overdue_count, $issue_count, $total_fines) = &GetMemberIssuesAndFines($borrowernumber);
689
690 Returns aggregate data about items borrowed by the patron with the
691 given borrowernumber.
692
693 C<&GetMemberIssuesAndFines> returns a three-element array.  C<$overdue_count> is the
694 number of overdue items the patron currently has borrowed. C<$issue_count> is the
695 number of books the patron currently has borrowed.  C<$total_fines> is
696 the total fine currently due by the borrower.
697
698 =cut
699
700 #'
701 sub GetMemberIssuesAndFines {
702     my ( $borrowernumber ) = @_;
703     my $dbh   = C4::Context->dbh;
704     my $query = "SELECT COUNT(*) FROM issues WHERE borrowernumber = ?";
705
706     $debug and warn $query."\n";
707     my $sth = $dbh->prepare($query);
708     $sth->execute($borrowernumber);
709     my $issue_count = $sth->fetchrow_arrayref->[0];
710
711     $sth = $dbh->prepare(
712         "SELECT COUNT(*) FROM issues 
713          WHERE borrowernumber = ? 
714          AND date_due < now()"
715     );
716     $sth->execute($borrowernumber);
717     my $overdue_count = $sth->fetchrow_arrayref->[0];
718
719     $sth = $dbh->prepare("SELECT SUM(amountoutstanding) FROM accountlines WHERE borrowernumber = ?");
720     $sth->execute($borrowernumber);
721     my $total_fines = $sth->fetchrow_arrayref->[0];
722
723     return ($overdue_count, $issue_count, $total_fines);
724 }
725
726
727 =head2 columns
728
729   my @columns = C4::Member::columns();
730
731 Returns an array of borrowers' table columns on success,
732 and an empty array on failure.
733
734 =cut
735
736 sub columns {
737
738     # Pure ANSI SQL goodness.
739     my $sql = 'SELECT * FROM borrowers WHERE 1=0;';
740
741     # Get the database handle.
742     my $dbh = C4::Context->dbh;
743
744     # Run the SQL statement to load STH's readonly properties.
745     my $sth = $dbh->prepare($sql);
746     my $rv = $sth->execute();
747
748     # This only fails if the table doesn't exist.
749     # This will always be called AFTER an install or upgrade,
750     # so borrowers will exist!
751     my @data;
752     if ($sth->{NUM_OF_FIELDS}>0) {
753         @data = @{$sth->{NAME}};
754     }
755     else {
756         @data = ();
757     }
758     return @data;
759 }
760
761
762 =head2 ModMember
763
764   my $success = ModMember(borrowernumber => $borrowernumber,
765                                             [ field => value ]... );
766
767 Modify borrower's data.  All date fields should ALREADY be in ISO format.
768
769 return :
770 true on success, or false on failure
771
772 =cut
773
774 sub ModMember {
775     my (%data) = @_;
776     # test to know if you must update or not the borrower password
777     if (exists $data{password}) {
778         if ($data{password} eq '****' or $data{password} eq '') {
779             delete $data{password};
780         } else {
781             $data{password} = hash_password($data{password});
782         }
783     }
784     my $old_categorycode = GetBorrowerCategorycode( $data{borrowernumber} );
785     my $execute_success=UpdateInTable("borrowers",\%data);
786     if ($execute_success) { # only proceed if the update was a success
787         # ok if its an adult (type) it may have borrowers that depend on it as a guarantor
788         # so when we update information for an adult we should check for guarantees and update the relevant part
789         # of their records, ie addresses and phone numbers
790         my $borrowercategory= GetBorrowercategory( $data{'category_type'} );
791         if ( exists  $borrowercategory->{'category_type'} && $borrowercategory->{'category_type'} eq ('A' || 'S') ) {
792             # is adult check guarantees;
793             UpdateGuarantees(%data);
794         }
795
796         # If the patron changes to a category with enrollment fee, we add a fee
797         if ( $data{categorycode} and $data{categorycode} ne $old_categorycode ) {
798             AddEnrolmentFeeIfNeeded( $data{categorycode}, $data{borrowernumber} );
799         }
800
801         logaction("MEMBERS", "MODIFY", $data{'borrowernumber'}, "UPDATE (executed w/ arg: $data{'borrowernumber'})") if C4::Context->preference("BorrowersLog");
802     }
803     return $execute_success;
804 }
805
806 =head2 AddMember
807
808   $borrowernumber = &AddMember(%borrower);
809
810 insert new borrower into table
811 Returns the borrowernumber upon success
812
813 Returns as undef upon any db error without further processing
814
815 =cut
816
817 #'
818 sub AddMember {
819     my (%data) = @_;
820     my $dbh = C4::Context->dbh;
821
822     # generate a proper login if none provided
823     $data{'userid'} = Generate_Userid($data{'borrowernumber'}, $data{'firstname'}, $data{'surname'}) if $data{'userid'} eq '';
824
825     # add expiration date if it isn't already there
826     unless ( $data{'dateexpiry'} ) {
827         $data{'dateexpiry'} = GetExpiryDate( $data{'categorycode'}, C4::Dates->new()->output("iso") );
828     }
829
830     # add enrollment date if it isn't already there
831     unless ( $data{'dateenrolled'} ) {
832         $data{'dateenrolled'} = C4::Dates->new()->output("iso");
833     }
834
835     # create a disabled account if no password provided
836     $data{'password'} = ($data{'password'})? hash_password($data{'password'}) : '!';
837     $data{'borrowernumber'}=InsertInTable("borrowers",\%data);
838
839     # mysql_insertid is probably bad.  not necessarily accurate and mysql-specific at best.
840     logaction("MEMBERS", "CREATE", $data{'borrowernumber'}, "") if C4::Context->preference("BorrowersLog");
841
842     AddEnrolmentFeeIfNeeded( $data{categorycode}, $data{borrowernumber} );
843
844     return $data{'borrowernumber'};
845 }
846
847 =head2 Check_Userid
848
849     my $uniqueness = Check_Userid($userid,$borrowernumber);
850
851     $borrowernumber is optional (i.e. it can contain a blank value). If $userid is passed with a blank $borrowernumber variable, the database will be checked for all instances of that userid (i.e. userid=? AND borrowernumber != '').
852
853     If $borrowernumber is provided, the database will be checked for every instance of that userid coupled with a different borrower(number) than the one provided.
854
855     return :
856         0 for not unique (i.e. this $userid already exists)
857         1 for unique (i.e. this $userid does not exist, or this $userid/$borrowernumber combination already exists)
858
859 =cut
860
861 sub Check_Userid {
862     my ($uid,$member) = @_;
863     my $dbh = C4::Context->dbh;
864     my $sth =
865       $dbh->prepare(
866         "SELECT * FROM borrowers WHERE userid=? AND borrowernumber != ?");
867     $sth->execute( $uid, $member );
868     if ( ( $uid ne '' ) && ( my $row = $sth->fetchrow_hashref ) ) {
869         return 0;
870     }
871     else {
872         return 1;
873     }
874 }
875
876 =head2 Generate_Userid
877
878     my $newuid = Generate_Userid($borrowernumber, $firstname, $surname);
879
880     Generate a userid using the $surname and the $firstname (if there is a value in $firstname).
881
882     $borrowernumber is optional (i.e. it can contain a blank value). A value is passed when generating a new userid for an existing borrower. When a new userid is created for a new borrower, a blank value is passed to this sub.
883
884     return :
885         new userid ($firstname.$surname if there is a $firstname, or $surname if there is no value in $firstname) plus offset (0 if the $newuid is unique, or a higher numeric value if Check_Userid finds an existing match for the $newuid in the database).
886
887 =cut
888
889 sub Generate_Userid {
890   my ($borrowernumber, $firstname, $surname) = @_;
891   my $newuid;
892   my $offset = 0;
893   #The script will "do" the following code and increment the $offset until Check_Userid = 1 (i.e. until $newuid comes back as unique)
894   do {
895     $firstname =~ s/[[:digit:][:space:][:blank:][:punct:][:cntrl:]]//g;
896     $surname =~ s/[[:digit:][:space:][:blank:][:punct:][:cntrl:]]//g;
897     $newuid = lc(($firstname)? "$firstname.$surname" : $surname);
898     $newuid = unac_string('utf-8',$newuid);
899     $newuid .= $offset unless $offset == 0;
900     $offset++;
901
902    } while (!Check_Userid($newuid,$borrowernumber));
903
904    return $newuid;
905 }
906
907 sub changepassword {
908     my ( $uid, $member, $digest ) = @_;
909     my $dbh = C4::Context->dbh;
910
911 #Make sure the userid chosen is unique and not theirs if non-empty. If it is not,
912 #Then we need to tell the user and have them create a new one.
913     my $resultcode;
914     my $sth =
915       $dbh->prepare(
916         "SELECT * FROM borrowers WHERE userid=? AND borrowernumber != ?");
917     $sth->execute( $uid, $member );
918     if ( ( $uid ne '' ) && ( my $row = $sth->fetchrow_hashref ) ) {
919         $resultcode=0;
920     }
921     else {
922         #Everything is good so we can update the information.
923         $sth =
924           $dbh->prepare(
925             "update borrowers set userid=?, password=? where borrowernumber=?");
926         $sth->execute( $uid, $digest, $member );
927         $resultcode=1;
928     }
929     
930     logaction("MEMBERS", "CHANGE PASS", $member, "") if C4::Context->preference("BorrowersLog");
931     return $resultcode;    
932 }
933
934
935
936 =head2 fixup_cardnumber
937
938 Warning: The caller is responsible for locking the members table in write
939 mode, to avoid database corruption.
940
941 =cut
942
943 use vars qw( @weightings );
944 my @weightings = ( 8, 4, 6, 3, 5, 2, 1 );
945
946 sub fixup_cardnumber {
947     my ($cardnumber) = @_;
948     my $autonumber_members = C4::Context->boolean_preference('autoMemberNum') || 0;
949
950     # Find out whether member numbers should be generated
951     # automatically. Should be either "1" or something else.
952     # Defaults to "0", which is interpreted as "no".
953
954     #     if ($cardnumber !~ /\S/ && $autonumber_members) {
955     ($autonumber_members) or return $cardnumber;
956     my $checkdigit = C4::Context->preference('checkdigit');
957     my $dbh = C4::Context->dbh;
958     if ( $checkdigit and $checkdigit eq 'katipo' ) {
959
960         # if checkdigit is selected, calculate katipo-style cardnumber.
961         # otherwise, just use the max()
962         # purpose: generate checksum'd member numbers.
963         # We'll assume we just got the max value of digits 2-8 of member #'s
964         # from the database and our job is to increment that by one,
965         # determine the 1st and 9th digits and return the full string.
966         my $sth = $dbh->prepare(
967             "select max(substring(borrowers.cardnumber,2,7)) as new_num from borrowers"
968         );
969         $sth->execute;
970         my $data = $sth->fetchrow_hashref;
971         $cardnumber = $data->{new_num};
972         if ( !$cardnumber ) {    # If DB has no values,
973             $cardnumber = 1000000;    # start at 1000000
974         } else {
975             $cardnumber += 1;
976         }
977
978         my $sum = 0;
979         for ( my $i = 0 ; $i < 8 ; $i += 1 ) {
980             # read weightings, left to right, 1 char at a time
981             my $temp1 = $weightings[$i];
982
983             # sequence left to right, 1 char at a time
984             my $temp2 = substr( $cardnumber, $i, 1 );
985
986             # mult each char 1-7 by its corresponding weighting
987             $sum += $temp1 * $temp2;
988         }
989
990         my $rem = ( $sum % 11 );
991         $rem = 'X' if $rem == 10;
992
993         return "V$cardnumber$rem";
994      } else {
995
996         my $sth = $dbh->prepare(
997             'SELECT MAX( CAST( cardnumber AS SIGNED ) ) FROM borrowers WHERE cardnumber REGEXP "^-?[0-9]+$"'
998         );
999         $sth->execute;
1000         my ($result) = $sth->fetchrow;
1001         return $result + 1;
1002     }
1003     return $cardnumber;     # just here as a fallback/reminder 
1004 }
1005
1006 =head2 GetGuarantees
1007
1008   ($num_children, $children_arrayref) = &GetGuarantees($parent_borrno);
1009   $child0_cardno = $children_arrayref->[0]{"cardnumber"};
1010   $child0_borrno = $children_arrayref->[0]{"borrowernumber"};
1011
1012 C<&GetGuarantees> takes a borrower number (e.g., that of a patron
1013 with children) and looks up the borrowers who are guaranteed by that
1014 borrower (i.e., the patron's children).
1015
1016 C<&GetGuarantees> returns two values: an integer giving the number of
1017 borrowers guaranteed by C<$parent_borrno>, and a reference to an array
1018 of references to hash, which gives the actual results.
1019
1020 =cut
1021
1022 #'
1023 sub GetGuarantees {
1024     my ($borrowernumber) = @_;
1025     my $dbh              = C4::Context->dbh;
1026     my $sth              =
1027       $dbh->prepare(
1028 "select cardnumber,borrowernumber, firstname, surname from borrowers where guarantorid=?"
1029       );
1030     $sth->execute($borrowernumber);
1031
1032     my @dat;
1033     my $data = $sth->fetchall_arrayref({}); 
1034     return ( scalar(@$data), $data );
1035 }
1036
1037 =head2 UpdateGuarantees
1038
1039   &UpdateGuarantees($parent_borrno);
1040   
1041
1042 C<&UpdateGuarantees> borrower data for an adult and updates all the guarantees
1043 with the modified information
1044
1045 =cut
1046
1047 #'
1048 sub UpdateGuarantees {
1049     my %data = shift;
1050     my $dbh = C4::Context->dbh;
1051     my ( $count, $guarantees ) = GetGuarantees( $data{'borrowernumber'} );
1052     foreach my $guarantee (@$guarantees){
1053         my $guaquery = qq|UPDATE borrowers 
1054               SET address=?,fax=?,B_city=?,mobile=?,city=?,phone=?
1055               WHERE borrowernumber=?
1056         |;
1057         my $sth = $dbh->prepare($guaquery);
1058         $sth->execute($data{'address'},$data{'fax'},$data{'B_city'},$data{'mobile'},$data{'city'},$data{'phone'},$guarantee->{'borrowernumber'});
1059     }
1060 }
1061 =head2 GetPendingIssues
1062
1063   my $issues = &GetPendingIssues(@borrowernumber);
1064
1065 Looks up what the patron with the given borrowernumber has borrowed.
1066
1067 C<&GetPendingIssues> returns a
1068 reference-to-array where each element is a reference-to-hash; the
1069 keys are the fields from the C<issues>, C<biblio>, and C<items> tables.
1070 The keys include C<biblioitems> fields except marc and marcxml.
1071
1072 =cut
1073
1074 #'
1075 sub GetPendingIssues {
1076     my @borrowernumbers = @_;
1077
1078     unless (@borrowernumbers ) { # return a ref_to_array
1079         return \@borrowernumbers; # to not cause surprise to caller
1080     }
1081
1082     # Borrowers part of the query
1083     my $bquery = '';
1084     for (my $i = 0; $i < @borrowernumbers; $i++) {
1085         $bquery .= ' issues.borrowernumber = ?';
1086         if ($i < $#borrowernumbers ) {
1087             $bquery .= ' OR';
1088         }
1089     }
1090
1091     # must avoid biblioitems.* to prevent large marc and marcxml fields from killing performance
1092     # FIXME: namespace collision: each table has "timestamp" fields.  Which one is "timestamp" ?
1093     # FIXME: circ/ciculation.pl tries to sort by timestamp!
1094     # FIXME: namespace collision: other collisions possible.
1095     # FIXME: most of this data isn't really being used by callers.
1096     my $query =
1097    "SELECT issues.*,
1098             items.*,
1099            biblio.*,
1100            biblioitems.volume,
1101            biblioitems.number,
1102            biblioitems.itemtype,
1103            biblioitems.isbn,
1104            biblioitems.issn,
1105            biblioitems.publicationyear,
1106            biblioitems.publishercode,
1107            biblioitems.volumedate,
1108            biblioitems.volumedesc,
1109            biblioitems.lccn,
1110            biblioitems.url,
1111            borrowers.firstname,
1112            borrowers.surname,
1113            borrowers.cardnumber,
1114            issues.timestamp AS timestamp,
1115            issues.renewals  AS renewals,
1116            issues.borrowernumber AS borrowernumber,
1117             items.renewals  AS totalrenewals
1118     FROM   issues
1119     LEFT JOIN items       ON items.itemnumber       =      issues.itemnumber
1120     LEFT JOIN biblio      ON items.biblionumber     =      biblio.biblionumber
1121     LEFT JOIN biblioitems ON items.biblioitemnumber = biblioitems.biblioitemnumber
1122     LEFT JOIN borrowers ON issues.borrowernumber = borrowers.borrowernumber
1123     WHERE
1124       $bquery
1125     ORDER BY issues.issuedate"
1126     ;
1127
1128     my $sth = C4::Context->dbh->prepare($query);
1129     $sth->execute(@borrowernumbers);
1130     my $data = $sth->fetchall_arrayref({});
1131     my $tz = C4::Context->tz();
1132     my $today = DateTime->now( time_zone => $tz);
1133     foreach (@{$data}) {
1134         if ($_->{issuedate}) {
1135             $_->{issuedate} = dt_from_string($_->{issuedate}, 'sql');
1136         }
1137         $_->{date_due} or next;
1138         $_->{date_due} = DateTime::Format::DateParse->parse_datetime($_->{date_due}, $tz->name());
1139         if ( DateTime->compare($_->{date_due}, $today) == -1 ) {
1140             $_->{overdue} = 1;
1141         }
1142     }
1143     return $data;
1144 }
1145
1146 =head2 GetAllIssues
1147
1148   $issues = &GetAllIssues($borrowernumber, $sortkey, $limit);
1149
1150 Looks up what the patron with the given borrowernumber has borrowed,
1151 and sorts the results.
1152
1153 C<$sortkey> is the name of a field on which to sort the results. This
1154 should be the name of a field in the C<issues>, C<biblio>,
1155 C<biblioitems>, or C<items> table in the Koha database.
1156
1157 C<$limit> is the maximum number of results to return.
1158
1159 C<&GetAllIssues> an arrayref, C<$issues>, of hashrefs, the keys of which
1160 are the fields from the C<issues>, C<biblio>, C<biblioitems>, and
1161 C<items> tables of the Koha database.
1162
1163 =cut
1164
1165 #'
1166 sub GetAllIssues {
1167     my ( $borrowernumber, $order, $limit ) = @_;
1168
1169     my $dbh = C4::Context->dbh;
1170     my $query =
1171 'SELECT *, issues.timestamp as issuestimestamp, issues.renewals AS renewals,items.renewals AS totalrenewals,items.timestamp AS itemstimestamp
1172   FROM issues 
1173   LEFT JOIN items on items.itemnumber=issues.itemnumber
1174   LEFT JOIN biblio ON items.biblionumber=biblio.biblionumber
1175   LEFT JOIN biblioitems ON items.biblioitemnumber=biblioitems.biblioitemnumber
1176   WHERE borrowernumber=? 
1177   UNION ALL
1178   SELECT *, old_issues.timestamp as issuestimestamp, old_issues.renewals AS renewals,items.renewals AS totalrenewals,items.timestamp AS itemstimestamp 
1179   FROM old_issues 
1180   LEFT JOIN items on items.itemnumber=old_issues.itemnumber
1181   LEFT JOIN biblio ON items.biblionumber=biblio.biblionumber
1182   LEFT JOIN biblioitems ON items.biblioitemnumber=biblioitems.biblioitemnumber
1183   WHERE borrowernumber=? AND old_issues.itemnumber IS NOT NULL
1184   order by ' . $order;
1185     if ($limit) {
1186         $query .= " limit $limit";
1187     }
1188
1189     my $sth = $dbh->prepare($query);
1190     $sth->execute( $borrowernumber, $borrowernumber );
1191     return $sth->fetchall_arrayref( {} );
1192 }
1193
1194
1195 =head2 GetMemberAccountRecords
1196
1197   ($total, $acctlines, $count) = &GetMemberAccountRecords($borrowernumber);
1198
1199 Looks up accounting data for the patron with the given borrowernumber.
1200
1201 C<&GetMemberAccountRecords> returns a three-element array. C<$acctlines> is a
1202 reference-to-array, where each element is a reference-to-hash; the
1203 keys are the fields of the C<accountlines> table in the Koha database.
1204 C<$count> is the number of elements in C<$acctlines>. C<$total> is the
1205 total amount outstanding for all of the account lines.
1206
1207 =cut
1208
1209 sub GetMemberAccountRecords {
1210     my ($borrowernumber) = @_;
1211     my $dbh = C4::Context->dbh;
1212     my @acctlines;
1213     my $numlines = 0;
1214     my $strsth      = qq(
1215                         SELECT * 
1216                         FROM accountlines 
1217                         WHERE borrowernumber=?);
1218     $strsth.=" ORDER BY date desc,timestamp DESC";
1219     my $sth= $dbh->prepare( $strsth );
1220     $sth->execute( $borrowernumber );
1221
1222     my $total = 0;
1223     while ( my $data = $sth->fetchrow_hashref ) {
1224         if ( $data->{itemnumber} ) {
1225             my $biblio = GetBiblioFromItemNumber( $data->{itemnumber} );
1226             $data->{biblionumber} = $biblio->{biblionumber};
1227             $data->{title}        = $biblio->{title};
1228         }
1229         $acctlines[$numlines] = $data;
1230         $numlines++;
1231         $total += int(1000 * $data->{'amountoutstanding'}); # convert float to integer to avoid round-off errors
1232     }
1233     $total /= 1000;
1234     return ( $total, \@acctlines,$numlines);
1235 }
1236
1237 =head2 GetMemberAccountBalance
1238
1239   ($total_balance, $non_issue_balance, $other_charges) = &GetMemberAccountBalance($borrowernumber);
1240
1241 Calculates amount immediately owing by the patron - non-issue charges.
1242 Based on GetMemberAccountRecords.
1243 Charges exempt from non-issue are:
1244 * Res (reserves)
1245 * Rent (rental) if RentalsInNoissuesCharge syspref is set to false
1246 * Manual invoices if ManInvInNoissuesCharge syspref is set to false
1247
1248 =cut
1249
1250 sub GetMemberAccountBalance {
1251     my ($borrowernumber) = @_;
1252
1253     my $ACCOUNT_TYPE_LENGTH = 5; # this is plain ridiculous...
1254
1255     my @not_fines = ('Res');
1256     push @not_fines, 'Rent' unless C4::Context->preference('RentalsInNoissuesCharge');
1257     unless ( C4::Context->preference('ManInvInNoissuesCharge') ) {
1258         my $dbh = C4::Context->dbh;
1259         my $man_inv_types = $dbh->selectcol_arrayref(qq{SELECT authorised_value FROM authorised_values WHERE category = 'MANUAL_INV'});
1260         push @not_fines, map substr($_, 0, $ACCOUNT_TYPE_LENGTH), @$man_inv_types;
1261     }
1262     my %not_fine = map {$_ => 1} @not_fines;
1263
1264     my ($total, $acctlines) = GetMemberAccountRecords($borrowernumber);
1265     my $other_charges = 0;
1266     foreach (@$acctlines) {
1267         $other_charges += $_->{amountoutstanding} if $not_fine{ substr($_->{accounttype}, 0, $ACCOUNT_TYPE_LENGTH) };
1268     }
1269
1270     return ( $total, $total - $other_charges, $other_charges);
1271 }
1272
1273 =head2 GetBorNotifyAcctRecord
1274
1275   ($total, $acctlines, $count) = &GetBorNotifyAcctRecord($params,$notifyid);
1276
1277 Looks up accounting data for the patron with the given borrowernumber per file number.
1278
1279 C<&GetBorNotifyAcctRecord> returns a three-element array. C<$acctlines> is a
1280 reference-to-array, where each element is a reference-to-hash; the
1281 keys are the fields of the C<accountlines> table in the Koha database.
1282 C<$count> is the number of elements in C<$acctlines>. C<$total> is the
1283 total amount outstanding for all of the account lines.
1284
1285 =cut
1286
1287 sub GetBorNotifyAcctRecord {
1288     my ( $borrowernumber, $notifyid ) = @_;
1289     my $dbh = C4::Context->dbh;
1290     my @acctlines;
1291     my $numlines = 0;
1292     my $sth = $dbh->prepare(
1293             "SELECT * 
1294                 FROM accountlines 
1295                 WHERE borrowernumber=? 
1296                     AND notify_id=? 
1297                     AND amountoutstanding != '0' 
1298                 ORDER BY notify_id,accounttype
1299                 ");
1300
1301     $sth->execute( $borrowernumber, $notifyid );
1302     my $total = 0;
1303     while ( my $data = $sth->fetchrow_hashref ) {
1304         if ( $data->{itemnumber} ) {
1305             my $biblio = GetBiblioFromItemNumber( $data->{itemnumber} );
1306             $data->{biblionumber} = $biblio->{biblionumber};
1307             $data->{title}        = $biblio->{title};
1308         }
1309         $acctlines[$numlines] = $data;
1310         $numlines++;
1311         $total += int(100 * $data->{'amountoutstanding'});
1312     }
1313     $total /= 100;
1314     return ( $total, \@acctlines, $numlines );
1315 }
1316
1317 =head2 checkuniquemember (OUEST-PROVENCE)
1318
1319   ($result,$categorycode)  = &checkuniquemember($collectivity,$surname,$firstname,$dateofbirth);
1320
1321 Checks that a member exists or not in the database.
1322
1323 C<&result> is nonzero (=exist) or 0 (=does not exist)
1324 C<&categorycode> is from categorycode table
1325 C<&collectivity> is 1 (= we add a collectivity) or 0 (= we add a physical member)
1326 C<&surname> is the surname
1327 C<&firstname> is the firstname (only if collectivity=0)
1328 C<&dateofbirth> is the date of birth in ISO format (only if collectivity=0)
1329
1330 =cut
1331
1332 # FIXME: This function is not legitimate.  Multiple patrons might have the same first/last name and birthdate.
1333 # This is especially true since first name is not even a required field.
1334
1335 sub checkuniquemember {
1336     my ( $collectivity, $surname, $firstname, $dateofbirth ) = @_;
1337     my $dbh = C4::Context->dbh;
1338     my $request = ($collectivity) ?
1339         "SELECT borrowernumber,categorycode FROM borrowers WHERE surname=? " :
1340             ($dateofbirth) ?
1341             "SELECT borrowernumber,categorycode FROM borrowers WHERE surname=? and firstname=?  and dateofbirth=?" :
1342             "SELECT borrowernumber,categorycode FROM borrowers WHERE surname=? and firstname=?";
1343     my $sth = $dbh->prepare($request);
1344     if ($collectivity) {
1345         $sth->execute( uc($surname) );
1346     } elsif($dateofbirth){
1347         $sth->execute( uc($surname), ucfirst($firstname), $dateofbirth );
1348     }else{
1349         $sth->execute( uc($surname), ucfirst($firstname));
1350     }
1351     my @data = $sth->fetchrow;
1352     ( $data[0] ) and return $data[0], $data[1];
1353     return 0;
1354 }
1355
1356 sub checkcardnumber {
1357     my ( $cardnumber, $borrowernumber ) = @_;
1358
1359     # If cardnumber is null, we assume they're allowed.
1360     return 0 unless defined $cardnumber;
1361
1362     my $dbh = C4::Context->dbh;
1363     my $query = "SELECT * FROM borrowers WHERE cardnumber=?";
1364     $query .= " AND borrowernumber <> ?" if ($borrowernumber);
1365     my $sth = $dbh->prepare($query);
1366     $sth->execute(
1367         $cardnumber,
1368         ( $borrowernumber ? $borrowernumber : () )
1369     );
1370
1371     return 1 if $sth->fetchrow_hashref;
1372
1373     my ( $min_length, $max_length ) = get_cardnumber_length();
1374     return 2
1375         if length $cardnumber > $max_length
1376         or length $cardnumber < $min_length;
1377
1378     return 0;
1379 }
1380
1381 =head2 get_cardnumber_length
1382
1383     my ($min, $max) = C4::Members::get_cardnumber_length()
1384
1385 Returns the minimum and maximum length for patron cardnumbers as
1386 determined by the CardnumberLength system preference, the
1387 BorrowerMandatoryField system preference, and the width of the
1388 database column.
1389
1390 =cut
1391
1392 sub get_cardnumber_length {
1393     my ( $min, $max ) = ( 0, 16 ); # borrowers.cardnumber is a nullable varchar(16)
1394     $min = 1 if C4::Context->preference('BorrowerMandatoryField') =~ /cardnumber/;
1395     if ( my $cardnumber_length = C4::Context->preference('CardnumberLength') ) {
1396         # Is integer and length match
1397         if ( $cardnumber_length =~ m|^\d+$| ) {
1398             $min = $max = $cardnumber_length
1399                 if $cardnumber_length >= $min
1400                     and $cardnumber_length <= $max;
1401         }
1402         # Else assuming it is a range
1403         elsif ( $cardnumber_length =~ m|(\d*),(\d*)| ) {
1404             $min = $1 if $1 and $min < $1;
1405             $max = $2 if $2 and $max > $2;
1406         }
1407
1408     }
1409     return ( $min, $max );
1410 }
1411
1412 =head2 getzipnamecity (OUEST-PROVENCE)
1413
1414 take all info from table city for the fields city and  zip
1415 check for the name and the zip code of the city selected
1416
1417 =cut
1418
1419 sub getzipnamecity {
1420     my ($cityid) = @_;
1421     my $dbh      = C4::Context->dbh;
1422     my $sth      =
1423       $dbh->prepare(
1424         "select city_name,city_state,city_zipcode,city_country from cities where cityid=? ");
1425     $sth->execute($cityid);
1426     my @data = $sth->fetchrow;
1427     return $data[0], $data[1], $data[2], $data[3];
1428 }
1429
1430
1431 =head2 getdcity (OUEST-PROVENCE)
1432
1433 recover cityid  with city_name condition
1434
1435 =cut
1436
1437 sub getidcity {
1438     my ($city_name) = @_;
1439     my $dbh = C4::Context->dbh;
1440     my $sth = $dbh->prepare("select cityid from cities where city_name=? ");
1441     $sth->execute($city_name);
1442     my $data = $sth->fetchrow;
1443     return $data;
1444 }
1445
1446 =head2 GetFirstValidEmailAddress
1447
1448   $email = GetFirstValidEmailAddress($borrowernumber);
1449
1450 Return the first valid email address for a borrower, given the borrowernumber.  For now, the order 
1451 is defined as email, emailpro, B_email.  Returns the empty string if the borrower has no email 
1452 addresses.
1453
1454 =cut
1455
1456 sub GetFirstValidEmailAddress {
1457     my $borrowernumber = shift;
1458     my $dbh = C4::Context->dbh;
1459     my $sth = $dbh->prepare( "SELECT email, emailpro, B_email FROM borrowers where borrowernumber = ? ");
1460     $sth->execute( $borrowernumber );
1461     my $data = $sth->fetchrow_hashref;
1462
1463     if ($data->{'email'}) {
1464        return $data->{'email'};
1465     } elsif ($data->{'emailpro'}) {
1466        return $data->{'emailpro'};
1467     } elsif ($data->{'B_email'}) {
1468        return $data->{'B_email'};
1469     } else {
1470        return '';
1471     }
1472 }
1473
1474 =head2 GetNoticeEmailAddress
1475
1476   $email = GetNoticeEmailAddress($borrowernumber);
1477
1478 Return the email address of borrower used for notices, given the borrowernumber.
1479 Returns the empty string if no email address.
1480
1481 =cut
1482
1483 sub GetNoticeEmailAddress {
1484     my $borrowernumber = shift;
1485
1486     my $which_address = C4::Context->preference("AutoEmailPrimaryAddress");
1487     # if syspref is set to 'first valid' (value == OFF), look up email address
1488     if ( $which_address eq 'OFF' ) {
1489         return GetFirstValidEmailAddress($borrowernumber);
1490     }
1491     # specified email address field
1492     my $dbh = C4::Context->dbh;
1493     my $sth = $dbh->prepare( qq{
1494         SELECT $which_address AS primaryemail
1495         FROM borrowers
1496         WHERE borrowernumber=?
1497     } );
1498     $sth->execute($borrowernumber);
1499     my $data = $sth->fetchrow_hashref;
1500     return $data->{'primaryemail'} || '';
1501 }
1502
1503 =head2 GetExpiryDate 
1504
1505   $expirydate = GetExpiryDate($categorycode, $dateenrolled);
1506
1507 Calculate expiry date given a categorycode and starting date.  Date argument must be in ISO format.
1508 Return date is also in ISO format.
1509
1510 =cut
1511
1512 sub GetExpiryDate {
1513     my ( $categorycode, $dateenrolled ) = @_;
1514     my $enrolments;
1515     if ($categorycode) {
1516         my $dbh = C4::Context->dbh;
1517         my $sth = $dbh->prepare("SELECT enrolmentperiod,enrolmentperioddate FROM categories WHERE categorycode=?");
1518         $sth->execute($categorycode);
1519         $enrolments = $sth->fetchrow_hashref;
1520     }
1521     # die "GetExpiryDate: for enrollmentperiod $enrolmentperiod (category '$categorycode') starting $dateenrolled.\n";
1522     my @date = split (/-/,$dateenrolled);
1523     if($enrolments->{enrolmentperiod}){
1524         return sprintf("%04d-%02d-%02d", Add_Delta_YM(@date,0,$enrolments->{enrolmentperiod}));
1525     }else{
1526         return $enrolments->{enrolmentperioddate};
1527     }
1528 }
1529
1530 =head2 GetborCatFromCatType
1531
1532   ($codes_arrayref, $labels_hashref) = &GetborCatFromCatType();
1533
1534 Looks up the different types of borrowers in the database. Returns two
1535 elements: a reference-to-array, which lists the borrower category
1536 codes, and a reference-to-hash, which maps the borrower category codes
1537 to category descriptions.
1538
1539 =cut
1540
1541 #'
1542 sub GetborCatFromCatType {
1543     my ( $category_type, $action, $no_branch_limit ) = @_;
1544
1545     my $branch_limit = $no_branch_limit
1546         ? 0
1547         : C4::Context->userenv ? C4::Context->userenv->{"branch"} : "";
1548
1549     # FIXME - This API  seems both limited and dangerous.
1550     my $dbh     = C4::Context->dbh;
1551
1552     my $request = qq{
1553         SELECT categories.categorycode, categories.description
1554         FROM categories
1555     };
1556     $request .= qq{
1557         LEFT JOIN categories_branches ON categories.categorycode = categories_branches.categorycode
1558     } if $branch_limit;
1559     if($action) {
1560         $request .= " $action ";
1561         $request .= " AND (branchcode = ? OR branchcode IS NULL) GROUP BY description" if $branch_limit;
1562     } else {
1563         $request .= " WHERE branchcode = ? OR branchcode IS NULL GROUP BY description" if $branch_limit;
1564     }
1565     $request .= " ORDER BY categorycode";
1566
1567     my $sth = $dbh->prepare($request);
1568     $sth->execute(
1569         $action ? $category_type : (),
1570         $branch_limit ? $branch_limit : ()
1571     );
1572
1573     my %labels;
1574     my @codes;
1575
1576     while ( my $data = $sth->fetchrow_hashref ) {
1577         push @codes, $data->{'categorycode'};
1578         $labels{ $data->{'categorycode'} } = $data->{'description'};
1579     }
1580     $sth->finish;
1581     return ( \@codes, \%labels );
1582 }
1583
1584 =head2 GetBorrowercategory
1585
1586   $hashref = &GetBorrowercategory($categorycode);
1587
1588 Given the borrower's category code, the function returns the corresponding
1589 data hashref for a comprehensive information display.
1590
1591 =cut
1592
1593 sub GetBorrowercategory {
1594     my ($catcode) = @_;
1595     my $dbh       = C4::Context->dbh;
1596     if ($catcode){
1597         my $sth       =
1598         $dbh->prepare(
1599     "SELECT description,dateofbirthrequired,upperagelimit,category_type 
1600     FROM categories 
1601     WHERE categorycode = ?"
1602         );
1603         $sth->execute($catcode);
1604         my $data =
1605         $sth->fetchrow_hashref;
1606         return $data;
1607     } 
1608     return;  
1609 }    # sub getborrowercategory
1610
1611
1612 =head2 GetBorrowerCategorycode
1613
1614     $categorycode = &GetBorrowerCategoryCode( $borrowernumber );
1615
1616 Given the borrowernumber, the function returns the corresponding categorycode
1617 =cut
1618
1619 sub GetBorrowerCategorycode {
1620     my ( $borrowernumber ) = @_;
1621     my $dbh = C4::Context->dbh;
1622     my $sth = $dbh->prepare( qq{
1623         SELECT categorycode
1624         FROM borrowers
1625         WHERE borrowernumber = ?
1626     } );
1627     $sth->execute( $borrowernumber );
1628     return $sth->fetchrow;
1629 }
1630
1631 =head2 GetBorrowercategoryList
1632
1633   $arrayref_hashref = &GetBorrowercategoryList;
1634 If no category code provided, the function returns all the categories.
1635
1636 =cut
1637
1638 sub GetBorrowercategoryList {
1639     my $no_branch_limit = @_ ? shift : 0;
1640     my $branch_limit = $no_branch_limit
1641         ? 0
1642         : C4::Context->userenv ? C4::Context->userenv->{"branch"} : "";
1643     my $dbh       = C4::Context->dbh;
1644     my $query = "SELECT categories.* FROM categories";
1645     $query .= qq{
1646         LEFT JOIN categories_branches ON categories.categorycode = categories_branches.categorycode
1647         WHERE branchcode = ? OR branchcode IS NULL GROUP BY description
1648     } if $branch_limit;
1649     $query .= " ORDER BY description";
1650     my $sth = $dbh->prepare( $query );
1651     $sth->execute( $branch_limit ? $branch_limit : () );
1652     my $data = $sth->fetchall_arrayref( {} );
1653     $sth->finish;
1654     return $data;
1655 }    # sub getborrowercategory
1656
1657 =head2 ethnicitycategories
1658
1659   ($codes_arrayref, $labels_hashref) = &ethnicitycategories();
1660
1661 Looks up the different ethnic types in the database. Returns two
1662 elements: a reference-to-array, which lists the ethnicity codes, and a
1663 reference-to-hash, which maps the ethnicity codes to ethnicity
1664 descriptions.
1665
1666 =cut
1667
1668 #'
1669
1670 sub ethnicitycategories {
1671     my $dbh = C4::Context->dbh;
1672     my $sth = $dbh->prepare("Select code,name from ethnicity order by name");
1673     $sth->execute;
1674     my %labels;
1675     my @codes;
1676     while ( my $data = $sth->fetchrow_hashref ) {
1677         push @codes, $data->{'code'};
1678         $labels{ $data->{'code'} } = $data->{'name'};
1679     }
1680     return ( \@codes, \%labels );
1681 }
1682
1683 =head2 fixEthnicity
1684
1685   $ethn_name = &fixEthnicity($ethn_code);
1686
1687 Takes an ethnicity code (e.g., "european" or "pi") and returns the
1688 corresponding descriptive name from the C<ethnicity> table in the
1689 Koha database ("European" or "Pacific Islander").
1690
1691 =cut
1692
1693 #'
1694
1695 sub fixEthnicity {
1696     my $ethnicity = shift;
1697     return unless $ethnicity;
1698     my $dbh       = C4::Context->dbh;
1699     my $sth       = $dbh->prepare("Select name from ethnicity where code = ?");
1700     $sth->execute($ethnicity);
1701     my $data = $sth->fetchrow_hashref;
1702     return $data->{'name'};
1703 }    # sub fixEthnicity
1704
1705 =head2 GetAge
1706
1707   $dateofbirth,$date = &GetAge($date);
1708
1709 this function return the borrowers age with the value of dateofbirth
1710
1711 =cut
1712
1713 #'
1714 sub GetAge{
1715     my ( $date, $date_ref ) = @_;
1716
1717     if ( not defined $date_ref ) {
1718         $date_ref = sprintf( '%04d-%02d-%02d', Today() );
1719     }
1720
1721     my ( $year1, $month1, $day1 ) = split /-/, $date;
1722     my ( $year2, $month2, $day2 ) = split /-/, $date_ref;
1723
1724     my $age = $year2 - $year1;
1725     if ( $month1 . $day1 > $month2 . $day2 ) {
1726         $age--;
1727     }
1728
1729     return $age;
1730 }    # sub get_age
1731
1732 =head2 GetCities
1733
1734   $cityarrayref = GetCities();
1735
1736   Returns an array_ref of the entries in the cities table
1737   If there are entries in the table an empty row is returned
1738   This is currently only used to populate a popup in memberentry
1739
1740 =cut
1741
1742 sub GetCities {
1743
1744     my $dbh   = C4::Context->dbh;
1745     my $city_arr = $dbh->selectall_arrayref(
1746         q|SELECT cityid,city_zipcode,city_name,city_state,city_country FROM cities ORDER BY city_name|,
1747         { Slice => {} });
1748     if ( @{$city_arr} ) {
1749         unshift @{$city_arr}, {
1750             city_zipcode => q{},
1751             city_name    => q{},
1752             cityid       => q{},
1753             city_state   => q{},
1754             city_country => q{},
1755         };
1756     }
1757
1758     return  $city_arr;
1759 }
1760
1761 =head2 GetSortDetails (OUEST-PROVENCE)
1762
1763   ($lib) = &GetSortDetails($category,$sortvalue);
1764
1765 Returns the authorized value  details
1766 C<&$lib>return value of authorized value details
1767 C<&$sortvalue>this is the value of authorized value 
1768 C<&$category>this is the value of authorized value category
1769
1770 =cut
1771
1772 sub GetSortDetails {
1773     my ( $category, $sortvalue ) = @_;
1774     my $dbh   = C4::Context->dbh;
1775     my $query = qq|SELECT lib 
1776         FROM authorised_values 
1777         WHERE category=?
1778         AND authorised_value=? |;
1779     my $sth = $dbh->prepare($query);
1780     $sth->execute( $category, $sortvalue );
1781     my $lib = $sth->fetchrow;
1782     return ($lib) if ($lib);
1783     return ($sortvalue) unless ($lib);
1784 }
1785
1786 =head2 MoveMemberToDeleted
1787
1788   $result = &MoveMemberToDeleted($borrowernumber);
1789
1790 Copy the record from borrowers to deletedborrowers table.
1791
1792 =cut
1793
1794 # FIXME: should do it in one SQL statement w/ subquery
1795 # Otherwise, we should return the @data on success
1796
1797 sub MoveMemberToDeleted {
1798     my ($member) = shift or return;
1799     my $dbh = C4::Context->dbh;
1800     my $query = qq|SELECT * 
1801           FROM borrowers 
1802           WHERE borrowernumber=?|;
1803     my $sth = $dbh->prepare($query);
1804     $sth->execute($member);
1805     my @data = $sth->fetchrow_array;
1806     (@data) or return;  # if we got a bad borrowernumber, there's nothing to insert
1807     $sth =
1808       $dbh->prepare( "INSERT INTO deletedborrowers VALUES ("
1809           . ( "?," x ( scalar(@data) - 1 ) )
1810           . "?)" );
1811     $sth->execute(@data);
1812 }
1813
1814 =head2 DelMember
1815
1816     DelMember($borrowernumber);
1817
1818 This function remove directly a borrower whitout writing it on deleteborrower.
1819 + Deletes reserves for the borrower
1820
1821 =cut
1822
1823 sub DelMember {
1824     my $dbh            = C4::Context->dbh;
1825     my $borrowernumber = shift;
1826     #warn "in delmember with $borrowernumber";
1827     return unless $borrowernumber;    # borrowernumber is mandatory.
1828
1829     my $query = qq|DELETE 
1830           FROM  reserves 
1831           WHERE borrowernumber=?|;
1832     my $sth = $dbh->prepare($query);
1833     $sth->execute($borrowernumber);
1834     $query = "
1835        DELETE
1836        FROM borrowers
1837        WHERE borrowernumber = ?
1838    ";
1839     $sth = $dbh->prepare($query);
1840     $sth->execute($borrowernumber);
1841     logaction("MEMBERS", "DELETE", $borrowernumber, "") if C4::Context->preference("BorrowersLog");
1842     return $sth->rows;
1843 }
1844
1845 =head2 ExtendMemberSubscriptionTo (OUEST-PROVENCE)
1846
1847     $date = ExtendMemberSubscriptionTo($borrowerid, $date);
1848
1849 Extending the subscription to a given date or to the expiry date calculated on ISO date.
1850 Returns ISO date.
1851
1852 =cut
1853
1854 sub ExtendMemberSubscriptionTo {
1855     my ( $borrowerid,$date) = @_;
1856     my $dbh = C4::Context->dbh;
1857     my $borrower = GetMember('borrowernumber'=>$borrowerid);
1858     unless ($date){
1859       $date = (C4::Context->preference('BorrowerRenewalPeriodBase') eq 'dateexpiry') ?
1860                                         C4::Dates->new($borrower->{'dateexpiry'}, 'iso')->output("iso") :
1861                                         C4::Dates->new()->output("iso");
1862       $date = GetExpiryDate( $borrower->{'categorycode'}, $date );
1863     }
1864     my $sth = $dbh->do(<<EOF);
1865 UPDATE borrowers 
1866 SET  dateexpiry='$date' 
1867 WHERE borrowernumber='$borrowerid'
1868 EOF
1869
1870     AddEnrolmentFeeIfNeeded( $borrower->{categorycode}, $borrower->{borrowernumber} );
1871
1872     logaction("MEMBERS", "RENEW", $borrower->{'borrowernumber'}, "Membership renewed")if C4::Context->preference("BorrowersLog");
1873     return $date if ($sth);
1874     return 0;
1875 }
1876
1877 =head2 GetTitles (OUEST-PROVENCE)
1878
1879   ($borrowertitle)= &GetTitles();
1880
1881 Looks up the different title . Returns array  with all borrowers title
1882
1883 =cut
1884
1885 sub GetTitles {
1886     my @borrowerTitle = split (/,|\|/,C4::Context->preference('BorrowersTitles'));
1887     unshift( @borrowerTitle, "" );
1888     my $count=@borrowerTitle;
1889     if ($count == 1){
1890         return ();
1891     }
1892     else {
1893         return ( \@borrowerTitle);
1894     }
1895 }
1896
1897 =head2 GetPatronImage
1898
1899     my ($imagedata, $dberror) = GetPatronImage($borrowernumber);
1900
1901 Returns the mimetype and binary image data of the image for the patron with the supplied borrowernumber.
1902
1903 =cut
1904
1905 sub GetPatronImage {
1906     my ($borrowernumber) = @_;
1907     warn "Borrowernumber passed to GetPatronImage is $borrowernumber" if $debug;
1908     my $dbh = C4::Context->dbh;
1909     my $query = 'SELECT mimetype, imagefile FROM patronimage WHERE borrowernumber = ?';
1910     my $sth = $dbh->prepare($query);
1911     $sth->execute($borrowernumber);
1912     my $imagedata = $sth->fetchrow_hashref;
1913     warn "Database error!" if $sth->errstr;
1914     return $imagedata, $sth->errstr;
1915 }
1916
1917 =head2 PutPatronImage
1918
1919     PutPatronImage($cardnumber, $mimetype, $imgfile);
1920
1921 Stores patron binary image data and mimetype in database.
1922 NOTE: This function is good for updating images as well as inserting new images in the database.
1923
1924 =cut
1925
1926 sub PutPatronImage {
1927     my ($cardnumber, $mimetype, $imgfile) = @_;
1928     warn "Parameters passed in: Cardnumber=$cardnumber, Mimetype=$mimetype, " . ($imgfile ? "Imagefile" : "No Imagefile") if $debug;
1929     my $dbh = C4::Context->dbh;
1930     my $query = "INSERT INTO patronimage (borrowernumber, mimetype, imagefile) VALUES ( ( SELECT borrowernumber from borrowers WHERE cardnumber = ? ),?,?) ON DUPLICATE KEY UPDATE imagefile = ?;";
1931     my $sth = $dbh->prepare($query);
1932     $sth->execute($cardnumber,$mimetype,$imgfile,$imgfile);
1933     warn "Error returned inserting $cardnumber.$mimetype." if $sth->errstr;
1934     return $sth->errstr;
1935 }
1936
1937 =head2 RmPatronImage
1938
1939     my ($dberror) = RmPatronImage($borrowernumber);
1940
1941 Removes the image for the patron with the supplied borrowernumber.
1942
1943 =cut
1944
1945 sub RmPatronImage {
1946     my ($borrowernumber) = @_;
1947     warn "Borrowernumber passed to GetPatronImage is $borrowernumber" if $debug;
1948     my $dbh = C4::Context->dbh;
1949     my $query = "DELETE FROM patronimage WHERE borrowernumber = ?;";
1950     my $sth = $dbh->prepare($query);
1951     $sth->execute($borrowernumber);
1952     my $dberror = $sth->errstr;
1953     warn "Database error!" if $sth->errstr;
1954     return $dberror;
1955 }
1956
1957 =head2 GetHideLostItemsPreference
1958
1959   $hidelostitemspref = &GetHideLostItemsPreference($borrowernumber);
1960
1961 Returns the HideLostItems preference for the patron category of the supplied borrowernumber
1962 C<&$hidelostitemspref>return value of function, 0 or 1
1963
1964 =cut
1965
1966 sub GetHideLostItemsPreference {
1967     my ($borrowernumber) = @_;
1968     my $dbh = C4::Context->dbh;
1969     my $query = "SELECT hidelostitems FROM borrowers,categories WHERE borrowers.categorycode = categories.categorycode AND borrowernumber = ?";
1970     my $sth = $dbh->prepare($query);
1971     $sth->execute($borrowernumber);
1972     my $hidelostitems = $sth->fetchrow;    
1973     return $hidelostitems;    
1974 }
1975
1976 =head2 GetBorrowersToExpunge
1977
1978   $borrowers = &GetBorrowersToExpunge(
1979       not_borrowered_since => $not_borrowered_since,
1980       expired_before       => $expired_before,
1981       category_code        => $category_code,
1982       branchcode           => $branchcode
1983   );
1984
1985   This function get all borrowers based on the given criteria.
1986
1987 =cut
1988
1989 sub GetBorrowersToExpunge {
1990     my $params = shift;
1991
1992     my $filterdate     = $params->{'not_borrowered_since'};
1993     my $filterexpiry   = $params->{'expired_before'};
1994     my $filtercategory = $params->{'category_code'};
1995     my $filterbranch   = $params->{'branchcode'} ||
1996                         ((C4::Context->preference('IndependentBranches')
1997                              && C4::Context->userenv 
1998                              && !C4::Context->IsSuperLibrarian()
1999                              && C4::Context->userenv->{branch})
2000                          ? C4::Context->userenv->{branch}
2001                          : "");  
2002
2003     my $dbh   = C4::Context->dbh;
2004     my $query = "
2005         SELECT borrowers.borrowernumber,
2006                MAX(old_issues.timestamp) AS latestissue,
2007                MAX(issues.timestamp) AS currentissue
2008         FROM   borrowers
2009         JOIN   categories USING (categorycode)
2010         LEFT JOIN old_issues USING (borrowernumber)
2011         LEFT JOIN issues USING (borrowernumber) 
2012         WHERE  category_type <> 'S'
2013         AND borrowernumber NOT IN (SELECT guarantorid FROM borrowers WHERE guarantorid IS NOT NULL AND guarantorid <> 0)
2014    ";
2015     my @query_params;
2016     if ( $filterbranch && $filterbranch ne "" ) {
2017         $query.= " AND borrowers.branchcode = ? ";
2018         push( @query_params, $filterbranch );
2019     }
2020     if ( $filterexpiry ) {
2021         $query .= " AND dateexpiry < ? ";
2022         push( @query_params, $filterexpiry );
2023     }
2024     if ( $filtercategory ) {
2025         $query .= " AND categorycode = ? ";
2026         push( @query_params, $filtercategory );
2027     }
2028     $query.=" GROUP BY borrowers.borrowernumber HAVING currentissue IS NULL ";
2029     if ( $filterdate ) {
2030         $query.=" AND ( latestissue < ? OR latestissue IS NULL ) ";
2031         push @query_params,$filterdate;
2032     }
2033     warn $query if $debug;
2034
2035     my $sth = $dbh->prepare($query);
2036     if (scalar(@query_params)>0){  
2037         $sth->execute(@query_params);
2038     } 
2039     else {
2040         $sth->execute;
2041     }      
2042     
2043     my @results;
2044     while ( my $data = $sth->fetchrow_hashref ) {
2045         push @results, $data;
2046     }
2047     return \@results;
2048 }
2049
2050 =head2 GetBorrowersWhoHaveNeverBorrowed
2051
2052   $results = &GetBorrowersWhoHaveNeverBorrowed
2053
2054 This function get all borrowers who have never borrowed.
2055
2056 I<$result> is a ref to an array which all elements are a hasref.
2057
2058 =cut
2059
2060 sub GetBorrowersWhoHaveNeverBorrowed {
2061     my $filterbranch = shift || 
2062                         ((C4::Context->preference('IndependentBranches')
2063                              && C4::Context->userenv 
2064                              && !C4::Context->IsSuperLibrarian()
2065                              && C4::Context->userenv->{branch})
2066                          ? C4::Context->userenv->{branch}
2067                          : "");  
2068     my $dbh   = C4::Context->dbh;
2069     my $query = "
2070         SELECT borrowers.borrowernumber,max(timestamp) as latestissue
2071         FROM   borrowers
2072           LEFT JOIN issues ON borrowers.borrowernumber = issues.borrowernumber
2073         WHERE issues.borrowernumber IS NULL
2074    ";
2075     my @query_params;
2076     if ($filterbranch && $filterbranch ne ""){ 
2077         $query.=" AND borrowers.branchcode= ?";
2078         push @query_params,$filterbranch;
2079     }
2080     warn $query if $debug;
2081   
2082     my $sth = $dbh->prepare($query);
2083     if (scalar(@query_params)>0){  
2084         $sth->execute(@query_params);
2085     } 
2086     else {
2087         $sth->execute;
2088     }      
2089     
2090     my @results;
2091     while ( my $data = $sth->fetchrow_hashref ) {
2092         push @results, $data;
2093     }
2094     return \@results;
2095 }
2096
2097 =head2 GetBorrowersWithIssuesHistoryOlderThan
2098
2099   $results = &GetBorrowersWithIssuesHistoryOlderThan($date)
2100
2101 this function get all borrowers who has an issue history older than I<$date> given on input arg.
2102
2103 I<$result> is a ref to an array which all elements are a hashref.
2104 This hashref is containt the number of time this borrowers has borrowed before I<$date> and the borrowernumber.
2105
2106 =cut
2107
2108 sub GetBorrowersWithIssuesHistoryOlderThan {
2109     my $dbh  = C4::Context->dbh;
2110     my $date = shift ||POSIX::strftime("%Y-%m-%d",localtime());
2111     my $filterbranch = shift || 
2112                         ((C4::Context->preference('IndependentBranches')
2113                              && C4::Context->userenv 
2114                              && !C4::Context->IsSuperLibrarian()
2115                              && C4::Context->userenv->{branch})
2116                          ? C4::Context->userenv->{branch}
2117                          : "");  
2118     my $query = "
2119        SELECT count(borrowernumber) as n,borrowernumber
2120        FROM old_issues
2121        WHERE returndate < ?
2122          AND borrowernumber IS NOT NULL 
2123     "; 
2124     my @query_params;
2125     push @query_params, $date;
2126     if ($filterbranch){
2127         $query.="   AND branchcode = ?";
2128         push @query_params, $filterbranch;
2129     }    
2130     $query.=" GROUP BY borrowernumber ";
2131     warn $query if $debug;
2132     my $sth = $dbh->prepare($query);
2133     $sth->execute(@query_params);
2134     my @results;
2135
2136     while ( my $data = $sth->fetchrow_hashref ) {
2137         push @results, $data;
2138     }
2139     return \@results;
2140 }
2141
2142 =head2 GetBorrowersNamesAndLatestIssue
2143
2144   $results = &GetBorrowersNamesAndLatestIssueList(@borrowernumbers)
2145
2146 this function get borrowers Names and surnames and Issue information.
2147
2148 I<@borrowernumbers> is an array which all elements are borrowernumbers.
2149 This hashref is containt the number of time this borrowers has borrowed before I<$date> and the borrowernumber.
2150
2151 =cut
2152
2153 sub GetBorrowersNamesAndLatestIssue {
2154     my $dbh  = C4::Context->dbh;
2155     my @borrowernumbers=@_;  
2156     my $query = "
2157        SELECT surname,lastname, phone, email,max(timestamp)
2158        FROM borrowers 
2159          LEFT JOIN issues ON borrowers.borrowernumber=issues.borrowernumber
2160        GROUP BY borrowernumber
2161    ";
2162     my $sth = $dbh->prepare($query);
2163     $sth->execute;
2164     my $results = $sth->fetchall_arrayref({});
2165     return $results;
2166 }
2167
2168 =head2 ModPrivacy
2169
2170 =over 4
2171
2172 my $success = ModPrivacy( $borrowernumber, $privacy );
2173
2174 Update the privacy of a patron.
2175
2176 return :
2177 true on success, false on failure
2178
2179 =back
2180
2181 =cut
2182
2183 sub ModPrivacy {
2184     my $borrowernumber = shift;
2185     my $privacy = shift;
2186     return unless defined $borrowernumber;
2187     return unless $borrowernumber =~ /^\d+$/;
2188
2189     return ModMember( borrowernumber => $borrowernumber,
2190                       privacy        => $privacy );
2191 }
2192
2193 =head2 AddMessage
2194
2195   AddMessage( $borrowernumber, $message_type, $message, $branchcode );
2196
2197 Adds a message to the messages table for the given borrower.
2198
2199 Returns:
2200   True on success
2201   False on failure
2202
2203 =cut
2204
2205 sub AddMessage {
2206     my ( $borrowernumber, $message_type, $message, $branchcode ) = @_;
2207
2208     my $dbh  = C4::Context->dbh;
2209
2210     if ( ! ( $borrowernumber && $message_type && $message && $branchcode ) ) {
2211       return;
2212     }
2213
2214     my $query = "INSERT INTO messages ( borrowernumber, branchcode, message_type, message ) VALUES ( ?, ?, ?, ? )";
2215     my $sth = $dbh->prepare($query);
2216     $sth->execute( $borrowernumber, $branchcode, $message_type, $message );
2217     logaction("MEMBERS", "ADDCIRCMESSAGE", $borrowernumber, $message) if C4::Context->preference("BorrowersLog");
2218     return 1;
2219 }
2220
2221 =head2 GetMessages
2222
2223   GetMessages( $borrowernumber, $type );
2224
2225 $type is message type, B for borrower, or L for Librarian.
2226 Empty type returns all messages of any type.
2227
2228 Returns all messages for the given borrowernumber
2229
2230 =cut
2231
2232 sub GetMessages {
2233     my ( $borrowernumber, $type, $branchcode ) = @_;
2234
2235     if ( ! $type ) {
2236       $type = '%';
2237     }
2238
2239     my $dbh  = C4::Context->dbh;
2240
2241     my $query = "SELECT
2242                   branches.branchname,
2243                   messages.*,
2244                   message_date,
2245                   messages.branchcode LIKE '$branchcode' AS can_delete
2246                   FROM messages, branches
2247                   WHERE borrowernumber = ?
2248                   AND message_type LIKE ?
2249                   AND messages.branchcode = branches.branchcode
2250                   ORDER BY message_date DESC";
2251     my $sth = $dbh->prepare($query);
2252     $sth->execute( $borrowernumber, $type ) ;
2253     my @results;
2254
2255     while ( my $data = $sth->fetchrow_hashref ) {
2256         my $d = C4::Dates->new( $data->{message_date}, 'iso' );
2257         $data->{message_date_formatted} = $d->output;
2258         push @results, $data;
2259     }
2260     return \@results;
2261
2262 }
2263
2264 =head2 GetMessages
2265
2266   GetMessagesCount( $borrowernumber, $type );
2267
2268 $type is message type, B for borrower, or L for Librarian.
2269 Empty type returns all messages of any type.
2270
2271 Returns the number of messages for the given borrowernumber
2272
2273 =cut
2274
2275 sub GetMessagesCount {
2276     my ( $borrowernumber, $type, $branchcode ) = @_;
2277
2278     if ( ! $type ) {
2279       $type = '%';
2280     }
2281
2282     my $dbh  = C4::Context->dbh;
2283
2284     my $query = "SELECT COUNT(*) as MsgCount FROM messages WHERE borrowernumber = ? AND message_type LIKE ?";
2285     my $sth = $dbh->prepare($query);
2286     $sth->execute( $borrowernumber, $type ) ;
2287     my @results;
2288
2289     my $data = $sth->fetchrow_hashref;
2290     my $count = $data->{'MsgCount'};
2291
2292     return $count;
2293 }
2294
2295
2296
2297 =head2 DeleteMessage
2298
2299   DeleteMessage( $message_id );
2300
2301 =cut
2302
2303 sub DeleteMessage {
2304     my ( $message_id ) = @_;
2305
2306     my $dbh = C4::Context->dbh;
2307     my $query = "SELECT * FROM messages WHERE message_id = ?";
2308     my $sth = $dbh->prepare($query);
2309     $sth->execute( $message_id );
2310     my $message = $sth->fetchrow_hashref();
2311
2312     $query = "DELETE FROM messages WHERE message_id = ?";
2313     $sth = $dbh->prepare($query);
2314     $sth->execute( $message_id );
2315     logaction("MEMBERS", "DELCIRCMESSAGE", $message->{'borrowernumber'}, $message->{'message'}) if C4::Context->preference("BorrowersLog");
2316 }
2317
2318 =head2 IssueSlip
2319
2320   IssueSlip($branchcode, $borrowernumber, $quickslip)
2321
2322   Returns letter hash ( see C4::Letters::GetPreparedLetter )
2323
2324   $quickslip is boolean, to indicate whether we want a quick slip
2325
2326 =cut
2327
2328 sub IssueSlip {
2329     my ($branch, $borrowernumber, $quickslip) = @_;
2330
2331 #   return unless ( C4::Context->boolean_preference('printcirculationslips') );
2332
2333     my $now       = POSIX::strftime("%Y-%m-%d", localtime);
2334
2335     my $issueslist = GetPendingIssues($borrowernumber);
2336     foreach my $it (@$issueslist){
2337         if ((substr $it->{'issuedate'}, 0, 10) eq $now || (substr $it->{'lastreneweddate'}, 0, 10) eq $now) {
2338             $it->{'now'} = 1;
2339         }
2340         elsif ((substr $it->{'date_due'}, 0, 10) le $now) {
2341             $it->{'overdue'} = 1;
2342         }
2343         my $dt = dt_from_string( $it->{'date_due'} );
2344         $it->{'date_due'} = output_pref( $dt );;
2345     }
2346     my @issues = sort { $b->{'timestamp'} <=> $a->{'timestamp'} } @$issueslist;
2347
2348     my ($letter_code, %repeat);
2349     if ( $quickslip ) {
2350         $letter_code = 'ISSUEQSLIP';
2351         %repeat =  (
2352             'checkedout' => [ map {
2353                 'biblio' => $_,
2354                 'items'  => $_,
2355                 'issues' => $_,
2356             }, grep { $_->{'now'} } @issues ],
2357         );
2358     }
2359     else {
2360         $letter_code = 'ISSUESLIP';
2361         %repeat =  (
2362             'checkedout' => [ map {
2363                 'biblio' => $_,
2364                 'items'  => $_,
2365                 'issues' => $_,
2366             }, grep { !$_->{'overdue'} } @issues ],
2367
2368             'overdue' => [ map {
2369                 'biblio' => $_,
2370                 'items'  => $_,
2371                 'issues' => $_,
2372             }, grep { $_->{'overdue'} } @issues ],
2373
2374             'news' => [ map {
2375                 $_->{'timestamp'} = $_->{'newdate'};
2376                 { opac_news => $_ }
2377             } @{ GetNewsToDisplay("slip",$branch) } ],
2378         );
2379     }
2380
2381     return  C4::Letters::GetPreparedLetter (
2382         module => 'circulation',
2383         letter_code => $letter_code,
2384         branchcode => $branch,
2385         tables => {
2386             'branches'    => $branch,
2387             'borrowers'   => $borrowernumber,
2388         },
2389         repeat => \%repeat,
2390     );
2391 }
2392
2393 =head2 GetBorrowersWithEmail
2394
2395     ([$borrnum,$userid], ...) = GetBorrowersWithEmail('me@example.com');
2396
2397 This gets a list of users and their basic details from their email address.
2398 As it's possible for multiple user to have the same email address, it provides
2399 you with all of them. If there is no userid for the user, there will be an
2400 C<undef> there. An empty list will be returned if there are no matches.
2401
2402 =cut
2403
2404 sub GetBorrowersWithEmail {
2405     my $email = shift;
2406
2407     my $dbh = C4::Context->dbh;
2408
2409     my $query = "SELECT borrowernumber, userid FROM borrowers WHERE email=?";
2410     my $sth=$dbh->prepare($query);
2411     $sth->execute($email);
2412     my @result = ();
2413     while (my $ref = $sth->fetch) {
2414         push @result, $ref;
2415     }
2416     die "Failure searching for borrowers by email address: $sth->errstr" if $sth->err;
2417     return @result;
2418 }
2419
2420 sub AddMember_Opac {
2421     my ( %borrower ) = @_;
2422
2423     $borrower{'categorycode'} = C4::Context->preference('PatronSelfRegistrationDefaultCategory');
2424
2425     my $sr = new String::Random;
2426     $sr->{'A'} = [ 'A'..'Z', 'a'..'z' ];
2427     my $password = $sr->randpattern("AAAAAAAAAA");
2428     $borrower{'password'} = $password;
2429
2430     $borrower{'cardnumber'} = fixup_cardnumber();
2431
2432     my $borrowernumber = AddMember(%borrower);
2433
2434     return ( $borrowernumber, $password );
2435 }
2436
2437 =head2 AddEnrolmentFeeIfNeeded
2438
2439     AddEnrolmentFeeIfNeeded( $borrower->{categorycode}, $borrower->{borrowernumber} );
2440
2441 Add enrolment fee for a patron if needed.
2442
2443 =cut
2444
2445 sub AddEnrolmentFeeIfNeeded {
2446     my ( $categorycode, $borrowernumber ) = @_;
2447     # check for enrollment fee & add it if needed
2448     my $dbh = C4::Context->dbh;
2449     my $sth = $dbh->prepare(q{
2450         SELECT enrolmentfee
2451         FROM categories
2452         WHERE categorycode=?
2453     });
2454     $sth->execute( $categorycode );
2455     if ( $sth->err ) {
2456         warn sprintf('Database returned the following error: %s', $sth->errstr);
2457         return;
2458     }
2459     my ($enrolmentfee) = $sth->fetchrow;
2460     if ($enrolmentfee && $enrolmentfee > 0) {
2461         # insert fee in patron debts
2462         C4::Accounts::manualinvoice( $borrowernumber, '', '', 'A', $enrolmentfee );
2463     }
2464 }
2465
2466 sub HasOverdues {
2467     my ( $borrowernumber ) = @_;
2468
2469     my $sql = "SELECT COUNT(*) FROM issues WHERE date_due < NOW() AND borrowernumber = ?";
2470     my $sth = C4::Context->dbh->prepare( $sql );
2471     $sth->execute( $borrowernumber );
2472     my ( $count ) = $sth->fetchrow_array();
2473
2474     return $count;
2475 }
2476
2477 END { }    # module clean-up code here (global destructor)
2478
2479 1;
2480
2481 __END__
2482
2483 =head1 AUTHOR
2484
2485 Koha Team
2486
2487 =cut