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