Bug 14586 - Update about page with new 3.18 release team
[koha.git] / C4 / Members.pm
blobf410bf987697ace51bafa7fdbe62f307a9c46fa0
1 package C4::Members;
3 # Copyright 2000-2003 Katipo Communications
4 # Copyright 2010 BibLibre
5 # Parts Copyright 2010 Catalyst IT
7 # This file is part of Koha.
9 # Koha is free software; you can redistribute it and/or modify it
10 # under the terms of the GNU General Public License as published by
11 # the Free Software Foundation; either version 3 of the License, or
12 # (at your option) any later version.
14 # Koha is distributed in the hope that it will be useful, but
15 # WITHOUT ANY WARRANTY; without even the implied warranty of
16 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 # GNU General Public License for more details.
19 # You should have received a copy of the GNU General Public License
20 # along with Koha; if not, see <http://www.gnu.org/licenses>.
23 use strict;
24 #use warnings; FIXME - Bug 2505
25 use C4::Context;
26 use C4::Dates qw(format_date_in_iso format_date);
27 use String::Random qw( random_string );
28 use Date::Calc qw/Today Add_Delta_YM check_date Date_to_Days/;
29 use C4::Log; # logaction
30 use C4::Overdues;
31 use C4::Reserves;
32 use C4::Accounts;
33 use C4::Biblio;
34 use C4::Letters;
35 use C4::SQLHelper qw(InsertInTable UpdateInTable SearchInTable);
36 use C4::Members::Attributes qw(SearchIdMatchingAttribute UpdateBorrowerAttribute);
37 use C4::NewsChannels; #get slip news
38 use DateTime;
39 use DateTime::Format::DateParse;
40 use Koha::Database;
41 use Koha::DateUtils;
42 use Koha::Borrower::Debarments qw(IsDebarred);
43 use Text::Unaccent qw( unac_string );
44 use Koha::AuthUtils qw(hash_password);
45 use Koha::Database;
46 use Module::Load;
47 if ( C4::Context->preference('NorwegianPatronDBEnable') && C4::Context->preference('NorwegianPatronDBEnable') == 1 ) {
48 load Koha::NorwegianPatronDB, qw( NLUpdateHashedPIN NLEncryptPIN NLSync );
51 our ($VERSION,@ISA,@EXPORT,@EXPORT_OK,$debug);
53 BEGIN {
54 $VERSION = 3.07.00.049;
55 $debug = $ENV{DEBUG} || 0;
56 require Exporter;
57 @ISA = qw(Exporter);
58 #Get data
59 push @EXPORT, qw(
60 &Search
61 &GetMemberDetails
62 &GetMemberRelatives
63 &GetMember
65 &GetGuarantees
67 &GetMemberIssuesAndFines
68 &GetPendingIssues
69 &GetAllIssues
71 &getzipnamecity
72 &getidcity
74 &GetFirstValidEmailAddress
75 &GetNoticeEmailAddress
77 &GetAge
78 &GetCities
79 &GetSortDetails
80 &GetTitles
82 &GetPatronImage
83 &PutPatronImage
84 &RmPatronImage
86 &GetHideLostItemsPreference
88 &IsMemberBlocked
89 &GetMemberAccountRecords
90 &GetBorNotifyAcctRecord
92 &GetborCatFromCatType
93 &GetBorrowercategory
94 GetBorrowerCategorycode
95 &GetBorrowercategoryList
97 &GetBorrowersToExpunge
98 &GetBorrowersWhoHaveNeverBorrowed
99 &GetBorrowersWithIssuesHistoryOlderThan
101 &GetExpiryDate
103 &AddMessage
104 &DeleteMessage
105 &GetMessages
106 &GetMessagesCount
108 &IssueSlip
109 GetBorrowersWithEmail
111 HasOverdues
114 #Modify data
115 push @EXPORT, qw(
116 &ModMember
117 &changepassword
118 &ModPrivacy
121 #Delete data
122 push @EXPORT, qw(
123 &DelMember
126 #Insert data
127 push @EXPORT, qw(
128 &AddMember
129 &AddMember_Opac
130 &MoveMemberToDeleted
131 &ExtendMemberSubscriptionTo
134 #Check data
135 push @EXPORT, qw(
136 &checkuniquemember
137 &checkuserpassword
138 &Check_Userid
139 &Generate_Userid
140 &fixEthnicity
141 &ethnicitycategories
142 &fixup_cardnumber
143 &checkcardnumber
147 =head1 NAME
149 C4::Members - Perl Module containing convenience functions for member handling
151 =head1 SYNOPSIS
153 use C4::Members;
155 =head1 DESCRIPTION
157 This module contains routines for adding, modifying and deleting members/patrons/borrowers
159 =head1 FUNCTIONS
161 =head2 Search
163 $borrowers_result_array_ref = &Search($filter,$orderby, $limit,
164 $columns_out, $search_on_fields,$searchtype);
166 Looks up patrons (borrowers) on filter. A wrapper for SearchInTable('borrowers').
168 For C<$filter>, C<$orderby>, C<$limit>, C<&columns_out>, C<&search_on_fields> and C<&searchtype>
169 refer to C4::SQLHelper:SearchInTable().
171 Special C<$filter> key '' is effectively expanded to search on surname firstname othernamescw
172 and cardnumber unless C<&search_on_fields> is defined
174 Examples:
176 $borrowers = Search('abcd', 'cardnumber');
178 $borrowers = Search({''=>'abcd', category_type=>'I'}, 'surname');
180 =cut
182 sub _express_member_find {
183 my ($filter) = @_;
185 # this is used by circulation everytime a new borrowers cardnumber is scanned
186 # so we can check an exact match first, if that works return, otherwise do the rest
187 my $dbh = C4::Context->dbh;
188 my $query = "SELECT borrowernumber FROM borrowers WHERE cardnumber = ?";
189 if ( my $borrowernumber = $dbh->selectrow_array($query, undef, $filter) ) {
190 return( {"borrowernumber"=>$borrowernumber} );
193 my ($search_on_fields, $searchtype);
194 if ( length($filter) == 1 ) {
195 $search_on_fields = [ qw(surname) ];
196 $searchtype = 'start_with';
197 } else {
198 $search_on_fields = [ qw(surname firstname othernames cardnumber) ];
199 $searchtype = 'contain';
202 return (undef, $search_on_fields, $searchtype);
205 sub Search {
206 my ( $filter, $orderby, $limit, $columns_out, $search_on_fields, $searchtype ) = @_;
208 my $search_string;
209 my $found_borrower;
211 if ( my $fr = ref $filter ) {
212 if ( $fr eq "HASH" ) {
213 if ( my $search_string = $filter->{''} ) {
214 my ($member_filter, $member_search_on_fields, $member_searchtype) = _express_member_find($search_string);
215 if ($member_filter) {
216 $filter = $member_filter;
217 $found_borrower = 1;
218 } else {
219 $search_on_fields ||= $member_search_on_fields;
220 $searchtype ||= $member_searchtype;
224 else {
225 $search_string = $filter;
228 else {
229 $search_string = $filter;
230 my ($member_filter, $member_search_on_fields, $member_searchtype) = _express_member_find($search_string);
231 if ($member_filter) {
232 $filter = $member_filter;
233 $found_borrower = 1;
234 } else {
235 $search_on_fields ||= $member_search_on_fields;
236 $searchtype ||= $member_searchtype;
240 if ( !$found_borrower && C4::Context->preference('ExtendedPatronAttributes') && $search_string ) {
241 my $matching_records = C4::Members::Attributes::SearchIdMatchingAttribute($search_string);
242 if(scalar(@$matching_records)>0) {
243 if ( my $fr = ref $filter ) {
244 if ( $fr eq "HASH" ) {
245 my %f = %$filter;
246 $filter = [ $filter ];
247 delete $f{''};
248 push @$filter, { %f, "borrowernumber"=>$$matching_records };
250 else {
251 push @$filter, {"borrowernumber"=>$matching_records};
254 else {
255 $filter = [ $filter ];
256 push @$filter, {"borrowernumber"=>$matching_records};
261 # $showallbranches was not used at the time SearchMember() was mainstreamed into Search().
262 # Mentioning for the reference
264 if ( C4::Context->preference("IndependentBranches") ) { # && !$showallbranches){
265 if ( my $userenv = C4::Context->userenv ) {
266 my $branch = $userenv->{'branch'};
267 if ( !C4::Context->IsSuperLibrarian() && $branch ){
268 if (my $fr = ref $filter) {
269 if ( $fr eq "HASH" ) {
270 $filter->{branchcode} = $branch;
272 else {
273 foreach (@$filter) {
274 $_ = { '' => $_ } unless ref $_;
275 $_->{branchcode} = $branch;
279 else {
280 $filter = { '' => $filter, branchcode => $branch };
286 if ($found_borrower) {
287 $searchtype = "exact";
289 $searchtype ||= "start_with";
291 return SearchInTable( "borrowers", $filter, $orderby, $limit, $columns_out, $search_on_fields, $searchtype );
294 =head2 GetMemberDetails
296 ($borrower) = &GetMemberDetails($borrowernumber, $cardnumber);
298 Looks up a patron and returns information about him or her. If
299 C<$borrowernumber> is true (nonzero), C<&GetMemberDetails> looks
300 up the borrower by number; otherwise, it looks up the borrower by card
301 number.
303 C<$borrower> is a reference-to-hash whose keys are the fields of the
304 borrowers table in the Koha database. In addition,
305 C<$borrower-E<gt>{flags}> is a hash giving more detailed information
306 about the patron. Its keys act as flags :
308 if $borrower->{flags}->{LOST} {
309 # Patron's card was reported lost
312 If the state of a flag means that the patron should not be
313 allowed to borrow any more books, then it will have a C<noissues> key
314 with a true value.
316 See patronflags for more details.
318 C<$borrower-E<gt>{authflags}> is a hash giving more detailed information
319 about the top-level permissions flags set for the borrower. For example,
320 if a user has the "editcatalogue" permission,
321 C<$borrower-E<gt>{authflags}-E<gt>{editcatalogue}> will exist and have
322 the value "1".
324 =cut
326 sub GetMemberDetails {
327 my ( $borrowernumber, $cardnumber ) = @_;
328 my $dbh = C4::Context->dbh;
329 my $query;
330 my $sth;
331 if ($borrowernumber) {
332 $sth = $dbh->prepare("
333 SELECT borrowers.*,
334 category_type,
335 categories.description,
336 categories.BlockExpiredPatronOpacActions,
337 reservefee,
338 enrolmentperiod
339 FROM borrowers
340 LEFT JOIN categories ON borrowers.categorycode=categories.categorycode
341 WHERE borrowernumber = ?
343 $sth->execute($borrowernumber);
345 elsif ($cardnumber) {
346 $sth = $dbh->prepare("
347 SELECT borrowers.*,
348 category_type,
349 categories.description,
350 categories.BlockExpiredPatronOpacActions,
351 reservefee,
352 enrolmentperiod
353 FROM borrowers
354 LEFT JOIN categories ON borrowers.categorycode = categories.categorycode
355 WHERE cardnumber = ?
357 $sth->execute($cardnumber);
359 else {
360 return;
362 my $borrower = $sth->fetchrow_hashref;
363 return unless $borrower;
364 my ($amount) = GetMemberAccountRecords($borrower->{borrowernumber});
365 $borrower->{'amountoutstanding'} = $amount;
366 # FIXME - patronflags calls GetMemberAccountRecords... just have patronflags return $amount
367 my $flags = patronflags( $borrower);
368 my $accessflagshash;
370 $sth = $dbh->prepare("select bit,flag from userflags");
371 $sth->execute;
372 while ( my ( $bit, $flag ) = $sth->fetchrow ) {
373 if ( $borrower->{'flags'} && $borrower->{'flags'} & 2**$bit ) {
374 $accessflagshash->{$flag} = 1;
377 $borrower->{'flags'} = $flags;
378 $borrower->{'authflags'} = $accessflagshash;
380 # For the purposes of making templates easier, we'll define a
381 # 'showname' which is the alternate form the user's first name if
382 # 'other name' is defined.
383 if ($borrower->{category_type} eq 'I') {
384 $borrower->{'showname'} = $borrower->{'othernames'};
385 $borrower->{'showname'} .= " $borrower->{'firstname'}" if $borrower->{'firstname'};
386 } else {
387 $borrower->{'showname'} = $borrower->{'firstname'};
390 # Handle setting the true behavior for BlockExpiredPatronOpacActions
391 $borrower->{'BlockExpiredPatronOpacActions'} =
392 C4::Context->preference('BlockExpiredPatronOpacActions')
393 if ( $borrower->{'BlockExpiredPatronOpacActions'} == -1 );
395 $borrower->{'is_expired'} = 0;
396 $borrower->{'is_expired'} = 1 if
397 defined($borrower->{dateexpiry}) &&
398 $borrower->{'dateexpiry'} ne '0000-00-00' &&
399 Date_to_Days( Today() ) >
400 Date_to_Days( split /-/, $borrower->{'dateexpiry'} );
402 return ($borrower); #, $flags, $accessflagshash);
405 =head2 patronflags
407 $flags = &patronflags($patron);
409 This function is not exported.
411 The following will be set where applicable:
412 $flags->{CHARGES}->{amount} Amount of debt
413 $flags->{CHARGES}->{noissues} Set if debt amount >$5.00 (or syspref noissuescharge)
414 $flags->{CHARGES}->{message} Message -- deprecated
416 $flags->{CREDITS}->{amount} Amount of credit
417 $flags->{CREDITS}->{message} Message -- deprecated
419 $flags->{ GNA } Patron has no valid address
420 $flags->{ GNA }->{noissues} Set for each GNA
421 $flags->{ GNA }->{message} "Borrower has no valid address" -- deprecated
423 $flags->{ LOST } Patron's card reported lost
424 $flags->{ LOST }->{noissues} Set for each LOST
425 $flags->{ LOST }->{message} Message -- deprecated
427 $flags->{DBARRED} Set if patron debarred, no access
428 $flags->{DBARRED}->{noissues} Set for each DBARRED
429 $flags->{DBARRED}->{message} Message -- deprecated
431 $flags->{ NOTES }
432 $flags->{ NOTES }->{message} The note itself. NOT deprecated
434 $flags->{ ODUES } Set if patron has overdue books.
435 $flags->{ ODUES }->{message} "Yes" -- deprecated
436 $flags->{ ODUES }->{itemlist} ref-to-array: list of overdue books
437 $flags->{ ODUES }->{itemlisttext} Text list of overdue items -- deprecated
439 $flags->{WAITING} Set if any of patron's reserves are available
440 $flags->{WAITING}->{message} Message -- deprecated
441 $flags->{WAITING}->{itemlist} ref-to-array: list of available items
443 =over
445 =item C<$flags-E<gt>{ODUES}-E<gt>{itemlist}> is a reference-to-array listing the
446 overdue items. Its elements are references-to-hash, each describing an
447 overdue item. The keys are selected fields from the issues, biblio,
448 biblioitems, and items tables of the Koha database.
450 =item C<$flags-E<gt>{ODUES}-E<gt>{itemlisttext}> is a string giving a text listing of
451 the overdue items, one per line. Deprecated.
453 =item C<$flags-E<gt>{WAITING}-E<gt>{itemlist}> is a reference-to-array listing the
454 available items. Each element is a reference-to-hash whose keys are
455 fields from the reserves table of the Koha database.
457 =back
459 All the "message" fields that include language generated in this function are deprecated,
460 because such strings belong properly in the display layer.
462 The "message" field that comes from the DB is OK.
464 =cut
466 # TODO: use {anonymous => hashes} instead of a dozen %flaginfo
467 # FIXME rename this function.
468 sub patronflags {
469 my %flags;
470 my ( $patroninformation) = @_;
471 my $dbh=C4::Context->dbh;
472 my ($balance, $owing) = GetMemberAccountBalance( $patroninformation->{'borrowernumber'});
473 if ( $owing > 0 ) {
474 my %flaginfo;
475 my $noissuescharge = C4::Context->preference("noissuescharge") || 5;
476 $flaginfo{'message'} = sprintf 'Patron owes %.02f', $owing;
477 $flaginfo{'amount'} = sprintf "%.02f", $owing;
478 if ( $owing > $noissuescharge && !C4::Context->preference("AllowFineOverride") ) {
479 $flaginfo{'noissues'} = 1;
481 $flags{'CHARGES'} = \%flaginfo;
483 elsif ( $balance < 0 ) {
484 my %flaginfo;
485 $flaginfo{'message'} = sprintf 'Patron has credit of %.02f', -$balance;
486 $flaginfo{'amount'} = sprintf "%.02f", $balance;
487 $flags{'CREDITS'} = \%flaginfo;
489 if ( $patroninformation->{'gonenoaddress'}
490 && $patroninformation->{'gonenoaddress'} == 1 )
492 my %flaginfo;
493 $flaginfo{'message'} = 'Borrower has no valid address.';
494 $flaginfo{'noissues'} = 1;
495 $flags{'GNA'} = \%flaginfo;
497 if ( $patroninformation->{'lost'} && $patroninformation->{'lost'} == 1 ) {
498 my %flaginfo;
499 $flaginfo{'message'} = 'Borrower\'s card reported lost.';
500 $flaginfo{'noissues'} = 1;
501 $flags{'LOST'} = \%flaginfo;
503 if ( $patroninformation->{'debarred'} && check_date( split( /-/, $patroninformation->{'debarred'} ) ) ) {
504 if ( Date_to_Days(Date::Calc::Today) < Date_to_Days( split( /-/, $patroninformation->{'debarred'} ) ) ) {
505 my %flaginfo;
506 $flaginfo{'debarredcomment'} = $patroninformation->{'debarredcomment'};
507 $flaginfo{'message'} = $patroninformation->{'debarredcomment'};
508 $flaginfo{'noissues'} = 1;
509 $flaginfo{'dateend'} = $patroninformation->{'debarred'};
510 $flags{'DBARRED'} = \%flaginfo;
513 if ( $patroninformation->{'borrowernotes'}
514 && $patroninformation->{'borrowernotes'} )
516 my %flaginfo;
517 $flaginfo{'message'} = $patroninformation->{'borrowernotes'};
518 $flags{'NOTES'} = \%flaginfo;
520 my ( $odues, $itemsoverdue ) = C4::Overdues::checkoverdues($patroninformation->{'borrowernumber'});
521 if ( $odues && $odues > 0 ) {
522 my %flaginfo;
523 $flaginfo{'message'} = "Yes";
524 $flaginfo{'itemlist'} = $itemsoverdue;
525 foreach ( sort { $a->{'date_due'} cmp $b->{'date_due'} }
526 @$itemsoverdue )
528 $flaginfo{'itemlisttext'} .=
529 "$_->{'date_due'} $_->{'barcode'} $_->{'title'} \n"; # newline is display layer
531 $flags{'ODUES'} = \%flaginfo;
533 my @itemswaiting = C4::Reserves::GetReservesFromBorrowernumber( $patroninformation->{'borrowernumber'},'W' );
534 my $nowaiting = scalar @itemswaiting;
535 if ( $nowaiting > 0 ) {
536 my %flaginfo;
537 $flaginfo{'message'} = "Reserved items available";
538 $flaginfo{'itemlist'} = \@itemswaiting;
539 $flags{'WAITING'} = \%flaginfo;
541 return ( \%flags );
545 =head2 GetMember
547 $borrower = &GetMember(%information);
549 Retrieve the first patron record meeting on criteria listed in the
550 C<%information> hash, which should contain one or more
551 pairs of borrowers column names and values, e.g.,
553 $borrower = GetMember(borrowernumber => id);
555 C<&GetBorrower> returns a reference-to-hash whose keys are the fields of
556 the C<borrowers> table in the Koha database.
558 FIXME: GetMember() is used throughout the code as a lookup
559 on a unique key such as the borrowernumber, but this meaning is not
560 enforced in the routine itself.
562 =cut
565 sub GetMember {
566 my ( %information ) = @_;
567 if (exists $information{borrowernumber} && !defined $information{borrowernumber}) {
568 #passing mysql's kohaadmin?? Makes no sense as a query
569 return;
571 my $dbh = C4::Context->dbh;
572 my $select =
573 q{SELECT borrowers.*, categories.category_type, categories.description
574 FROM borrowers
575 LEFT JOIN categories on borrowers.categorycode=categories.categorycode WHERE };
576 my $more_p = 0;
577 my @values = ();
578 for (keys %information ) {
579 if ($more_p) {
580 $select .= ' AND ';
582 else {
583 $more_p++;
586 if (defined $information{$_}) {
587 $select .= "$_ = ?";
588 push @values, $information{$_};
590 else {
591 $select .= "$_ IS NULL";
594 $debug && warn $select, " ",values %information;
595 my $sth = $dbh->prepare("$select");
596 $sth->execute(map{$information{$_}} keys %information);
597 my $data = $sth->fetchall_arrayref({});
598 #FIXME interface to this routine now allows generation of a result set
599 #so whole array should be returned but bowhere in the current code expects this
600 if (@{$data} ) {
601 return $data->[0];
604 return;
607 =head2 GetMemberRelatives
609 @borrowernumbers = GetMemberRelatives($borrowernumber);
611 C<GetMemberRelatives> returns a borrowersnumber's list of guarantor/guarantees of the member given in parameter
613 =cut
615 sub GetMemberRelatives {
616 my $borrowernumber = shift;
617 my $dbh = C4::Context->dbh;
618 my @glist;
620 # Getting guarantor
621 my $query = "SELECT guarantorid FROM borrowers WHERE borrowernumber=?";
622 my $sth = $dbh->prepare($query);
623 $sth->execute($borrowernumber);
624 my $data = $sth->fetchrow_arrayref();
625 push @glist, $data->[0] if $data->[0];
626 my $guarantor = $data->[0] ? $data->[0] : undef;
628 # Getting guarantees
629 $query = "SELECT borrowernumber FROM borrowers WHERE guarantorid=?";
630 $sth = $dbh->prepare($query);
631 $sth->execute($borrowernumber);
632 while ($data = $sth->fetchrow_arrayref()) {
633 push @glist, $data->[0];
636 # Getting sibling guarantees
637 if ($guarantor) {
638 $query = "SELECT borrowernumber FROM borrowers WHERE guarantorid=?";
639 $sth = $dbh->prepare($query);
640 $sth->execute($guarantor);
641 while ($data = $sth->fetchrow_arrayref()) {
642 push @glist, $data->[0] if ($data->[0] != $borrowernumber);
646 return @glist;
649 =head2 IsMemberBlocked
651 my ($block_status, $count) = IsMemberBlocked( $borrowernumber );
653 Returns whether a patron has overdue items that may result
654 in a block or whether the patron has active fine days
655 that would block circulation privileges.
657 C<$block_status> can have the following values:
659 1 if the patron has outstanding fine days or a manual debarment, in which case
660 C<$count> is the expiration date (9999-12-31 for indefinite)
662 -1 if the patron has overdue items, in which case C<$count> is the number of them
664 0 if the patron has no overdue items or outstanding fine days, in which case C<$count> is 0
666 Outstanding fine days are checked before current overdue items
667 are.
669 FIXME: this needs to be split into two functions; a potential block
670 based on the number of current overdue items could be orthogonal
671 to a block based on whether the patron has any fine days accrued.
673 =cut
675 sub IsMemberBlocked {
676 my $borrowernumber = shift;
677 my $dbh = C4::Context->dbh;
679 my $blockeddate = Koha::Borrower::Debarments::IsDebarred($borrowernumber);
681 return ( 1, $blockeddate ) if $blockeddate;
683 # if he have late issues
684 my $sth = $dbh->prepare(
685 "SELECT COUNT(*) as latedocs
686 FROM issues
687 WHERE borrowernumber = ?
688 AND date_due < now()"
690 $sth->execute($borrowernumber);
691 my $latedocs = $sth->fetchrow_hashref->{'latedocs'};
693 return ( -1, $latedocs ) if $latedocs > 0;
695 return ( 0, 0 );
698 =head2 GetMemberIssuesAndFines
700 ($overdue_count, $issue_count, $total_fines) = &GetMemberIssuesAndFines($borrowernumber);
702 Returns aggregate data about items borrowed by the patron with the
703 given borrowernumber.
705 C<&GetMemberIssuesAndFines> returns a three-element array. C<$overdue_count> is the
706 number of overdue items the patron currently has borrowed. C<$issue_count> is the
707 number of books the patron currently has borrowed. C<$total_fines> is
708 the total fine currently due by the borrower.
710 =cut
713 sub GetMemberIssuesAndFines {
714 my ( $borrowernumber ) = @_;
715 my $dbh = C4::Context->dbh;
716 my $query = "SELECT COUNT(*) FROM issues WHERE borrowernumber = ?";
718 $debug and warn $query."\n";
719 my $sth = $dbh->prepare($query);
720 $sth->execute($borrowernumber);
721 my $issue_count = $sth->fetchrow_arrayref->[0];
723 $sth = $dbh->prepare(
724 "SELECT COUNT(*) FROM issues
725 WHERE borrowernumber = ?
726 AND date_due < now()"
728 $sth->execute($borrowernumber);
729 my $overdue_count = $sth->fetchrow_arrayref->[0];
731 $sth = $dbh->prepare("SELECT SUM(amountoutstanding) FROM accountlines WHERE borrowernumber = ?");
732 $sth->execute($borrowernumber);
733 my $total_fines = $sth->fetchrow_arrayref->[0];
735 return ($overdue_count, $issue_count, $total_fines);
739 =head2 columns
741 my @columns = C4::Member::columns();
743 Returns an array of borrowers' table columns on success,
744 and an empty array on failure.
746 =cut
748 sub columns {
750 # Pure ANSI SQL goodness.
751 my $sql = 'SELECT * FROM borrowers WHERE 1=0;';
753 # Get the database handle.
754 my $dbh = C4::Context->dbh;
756 # Run the SQL statement to load STH's readonly properties.
757 my $sth = $dbh->prepare($sql);
758 my $rv = $sth->execute();
760 # This only fails if the table doesn't exist.
761 # This will always be called AFTER an install or upgrade,
762 # so borrowers will exist!
763 my @data;
764 if ($sth->{NUM_OF_FIELDS}>0) {
765 @data = @{$sth->{NAME}};
767 else {
768 @data = ();
770 return @data;
774 =head2 ModMember
776 my $success = ModMember(borrowernumber => $borrowernumber,
777 [ field => value ]... );
779 Modify borrower's data. All date fields should ALREADY be in ISO format.
781 return :
782 true on success, or false on failure
784 =cut
786 sub ModMember {
787 my (%data) = @_;
788 # test to know if you must update or not the borrower password
789 if (exists $data{password}) {
790 if ($data{password} eq '****' or $data{password} eq '') {
791 delete $data{password};
792 } else {
793 if ( C4::Context->preference('NorwegianPatronDBEnable') && C4::Context->preference('NorwegianPatronDBEnable') == 1 ) {
794 # Update the hashed PIN in borrower_sync.hashed_pin, before Koha hashes it
795 NLUpdateHashedPIN( $data{'borrowernumber'}, $data{password} );
797 $data{password} = hash_password($data{password});
800 my $old_categorycode = GetBorrowerCategorycode( $data{borrowernumber} );
801 my $execute_success=UpdateInTable("borrowers",\%data);
802 if ($execute_success) { # only proceed if the update was a success
803 # ok if its an adult (type) it may have borrowers that depend on it as a guarantor
804 # so when we update information for an adult we should check for guarantees and update the relevant part
805 # of their records, ie addresses and phone numbers
806 my $borrowercategory= GetBorrowercategory( $data{'category_type'} );
807 if ( exists $borrowercategory->{'category_type'} && $borrowercategory->{'category_type'} eq ('A' || 'S') ) {
808 # is adult check guarantees;
809 UpdateGuarantees(%data);
812 # If the patron changes to a category with enrollment fee, we add a fee
813 if ( $data{categorycode} and $data{categorycode} ne $old_categorycode ) {
814 AddEnrolmentFeeIfNeeded( $data{categorycode}, $data{borrowernumber} );
817 # If NorwegianPatronDBEnable is enabled, we set syncstatus to something that a
818 # cronjob will use for syncing with NL
819 if ( C4::Context->preference('NorwegianPatronDBEnable') && C4::Context->preference('NorwegianPatronDBEnable') == 1 ) {
820 my $borrowersync = Koha::Database->new->schema->resultset('BorrowerSync')->find({
821 'synctype' => 'norwegianpatrondb',
822 'borrowernumber' => $data{'borrowernumber'}
824 # Do not set to "edited" if syncstatus is "new". We need to sync as new before
825 # we can sync as changed. And the "new sync" will pick up all changes since
826 # the patron was created anyway.
827 if ( $borrowersync->syncstatus ne 'new' && $borrowersync->syncstatus ne 'delete' ) {
828 $borrowersync->update( { 'syncstatus' => 'edited' } );
830 # Set the value of 'sync'
831 $borrowersync->update( { 'sync' => $data{'sync'} } );
832 # Try to do the live sync
833 NLSync({ 'borrowernumber' => $data{'borrowernumber'} });
836 logaction("MEMBERS", "MODIFY", $data{'borrowernumber'}, "UPDATE (executed w/ arg: $data{'borrowernumber'})") if C4::Context->preference("BorrowersLog");
838 return $execute_success;
841 =head2 AddMember
843 $borrowernumber = &AddMember(%borrower);
845 insert new borrower into table
847 (%borrower keys are database columns. Database columns could be
848 different in different versions. Please look into database for correct
849 column names.)
851 Returns the borrowernumber upon success
853 Returns as undef upon any db error without further processing
855 =cut
858 sub AddMember {
859 my (%data) = @_;
860 my $dbh = C4::Context->dbh;
862 # generate a proper login if none provided
863 $data{'userid'} = Generate_Userid( $data{'borrowernumber'}, $data{'firstname'}, $data{'surname'} )
864 if ( $data{'userid'} eq '' || !Check_Userid( $data{'userid'} ) );
866 # add expiration date if it isn't already there
867 unless ( $data{'dateexpiry'} ) {
868 $data{'dateexpiry'} = GetExpiryDate( $data{'categorycode'}, C4::Dates->new()->output("iso") );
871 # add enrollment date if it isn't already there
872 unless ( $data{'dateenrolled'} ) {
873 $data{'dateenrolled'} = C4::Dates->new()->output("iso");
876 my $patron_category =
877 Koha::Database->new()->schema()->resultset('Category')
878 ->find( $data{'categorycode'} );
879 $data{'privacy'} =
880 $patron_category->default_privacy() eq 'default' ? 1
881 : $patron_category->default_privacy() eq 'never' ? 2
882 : $patron_category->default_privacy() eq 'forever' ? 0
883 : undef;
884 # Make a copy of the plain text password for later use
885 my $plain_text_password = $data{'password'};
887 # create a disabled account if no password provided
888 $data{'password'} = ($data{'password'})? hash_password($data{'password'}) : '!';
889 $data{'borrowernumber'}=InsertInTable("borrowers",\%data);
891 # If NorwegianPatronDBEnable is enabled, we set syncstatus to something that a
892 # cronjob will use for syncing with NL
893 if ( exists $data{'borrowernumber'} && C4::Context->preference('NorwegianPatronDBEnable') && C4::Context->preference('NorwegianPatronDBEnable') == 1 ) {
894 Koha::Database->new->schema->resultset('BorrowerSync')->create({
895 'borrowernumber' => $data{'borrowernumber'},
896 'synctype' => 'norwegianpatrondb',
897 'sync' => 1,
898 'syncstatus' => 'new',
899 'hashed_pin' => NLEncryptPIN( $plain_text_password ),
903 # mysql_insertid is probably bad. not necessarily accurate and mysql-specific at best.
904 logaction("MEMBERS", "CREATE", $data{'borrowernumber'}, "") if C4::Context->preference("BorrowersLog");
906 AddEnrolmentFeeIfNeeded( $data{categorycode}, $data{borrowernumber} );
908 return $data{'borrowernumber'};
911 =head2 Check_Userid
913 my $uniqueness = Check_Userid($userid,$borrowernumber);
915 $borrowernumber is optional (i.e. it can contain a blank value). If $userid is passed with a blank $borrowernumber variable, the database will be checked for all instances of that userid (i.e. userid=? AND borrowernumber != '').
917 If $borrowernumber is provided, the database will be checked for every instance of that userid coupled with a different borrower(number) than the one provided.
919 return :
920 0 for not unique (i.e. this $userid already exists)
921 1 for unique (i.e. this $userid does not exist, or this $userid/$borrowernumber combination already exists)
923 =cut
925 sub Check_Userid {
926 my ( $uid, $borrowernumber ) = @_;
928 return 0 unless ($uid); # userid is a unique column, we should assume NULL is not unique
930 return 0 if ( $uid eq C4::Context->config('user') );
932 my $rs = Koha::Database->new()->schema()->resultset('Borrower');
934 my $params;
935 $params->{userid} = $uid;
936 $params->{borrowernumber} = { '!=' => $borrowernumber } if ($borrowernumber);
938 my $count = $rs->count( $params );
940 return $count ? 0 : 1;
943 =head2 Generate_Userid
945 my $newuid = Generate_Userid($borrowernumber, $firstname, $surname);
947 Generate a userid using the $surname and the $firstname (if there is a value in $firstname).
949 $borrowernumber is optional (i.e. it can contain a blank value). A value is passed when generating a new userid for an existing borrower. When a new userid is created for a new borrower, a blank value is passed to this sub.
951 return :
952 new userid ($firstname.$surname if there is a $firstname, or $surname if there is no value in $firstname) plus offset (0 if the $newuid is unique, or a higher numeric value if Check_Userid finds an existing match for the $newuid in the database).
954 =cut
956 sub Generate_Userid {
957 my ($borrowernumber, $firstname, $surname) = @_;
958 my $newuid;
959 my $offset = 0;
960 #The script will "do" the following code and increment the $offset until Check_Userid = 1 (i.e. until $newuid comes back as unique)
961 do {
962 $firstname =~ s/[[:digit:][:space:][:blank:][:punct:][:cntrl:]]//g;
963 $surname =~ s/[[:digit:][:space:][:blank:][:punct:][:cntrl:]]//g;
964 $newuid = lc(($firstname)? "$firstname.$surname" : $surname);
965 $newuid = unac_string('utf-8',$newuid);
966 $newuid .= $offset unless $offset == 0;
967 $offset++;
969 } while (!Check_Userid($newuid,$borrowernumber));
971 return $newuid;
974 sub changepassword {
975 my ( $uid, $member, $digest ) = @_;
976 my $dbh = C4::Context->dbh;
978 #Make sure the userid chosen is unique and not theirs if non-empty. If it is not,
979 #Then we need to tell the user and have them create a new one.
980 my $resultcode;
981 my $sth =
982 $dbh->prepare(
983 "SELECT * FROM borrowers WHERE userid=? AND borrowernumber != ?");
984 $sth->execute( $uid, $member );
985 if ( ( $uid ne '' ) && ( my $row = $sth->fetchrow_hashref ) ) {
986 $resultcode=0;
988 else {
989 #Everything is good so we can update the information.
990 $sth =
991 $dbh->prepare(
992 "update borrowers set userid=?, password=? where borrowernumber=?");
993 $sth->execute( $uid, $digest, $member );
994 $resultcode=1;
997 logaction("MEMBERS", "CHANGE PASS", $member, "") if C4::Context->preference("BorrowersLog");
998 return $resultcode;
1003 =head2 fixup_cardnumber
1005 Warning: The caller is responsible for locking the members table in write
1006 mode, to avoid database corruption.
1008 =cut
1010 use vars qw( @weightings );
1011 my @weightings = ( 8, 4, 6, 3, 5, 2, 1 );
1013 sub fixup_cardnumber {
1014 my ($cardnumber) = @_;
1015 my $autonumber_members = C4::Context->boolean_preference('autoMemberNum') || 0;
1017 # Find out whether member numbers should be generated
1018 # automatically. Should be either "1" or something else.
1019 # Defaults to "0", which is interpreted as "no".
1021 # if ($cardnumber !~ /\S/ && $autonumber_members) {
1022 ($autonumber_members) or return $cardnumber;
1023 my $checkdigit = C4::Context->preference('checkdigit');
1024 my $dbh = C4::Context->dbh;
1025 if ( $checkdigit and $checkdigit eq 'katipo' ) {
1027 # if checkdigit is selected, calculate katipo-style cardnumber.
1028 # otherwise, just use the max()
1029 # purpose: generate checksum'd member numbers.
1030 # We'll assume we just got the max value of digits 2-8 of member #'s
1031 # from the database and our job is to increment that by one,
1032 # determine the 1st and 9th digits and return the full string.
1033 my $sth = $dbh->prepare(
1034 "select max(substring(borrowers.cardnumber,2,7)) as new_num from borrowers"
1036 $sth->execute;
1037 my $data = $sth->fetchrow_hashref;
1038 $cardnumber = $data->{new_num};
1039 if ( !$cardnumber ) { # If DB has no values,
1040 $cardnumber = 1000000; # start at 1000000
1041 } else {
1042 $cardnumber += 1;
1045 my $sum = 0;
1046 for ( my $i = 0 ; $i < 8 ; $i += 1 ) {
1047 # read weightings, left to right, 1 char at a time
1048 my $temp1 = $weightings[$i];
1050 # sequence left to right, 1 char at a time
1051 my $temp2 = substr( $cardnumber, $i, 1 );
1053 # mult each char 1-7 by its corresponding weighting
1054 $sum += $temp1 * $temp2;
1057 my $rem = ( $sum % 11 );
1058 $rem = 'X' if $rem == 10;
1060 return "V$cardnumber$rem";
1061 } else {
1063 my $sth = $dbh->prepare(
1064 'SELECT MAX( CAST( cardnumber AS SIGNED ) ) FROM borrowers WHERE cardnumber REGEXP "^-?[0-9]+$"'
1066 $sth->execute;
1067 my ($result) = $sth->fetchrow;
1068 return $result + 1;
1070 return $cardnumber; # just here as a fallback/reminder
1073 =head2 GetGuarantees
1075 ($num_children, $children_arrayref) = &GetGuarantees($parent_borrno);
1076 $child0_cardno = $children_arrayref->[0]{"cardnumber"};
1077 $child0_borrno = $children_arrayref->[0]{"borrowernumber"};
1079 C<&GetGuarantees> takes a borrower number (e.g., that of a patron
1080 with children) and looks up the borrowers who are guaranteed by that
1081 borrower (i.e., the patron's children).
1083 C<&GetGuarantees> returns two values: an integer giving the number of
1084 borrowers guaranteed by C<$parent_borrno>, and a reference to an array
1085 of references to hash, which gives the actual results.
1087 =cut
1090 sub GetGuarantees {
1091 my ($borrowernumber) = @_;
1092 my $dbh = C4::Context->dbh;
1093 my $sth =
1094 $dbh->prepare(
1095 "select cardnumber,borrowernumber, firstname, surname from borrowers where guarantorid=?"
1097 $sth->execute($borrowernumber);
1099 my @dat;
1100 my $data = $sth->fetchall_arrayref({});
1101 return ( scalar(@$data), $data );
1104 =head2 UpdateGuarantees
1106 &UpdateGuarantees($parent_borrno);
1109 C<&UpdateGuarantees> borrower data for an adult and updates all the guarantees
1110 with the modified information
1112 =cut
1115 sub UpdateGuarantees {
1116 my %data = shift;
1117 my $dbh = C4::Context->dbh;
1118 my ( $count, $guarantees ) = GetGuarantees( $data{'borrowernumber'} );
1119 foreach my $guarantee (@$guarantees){
1120 my $guaquery = qq|UPDATE borrowers
1121 SET address=?,fax=?,B_city=?,mobile=?,city=?,phone=?
1122 WHERE borrowernumber=?
1124 my $sth = $dbh->prepare($guaquery);
1125 $sth->execute($data{'address'},$data{'fax'},$data{'B_city'},$data{'mobile'},$data{'city'},$data{'phone'},$guarantee->{'borrowernumber'});
1128 =head2 GetPendingIssues
1130 my $issues = &GetPendingIssues(@borrowernumber);
1132 Looks up what the patron with the given borrowernumber has borrowed.
1134 C<&GetPendingIssues> returns a
1135 reference-to-array where each element is a reference-to-hash; the
1136 keys are the fields from the C<issues>, C<biblio>, and C<items> tables.
1137 The keys include C<biblioitems> fields except marc and marcxml.
1139 =cut
1142 sub GetPendingIssues {
1143 my @borrowernumbers = @_;
1145 unless (@borrowernumbers ) { # return a ref_to_array
1146 return \@borrowernumbers; # to not cause surprise to caller
1149 # Borrowers part of the query
1150 my $bquery = '';
1151 for (my $i = 0; $i < @borrowernumbers; $i++) {
1152 $bquery .= ' issues.borrowernumber = ?';
1153 if ($i < $#borrowernumbers ) {
1154 $bquery .= ' OR';
1158 # must avoid biblioitems.* to prevent large marc and marcxml fields from killing performance
1159 # FIXME: namespace collision: each table has "timestamp" fields. Which one is "timestamp" ?
1160 # FIXME: circ/ciculation.pl tries to sort by timestamp!
1161 # FIXME: namespace collision: other collisions possible.
1162 # FIXME: most of this data isn't really being used by callers.
1163 my $query =
1164 "SELECT issues.*,
1165 items.*,
1166 biblio.*,
1167 biblioitems.volume,
1168 biblioitems.number,
1169 biblioitems.itemtype,
1170 biblioitems.isbn,
1171 biblioitems.issn,
1172 biblioitems.publicationyear,
1173 biblioitems.publishercode,
1174 biblioitems.volumedate,
1175 biblioitems.volumedesc,
1176 biblioitems.lccn,
1177 biblioitems.url,
1178 borrowers.firstname,
1179 borrowers.surname,
1180 borrowers.cardnumber,
1181 issues.timestamp AS timestamp,
1182 issues.renewals AS renewals,
1183 issues.borrowernumber AS borrowernumber,
1184 items.renewals AS totalrenewals
1185 FROM issues
1186 LEFT JOIN items ON items.itemnumber = issues.itemnumber
1187 LEFT JOIN biblio ON items.biblionumber = biblio.biblionumber
1188 LEFT JOIN biblioitems ON items.biblioitemnumber = biblioitems.biblioitemnumber
1189 LEFT JOIN borrowers ON issues.borrowernumber = borrowers.borrowernumber
1190 WHERE
1191 $bquery
1192 ORDER BY issues.issuedate"
1195 my $sth = C4::Context->dbh->prepare($query);
1196 $sth->execute(@borrowernumbers);
1197 my $data = $sth->fetchall_arrayref({});
1198 my $tz = C4::Context->tz();
1199 my $today = DateTime->now( time_zone => $tz);
1200 foreach (@{$data}) {
1201 if ($_->{issuedate}) {
1202 $_->{issuedate} = dt_from_string($_->{issuedate}, 'sql');
1204 $_->{date_due_sql} = $_->{date_due};
1205 # FIXME no need to have this value
1206 $_->{date_due} or next;
1207 $_->{date_due} = DateTime::Format::DateParse->parse_datetime($_->{date_due}, $tz->name());
1208 if ( DateTime->compare($_->{date_due}, $today) == -1 ) {
1209 $_->{overdue} = 1;
1212 return $data;
1215 =head2 GetAllIssues
1217 $issues = &GetAllIssues($borrowernumber, $sortkey, $limit);
1219 Looks up what the patron with the given borrowernumber has borrowed,
1220 and sorts the results.
1222 C<$sortkey> is the name of a field on which to sort the results. This
1223 should be the name of a field in the C<issues>, C<biblio>,
1224 C<biblioitems>, or C<items> table in the Koha database.
1226 C<$limit> is the maximum number of results to return.
1228 C<&GetAllIssues> an arrayref, C<$issues>, of hashrefs, the keys of which
1229 are the fields from the C<issues>, C<biblio>, C<biblioitems>, and
1230 C<items> tables of the Koha database.
1232 =cut
1235 sub GetAllIssues {
1236 my ( $borrowernumber, $order, $limit ) = @_;
1238 return unless $borrowernumber;
1239 $order = 'date_due desc' unless $order;
1241 my $dbh = C4::Context->dbh;
1242 my $query =
1243 'SELECT *, issues.timestamp as issuestimestamp, issues.renewals AS renewals,items.renewals AS totalrenewals,items.timestamp AS itemstimestamp
1244 FROM issues
1245 LEFT JOIN items on items.itemnumber=issues.itemnumber
1246 LEFT JOIN biblio ON items.biblionumber=biblio.biblionumber
1247 LEFT JOIN biblioitems ON items.biblioitemnumber=biblioitems.biblioitemnumber
1248 WHERE borrowernumber=?
1249 UNION ALL
1250 SELECT *, old_issues.timestamp as issuestimestamp, old_issues.renewals AS renewals,items.renewals AS totalrenewals,items.timestamp AS itemstimestamp
1251 FROM old_issues
1252 LEFT JOIN items on items.itemnumber=old_issues.itemnumber
1253 LEFT JOIN biblio ON items.biblionumber=biblio.biblionumber
1254 LEFT JOIN biblioitems ON items.biblioitemnumber=biblioitems.biblioitemnumber
1255 WHERE borrowernumber=? AND old_issues.itemnumber IS NOT NULL
1256 order by ' . $order;
1257 if ($limit) {
1258 $query .= " limit $limit";
1261 my $sth = $dbh->prepare($query);
1262 $sth->execute( $borrowernumber, $borrowernumber );
1263 return $sth->fetchall_arrayref( {} );
1267 =head2 GetMemberAccountRecords
1269 ($total, $acctlines, $count) = &GetMemberAccountRecords($borrowernumber);
1271 Looks up accounting data for the patron with the given borrowernumber.
1273 C<&GetMemberAccountRecords> returns a three-element array. C<$acctlines> is a
1274 reference-to-array, where each element is a reference-to-hash; the
1275 keys are the fields of the C<accountlines> table in the Koha database.
1276 C<$count> is the number of elements in C<$acctlines>. C<$total> is the
1277 total amount outstanding for all of the account lines.
1279 =cut
1281 sub GetMemberAccountRecords {
1282 my ($borrowernumber) = @_;
1283 my $dbh = C4::Context->dbh;
1284 my @acctlines;
1285 my $numlines = 0;
1286 my $strsth = qq(
1287 SELECT *
1288 FROM accountlines
1289 WHERE borrowernumber=?);
1290 $strsth.=" ORDER BY date desc,timestamp DESC";
1291 my $sth= $dbh->prepare( $strsth );
1292 $sth->execute( $borrowernumber );
1294 my $total = 0;
1295 while ( my $data = $sth->fetchrow_hashref ) {
1296 if ( $data->{itemnumber} ) {
1297 my $biblio = GetBiblioFromItemNumber( $data->{itemnumber} );
1298 $data->{biblionumber} = $biblio->{biblionumber};
1299 $data->{title} = $biblio->{title};
1301 $acctlines[$numlines] = $data;
1302 $numlines++;
1303 $total += int(1000 * $data->{'amountoutstanding'}); # convert float to integer to avoid round-off errors
1305 $total /= 1000;
1306 return ( $total, \@acctlines,$numlines);
1309 =head2 GetMemberAccountBalance
1311 ($total_balance, $non_issue_balance, $other_charges) = &GetMemberAccountBalance($borrowernumber);
1313 Calculates amount immediately owing by the patron - non-issue charges.
1314 Based on GetMemberAccountRecords.
1315 Charges exempt from non-issue are:
1316 * Res (reserves)
1317 * Rent (rental) if RentalsInNoissuesCharge syspref is set to false
1318 * Manual invoices if ManInvInNoissuesCharge syspref is set to false
1320 =cut
1322 sub GetMemberAccountBalance {
1323 my ($borrowernumber) = @_;
1325 my $ACCOUNT_TYPE_LENGTH = 5; # this is plain ridiculous...
1327 my @not_fines;
1328 push @not_fines, 'Res' unless C4::Context->preference('HoldsInNoissuesCharge');
1329 push @not_fines, 'Rent' unless C4::Context->preference('RentalsInNoissuesCharge');
1330 unless ( C4::Context->preference('ManInvInNoissuesCharge') ) {
1331 my $dbh = C4::Context->dbh;
1332 my $man_inv_types = $dbh->selectcol_arrayref(qq{SELECT authorised_value FROM authorised_values WHERE category = 'MANUAL_INV'});
1333 push @not_fines, map substr($_, 0, $ACCOUNT_TYPE_LENGTH), @$man_inv_types;
1335 my %not_fine = map {$_ => 1} @not_fines;
1337 my ($total, $acctlines) = GetMemberAccountRecords($borrowernumber);
1338 my $other_charges = 0;
1339 foreach (@$acctlines) {
1340 $other_charges += $_->{amountoutstanding} if $not_fine{ substr($_->{accounttype}, 0, $ACCOUNT_TYPE_LENGTH) };
1343 return ( $total, $total - $other_charges, $other_charges);
1346 =head2 GetBorNotifyAcctRecord
1348 ($total, $acctlines, $count) = &GetBorNotifyAcctRecord($params,$notifyid);
1350 Looks up accounting data for the patron with the given borrowernumber per file number.
1352 C<&GetBorNotifyAcctRecord> returns a three-element array. C<$acctlines> is a
1353 reference-to-array, where each element is a reference-to-hash; the
1354 keys are the fields of the C<accountlines> table in the Koha database.
1355 C<$count> is the number of elements in C<$acctlines>. C<$total> is the
1356 total amount outstanding for all of the account lines.
1358 =cut
1360 sub GetBorNotifyAcctRecord {
1361 my ( $borrowernumber, $notifyid ) = @_;
1362 my $dbh = C4::Context->dbh;
1363 my @acctlines;
1364 my $numlines = 0;
1365 my $sth = $dbh->prepare(
1366 "SELECT *
1367 FROM accountlines
1368 WHERE borrowernumber=?
1369 AND notify_id=?
1370 AND amountoutstanding != '0'
1371 ORDER BY notify_id,accounttype
1374 $sth->execute( $borrowernumber, $notifyid );
1375 my $total = 0;
1376 while ( my $data = $sth->fetchrow_hashref ) {
1377 if ( $data->{itemnumber} ) {
1378 my $biblio = GetBiblioFromItemNumber( $data->{itemnumber} );
1379 $data->{biblionumber} = $biblio->{biblionumber};
1380 $data->{title} = $biblio->{title};
1382 $acctlines[$numlines] = $data;
1383 $numlines++;
1384 $total += int(100 * $data->{'amountoutstanding'});
1386 $total /= 100;
1387 return ( $total, \@acctlines, $numlines );
1390 =head2 checkuniquemember (OUEST-PROVENCE)
1392 ($result,$categorycode) = &checkuniquemember($collectivity,$surname,$firstname,$dateofbirth);
1394 Checks that a member exists or not in the database.
1396 C<&result> is nonzero (=exist) or 0 (=does not exist)
1397 C<&categorycode> is from categorycode table
1398 C<&collectivity> is 1 (= we add a collectivity) or 0 (= we add a physical member)
1399 C<&surname> is the surname
1400 C<&firstname> is the firstname (only if collectivity=0)
1401 C<&dateofbirth> is the date of birth in ISO format (only if collectivity=0)
1403 =cut
1405 # FIXME: This function is not legitimate. Multiple patrons might have the same first/last name and birthdate.
1406 # This is especially true since first name is not even a required field.
1408 sub checkuniquemember {
1409 my ( $collectivity, $surname, $firstname, $dateofbirth ) = @_;
1410 my $dbh = C4::Context->dbh;
1411 my $request = ($collectivity) ?
1412 "SELECT borrowernumber,categorycode FROM borrowers WHERE surname=? " :
1413 ($dateofbirth) ?
1414 "SELECT borrowernumber,categorycode FROM borrowers WHERE surname=? and firstname=? and dateofbirth=?" :
1415 "SELECT borrowernumber,categorycode FROM borrowers WHERE surname=? and firstname=?";
1416 my $sth = $dbh->prepare($request);
1417 if ($collectivity) {
1418 $sth->execute( uc($surname) );
1419 } elsif($dateofbirth){
1420 $sth->execute( uc($surname), ucfirst($firstname), $dateofbirth );
1421 }else{
1422 $sth->execute( uc($surname), ucfirst($firstname));
1424 my @data = $sth->fetchrow;
1425 ( $data[0] ) and return $data[0], $data[1];
1426 return 0;
1429 sub checkcardnumber {
1430 my ( $cardnumber, $borrowernumber ) = @_;
1432 # If cardnumber is null, we assume they're allowed.
1433 return 0 unless defined $cardnumber;
1435 my $dbh = C4::Context->dbh;
1436 my $query = "SELECT * FROM borrowers WHERE cardnumber=?";
1437 $query .= " AND borrowernumber <> ?" if ($borrowernumber);
1438 my $sth = $dbh->prepare($query);
1439 $sth->execute(
1440 $cardnumber,
1441 ( $borrowernumber ? $borrowernumber : () )
1444 return 1 if $sth->fetchrow_hashref;
1446 my ( $min_length, $max_length ) = get_cardnumber_length();
1447 return 2
1448 if length $cardnumber > $max_length
1449 or length $cardnumber < $min_length;
1451 return 0;
1454 =head2 get_cardnumber_length
1456 my ($min, $max) = C4::Members::get_cardnumber_length()
1458 Returns the minimum and maximum length for patron cardnumbers as
1459 determined by the CardnumberLength system preference, the
1460 BorrowerMandatoryField system preference, and the width of the
1461 database column.
1463 =cut
1465 sub get_cardnumber_length {
1466 my ( $min, $max ) = ( 0, 16 ); # borrowers.cardnumber is a nullable varchar(16)
1467 $min = 1 if C4::Context->preference('BorrowerMandatoryField') =~ /cardnumber/;
1468 if ( my $cardnumber_length = C4::Context->preference('CardnumberLength') ) {
1469 # Is integer and length match
1470 if ( $cardnumber_length =~ m|^\d+$| ) {
1471 $min = $max = $cardnumber_length
1472 if $cardnumber_length >= $min
1473 and $cardnumber_length <= $max;
1475 # Else assuming it is a range
1476 elsif ( $cardnumber_length =~ m|(\d*),(\d*)| ) {
1477 $min = $1 if $1 and $min < $1;
1478 $max = $2 if $2 and $max > $2;
1482 return ( $min, $max );
1485 =head2 getzipnamecity (OUEST-PROVENCE)
1487 take all info from table city for the fields city and zip
1488 check for the name and the zip code of the city selected
1490 =cut
1492 sub getzipnamecity {
1493 my ($cityid) = @_;
1494 my $dbh = C4::Context->dbh;
1495 my $sth =
1496 $dbh->prepare(
1497 "select city_name,city_state,city_zipcode,city_country from cities where cityid=? ");
1498 $sth->execute($cityid);
1499 my @data = $sth->fetchrow;
1500 return $data[0], $data[1], $data[2], $data[3];
1504 =head2 getdcity (OUEST-PROVENCE)
1506 recover cityid with city_name condition
1508 =cut
1510 sub getidcity {
1511 my ($city_name) = @_;
1512 my $dbh = C4::Context->dbh;
1513 my $sth = $dbh->prepare("select cityid from cities where city_name=? ");
1514 $sth->execute($city_name);
1515 my $data = $sth->fetchrow;
1516 return $data;
1519 =head2 GetFirstValidEmailAddress
1521 $email = GetFirstValidEmailAddress($borrowernumber);
1523 Return the first valid email address for a borrower, given the borrowernumber. For now, the order
1524 is defined as email, emailpro, B_email. Returns the empty string if the borrower has no email
1525 addresses.
1527 =cut
1529 sub GetFirstValidEmailAddress {
1530 my $borrowernumber = shift;
1531 my $dbh = C4::Context->dbh;
1532 my $sth = $dbh->prepare( "SELECT email, emailpro, B_email FROM borrowers where borrowernumber = ? ");
1533 $sth->execute( $borrowernumber );
1534 my $data = $sth->fetchrow_hashref;
1536 if ($data->{'email'}) {
1537 return $data->{'email'};
1538 } elsif ($data->{'emailpro'}) {
1539 return $data->{'emailpro'};
1540 } elsif ($data->{'B_email'}) {
1541 return $data->{'B_email'};
1542 } else {
1543 return '';
1547 =head2 GetNoticeEmailAddress
1549 $email = GetNoticeEmailAddress($borrowernumber);
1551 Return the email address of borrower used for notices, given the borrowernumber.
1552 Returns the empty string if no email address.
1554 =cut
1556 sub GetNoticeEmailAddress {
1557 my $borrowernumber = shift;
1559 my $which_address = C4::Context->preference("AutoEmailPrimaryAddress");
1560 # if syspref is set to 'first valid' (value == OFF), look up email address
1561 if ( $which_address eq 'OFF' ) {
1562 return GetFirstValidEmailAddress($borrowernumber);
1564 # specified email address field
1565 my $dbh = C4::Context->dbh;
1566 my $sth = $dbh->prepare( qq{
1567 SELECT $which_address AS primaryemail
1568 FROM borrowers
1569 WHERE borrowernumber=?
1570 } );
1571 $sth->execute($borrowernumber);
1572 my $data = $sth->fetchrow_hashref;
1573 return $data->{'primaryemail'} || '';
1576 =head2 GetExpiryDate
1578 $expirydate = GetExpiryDate($categorycode, $dateenrolled);
1580 Calculate expiry date given a categorycode and starting date. Date argument must be in ISO format.
1581 Return date is also in ISO format.
1583 =cut
1585 sub GetExpiryDate {
1586 my ( $categorycode, $dateenrolled ) = @_;
1587 my $enrolments;
1588 if ($categorycode) {
1589 my $dbh = C4::Context->dbh;
1590 my $sth = $dbh->prepare("SELECT enrolmentperiod,enrolmentperioddate FROM categories WHERE categorycode=?");
1591 $sth->execute($categorycode);
1592 $enrolments = $sth->fetchrow_hashref;
1594 # die "GetExpiryDate: for enrollmentperiod $enrolmentperiod (category '$categorycode') starting $dateenrolled.\n";
1595 my @date = split (/-/,$dateenrolled);
1596 if($enrolments->{enrolmentperiod}){
1597 return sprintf("%04d-%02d-%02d", Add_Delta_YM(@date,0,$enrolments->{enrolmentperiod}));
1598 }else{
1599 return $enrolments->{enrolmentperioddate};
1603 =head2 GetborCatFromCatType
1605 ($codes_arrayref, $labels_hashref) = &GetborCatFromCatType();
1607 Looks up the different types of borrowers in the database. Returns two
1608 elements: a reference-to-array, which lists the borrower category
1609 codes, and a reference-to-hash, which maps the borrower category codes
1610 to category descriptions.
1612 =cut
1615 sub GetborCatFromCatType {
1616 my ( $category_type, $action, $no_branch_limit ) = @_;
1618 my $branch_limit = $no_branch_limit
1620 : C4::Context->userenv ? C4::Context->userenv->{"branch"} : "";
1622 # FIXME - This API seems both limited and dangerous.
1623 my $dbh = C4::Context->dbh;
1625 my $request = qq{
1626 SELECT categories.categorycode, categories.description
1627 FROM categories
1629 $request .= qq{
1630 LEFT JOIN categories_branches ON categories.categorycode = categories_branches.categorycode
1631 } if $branch_limit;
1632 if($action) {
1633 $request .= " $action ";
1634 $request .= " AND (branchcode = ? OR branchcode IS NULL) GROUP BY description" if $branch_limit;
1635 } else {
1636 $request .= " WHERE branchcode = ? OR branchcode IS NULL GROUP BY description" if $branch_limit;
1638 $request .= " ORDER BY categorycode";
1640 my $sth = $dbh->prepare($request);
1641 $sth->execute(
1642 $action ? $category_type : (),
1643 $branch_limit ? $branch_limit : ()
1646 my %labels;
1647 my @codes;
1649 while ( my $data = $sth->fetchrow_hashref ) {
1650 push @codes, $data->{'categorycode'};
1651 $labels{ $data->{'categorycode'} } = $data->{'description'};
1653 $sth->finish;
1654 return ( \@codes, \%labels );
1657 =head2 GetBorrowercategory
1659 $hashref = &GetBorrowercategory($categorycode);
1661 Given the borrower's category code, the function returns the corresponding
1662 data hashref for a comprehensive information display.
1664 =cut
1666 sub GetBorrowercategory {
1667 my ($catcode) = @_;
1668 my $dbh = C4::Context->dbh;
1669 if ($catcode){
1670 my $sth =
1671 $dbh->prepare(
1672 "SELECT description,dateofbirthrequired,upperagelimit,category_type
1673 FROM categories
1674 WHERE categorycode = ?"
1676 $sth->execute($catcode);
1677 my $data =
1678 $sth->fetchrow_hashref;
1679 return $data;
1681 return;
1682 } # sub getborrowercategory
1685 =head2 GetBorrowerCategorycode
1687 $categorycode = &GetBorrowerCategoryCode( $borrowernumber );
1689 Given the borrowernumber, the function returns the corresponding categorycode
1691 =cut
1693 sub GetBorrowerCategorycode {
1694 my ( $borrowernumber ) = @_;
1695 my $dbh = C4::Context->dbh;
1696 my $sth = $dbh->prepare( qq{
1697 SELECT categorycode
1698 FROM borrowers
1699 WHERE borrowernumber = ?
1700 } );
1701 $sth->execute( $borrowernumber );
1702 return $sth->fetchrow;
1705 =head2 GetBorrowercategoryList
1707 $arrayref_hashref = &GetBorrowercategoryList;
1708 If no category code provided, the function returns all the categories.
1710 =cut
1712 sub GetBorrowercategoryList {
1713 my $no_branch_limit = @_ ? shift : 0;
1714 my $branch_limit = $no_branch_limit
1716 : C4::Context->userenv ? C4::Context->userenv->{"branch"} : "";
1717 my $dbh = C4::Context->dbh;
1718 my $query = "SELECT categories.* FROM categories";
1719 $query .= qq{
1720 LEFT JOIN categories_branches ON categories.categorycode = categories_branches.categorycode
1721 WHERE branchcode = ? OR branchcode IS NULL GROUP BY description
1722 } if $branch_limit;
1723 $query .= " ORDER BY description";
1724 my $sth = $dbh->prepare( $query );
1725 $sth->execute( $branch_limit ? $branch_limit : () );
1726 my $data = $sth->fetchall_arrayref( {} );
1727 $sth->finish;
1728 return $data;
1729 } # sub getborrowercategory
1731 =head2 ethnicitycategories
1733 ($codes_arrayref, $labels_hashref) = &ethnicitycategories();
1735 Looks up the different ethnic types in the database. Returns two
1736 elements: a reference-to-array, which lists the ethnicity codes, and a
1737 reference-to-hash, which maps the ethnicity codes to ethnicity
1738 descriptions.
1740 =cut
1744 sub ethnicitycategories {
1745 my $dbh = C4::Context->dbh;
1746 my $sth = $dbh->prepare("Select code,name from ethnicity order by name");
1747 $sth->execute;
1748 my %labels;
1749 my @codes;
1750 while ( my $data = $sth->fetchrow_hashref ) {
1751 push @codes, $data->{'code'};
1752 $labels{ $data->{'code'} } = $data->{'name'};
1754 return ( \@codes, \%labels );
1757 =head2 fixEthnicity
1759 $ethn_name = &fixEthnicity($ethn_code);
1761 Takes an ethnicity code (e.g., "european" or "pi") and returns the
1762 corresponding descriptive name from the C<ethnicity> table in the
1763 Koha database ("European" or "Pacific Islander").
1765 =cut
1769 sub fixEthnicity {
1770 my $ethnicity = shift;
1771 return unless $ethnicity;
1772 my $dbh = C4::Context->dbh;
1773 my $sth = $dbh->prepare("Select name from ethnicity where code = ?");
1774 $sth->execute($ethnicity);
1775 my $data = $sth->fetchrow_hashref;
1776 return $data->{'name'};
1777 } # sub fixEthnicity
1779 =head2 GetAge
1781 $dateofbirth,$date = &GetAge($date);
1783 this function return the borrowers age with the value of dateofbirth
1785 =cut
1788 sub GetAge{
1789 my ( $date, $date_ref ) = @_;
1791 if ( not defined $date_ref ) {
1792 $date_ref = sprintf( '%04d-%02d-%02d', Today() );
1795 my ( $year1, $month1, $day1 ) = split /-/, $date;
1796 my ( $year2, $month2, $day2 ) = split /-/, $date_ref;
1798 my $age = $year2 - $year1;
1799 if ( $month1 . $day1 > $month2 . $day2 ) {
1800 $age--;
1803 return $age;
1804 } # sub get_age
1806 =head2 SetAge
1808 $borrower = C4::Members::SetAge($borrower, $datetimeduration);
1809 $borrower = C4::Members::SetAge($borrower, '0015-12-10');
1810 $borrower = C4::Members::SetAge($borrower, $datetimeduration, $datetime_reference);
1812 eval { $borrower = C4::Members::SetAge($borrower, '015-1-10'); };
1813 if ($@) {print $@;} #Catch a bad ISO Date or kill your script!
1815 This function sets the borrower's dateofbirth to match the given age.
1816 Optionally relative to the given $datetime_reference.
1818 @PARAM1 koha.borrowers-object
1819 @PARAM2 DateTime::Duration-object as the desired age
1820 OR a ISO 8601 Date. (To make the API more pleasant)
1821 @PARAM3 DateTime-object as the relative date, defaults to now().
1822 RETURNS The given borrower reference @PARAM1.
1823 DIES If there was an error with the ISO Date handling.
1825 =cut
1828 sub SetAge{
1829 my ( $borrower, $datetimeduration, $datetime_ref ) = @_;
1830 $datetime_ref = DateTime->now() unless $datetime_ref;
1832 if ($datetimeduration && ref $datetimeduration ne 'DateTime::Duration') {
1833 if ($datetimeduration =~ /^(\d{4})-(\d{2})-(\d{2})/) {
1834 $datetimeduration = DateTime::Duration->new(years => $1, months => $2, days => $3);
1836 else {
1837 die "C4::Members::SetAge($borrower, $datetimeduration), datetimeduration not a valid ISO 8601 Date!\n";
1841 my $new_datetime_ref = $datetime_ref->clone();
1842 $new_datetime_ref->subtract_duration( $datetimeduration );
1844 $borrower->{dateofbirth} = $new_datetime_ref->ymd();
1846 return $borrower;
1847 } # sub SetAge
1849 =head2 GetCities
1851 $cityarrayref = GetCities();
1853 Returns an array_ref of the entries in the cities table
1854 If there are entries in the table an empty row is returned
1855 This is currently only used to populate a popup in memberentry
1857 =cut
1859 sub GetCities {
1861 my $dbh = C4::Context->dbh;
1862 my $city_arr = $dbh->selectall_arrayref(
1863 q|SELECT cityid,city_zipcode,city_name,city_state,city_country FROM cities ORDER BY city_name|,
1864 { Slice => {} });
1865 if ( @{$city_arr} ) {
1866 unshift @{$city_arr}, {
1867 city_zipcode => q{},
1868 city_name => q{},
1869 cityid => q{},
1870 city_state => q{},
1871 city_country => q{},
1875 return $city_arr;
1878 =head2 GetSortDetails (OUEST-PROVENCE)
1880 ($lib) = &GetSortDetails($category,$sortvalue);
1882 Returns the authorized value details
1883 C<&$lib>return value of authorized value details
1884 C<&$sortvalue>this is the value of authorized value
1885 C<&$category>this is the value of authorized value category
1887 =cut
1889 sub GetSortDetails {
1890 my ( $category, $sortvalue ) = @_;
1891 my $dbh = C4::Context->dbh;
1892 my $query = qq|SELECT lib
1893 FROM authorised_values
1894 WHERE category=?
1895 AND authorised_value=? |;
1896 my $sth = $dbh->prepare($query);
1897 $sth->execute( $category, $sortvalue );
1898 my $lib = $sth->fetchrow;
1899 return ($lib) if ($lib);
1900 return ($sortvalue) unless ($lib);
1903 =head2 MoveMemberToDeleted
1905 $result = &MoveMemberToDeleted($borrowernumber);
1907 Copy the record from borrowers to deletedborrowers table.
1908 The routine returns 1 for success, undef for failure.
1910 =cut
1912 sub MoveMemberToDeleted {
1913 my ($member) = shift or return;
1915 my $schema = Koha::Database->new()->schema();
1916 my $borrowers_rs = $schema->resultset('Borrower');
1917 $borrowers_rs->result_class('DBIx::Class::ResultClass::HashRefInflator');
1918 my $borrower = $borrowers_rs->find($member);
1919 return unless $borrower;
1921 my $deleted = $schema->resultset('Deletedborrower')->create($borrower);
1923 return $deleted ? 1 : undef;
1926 =head2 DelMember
1928 DelMember($borrowernumber);
1930 This function remove directly a borrower whitout writing it on deleteborrower.
1931 + Deletes reserves for the borrower
1933 =cut
1935 sub DelMember {
1936 my $dbh = C4::Context->dbh;
1937 my $borrowernumber = shift;
1938 #warn "in delmember with $borrowernumber";
1939 return unless $borrowernumber; # borrowernumber is mandatory.
1941 my $query = qq|DELETE
1942 FROM reserves
1943 WHERE borrowernumber=?|;
1944 my $sth = $dbh->prepare($query);
1945 $sth->execute($borrowernumber);
1946 $query = "
1947 DELETE
1948 FROM borrowers
1949 WHERE borrowernumber = ?
1951 $sth = $dbh->prepare($query);
1952 $sth->execute($borrowernumber);
1953 logaction("MEMBERS", "DELETE", $borrowernumber, "") if C4::Context->preference("BorrowersLog");
1954 return $sth->rows;
1957 =head2 ExtendMemberSubscriptionTo (OUEST-PROVENCE)
1959 $date = ExtendMemberSubscriptionTo($borrowerid, $date);
1961 Extending the subscription to a given date or to the expiry date calculated on ISO date.
1962 Returns ISO date.
1964 =cut
1966 sub ExtendMemberSubscriptionTo {
1967 my ( $borrowerid,$date) = @_;
1968 my $dbh = C4::Context->dbh;
1969 my $borrower = GetMember('borrowernumber'=>$borrowerid);
1970 unless ($date){
1971 $date = (C4::Context->preference('BorrowerRenewalPeriodBase') eq 'dateexpiry') ?
1972 C4::Dates->new($borrower->{'dateexpiry'}, 'iso')->output("iso") :
1973 C4::Dates->new()->output("iso");
1974 $date = GetExpiryDate( $borrower->{'categorycode'}, $date );
1976 my $sth = $dbh->do(<<EOF);
1977 UPDATE borrowers
1978 SET dateexpiry='$date'
1979 WHERE borrowernumber='$borrowerid'
1982 AddEnrolmentFeeIfNeeded( $borrower->{categorycode}, $borrower->{borrowernumber} );
1984 logaction("MEMBERS", "RENEW", $borrower->{'borrowernumber'}, "Membership renewed")if C4::Context->preference("BorrowersLog");
1985 return $date if ($sth);
1986 return 0;
1989 =head2 GetTitles (OUEST-PROVENCE)
1991 ($borrowertitle)= &GetTitles();
1993 Looks up the different title . Returns array with all borrowers title
1995 =cut
1997 sub GetTitles {
1998 my @borrowerTitle = split (/,|\|/,C4::Context->preference('BorrowersTitles'));
1999 unshift( @borrowerTitle, "" );
2000 my $count=@borrowerTitle;
2001 if ($count == 1){
2002 return ();
2004 else {
2005 return ( \@borrowerTitle);
2009 =head2 GetPatronImage
2011 my ($imagedata, $dberror) = GetPatronImage($borrowernumber);
2013 Returns the mimetype and binary image data of the image for the patron with the supplied borrowernumber.
2015 =cut
2017 sub GetPatronImage {
2018 my ($borrowernumber) = @_;
2019 warn "Borrowernumber passed to GetPatronImage is $borrowernumber" if $debug;
2020 my $dbh = C4::Context->dbh;
2021 my $query = 'SELECT mimetype, imagefile FROM patronimage WHERE borrowernumber = ?';
2022 my $sth = $dbh->prepare($query);
2023 $sth->execute($borrowernumber);
2024 my $imagedata = $sth->fetchrow_hashref;
2025 warn "Database error!" if $sth->errstr;
2026 return $imagedata, $sth->errstr;
2029 =head2 PutPatronImage
2031 PutPatronImage($cardnumber, $mimetype, $imgfile);
2033 Stores patron binary image data and mimetype in database.
2034 NOTE: This function is good for updating images as well as inserting new images in the database.
2036 =cut
2038 sub PutPatronImage {
2039 my ($cardnumber, $mimetype, $imgfile) = @_;
2040 warn "Parameters passed in: Cardnumber=$cardnumber, Mimetype=$mimetype, " . ($imgfile ? "Imagefile" : "No Imagefile") if $debug;
2041 my $dbh = C4::Context->dbh;
2042 my $query = "INSERT INTO patronimage (borrowernumber, mimetype, imagefile) VALUES ( ( SELECT borrowernumber from borrowers WHERE cardnumber = ? ),?,?) ON DUPLICATE KEY UPDATE imagefile = ?;";
2043 my $sth = $dbh->prepare($query);
2044 $sth->execute($cardnumber,$mimetype,$imgfile,$imgfile);
2045 warn "Error returned inserting $cardnumber.$mimetype." if $sth->errstr;
2046 return $sth->errstr;
2049 =head2 RmPatronImage
2051 my ($dberror) = RmPatronImage($borrowernumber);
2053 Removes the image for the patron with the supplied borrowernumber.
2055 =cut
2057 sub RmPatronImage {
2058 my ($borrowernumber) = @_;
2059 warn "Borrowernumber passed to GetPatronImage is $borrowernumber" if $debug;
2060 my $dbh = C4::Context->dbh;
2061 my $query = "DELETE FROM patronimage WHERE borrowernumber = ?;";
2062 my $sth = $dbh->prepare($query);
2063 $sth->execute($borrowernumber);
2064 my $dberror = $sth->errstr;
2065 warn "Database error!" if $sth->errstr;
2066 return $dberror;
2069 =head2 GetHideLostItemsPreference
2071 $hidelostitemspref = &GetHideLostItemsPreference($borrowernumber);
2073 Returns the HideLostItems preference for the patron category of the supplied borrowernumber
2074 C<&$hidelostitemspref>return value of function, 0 or 1
2076 =cut
2078 sub GetHideLostItemsPreference {
2079 my ($borrowernumber) = @_;
2080 my $dbh = C4::Context->dbh;
2081 my $query = "SELECT hidelostitems FROM borrowers,categories WHERE borrowers.categorycode = categories.categorycode AND borrowernumber = ?";
2082 my $sth = $dbh->prepare($query);
2083 $sth->execute($borrowernumber);
2084 my $hidelostitems = $sth->fetchrow;
2085 return $hidelostitems;
2088 =head2 GetBorrowersToExpunge
2090 $borrowers = &GetBorrowersToExpunge(
2091 not_borrowered_since => $not_borrowered_since,
2092 expired_before => $expired_before,
2093 category_code => $category_code,
2094 branchcode => $branchcode
2097 This function get all borrowers based on the given criteria.
2099 =cut
2101 sub GetBorrowersToExpunge {
2102 my $params = shift;
2104 my $filterdate = $params->{'not_borrowered_since'};
2105 my $filterexpiry = $params->{'expired_before'};
2106 my $filtercategory = $params->{'category_code'};
2107 my $filterbranch = $params->{'branchcode'} ||
2108 ((C4::Context->preference('IndependentBranches')
2109 && C4::Context->userenv
2110 && !C4::Context->IsSuperLibrarian()
2111 && C4::Context->userenv->{branch})
2112 ? C4::Context->userenv->{branch}
2113 : "");
2115 my $dbh = C4::Context->dbh;
2116 my $query = q|
2117 SELECT borrowers.borrowernumber,
2118 MAX(old_issues.timestamp) AS latestissue,
2119 MAX(issues.timestamp) AS currentissue
2120 FROM borrowers
2121 JOIN categories USING (categorycode)
2122 LEFT JOIN (
2123 SELECT guarantorid
2124 FROM borrowers
2125 WHERE guarantorid IS NOT NULL
2126 AND guarantorid <> 0
2127 ) as tmp ON borrowers.borrowernumber=tmp.guarantorid
2128 LEFT JOIN old_issues USING (borrowernumber)
2129 LEFT JOIN issues USING (borrowernumber)
2130 WHERE category_type <> 'S'
2131 AND tmp.guarantorid IS NULL
2134 my @query_params;
2135 if ( $filterbranch && $filterbranch ne "" ) {
2136 $query.= " AND borrowers.branchcode = ? ";
2137 push( @query_params, $filterbranch );
2139 if ( $filterexpiry ) {
2140 $query .= " AND dateexpiry < ? ";
2141 push( @query_params, $filterexpiry );
2143 if ( $filtercategory ) {
2144 $query .= " AND categorycode = ? ";
2145 push( @query_params, $filtercategory );
2147 $query.=" GROUP BY borrowers.borrowernumber HAVING currentissue IS NULL ";
2148 if ( $filterdate ) {
2149 $query.=" AND ( latestissue < ? OR latestissue IS NULL ) ";
2150 push @query_params,$filterdate;
2152 warn $query if $debug;
2154 my $sth = $dbh->prepare($query);
2155 if (scalar(@query_params)>0){
2156 $sth->execute(@query_params);
2158 else {
2159 $sth->execute;
2162 my @results;
2163 while ( my $data = $sth->fetchrow_hashref ) {
2164 push @results, $data;
2166 return \@results;
2169 =head2 GetBorrowersWhoHaveNeverBorrowed
2171 $results = &GetBorrowersWhoHaveNeverBorrowed
2173 This function get all borrowers who have never borrowed.
2175 I<$result> is a ref to an array which all elements are a hasref.
2177 =cut
2179 sub GetBorrowersWhoHaveNeverBorrowed {
2180 my $filterbranch = shift ||
2181 ((C4::Context->preference('IndependentBranches')
2182 && C4::Context->userenv
2183 && !C4::Context->IsSuperLibrarian()
2184 && C4::Context->userenv->{branch})
2185 ? C4::Context->userenv->{branch}
2186 : "");
2187 my $dbh = C4::Context->dbh;
2188 my $query = "
2189 SELECT borrowers.borrowernumber,max(timestamp) as latestissue
2190 FROM borrowers
2191 LEFT JOIN issues ON borrowers.borrowernumber = issues.borrowernumber
2192 WHERE issues.borrowernumber IS NULL
2194 my @query_params;
2195 if ($filterbranch && $filterbranch ne ""){
2196 $query.=" AND borrowers.branchcode= ?";
2197 push @query_params,$filterbranch;
2199 warn $query if $debug;
2201 my $sth = $dbh->prepare($query);
2202 if (scalar(@query_params)>0){
2203 $sth->execute(@query_params);
2205 else {
2206 $sth->execute;
2209 my @results;
2210 while ( my $data = $sth->fetchrow_hashref ) {
2211 push @results, $data;
2213 return \@results;
2216 =head2 GetBorrowersWithIssuesHistoryOlderThan
2218 $results = &GetBorrowersWithIssuesHistoryOlderThan($date)
2220 this function get all borrowers who has an issue history older than I<$date> given on input arg.
2222 I<$result> is a ref to an array which all elements are a hashref.
2223 This hashref is containt the number of time this borrowers has borrowed before I<$date> and the borrowernumber.
2225 =cut
2227 sub GetBorrowersWithIssuesHistoryOlderThan {
2228 my $dbh = C4::Context->dbh;
2229 my $date = shift ||POSIX::strftime("%Y-%m-%d",localtime());
2230 my $filterbranch = shift ||
2231 ((C4::Context->preference('IndependentBranches')
2232 && C4::Context->userenv
2233 && !C4::Context->IsSuperLibrarian()
2234 && C4::Context->userenv->{branch})
2235 ? C4::Context->userenv->{branch}
2236 : "");
2237 my $query = "
2238 SELECT count(borrowernumber) as n,borrowernumber
2239 FROM old_issues
2240 WHERE returndate < ?
2241 AND borrowernumber IS NOT NULL
2243 my @query_params;
2244 push @query_params, $date;
2245 if ($filterbranch){
2246 $query.=" AND branchcode = ?";
2247 push @query_params, $filterbranch;
2249 $query.=" GROUP BY borrowernumber ";
2250 warn $query if $debug;
2251 my $sth = $dbh->prepare($query);
2252 $sth->execute(@query_params);
2253 my @results;
2255 while ( my $data = $sth->fetchrow_hashref ) {
2256 push @results, $data;
2258 return \@results;
2261 =head2 GetBorrowersNamesAndLatestIssue
2263 $results = &GetBorrowersNamesAndLatestIssueList(@borrowernumbers)
2265 this function get borrowers Names and surnames and Issue information.
2267 I<@borrowernumbers> is an array which all elements are borrowernumbers.
2268 This hashref is containt the number of time this borrowers has borrowed before I<$date> and the borrowernumber.
2270 =cut
2272 sub GetBorrowersNamesAndLatestIssue {
2273 my $dbh = C4::Context->dbh;
2274 my @borrowernumbers=@_;
2275 my $query = "
2276 SELECT surname,lastname, phone, email,max(timestamp)
2277 FROM borrowers
2278 LEFT JOIN issues ON borrowers.borrowernumber=issues.borrowernumber
2279 GROUP BY borrowernumber
2281 my $sth = $dbh->prepare($query);
2282 $sth->execute;
2283 my $results = $sth->fetchall_arrayref({});
2284 return $results;
2287 =head2 ModPrivacy
2289 my $success = ModPrivacy( $borrowernumber, $privacy );
2291 Update the privacy of a patron.
2293 return :
2294 true on success, false on failure
2296 =cut
2298 sub ModPrivacy {
2299 my $borrowernumber = shift;
2300 my $privacy = shift;
2301 return unless defined $borrowernumber;
2302 return unless $borrowernumber =~ /^\d+$/;
2304 return ModMember( borrowernumber => $borrowernumber,
2305 privacy => $privacy );
2308 =head2 AddMessage
2310 AddMessage( $borrowernumber, $message_type, $message, $branchcode );
2312 Adds a message to the messages table for the given borrower.
2314 Returns:
2315 True on success
2316 False on failure
2318 =cut
2320 sub AddMessage {
2321 my ( $borrowernumber, $message_type, $message, $branchcode ) = @_;
2323 my $dbh = C4::Context->dbh;
2325 if ( ! ( $borrowernumber && $message_type && $message && $branchcode ) ) {
2326 return;
2329 my $query = "INSERT INTO messages ( borrowernumber, branchcode, message_type, message ) VALUES ( ?, ?, ?, ? )";
2330 my $sth = $dbh->prepare($query);
2331 $sth->execute( $borrowernumber, $branchcode, $message_type, $message );
2332 logaction("MEMBERS", "ADDCIRCMESSAGE", $borrowernumber, $message) if C4::Context->preference("BorrowersLog");
2333 return 1;
2336 =head2 GetMessages
2338 GetMessages( $borrowernumber, $type );
2340 $type is message type, B for borrower, or L for Librarian.
2341 Empty type returns all messages of any type.
2343 Returns all messages for the given borrowernumber
2345 =cut
2347 sub GetMessages {
2348 my ( $borrowernumber, $type, $branchcode ) = @_;
2350 if ( ! $type ) {
2351 $type = '%';
2354 my $dbh = C4::Context->dbh;
2356 my $query = "SELECT
2357 branches.branchname,
2358 messages.*,
2359 message_date,
2360 messages.branchcode LIKE '$branchcode' AS can_delete
2361 FROM messages, branches
2362 WHERE borrowernumber = ?
2363 AND message_type LIKE ?
2364 AND messages.branchcode = branches.branchcode
2365 ORDER BY message_date DESC";
2366 my $sth = $dbh->prepare($query);
2367 $sth->execute( $borrowernumber, $type ) ;
2368 my @results;
2370 while ( my $data = $sth->fetchrow_hashref ) {
2371 my $d = C4::Dates->new( $data->{message_date}, 'iso' );
2372 $data->{message_date_formatted} = $d->output;
2373 push @results, $data;
2375 return \@results;
2379 =head2 GetMessages
2381 GetMessagesCount( $borrowernumber, $type );
2383 $type is message type, B for borrower, or L for Librarian.
2384 Empty type returns all messages of any type.
2386 Returns the number of messages for the given borrowernumber
2388 =cut
2390 sub GetMessagesCount {
2391 my ( $borrowernumber, $type, $branchcode ) = @_;
2393 if ( ! $type ) {
2394 $type = '%';
2397 my $dbh = C4::Context->dbh;
2399 my $query = "SELECT COUNT(*) as MsgCount FROM messages WHERE borrowernumber = ? AND message_type LIKE ?";
2400 my $sth = $dbh->prepare($query);
2401 $sth->execute( $borrowernumber, $type ) ;
2402 my @results;
2404 my $data = $sth->fetchrow_hashref;
2405 my $count = $data->{'MsgCount'};
2407 return $count;
2412 =head2 DeleteMessage
2414 DeleteMessage( $message_id );
2416 =cut
2418 sub DeleteMessage {
2419 my ( $message_id ) = @_;
2421 my $dbh = C4::Context->dbh;
2422 my $query = "SELECT * FROM messages WHERE message_id = ?";
2423 my $sth = $dbh->prepare($query);
2424 $sth->execute( $message_id );
2425 my $message = $sth->fetchrow_hashref();
2427 $query = "DELETE FROM messages WHERE message_id = ?";
2428 $sth = $dbh->prepare($query);
2429 $sth->execute( $message_id );
2430 logaction("MEMBERS", "DELCIRCMESSAGE", $message->{'borrowernumber'}, $message->{'message'}) if C4::Context->preference("BorrowersLog");
2433 =head2 IssueSlip
2435 IssueSlip($branchcode, $borrowernumber, $quickslip)
2437 Returns letter hash ( see C4::Letters::GetPreparedLetter )
2439 $quickslip is boolean, to indicate whether we want a quick slip
2441 =cut
2443 sub IssueSlip {
2444 my ($branch, $borrowernumber, $quickslip) = @_;
2446 # FIXME Check callers before removing this statement
2447 #return unless $borrowernumber;
2449 my @issues = @{ GetPendingIssues($borrowernumber) };
2451 for my $issue (@issues) {
2452 $issue->{date_due} = $issue->{date_due_sql};
2453 if ($quickslip) {
2454 my $today = output_pref({ dt => dt_from_string, dateformat => 'iso', dateonly => 1 });
2455 if ( substr( $issue->{issuedate}, 0, 10 ) eq $today
2456 or substr( $issue->{lastreneweddate}, 0, 10 ) eq $today ) {
2457 $issue->{now} = 1;
2462 # Sort on timestamp then on issuedate (useful for tests and could be if modified in a batch
2463 @issues = sort {
2464 my $s = $b->{timestamp} <=> $a->{timestamp};
2465 $s == 0 ?
2466 $b->{issuedate} <=> $a->{issuedate} : $s;
2467 } @issues;
2469 my ($letter_code, %repeat);
2470 if ( $quickslip ) {
2471 $letter_code = 'ISSUEQSLIP';
2472 %repeat = (
2473 'checkedout' => [ map {
2474 'biblio' => $_,
2475 'items' => $_,
2476 'issues' => $_,
2477 }, grep { $_->{'now'} } @issues ],
2480 else {
2481 $letter_code = 'ISSUESLIP';
2482 %repeat = (
2483 'checkedout' => [ map {
2484 'biblio' => $_,
2485 'items' => $_,
2486 'issues' => $_,
2487 }, grep { !$_->{'overdue'} } @issues ],
2489 'overdue' => [ map {
2490 'biblio' => $_,
2491 'items' => $_,
2492 'issues' => $_,
2493 }, grep { $_->{'overdue'} } @issues ],
2495 'news' => [ map {
2496 $_->{'timestamp'} = $_->{'newdate'};
2497 { opac_news => $_ }
2498 } @{ GetNewsToDisplay("slip",$branch) } ],
2502 return C4::Letters::GetPreparedLetter (
2503 module => 'circulation',
2504 letter_code => $letter_code,
2505 branchcode => $branch,
2506 tables => {
2507 'branches' => $branch,
2508 'borrowers' => $borrowernumber,
2510 repeat => \%repeat,
2514 =head2 GetBorrowersWithEmail
2516 ([$borrnum,$userid], ...) = GetBorrowersWithEmail('me@example.com');
2518 This gets a list of users and their basic details from their email address.
2519 As it's possible for multiple user to have the same email address, it provides
2520 you with all of them. If there is no userid for the user, there will be an
2521 C<undef> there. An empty list will be returned if there are no matches.
2523 =cut
2525 sub GetBorrowersWithEmail {
2526 my $email = shift;
2528 my $dbh = C4::Context->dbh;
2530 my $query = "SELECT borrowernumber, userid FROM borrowers WHERE email=?";
2531 my $sth=$dbh->prepare($query);
2532 $sth->execute($email);
2533 my @result = ();
2534 while (my $ref = $sth->fetch) {
2535 push @result, $ref;
2537 die "Failure searching for borrowers by email address: $sth->errstr" if $sth->err;
2538 return @result;
2541 sub AddMember_Opac {
2542 my ( %borrower ) = @_;
2544 $borrower{'categorycode'} = C4::Context->preference('PatronSelfRegistrationDefaultCategory');
2546 my $sr = new String::Random;
2547 $sr->{'A'} = [ 'A'..'Z', 'a'..'z' ];
2548 my $password = $sr->randpattern("AAAAAAAAAA");
2549 $borrower{'password'} = $password;
2551 $borrower{'cardnumber'} = fixup_cardnumber();
2553 my $borrowernumber = AddMember(%borrower);
2555 return ( $borrowernumber, $password );
2558 =head2 AddEnrolmentFeeIfNeeded
2560 AddEnrolmentFeeIfNeeded( $borrower->{categorycode}, $borrower->{borrowernumber} );
2562 Add enrolment fee for a patron if needed.
2564 =cut
2566 sub AddEnrolmentFeeIfNeeded {
2567 my ( $categorycode, $borrowernumber ) = @_;
2568 # check for enrollment fee & add it if needed
2569 my $dbh = C4::Context->dbh;
2570 my $sth = $dbh->prepare(q{
2571 SELECT enrolmentfee
2572 FROM categories
2573 WHERE categorycode=?
2575 $sth->execute( $categorycode );
2576 if ( $sth->err ) {
2577 warn sprintf('Database returned the following error: %s', $sth->errstr);
2578 return;
2580 my ($enrolmentfee) = $sth->fetchrow;
2581 if ($enrolmentfee && $enrolmentfee > 0) {
2582 # insert fee in patron debts
2583 C4::Accounts::manualinvoice( $borrowernumber, '', '', 'A', $enrolmentfee );
2587 sub HasOverdues {
2588 my ( $borrowernumber ) = @_;
2590 my $sql = "SELECT COUNT(*) FROM issues WHERE date_due < NOW() AND borrowernumber = ?";
2591 my $sth = C4::Context->dbh->prepare( $sql );
2592 $sth->execute( $borrowernumber );
2593 my ( $count ) = $sth->fetchrow_array();
2595 return $count;
2598 END { } # module clean-up code here (global destructor)
2602 __END__
2604 =head1 AUTHOR
2606 Koha Team
2608 =cut