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