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