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