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>.
24 #use warnings; FIXME - Bug 2505
26 use String::Random qw( random_string );
27 use Date::Calc qw/Today Add_Delta_YM check_date Date_to_Days/;
28 use C4::Log; # logaction
34 use C4::Members::Attributes qw(SearchIdMatchingAttribute UpdateBorrowerAttribute);
35 use C4::NewsChannels; #get slip news
39 use Koha::Patron::Debarments qw(IsDebarred);
40 use Text::Unaccent qw( unac_string );
41 use Koha::AuthUtils qw(hash_password);
44 our ($VERSION,@ISA,@EXPORT,@EXPORT_OK,$debug);
46 use Module::Load::Conditional qw( can_load );
47 if ( ! can_load( modules => { 'Koha::NorwegianPatronDB' => undef } ) ) {
48 $debug && warn "Unable to load Koha::NorwegianPatronDB";
53 $VERSION = 3.07.00.049;
54 $debug = $ENV{DEBUG} || 0;
66 &GetMemberIssuesAndFines
70 &GetFirstValidEmailAddress
71 &GetNoticeEmailAddress
80 &GetHideLostItemsPreference
83 &GetMemberAccountRecords
84 &GetBorNotifyAcctRecord
88 GetBorrowerCategorycode
89 &GetBorrowercategoryList
91 &GetBorrowersToExpunge
92 &GetBorrowersWhoHaveNeverBorrowed
93 &GetBorrowersWithIssuesHistoryOlderThan
96 &GetUpcomingMembershipExpires
121 &ExtendMemberSubscriptionTo
137 C4::Members - Perl Module containing convenience functions for member handling
145 This module contains routines for adding, modifying and deleting members/patrons/borrowers
149 =head2 GetMemberDetails
151 ($borrower) = &GetMemberDetails($borrowernumber, $cardnumber);
153 Looks up a patron and returns information about him or her. If
154 C<$borrowernumber> is true (nonzero), C<&GetMemberDetails> looks
155 up the borrower by number; otherwise, it looks up the borrower by card
158 C<$borrower> is a reference-to-hash whose keys are the fields of the
159 borrowers table in the Koha database. In addition,
160 C<$borrower-E<gt>{flags}> is a hash giving more detailed information
161 about the patron. Its keys act as flags :
163 if $borrower->{flags}->{LOST} {
164 # Patron's card was reported lost
167 If the state of a flag means that the patron should not be
168 allowed to borrow any more books, then it will have a C<noissues> key
171 See patronflags for more details.
173 C<$borrower-E<gt>{authflags}> is a hash giving more detailed information
174 about the top-level permissions flags set for the borrower. For example,
175 if a user has the "editcatalogue" permission,
176 C<$borrower-E<gt>{authflags}-E<gt>{editcatalogue}> will exist and have
181 sub GetMemberDetails {
182 my ( $borrowernumber, $cardnumber ) = @_;
183 my $dbh = C4::Context->dbh;
186 if ($borrowernumber) {
187 $sth = $dbh->prepare("
190 categories.description,
191 categories.BlockExpiredPatronOpacActions,
195 LEFT JOIN categories ON borrowers.categorycode=categories.categorycode
196 WHERE borrowernumber = ?
198 $sth->execute($borrowernumber);
200 elsif ($cardnumber) {
201 $sth = $dbh->prepare("
204 categories.description,
205 categories.BlockExpiredPatronOpacActions,
209 LEFT JOIN categories ON borrowers.categorycode = categories.categorycode
212 $sth->execute($cardnumber);
217 my $borrower = $sth->fetchrow_hashref;
218 return unless $borrower;
219 my ($amount) = GetMemberAccountRecords($borrower->{borrowernumber});
220 $borrower->{'amountoutstanding'} = $amount;
221 # FIXME - patronflags calls GetMemberAccountRecords... just have patronflags return $amount
222 my $flags = patronflags( $borrower);
225 $sth = $dbh->prepare("select bit,flag from userflags");
227 while ( my ( $bit, $flag ) = $sth->fetchrow ) {
228 if ( $borrower->{'flags'} && $borrower->{'flags'} & 2**$bit ) {
229 $accessflagshash->{$flag} = 1;
232 $borrower->{'flags'} = $flags;
233 $borrower->{'authflags'} = $accessflagshash;
235 # Handle setting the true behavior for BlockExpiredPatronOpacActions
236 $borrower->{'BlockExpiredPatronOpacActions'} =
237 C4::Context->preference('BlockExpiredPatronOpacActions')
238 if ( $borrower->{'BlockExpiredPatronOpacActions'} == -1 );
240 $borrower->{'is_expired'} = 0;
241 $borrower->{'is_expired'} = 1 if
242 defined($borrower->{dateexpiry}) &&
243 $borrower->{'dateexpiry'} ne '0000-00-00' &&
244 Date_to_Days( Today() ) >
245 Date_to_Days( split /-/, $borrower->{'dateexpiry'} );
247 return ($borrower); #, $flags, $accessflagshash);
252 $flags = &patronflags($patron);
254 This function is not exported.
256 The following will be set where applicable:
257 $flags->{CHARGES}->{amount} Amount of debt
258 $flags->{CHARGES}->{noissues} Set if debt amount >$5.00 (or syspref noissuescharge)
259 $flags->{CHARGES}->{message} Message -- deprecated
261 $flags->{CREDITS}->{amount} Amount of credit
262 $flags->{CREDITS}->{message} Message -- deprecated
264 $flags->{ GNA } Patron has no valid address
265 $flags->{ GNA }->{noissues} Set for each GNA
266 $flags->{ GNA }->{message} "Borrower has no valid address" -- deprecated
268 $flags->{ LOST } Patron's card reported lost
269 $flags->{ LOST }->{noissues} Set for each LOST
270 $flags->{ LOST }->{message} Message -- deprecated
272 $flags->{DBARRED} Set if patron debarred, no access
273 $flags->{DBARRED}->{noissues} Set for each DBARRED
274 $flags->{DBARRED}->{message} Message -- deprecated
277 $flags->{ NOTES }->{message} The note itself. NOT deprecated
279 $flags->{ ODUES } Set if patron has overdue books.
280 $flags->{ ODUES }->{message} "Yes" -- deprecated
281 $flags->{ ODUES }->{itemlist} ref-to-array: list of overdue books
282 $flags->{ ODUES }->{itemlisttext} Text list of overdue items -- deprecated
284 $flags->{WAITING} Set if any of patron's reserves are available
285 $flags->{WAITING}->{message} Message -- deprecated
286 $flags->{WAITING}->{itemlist} ref-to-array: list of available items
290 =item C<$flags-E<gt>{ODUES}-E<gt>{itemlist}> is a reference-to-array listing the
291 overdue items. Its elements are references-to-hash, each describing an
292 overdue item. The keys are selected fields from the issues, biblio,
293 biblioitems, and items tables of the Koha database.
295 =item C<$flags-E<gt>{ODUES}-E<gt>{itemlisttext}> is a string giving a text listing of
296 the overdue items, one per line. Deprecated.
298 =item C<$flags-E<gt>{WAITING}-E<gt>{itemlist}> is a reference-to-array listing the
299 available items. Each element is a reference-to-hash whose keys are
300 fields from the reserves table of the Koha database.
304 All the "message" fields that include language generated in this function are deprecated,
305 because such strings belong properly in the display layer.
307 The "message" field that comes from the DB is OK.
311 # TODO: use {anonymous => hashes} instead of a dozen %flaginfo
312 # FIXME rename this function.
315 my ( $patroninformation) = @_;
316 my $dbh=C4::Context->dbh;
317 my ($balance, $owing) = GetMemberAccountBalance( $patroninformation->{'borrowernumber'});
320 my $noissuescharge = C4::Context->preference("noissuescharge") || 5;
321 $flaginfo{'message'} = sprintf 'Patron owes %.02f', $owing;
322 $flaginfo{'amount'} = sprintf "%.02f", $owing;
323 if ( $owing > $noissuescharge && !C4::Context->preference("AllowFineOverride") ) {
324 $flaginfo{'noissues'} = 1;
326 $flags{'CHARGES'} = \%flaginfo;
328 elsif ( $balance < 0 ) {
330 $flaginfo{'message'} = sprintf 'Patron has credit of %.02f', -$balance;
331 $flaginfo{'amount'} = sprintf "%.02f", $balance;
332 $flags{'CREDITS'} = \%flaginfo;
334 if ( $patroninformation->{'gonenoaddress'}
335 && $patroninformation->{'gonenoaddress'} == 1 )
338 $flaginfo{'message'} = 'Borrower has no valid address.';
339 $flaginfo{'noissues'} = 1;
340 $flags{'GNA'} = \%flaginfo;
342 if ( $patroninformation->{'lost'} && $patroninformation->{'lost'} == 1 ) {
344 $flaginfo{'message'} = 'Borrower\'s card reported lost.';
345 $flaginfo{'noissues'} = 1;
346 $flags{'LOST'} = \%flaginfo;
348 if ( $patroninformation->{'debarred'} && check_date( split( /-/, $patroninformation->{'debarred'} ) ) ) {
349 if ( Date_to_Days(Date::Calc::Today) < Date_to_Days( split( /-/, $patroninformation->{'debarred'} ) ) ) {
351 $flaginfo{'debarredcomment'} = $patroninformation->{'debarredcomment'};
352 $flaginfo{'message'} = $patroninformation->{'debarredcomment'};
353 $flaginfo{'noissues'} = 1;
354 $flaginfo{'dateend'} = $patroninformation->{'debarred'};
355 $flags{'DBARRED'} = \%flaginfo;
358 if ( $patroninformation->{'borrowernotes'}
359 && $patroninformation->{'borrowernotes'} )
362 $flaginfo{'message'} = $patroninformation->{'borrowernotes'};
363 $flags{'NOTES'} = \%flaginfo;
365 my ( $odues, $itemsoverdue ) = C4::Overdues::checkoverdues($patroninformation->{'borrowernumber'});
366 if ( $odues && $odues > 0 ) {
368 $flaginfo{'message'} = "Yes";
369 $flaginfo{'itemlist'} = $itemsoverdue;
370 foreach ( sort { $a->{'date_due'} cmp $b->{'date_due'} }
373 $flaginfo{'itemlisttext'} .=
374 "$_->{'date_due'} $_->{'barcode'} $_->{'title'} \n"; # newline is display layer
376 $flags{'ODUES'} = \%flaginfo;
378 my @itemswaiting = C4::Reserves::GetReservesFromBorrowernumber( $patroninformation->{'borrowernumber'},'W' );
379 my $nowaiting = scalar @itemswaiting;
380 if ( $nowaiting > 0 ) {
382 $flaginfo{'message'} = "Reserved items available";
383 $flaginfo{'itemlist'} = \@itemswaiting;
384 $flags{'WAITING'} = \%flaginfo;
392 $borrower = &GetMember(%information);
394 Retrieve the first patron record meeting on criteria listed in the
395 C<%information> hash, which should contain one or more
396 pairs of borrowers column names and values, e.g.,
398 $borrower = GetMember(borrowernumber => id);
400 C<&GetBorrower> returns a reference-to-hash whose keys are the fields of
401 the C<borrowers> table in the Koha database.
403 FIXME: GetMember() is used throughout the code as a lookup
404 on a unique key such as the borrowernumber, but this meaning is not
405 enforced in the routine itself.
411 my ( %information ) = @_;
412 if (exists $information{borrowernumber} && !defined $information{borrowernumber}) {
413 #passing mysql's kohaadmin?? Makes no sense as a query
416 my $dbh = C4::Context->dbh;
418 q{SELECT borrowers.*, categories.category_type, categories.description
420 LEFT JOIN categories on borrowers.categorycode=categories.categorycode WHERE };
423 for (keys %information ) {
431 if (defined $information{$_}) {
433 push @values, $information{$_};
436 $select .= "$_ IS NULL";
439 $debug && warn $select, " ",values %information;
440 my $sth = $dbh->prepare("$select");
441 $sth->execute(map{$information{$_}} keys %information);
442 my $data = $sth->fetchall_arrayref({});
443 #FIXME interface to this routine now allows generation of a result set
444 #so whole array should be returned but bowhere in the current code expects this
452 =head2 GetMemberRelatives
454 @borrowernumbers = GetMemberRelatives($borrowernumber);
456 C<GetMemberRelatives> returns a borrowersnumber's list of guarantor/guarantees of the member given in parameter
460 sub GetMemberRelatives {
461 my $borrowernumber = shift;
462 my $dbh = C4::Context->dbh;
466 my $query = "SELECT guarantorid FROM borrowers WHERE borrowernumber=?";
467 my $sth = $dbh->prepare($query);
468 $sth->execute($borrowernumber);
469 my $data = $sth->fetchrow_arrayref();
470 push @glist, $data->[0] if $data->[0];
471 my $guarantor = $data->[0] ? $data->[0] : undef;
474 $query = "SELECT borrowernumber FROM borrowers WHERE guarantorid=?";
475 $sth = $dbh->prepare($query);
476 $sth->execute($borrowernumber);
477 while ($data = $sth->fetchrow_arrayref()) {
478 push @glist, $data->[0];
481 # Getting sibling guarantees
483 $query = "SELECT borrowernumber FROM borrowers WHERE guarantorid=?";
484 $sth = $dbh->prepare($query);
485 $sth->execute($guarantor);
486 while ($data = $sth->fetchrow_arrayref()) {
487 push @glist, $data->[0] if ($data->[0] != $borrowernumber);
494 =head2 IsMemberBlocked
496 my ($block_status, $count) = IsMemberBlocked( $borrowernumber );
498 Returns whether a patron is restricted or has overdue items that may result
499 in a block of circulation privileges.
501 C<$block_status> can have the following values:
503 1 if the patron is currently restricted, in which case
504 C<$count> is the expiration date (9999-12-31 for indefinite)
506 -1 if the patron has overdue items, in which case C<$count> is the number of them
508 0 if the patron has no overdue items or outstanding fine days, in which case C<$count> is 0
510 Existing active restrictions are checked before current overdue items.
514 sub IsMemberBlocked {
515 my $borrowernumber = shift;
516 my $dbh = C4::Context->dbh;
518 my $blockeddate = Koha::Patron::Debarments::IsDebarred($borrowernumber);
520 return ( 1, $blockeddate ) if $blockeddate;
522 # if he have late issues
523 my $sth = $dbh->prepare(
524 "SELECT COUNT(*) as latedocs
526 WHERE borrowernumber = ?
527 AND date_due < now()"
529 $sth->execute($borrowernumber);
530 my $latedocs = $sth->fetchrow_hashref->{'latedocs'};
532 return ( -1, $latedocs ) if $latedocs > 0;
537 =head2 GetMemberIssuesAndFines
539 ($overdue_count, $issue_count, $total_fines) = &GetMemberIssuesAndFines($borrowernumber);
541 Returns aggregate data about items borrowed by the patron with the
542 given borrowernumber.
544 C<&GetMemberIssuesAndFines> returns a three-element array. C<$overdue_count> is the
545 number of overdue items the patron currently has borrowed. C<$issue_count> is the
546 number of books the patron currently has borrowed. C<$total_fines> is
547 the total fine currently due by the borrower.
552 sub GetMemberIssuesAndFines {
553 my ( $borrowernumber ) = @_;
554 my $dbh = C4::Context->dbh;
555 my $query = "SELECT COUNT(*) FROM issues WHERE borrowernumber = ?";
557 $debug and warn $query."\n";
558 my $sth = $dbh->prepare($query);
559 $sth->execute($borrowernumber);
560 my $issue_count = $sth->fetchrow_arrayref->[0];
562 $sth = $dbh->prepare(
563 "SELECT COUNT(*) FROM issues
564 WHERE borrowernumber = ?
565 AND date_due < now()"
567 $sth->execute($borrowernumber);
568 my $overdue_count = $sth->fetchrow_arrayref->[0];
570 $sth = $dbh->prepare("SELECT SUM(amountoutstanding) FROM accountlines WHERE borrowernumber = ?");
571 $sth->execute($borrowernumber);
572 my $total_fines = $sth->fetchrow_arrayref->[0];
574 return ($overdue_count, $issue_count, $total_fines);
580 my @columns = C4::Member::columns();
582 Returns an array of borrowers' table columns on success,
583 and an empty array on failure.
589 # Pure ANSI SQL goodness.
590 my $sql = 'SELECT * FROM borrowers WHERE 1=0;';
592 # Get the database handle.
593 my $dbh = C4::Context->dbh;
595 # Run the SQL statement to load STH's readonly properties.
596 my $sth = $dbh->prepare($sql);
597 my $rv = $sth->execute();
599 # This only fails if the table doesn't exist.
600 # This will always be called AFTER an install or upgrade,
601 # so borrowers will exist!
603 if ($sth->{NUM_OF_FIELDS}>0) {
604 @data = @{$sth->{NAME}};
615 my $success = ModMember(borrowernumber => $borrowernumber,
616 [ field => value ]... );
618 Modify borrower's data. All date fields should ALREADY be in ISO format.
621 true on success, or false on failure
627 # test to know if you must update or not the borrower password
628 if (exists $data{password}) {
629 if ($data{password} eq '****' or $data{password} eq '') {
630 delete $data{password};
632 if ( C4::Context->preference('NorwegianPatronDBEnable') && C4::Context->preference('NorwegianPatronDBEnable') == 1 ) {
633 # Update the hashed PIN in borrower_sync.hashed_pin, before Koha hashes it
634 Koha::NorwegianPatronDB::NLUpdateHashedPIN( $data{'borrowernumber'}, $data{password} );
636 $data{password} = hash_password($data{password});
640 my $old_categorycode = GetBorrowerCategorycode( $data{borrowernumber} );
642 # get only the columns of a borrower
643 my $schema = Koha::Database->new()->schema;
644 my @columns = $schema->source('Borrower')->columns;
645 my $new_borrower = { map { join(' ', @columns) =~ /$_/ ? ( $_ => $data{$_} ) : () } keys(%data) };
646 delete $new_borrower->{flags};
648 $new_borrower->{dateofbirth} ||= undef if exists $new_borrower->{dateofbirth};
649 $new_borrower->{dateenrolled} ||= undef if exists $new_borrower->{dateenrolled};
650 $new_borrower->{dateexpiry} ||= undef if exists $new_borrower->{dateexpiry};
651 $new_borrower->{debarred} ||= undef if exists $new_borrower->{debarred};
652 $new_borrower->{sms_provider_id} ||= undef if exists $new_borrower->{sms_provider_id};
654 my $rs = $schema->resultset('Borrower')->search({
655 borrowernumber => $new_borrower->{borrowernumber},
658 my $execute_success = $rs->update($new_borrower);
659 if ($execute_success ne '0E0') { # only proceed if the update was a success
661 # ok if its an adult (type) it may have borrowers that depend on it as a guarantor
662 # so when we update information for an adult we should check for guarantees and update the relevant part
663 # of their records, ie addresses and phone numbers
664 my $borrowercategory= GetBorrowercategory( $data{'category_type'} );
665 if ( exists $borrowercategory->{'category_type'} && $borrowercategory->{'category_type'} eq ('A' || 'S') ) {
666 # is adult check guarantees;
667 UpdateGuarantees(%data);
670 # If the patron changes to a category with enrollment fee, we add a fee
671 if ( $data{categorycode} and $data{categorycode} ne $old_categorycode ) {
672 if ( C4::Context->preference('FeeOnChangePatronCategory') ) {
673 AddEnrolmentFeeIfNeeded( $data{categorycode}, $data{borrowernumber} );
677 # If NorwegianPatronDBEnable is enabled, we set syncstatus to something that a
678 # cronjob will use for syncing with NL
679 if ( C4::Context->preference('NorwegianPatronDBEnable') && C4::Context->preference('NorwegianPatronDBEnable') == 1 ) {
680 my $borrowersync = Koha::Database->new->schema->resultset('BorrowerSync')->find({
681 'synctype' => 'norwegianpatrondb',
682 'borrowernumber' => $data{'borrowernumber'}
684 # Do not set to "edited" if syncstatus is "new". We need to sync as new before
685 # we can sync as changed. And the "new sync" will pick up all changes since
686 # the patron was created anyway.
687 if ( $borrowersync->syncstatus ne 'new' && $borrowersync->syncstatus ne 'delete' ) {
688 $borrowersync->update( { 'syncstatus' => 'edited' } );
690 # Set the value of 'sync'
691 $borrowersync->update( { 'sync' => $data{'sync'} } );
692 # Try to do the live sync
693 Koha::NorwegianPatronDB::NLSync({ 'borrowernumber' => $data{'borrowernumber'} });
696 logaction("MEMBERS", "MODIFY", $data{'borrowernumber'}, "UPDATE (executed w/ arg: $data{'borrowernumber'})") if C4::Context->preference("BorrowersLog");
698 return $execute_success;
703 $borrowernumber = &AddMember(%borrower);
705 insert new borrower into table
707 (%borrower keys are database columns. Database columns could be
708 different in different versions. Please look into database for correct
711 Returns the borrowernumber upon success
713 Returns as undef upon any db error without further processing
720 my $dbh = C4::Context->dbh;
721 my $schema = Koha::Database->new()->schema;
723 # generate a proper login if none provided
724 $data{'userid'} = Generate_Userid( $data{'borrowernumber'}, $data{'firstname'}, $data{'surname'} )
725 if ( $data{'userid'} eq '' || !Check_Userid( $data{'userid'} ) );
727 # add expiration date if it isn't already there
728 unless ( $data{'dateexpiry'} ) {
729 $data{'dateexpiry'} = GetExpiryDate( $data{'categorycode'}, output_pref( { dt => dt_from_string, dateonly => 1, dateformat => 'iso' } ) );
732 # add enrollment date if it isn't already there
733 unless ( $data{'dateenrolled'} ) {
734 $data{'dateenrolled'} = output_pref( { dt => dt_from_string, dateonly => 1, dateformat => 'iso' } );
737 my $patron_category = $schema->resultset('Category')->find( $data{'categorycode'} );
739 $patron_category->default_privacy() eq 'default' ? 1
740 : $patron_category->default_privacy() eq 'never' ? 2
741 : $patron_category->default_privacy() eq 'forever' ? 0
744 $data{'privacy_guarantor_checkouts'} = 0 unless defined( $data{'privacy_guarantor_checkouts'} );
746 # Make a copy of the plain text password for later use
747 my $plain_text_password = $data{'password'};
749 # create a disabled account if no password provided
750 $data{'password'} = ($data{'password'})? hash_password($data{'password'}) : '!';
752 # we don't want invalid dates in the db (mysql has a bad habit of inserting 0000-00-00
753 $data{'dateofbirth'} = undef if ( not $data{'dateofbirth'} );
754 $data{'debarred'} = undef if ( not $data{'debarred'} );
755 $data{'sms_provider_id'} = undef if ( not $data{'sms_provider_id'} );
757 # get only the columns of Borrower
758 my @columns = $schema->source('Borrower')->columns;
759 my $new_member = { map { join(' ',@columns) =~ /$_/ ? ( $_ => $data{$_} ) : () } keys(%data) } ;
760 delete $new_member->{borrowernumber};
762 my $rs = $schema->resultset('Borrower');
763 $data{borrowernumber} = $rs->create($new_member)->id;
765 # If NorwegianPatronDBEnable is enabled, we set syncstatus to something that a
766 # cronjob will use for syncing with NL
767 if ( exists $data{'borrowernumber'} && C4::Context->preference('NorwegianPatronDBEnable') && C4::Context->preference('NorwegianPatronDBEnable') == 1 ) {
768 Koha::Database->new->schema->resultset('BorrowerSync')->create({
769 'borrowernumber' => $data{'borrowernumber'},
770 'synctype' => 'norwegianpatrondb',
772 'syncstatus' => 'new',
773 'hashed_pin' => Koha::NorwegianPatronDB::NLEncryptPIN( $plain_text_password ),
777 # mysql_insertid is probably bad. not necessarily accurate and mysql-specific at best.
778 logaction("MEMBERS", "CREATE", $data{'borrowernumber'}, "") if C4::Context->preference("BorrowersLog");
780 AddEnrolmentFeeIfNeeded( $data{categorycode}, $data{borrowernumber} );
782 return $data{borrowernumber};
787 my $uniqueness = Check_Userid($userid,$borrowernumber);
789 $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 != '').
791 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.
794 0 for not unique (i.e. this $userid already exists)
795 1 for unique (i.e. this $userid does not exist, or this $userid/$borrowernumber combination already exists)
800 my ( $uid, $borrowernumber ) = @_;
802 return 0 unless ($uid); # userid is a unique column, we should assume NULL is not unique
804 return 0 if ( $uid eq C4::Context->config('user') );
806 my $rs = Koha::Database->new()->schema()->resultset('Borrower');
809 $params->{userid} = $uid;
810 $params->{borrowernumber} = { '!=' => $borrowernumber } if ($borrowernumber);
812 my $count = $rs->count( $params );
814 return $count ? 0 : 1;
817 =head2 Generate_Userid
819 my $newuid = Generate_Userid($borrowernumber, $firstname, $surname);
821 Generate a userid using the $surname and the $firstname (if there is a value in $firstname).
823 $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.
826 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).
830 sub Generate_Userid {
831 my ($borrowernumber, $firstname, $surname) = @_;
834 #The script will "do" the following code and increment the $offset until Check_Userid = 1 (i.e. until $newuid comes back as unique)
836 $firstname =~ s/[[:digit:][:space:][:blank:][:punct:][:cntrl:]]//g;
837 $surname =~ s/[[:digit:][:space:][:blank:][:punct:][:cntrl:]]//g;
838 $newuid = lc(($firstname)? "$firstname.$surname" : $surname);
839 $newuid = unac_string('utf-8',$newuid);
840 $newuid .= $offset unless $offset == 0;
843 } while (!Check_Userid($newuid,$borrowernumber));
849 my ( $uid, $member, $digest ) = @_;
850 my $dbh = C4::Context->dbh;
852 #Make sure the userid chosen is unique and not theirs if non-empty. If it is not,
853 #Then we need to tell the user and have them create a new one.
857 "SELECT * FROM borrowers WHERE userid=? AND borrowernumber != ?");
858 $sth->execute( $uid, $member );
859 if ( ( $uid ne '' ) && ( my $row = $sth->fetchrow_hashref ) ) {
863 #Everything is good so we can update the information.
866 "update borrowers set userid=?, password=? where borrowernumber=?");
867 $sth->execute( $uid, $digest, $member );
871 logaction("MEMBERS", "CHANGE PASS", $member, "") if C4::Context->preference("BorrowersLog");
877 =head2 fixup_cardnumber
879 Warning: The caller is responsible for locking the members table in write
880 mode, to avoid database corruption.
884 use vars qw( @weightings );
885 my @weightings = ( 8, 4, 6, 3, 5, 2, 1 );
887 sub fixup_cardnumber {
888 my ($cardnumber) = @_;
889 my $autonumber_members = C4::Context->boolean_preference('autoMemberNum') || 0;
891 # Find out whether member numbers should be generated
892 # automatically. Should be either "1" or something else.
893 # Defaults to "0", which is interpreted as "no".
895 # if ($cardnumber !~ /\S/ && $autonumber_members) {
896 ($autonumber_members) or return $cardnumber;
897 my $checkdigit = C4::Context->preference('checkdigit');
898 my $dbh = C4::Context->dbh;
899 if ( $checkdigit and $checkdigit eq 'katipo' ) {
901 # if checkdigit is selected, calculate katipo-style cardnumber.
902 # otherwise, just use the max()
903 # purpose: generate checksum'd member numbers.
904 # We'll assume we just got the max value of digits 2-8 of member #'s
905 # from the database and our job is to increment that by one,
906 # determine the 1st and 9th digits and return the full string.
907 my $sth = $dbh->prepare(
908 "select max(substring(borrowers.cardnumber,2,7)) as new_num from borrowers"
911 my $data = $sth->fetchrow_hashref;
912 $cardnumber = $data->{new_num};
913 if ( !$cardnumber ) { # If DB has no values,
914 $cardnumber = 1000000; # start at 1000000
920 for ( my $i = 0 ; $i < 8 ; $i += 1 ) {
921 # read weightings, left to right, 1 char at a time
922 my $temp1 = $weightings[$i];
924 # sequence left to right, 1 char at a time
925 my $temp2 = substr( $cardnumber, $i, 1 );
927 # mult each char 1-7 by its corresponding weighting
928 $sum += $temp1 * $temp2;
931 my $rem = ( $sum % 11 );
932 $rem = 'X' if $rem == 10;
934 return "V$cardnumber$rem";
937 my $sth = $dbh->prepare(
938 'SELECT MAX( CAST( cardnumber AS SIGNED ) ) FROM borrowers WHERE cardnumber REGEXP "^-?[0-9]+$"'
941 my ($result) = $sth->fetchrow;
944 return $cardnumber; # just here as a fallback/reminder
949 ($num_children, $children_arrayref) = &GetGuarantees($parent_borrno);
950 $child0_cardno = $children_arrayref->[0]{"cardnumber"};
951 $child0_borrno = $children_arrayref->[0]{"borrowernumber"};
953 C<&GetGuarantees> takes a borrower number (e.g., that of a patron
954 with children) and looks up the borrowers who are guaranteed by that
955 borrower (i.e., the patron's children).
957 C<&GetGuarantees> returns two values: an integer giving the number of
958 borrowers guaranteed by C<$parent_borrno>, and a reference to an array
959 of references to hash, which gives the actual results.
965 my ($borrowernumber) = @_;
966 my $dbh = C4::Context->dbh;
969 "select cardnumber,borrowernumber, firstname, surname from borrowers where guarantorid=?"
971 $sth->execute($borrowernumber);
974 my $data = $sth->fetchall_arrayref({});
975 return ( scalar(@$data), $data );
978 =head2 UpdateGuarantees
980 &UpdateGuarantees($parent_borrno);
983 C<&UpdateGuarantees> borrower data for an adult and updates all the guarantees
984 with the modified information
989 sub UpdateGuarantees {
991 my $dbh = C4::Context->dbh;
992 my ( $count, $guarantees ) = GetGuarantees( $data{'borrowernumber'} );
993 foreach my $guarantee (@$guarantees){
994 my $guaquery = qq|UPDATE borrowers
995 SET address=?,fax=?,B_city=?,mobile=?,city=?,phone=?
996 WHERE borrowernumber=?
998 my $sth = $dbh->prepare($guaquery);
999 $sth->execute($data{'address'},$data{'fax'},$data{'B_city'},$data{'mobile'},$data{'city'},$data{'phone'},$guarantee->{'borrowernumber'});
1002 =head2 GetPendingIssues
1004 my $issues = &GetPendingIssues(@borrowernumber);
1006 Looks up what the patron with the given borrowernumber has borrowed.
1008 C<&GetPendingIssues> returns a
1009 reference-to-array where each element is a reference-to-hash; the
1010 keys are the fields from the C<issues>, C<biblio>, and C<items> tables.
1011 The keys include C<biblioitems> fields except marc and marcxml.
1016 sub GetPendingIssues {
1017 my @borrowernumbers = @_;
1019 unless (@borrowernumbers ) { # return a ref_to_array
1020 return \@borrowernumbers; # to not cause surprise to caller
1023 # Borrowers part of the query
1025 for (my $i = 0; $i < @borrowernumbers; $i++) {
1026 $bquery .= ' issues.borrowernumber = ?';
1027 if ($i < $#borrowernumbers ) {
1032 # must avoid biblioitems.* to prevent large marc and marcxml fields from killing performance
1033 # FIXME: namespace collision: each table has "timestamp" fields. Which one is "timestamp" ?
1034 # FIXME: circ/ciculation.pl tries to sort by timestamp!
1035 # FIXME: namespace collision: other collisions possible.
1036 # FIXME: most of this data isn't really being used by callers.
1043 biblioitems.itemtype,
1046 biblioitems.publicationyear,
1047 biblioitems.publishercode,
1048 biblioitems.volumedate,
1049 biblioitems.volumedesc,
1052 borrowers.firstname,
1054 borrowers.cardnumber,
1055 issues.timestamp AS timestamp,
1056 issues.renewals AS renewals,
1057 issues.borrowernumber AS borrowernumber,
1058 items.renewals AS totalrenewals
1060 LEFT JOIN items ON items.itemnumber = issues.itemnumber
1061 LEFT JOIN biblio ON items.biblionumber = biblio.biblionumber
1062 LEFT JOIN biblioitems ON items.biblioitemnumber = biblioitems.biblioitemnumber
1063 LEFT JOIN borrowers ON issues.borrowernumber = borrowers.borrowernumber
1066 ORDER BY issues.issuedate"
1069 my $sth = C4::Context->dbh->prepare($query);
1070 $sth->execute(@borrowernumbers);
1071 my $data = $sth->fetchall_arrayref({});
1072 my $today = dt_from_string;
1073 foreach (@{$data}) {
1074 if ($_->{issuedate}) {
1075 $_->{issuedate} = dt_from_string($_->{issuedate}, 'sql');
1077 $_->{date_due_sql} = $_->{date_due};
1078 # FIXME no need to have this value
1079 $_->{date_due} or next;
1080 $_->{date_due_sql} = $_->{date_due};
1081 # FIXME no need to have this value
1082 $_->{date_due} = dt_from_string($_->{date_due}, 'sql');
1083 if ( DateTime->compare($_->{date_due}, $today) == -1 ) {
1092 $issues = &GetAllIssues($borrowernumber, $sortkey, $limit);
1094 Looks up what the patron with the given borrowernumber has borrowed,
1095 and sorts the results.
1097 C<$sortkey> is the name of a field on which to sort the results. This
1098 should be the name of a field in the C<issues>, C<biblio>,
1099 C<biblioitems>, or C<items> table in the Koha database.
1101 C<$limit> is the maximum number of results to return.
1103 C<&GetAllIssues> an arrayref, C<$issues>, of hashrefs, the keys of which
1104 are the fields from the C<issues>, C<biblio>, C<biblioitems>, and
1105 C<items> tables of the Koha database.
1111 my ( $borrowernumber, $order, $limit ) = @_;
1113 return unless $borrowernumber;
1114 $order = 'date_due desc' unless $order;
1116 my $dbh = C4::Context->dbh;
1118 'SELECT *, issues.timestamp as issuestimestamp, issues.renewals AS renewals,items.renewals AS totalrenewals,items.timestamp AS itemstimestamp
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 WHERE borrowernumber=?
1125 SELECT *, old_issues.timestamp as issuestimestamp, old_issues.renewals AS renewals,items.renewals AS totalrenewals,items.timestamp AS itemstimestamp
1127 LEFT JOIN items on items.itemnumber=old_issues.itemnumber
1128 LEFT JOIN biblio ON items.biblionumber=biblio.biblionumber
1129 LEFT JOIN biblioitems ON items.biblioitemnumber=biblioitems.biblioitemnumber
1130 WHERE borrowernumber=? AND old_issues.itemnumber IS NOT NULL
1131 order by ' . $order;
1133 $query .= " limit $limit";
1136 my $sth = $dbh->prepare($query);
1137 $sth->execute( $borrowernumber, $borrowernumber );
1138 return $sth->fetchall_arrayref( {} );
1142 =head2 GetMemberAccountRecords
1144 ($total, $acctlines, $count) = &GetMemberAccountRecords($borrowernumber);
1146 Looks up accounting data for the patron with the given borrowernumber.
1148 C<&GetMemberAccountRecords> returns a three-element array. C<$acctlines> is a
1149 reference-to-array, where each element is a reference-to-hash; the
1150 keys are the fields of the C<accountlines> table in the Koha database.
1151 C<$count> is the number of elements in C<$acctlines>. C<$total> is the
1152 total amount outstanding for all of the account lines.
1156 sub GetMemberAccountRecords {
1157 my ($borrowernumber) = @_;
1158 my $dbh = C4::Context->dbh;
1164 WHERE borrowernumber=?);
1165 $strsth.=" ORDER BY accountlines_id desc";
1166 my $sth= $dbh->prepare( $strsth );
1167 $sth->execute( $borrowernumber );
1170 while ( my $data = $sth->fetchrow_hashref ) {
1171 if ( $data->{itemnumber} ) {
1172 my $biblio = GetBiblioFromItemNumber( $data->{itemnumber} );
1173 $data->{biblionumber} = $biblio->{biblionumber};
1174 $data->{title} = $biblio->{title};
1176 $acctlines[$numlines] = $data;
1178 $total += int(1000 * $data->{'amountoutstanding'}); # convert float to integer to avoid round-off errors
1181 return ( $total, \@acctlines,$numlines);
1184 =head2 GetMemberAccountBalance
1186 ($total_balance, $non_issue_balance, $other_charges) = &GetMemberAccountBalance($borrowernumber);
1188 Calculates amount immediately owing by the patron - non-issue charges.
1189 Based on GetMemberAccountRecords.
1190 Charges exempt from non-issue are:
1192 * Rent (rental) if RentalsInNoissuesCharge syspref is set to false
1193 * Manual invoices if ManInvInNoissuesCharge syspref is set to false
1197 sub GetMemberAccountBalance {
1198 my ($borrowernumber) = @_;
1200 my $ACCOUNT_TYPE_LENGTH = 5; # this is plain ridiculous...
1203 push @not_fines, 'Res' unless C4::Context->preference('HoldsInNoissuesCharge');
1204 push @not_fines, 'Rent' unless C4::Context->preference('RentalsInNoissuesCharge');
1205 unless ( C4::Context->preference('ManInvInNoissuesCharge') ) {
1206 my $dbh = C4::Context->dbh;
1207 my $man_inv_types = $dbh->selectcol_arrayref(qq{SELECT authorised_value FROM authorised_values WHERE category = 'MANUAL_INV'});
1208 push @not_fines, map substr($_, 0, $ACCOUNT_TYPE_LENGTH), @$man_inv_types;
1210 my %not_fine = map {$_ => 1} @not_fines;
1212 my ($total, $acctlines) = GetMemberAccountRecords($borrowernumber);
1213 my $other_charges = 0;
1214 foreach (@$acctlines) {
1215 $other_charges += $_->{amountoutstanding} if $not_fine{ substr($_->{accounttype}, 0, $ACCOUNT_TYPE_LENGTH) };
1218 return ( $total, $total - $other_charges, $other_charges);
1221 =head2 GetBorNotifyAcctRecord
1223 ($total, $acctlines, $count) = &GetBorNotifyAcctRecord($params,$notifyid);
1225 Looks up accounting data for the patron with the given borrowernumber per file number.
1227 C<&GetBorNotifyAcctRecord> returns a three-element array. C<$acctlines> is a
1228 reference-to-array, where each element is a reference-to-hash; the
1229 keys are the fields of the C<accountlines> table in the Koha database.
1230 C<$count> is the number of elements in C<$acctlines>. C<$total> is the
1231 total amount outstanding for all of the account lines.
1235 sub GetBorNotifyAcctRecord {
1236 my ( $borrowernumber, $notifyid ) = @_;
1237 my $dbh = C4::Context->dbh;
1240 my $sth = $dbh->prepare(
1243 WHERE borrowernumber=?
1245 AND amountoutstanding != '0'
1246 ORDER BY notify_id,accounttype
1249 $sth->execute( $borrowernumber, $notifyid );
1251 while ( my $data = $sth->fetchrow_hashref ) {
1252 if ( $data->{itemnumber} ) {
1253 my $biblio = GetBiblioFromItemNumber( $data->{itemnumber} );
1254 $data->{biblionumber} = $biblio->{biblionumber};
1255 $data->{title} = $biblio->{title};
1257 $acctlines[$numlines] = $data;
1259 $total += int(100 * $data->{'amountoutstanding'});
1262 return ( $total, \@acctlines, $numlines );
1265 =head2 checkuniquemember (OUEST-PROVENCE)
1267 ($result,$categorycode) = &checkuniquemember($collectivity,$surname,$firstname,$dateofbirth);
1269 Checks that a member exists or not in the database.
1271 C<&result> is nonzero (=exist) or 0 (=does not exist)
1272 C<&categorycode> is from categorycode table
1273 C<&collectivity> is 1 (= we add a collectivity) or 0 (= we add a physical member)
1274 C<&surname> is the surname
1275 C<&firstname> is the firstname (only if collectivity=0)
1276 C<&dateofbirth> is the date of birth in ISO format (only if collectivity=0)
1280 # FIXME: This function is not legitimate. Multiple patrons might have the same first/last name and birthdate.
1281 # This is especially true since first name is not even a required field.
1283 sub checkuniquemember {
1284 my ( $collectivity, $surname, $firstname, $dateofbirth ) = @_;
1285 my $dbh = C4::Context->dbh;
1286 my $request = ($collectivity) ?
1287 "SELECT borrowernumber,categorycode FROM borrowers WHERE surname=? " :
1289 "SELECT borrowernumber,categorycode FROM borrowers WHERE surname=? and firstname=? and dateofbirth=?" :
1290 "SELECT borrowernumber,categorycode FROM borrowers WHERE surname=? and firstname=?";
1291 my $sth = $dbh->prepare($request);
1292 if ($collectivity) {
1293 $sth->execute( uc($surname) );
1294 } elsif($dateofbirth){
1295 $sth->execute( uc($surname), ucfirst($firstname), $dateofbirth );
1297 $sth->execute( uc($surname), ucfirst($firstname));
1299 my @data = $sth->fetchrow;
1300 ( $data[0] ) and return $data[0], $data[1];
1304 sub checkcardnumber {
1305 my ( $cardnumber, $borrowernumber ) = @_;
1307 # If cardnumber is null, we assume they're allowed.
1308 return 0 unless defined $cardnumber;
1310 my $dbh = C4::Context->dbh;
1311 my $query = "SELECT * FROM borrowers WHERE cardnumber=?";
1312 $query .= " AND borrowernumber <> ?" if ($borrowernumber);
1313 my $sth = $dbh->prepare($query);
1316 ( $borrowernumber ? $borrowernumber : () )
1319 return 1 if $sth->fetchrow_hashref;
1321 my ( $min_length, $max_length ) = get_cardnumber_length();
1323 if length $cardnumber > $max_length
1324 or length $cardnumber < $min_length;
1329 =head2 get_cardnumber_length
1331 my ($min, $max) = C4::Members::get_cardnumber_length()
1333 Returns the minimum and maximum length for patron cardnumbers as
1334 determined by the CardnumberLength system preference, the
1335 BorrowerMandatoryField system preference, and the width of the
1340 sub get_cardnumber_length {
1341 my ( $min, $max ) = ( 0, 16 ); # borrowers.cardnumber is a nullable varchar(16)
1342 $min = 1 if C4::Context->preference('BorrowerMandatoryField') =~ /cardnumber/;
1343 if ( my $cardnumber_length = C4::Context->preference('CardnumberLength') ) {
1344 # Is integer and length match
1345 if ( $cardnumber_length =~ m|^\d+$| ) {
1346 $min = $max = $cardnumber_length
1347 if $cardnumber_length >= $min
1348 and $cardnumber_length <= $max;
1350 # Else assuming it is a range
1351 elsif ( $cardnumber_length =~ m|(\d*),(\d*)| ) {
1352 $min = $1 if $1 and $min < $1;
1353 $max = $2 if $2 and $max > $2;
1357 return ( $min, $max );
1360 =head2 GetFirstValidEmailAddress
1362 $email = GetFirstValidEmailAddress($borrowernumber);
1364 Return the first valid email address for a borrower, given the borrowernumber. For now, the order
1365 is defined as email, emailpro, B_email. Returns the empty string if the borrower has no email
1370 sub GetFirstValidEmailAddress {
1371 my $borrowernumber = shift;
1372 my $dbh = C4::Context->dbh;
1373 my $sth = $dbh->prepare( "SELECT email, emailpro, B_email FROM borrowers where borrowernumber = ? ");
1374 $sth->execute( $borrowernumber );
1375 my $data = $sth->fetchrow_hashref;
1377 if ($data->{'email'}) {
1378 return $data->{'email'};
1379 } elsif ($data->{'emailpro'}) {
1380 return $data->{'emailpro'};
1381 } elsif ($data->{'B_email'}) {
1382 return $data->{'B_email'};
1388 =head2 GetNoticeEmailAddress
1390 $email = GetNoticeEmailAddress($borrowernumber);
1392 Return the email address of borrower used for notices, given the borrowernumber.
1393 Returns the empty string if no email address.
1397 sub GetNoticeEmailAddress {
1398 my $borrowernumber = shift;
1400 my $which_address = C4::Context->preference("AutoEmailPrimaryAddress");
1401 # if syspref is set to 'first valid' (value == OFF), look up email address
1402 if ( $which_address eq 'OFF' ) {
1403 return GetFirstValidEmailAddress($borrowernumber);
1405 # specified email address field
1406 my $dbh = C4::Context->dbh;
1407 my $sth = $dbh->prepare( qq{
1408 SELECT $which_address AS primaryemail
1410 WHERE borrowernumber=?
1412 $sth->execute($borrowernumber);
1413 my $data = $sth->fetchrow_hashref;
1414 return $data->{'primaryemail'} || '';
1417 =head2 GetExpiryDate
1419 $expirydate = GetExpiryDate($categorycode, $dateenrolled);
1421 Calculate expiry date given a categorycode and starting date. Date argument must be in ISO format.
1422 Return date is also in ISO format.
1427 my ( $categorycode, $dateenrolled ) = @_;
1429 if ($categorycode) {
1430 my $dbh = C4::Context->dbh;
1431 my $sth = $dbh->prepare("SELECT enrolmentperiod,enrolmentperioddate FROM categories WHERE categorycode=?");
1432 $sth->execute($categorycode);
1433 $enrolments = $sth->fetchrow_hashref;
1435 # die "GetExpiryDate: for enrollmentperiod $enrolmentperiod (category '$categorycode') starting $dateenrolled.\n";
1436 my @date = split (/-/,$dateenrolled);
1437 if($enrolments->{enrolmentperiod}){
1438 return sprintf("%04d-%02d-%02d", Add_Delta_YM(@date,0,$enrolments->{enrolmentperiod}));
1440 return $enrolments->{enrolmentperioddate};
1444 =head2 GetUpcomingMembershipExpires
1446 my $upcoming_mem_expires = GetUpcomingMembershipExpires();
1450 sub GetUpcomingMembershipExpires {
1451 my $dbh = C4::Context->dbh;
1452 my $days = C4::Context->preference("MembershipExpiryDaysNotice") || 0;
1453 my $dateexpiry = output_pref({ dt => (dt_from_string()->add( days => $days)), dateformat => 'iso', dateonly => 1 });
1456 SELECT borrowers.*, categories.description,
1457 branches.branchname, branches.branchemail FROM borrowers
1458 LEFT JOIN branches on borrowers.branchcode = branches.branchcode
1459 LEFT JOIN categories on borrowers.categorycode = categories.categorycode
1460 WHERE dateexpiry = ?;
1462 my $sth = $dbh->prepare($query);
1463 $sth->execute($dateexpiry);
1464 my $results = $sth->fetchall_arrayref({});
1468 =head2 GetborCatFromCatType
1470 ($codes_arrayref, $labels_hashref) = &GetborCatFromCatType();
1472 Looks up the different types of borrowers in the database. Returns two
1473 elements: a reference-to-array, which lists the borrower category
1474 codes, and a reference-to-hash, which maps the borrower category codes
1475 to category descriptions.
1480 sub GetborCatFromCatType {
1481 my ( $category_type, $action, $no_branch_limit ) = @_;
1483 my $branch_limit = $no_branch_limit
1485 : C4::Context->userenv ? C4::Context->userenv->{"branch"} : "";
1487 # FIXME - This API seems both limited and dangerous.
1488 my $dbh = C4::Context->dbh;
1491 SELECT categories.categorycode, categories.description
1495 LEFT JOIN categories_branches ON categories.categorycode = categories_branches.categorycode
1498 $request .= " $action ";
1499 $request .= " AND (branchcode = ? OR branchcode IS NULL) GROUP BY description" if $branch_limit;
1501 $request .= " WHERE branchcode = ? OR branchcode IS NULL GROUP BY description" if $branch_limit;
1503 $request .= " ORDER BY categorycode";
1505 my $sth = $dbh->prepare($request);
1507 $action ? $category_type : (),
1508 $branch_limit ? $branch_limit : ()
1514 while ( my $data = $sth->fetchrow_hashref ) {
1515 push @codes, $data->{'categorycode'};
1516 $labels{ $data->{'categorycode'} } = $data->{'description'};
1519 return ( \@codes, \%labels );
1522 =head2 GetBorrowercategory
1524 $hashref = &GetBorrowercategory($categorycode);
1526 Given the borrower's category code, the function returns the corresponding
1527 data hashref for a comprehensive information display.
1531 sub GetBorrowercategory {
1533 my $dbh = C4::Context->dbh;
1537 "SELECT description,dateofbirthrequired,upperagelimit,category_type
1539 WHERE categorycode = ?"
1541 $sth->execute($catcode);
1543 $sth->fetchrow_hashref;
1547 } # sub getborrowercategory
1550 =head2 GetBorrowerCategorycode
1552 $categorycode = &GetBorrowerCategoryCode( $borrowernumber );
1554 Given the borrowernumber, the function returns the corresponding categorycode
1558 sub GetBorrowerCategorycode {
1559 my ( $borrowernumber ) = @_;
1560 my $dbh = C4::Context->dbh;
1561 my $sth = $dbh->prepare( qq{
1564 WHERE borrowernumber = ?
1566 $sth->execute( $borrowernumber );
1567 return $sth->fetchrow;
1570 =head2 GetBorrowercategoryList
1572 $arrayref_hashref = &GetBorrowercategoryList;
1573 If no category code provided, the function returns all the categories.
1577 sub GetBorrowercategoryList {
1578 my $no_branch_limit = @_ ? shift : 0;
1579 my $branch_limit = $no_branch_limit
1581 : C4::Context->userenv ? C4::Context->userenv->{"branch"} : "";
1582 my $dbh = C4::Context->dbh;
1583 my $query = "SELECT categories.* FROM categories";
1585 LEFT JOIN categories_branches ON categories.categorycode = categories_branches.categorycode
1586 WHERE branchcode = ? OR branchcode IS NULL GROUP BY description
1588 $query .= " ORDER BY description";
1589 my $sth = $dbh->prepare( $query );
1590 $sth->execute( $branch_limit ? $branch_limit : () );
1591 my $data = $sth->fetchall_arrayref( {} );
1594 } # sub getborrowercategory
1598 $dateofbirth,$date = &GetAge($date);
1600 this function return the borrowers age with the value of dateofbirth
1606 my ( $date, $date_ref ) = @_;
1608 if ( not defined $date_ref ) {
1609 $date_ref = sprintf( '%04d-%02d-%02d', Today() );
1612 my ( $year1, $month1, $day1 ) = split /-/, $date;
1613 my ( $year2, $month2, $day2 ) = split /-/, $date_ref;
1615 my $age = $year2 - $year1;
1616 if ( $month1 . $day1 > $month2 . $day2 ) {
1625 $borrower = C4::Members::SetAge($borrower, $datetimeduration);
1626 $borrower = C4::Members::SetAge($borrower, '0015-12-10');
1627 $borrower = C4::Members::SetAge($borrower, $datetimeduration, $datetime_reference);
1629 eval { $borrower = C4::Members::SetAge($borrower, '015-1-10'); };
1630 if ($@) {print $@;} #Catch a bad ISO Date or kill your script!
1632 This function sets the borrower's dateofbirth to match the given age.
1633 Optionally relative to the given $datetime_reference.
1635 @PARAM1 koha.borrowers-object
1636 @PARAM2 DateTime::Duration-object as the desired age
1637 OR a ISO 8601 Date. (To make the API more pleasant)
1638 @PARAM3 DateTime-object as the relative date, defaults to now().
1639 RETURNS The given borrower reference @PARAM1.
1640 DIES If there was an error with the ISO Date handling.
1646 my ( $borrower, $datetimeduration, $datetime_ref ) = @_;
1647 $datetime_ref = DateTime->now() unless $datetime_ref;
1649 if ($datetimeduration && ref $datetimeduration ne 'DateTime::Duration') {
1650 if ($datetimeduration =~ /^(\d{4})-(\d{2})-(\d{2})/) {
1651 $datetimeduration = DateTime::Duration->new(years => $1, months => $2, days => $3);
1654 die "C4::Members::SetAge($borrower, $datetimeduration), datetimeduration not a valid ISO 8601 Date!\n";
1658 my $new_datetime_ref = $datetime_ref->clone();
1659 $new_datetime_ref->subtract_duration( $datetimeduration );
1661 $borrower->{dateofbirth} = $new_datetime_ref->ymd();
1666 =head2 GetSortDetails (OUEST-PROVENCE)
1668 ($lib) = &GetSortDetails($category,$sortvalue);
1670 Returns the authorized value details
1671 C<&$lib>return value of authorized value details
1672 C<&$sortvalue>this is the value of authorized value
1673 C<&$category>this is the value of authorized value category
1677 sub GetSortDetails {
1678 my ( $category, $sortvalue ) = @_;
1679 my $dbh = C4::Context->dbh;
1680 my $query = qq|SELECT lib
1681 FROM authorised_values
1683 AND authorised_value=? |;
1684 my $sth = $dbh->prepare($query);
1685 $sth->execute( $category, $sortvalue );
1686 my $lib = $sth->fetchrow;
1687 return ($lib) if ($lib);
1688 return ($sortvalue) unless ($lib);
1691 =head2 MoveMemberToDeleted
1693 $result = &MoveMemberToDeleted($borrowernumber);
1695 Copy the record from borrowers to deletedborrowers table.
1696 The routine returns 1 for success, undef for failure.
1700 sub MoveMemberToDeleted {
1701 my ($member) = shift or return;
1703 my $schema = Koha::Database->new()->schema();
1704 my $borrowers_rs = $schema->resultset('Borrower');
1705 $borrowers_rs->result_class('DBIx::Class::ResultClass::HashRefInflator');
1706 my $borrower = $borrowers_rs->find($member);
1707 return unless $borrower;
1709 my $deleted = $schema->resultset('Deletedborrower')->create($borrower);
1711 return $deleted ? 1 : undef;
1716 DelMember($borrowernumber);
1718 This function remove directly a borrower whitout writing it on deleteborrower.
1719 + Deletes reserves for the borrower
1724 my $dbh = C4::Context->dbh;
1725 my $borrowernumber = shift;
1726 #warn "in delmember with $borrowernumber";
1727 return unless $borrowernumber; # borrowernumber is mandatory.
1729 my $query = qq|DELETE
1731 WHERE borrowernumber=?|;
1732 my $sth = $dbh->prepare($query);
1733 $sth->execute($borrowernumber);
1737 WHERE borrowernumber = ?
1739 $sth = $dbh->prepare($query);
1740 $sth->execute($borrowernumber);
1741 logaction("MEMBERS", "DELETE", $borrowernumber, "") if C4::Context->preference("BorrowersLog");
1745 =head2 HandleDelBorrower
1747 HandleDelBorrower($borrower);
1749 When a member is deleted (DelMember in Members.pm), you should call me first.
1750 This routine deletes/moves lists and entries for the deleted member/borrower.
1751 Lists owned by the borrower are deleted, but entries from the borrower to
1752 other lists are kept.
1756 sub HandleDelBorrower {
1759 my $dbh = C4::Context->dbh;
1761 #Delete all lists and all shares of this borrower
1762 #Consistent with the approach Koha uses on deleting individual lists
1763 #Note that entries in virtualshelfcontents added by this borrower to
1764 #lists of others will be handled by a table constraint: the borrower
1765 #is set to NULL in those entries.
1766 $query="DELETE FROM virtualshelves WHERE owner=?";
1767 $dbh->do($query,undef,($borrower));
1770 #We could handle the above deletes via a constraint too.
1771 #But a new BZ report 11889 has been opened to discuss another approach.
1772 #Instead of deleting we could also disown lists (based on a pref).
1773 #In that way we could save shared and public lists.
1774 #The current table constraints support that idea now.
1775 #This pref should then govern the results of other routines/methods such as
1776 #Koha::Virtualshelf->new->delete too.
1779 =head2 ExtendMemberSubscriptionTo (OUEST-PROVENCE)
1781 $date = ExtendMemberSubscriptionTo($borrowerid, $date);
1783 Extending the subscription to a given date or to the expiry date calculated on ISO date.
1788 sub ExtendMemberSubscriptionTo {
1789 my ( $borrowerid,$date) = @_;
1790 my $dbh = C4::Context->dbh;
1791 my $borrower = GetMember('borrowernumber'=>$borrowerid);
1793 $date = (C4::Context->preference('BorrowerRenewalPeriodBase') eq 'dateexpiry') ?
1794 eval { output_pref( { dt => dt_from_string( $borrower->{'dateexpiry'} ), dateonly => 1, dateformat => 'iso' } ); }
1796 output_pref( { dt => dt_from_string, dateonly => 1, dateformat => 'iso' } );
1797 $date = GetExpiryDate( $borrower->{'categorycode'}, $date );
1799 my $sth = $dbh->do(<<EOF);
1801 SET dateexpiry='$date'
1802 WHERE borrowernumber='$borrowerid'
1805 AddEnrolmentFeeIfNeeded( $borrower->{categorycode}, $borrower->{borrowernumber} );
1807 logaction("MEMBERS", "RENEW", $borrower->{'borrowernumber'}, "Membership renewed")if C4::Context->preference("BorrowersLog");
1808 return $date if ($sth);
1812 =head2 GetTitles (OUEST-PROVENCE)
1814 ($borrowertitle)= &GetTitles();
1816 Looks up the different title . Returns array with all borrowers title
1821 my @borrowerTitle = split (/,|\|/,C4::Context->preference('BorrowersTitles'));
1822 unshift( @borrowerTitle, "" );
1823 my $count=@borrowerTitle;
1828 return ( \@borrowerTitle);
1832 =head2 GetPatronImage
1834 my ($imagedata, $dberror) = GetPatronImage($borrowernumber);
1836 Returns the mimetype and binary image data of the image for the patron with the supplied borrowernumber.
1840 sub GetPatronImage {
1841 my ($borrowernumber) = @_;
1842 warn "Borrowernumber passed to GetPatronImage is $borrowernumber" if $debug;
1843 my $dbh = C4::Context->dbh;
1844 my $query = 'SELECT mimetype, imagefile FROM patronimage WHERE borrowernumber = ?';
1845 my $sth = $dbh->prepare($query);
1846 $sth->execute($borrowernumber);
1847 my $imagedata = $sth->fetchrow_hashref;
1848 warn "Database error!" if $sth->errstr;
1849 return $imagedata, $sth->errstr;
1852 =head2 RmPatronImage
1854 my ($dberror) = RmPatronImage($borrowernumber);
1856 Removes the image for the patron with the supplied borrowernumber.
1861 my ($borrowernumber) = @_;
1862 warn "Borrowernumber passed to GetPatronImage is $borrowernumber" if $debug;
1863 my $dbh = C4::Context->dbh;
1864 my $query = "DELETE FROM patronimage WHERE borrowernumber = ?;";
1865 my $sth = $dbh->prepare($query);
1866 $sth->execute($borrowernumber);
1867 my $dberror = $sth->errstr;
1868 warn "Database error!" if $sth->errstr;
1872 =head2 GetHideLostItemsPreference
1874 $hidelostitemspref = &GetHideLostItemsPreference($borrowernumber);
1876 Returns the HideLostItems preference for the patron category of the supplied borrowernumber
1877 C<&$hidelostitemspref>return value of function, 0 or 1
1881 sub GetHideLostItemsPreference {
1882 my ($borrowernumber) = @_;
1883 my $dbh = C4::Context->dbh;
1884 my $query = "SELECT hidelostitems FROM borrowers,categories WHERE borrowers.categorycode = categories.categorycode AND borrowernumber = ?";
1885 my $sth = $dbh->prepare($query);
1886 $sth->execute($borrowernumber);
1887 my $hidelostitems = $sth->fetchrow;
1888 return $hidelostitems;
1891 =head2 GetBorrowersToExpunge
1893 $borrowers = &GetBorrowersToExpunge(
1894 not_borrowered_since => $not_borrowered_since,
1895 expired_before => $expired_before,
1896 category_code => $category_code,
1897 branchcode => $branchcode
1900 This function get all borrowers based on the given criteria.
1904 sub GetBorrowersToExpunge {
1907 my $filterdate = $params->{'not_borrowered_since'};
1908 my $filterexpiry = $params->{'expired_before'};
1909 my $filtercategory = $params->{'category_code'};
1910 my $filterbranch = $params->{'branchcode'} ||
1911 ((C4::Context->preference('IndependentBranches')
1912 && C4::Context->userenv
1913 && !C4::Context->IsSuperLibrarian()
1914 && C4::Context->userenv->{branch})
1915 ? C4::Context->userenv->{branch}
1918 my $dbh = C4::Context->dbh;
1920 SELECT borrowers.borrowernumber,
1921 MAX(old_issues.timestamp) AS latestissue,
1922 MAX(issues.timestamp) AS currentissue
1924 JOIN categories USING (categorycode)
1928 WHERE guarantorid IS NOT NULL
1929 AND guarantorid <> 0
1930 ) as tmp ON borrowers.borrowernumber=tmp.guarantorid
1931 LEFT JOIN old_issues USING (borrowernumber)
1932 LEFT JOIN issues USING (borrowernumber)
1933 WHERE category_type <> 'S'
1934 AND tmp.guarantorid IS NULL
1938 if ( $filterbranch && $filterbranch ne "" ) {
1939 $query.= " AND borrowers.branchcode = ? ";
1940 push( @query_params, $filterbranch );
1942 if ( $filterexpiry ) {
1943 $query .= " AND dateexpiry < ? ";
1944 push( @query_params, $filterexpiry );
1946 if ( $filtercategory ) {
1947 $query .= " AND categorycode = ? ";
1948 push( @query_params, $filtercategory );
1950 $query.=" GROUP BY borrowers.borrowernumber HAVING currentissue IS NULL ";
1951 if ( $filterdate ) {
1952 $query.=" AND ( latestissue < ? OR latestissue IS NULL ) ";
1953 push @query_params,$filterdate;
1955 warn $query if $debug;
1957 my $sth = $dbh->prepare($query);
1958 if (scalar(@query_params)>0){
1959 $sth->execute(@query_params);
1966 while ( my $data = $sth->fetchrow_hashref ) {
1967 push @results, $data;
1972 =head2 GetBorrowersWhoHaveNeverBorrowed
1974 $results = &GetBorrowersWhoHaveNeverBorrowed
1976 This function get all borrowers who have never borrowed.
1978 I<$result> is a ref to an array which all elements are a hasref.
1982 sub GetBorrowersWhoHaveNeverBorrowed {
1983 my $filterbranch = shift ||
1984 ((C4::Context->preference('IndependentBranches')
1985 && C4::Context->userenv
1986 && !C4::Context->IsSuperLibrarian()
1987 && C4::Context->userenv->{branch})
1988 ? C4::Context->userenv->{branch}
1990 my $dbh = C4::Context->dbh;
1992 SELECT borrowers.borrowernumber,max(timestamp) as latestissue
1994 LEFT JOIN issues ON borrowers.borrowernumber = issues.borrowernumber
1995 WHERE issues.borrowernumber IS NULL
1998 if ($filterbranch && $filterbranch ne ""){
1999 $query.=" AND borrowers.branchcode= ?";
2000 push @query_params,$filterbranch;
2002 warn $query if $debug;
2004 my $sth = $dbh->prepare($query);
2005 if (scalar(@query_params)>0){
2006 $sth->execute(@query_params);
2013 while ( my $data = $sth->fetchrow_hashref ) {
2014 push @results, $data;
2019 =head2 GetBorrowersWithIssuesHistoryOlderThan
2021 $results = &GetBorrowersWithIssuesHistoryOlderThan($date)
2023 this function get all borrowers who has an issue history older than I<$date> given on input arg.
2025 I<$result> is a ref to an array which all elements are a hashref.
2026 This hashref is containt the number of time this borrowers has borrowed before I<$date> and the borrowernumber.
2030 sub GetBorrowersWithIssuesHistoryOlderThan {
2031 my $dbh = C4::Context->dbh;
2032 my $date = shift ||POSIX::strftime("%Y-%m-%d",localtime());
2033 my $filterbranch = shift ||
2034 ((C4::Context->preference('IndependentBranches')
2035 && C4::Context->userenv
2036 && !C4::Context->IsSuperLibrarian()
2037 && C4::Context->userenv->{branch})
2038 ? C4::Context->userenv->{branch}
2041 SELECT count(borrowernumber) as n,borrowernumber
2043 WHERE returndate < ?
2044 AND borrowernumber IS NOT NULL
2047 push @query_params, $date;
2049 $query.=" AND branchcode = ?";
2050 push @query_params, $filterbranch;
2052 $query.=" GROUP BY borrowernumber ";
2053 warn $query if $debug;
2054 my $sth = $dbh->prepare($query);
2055 $sth->execute(@query_params);
2058 while ( my $data = $sth->fetchrow_hashref ) {
2059 push @results, $data;
2064 =head2 GetBorrowersNamesAndLatestIssue
2066 $results = &GetBorrowersNamesAndLatestIssueList(@borrowernumbers)
2068 this function get borrowers Names and surnames and Issue information.
2070 I<@borrowernumbers> is an array which all elements are borrowernumbers.
2071 This hashref is containt the number of time this borrowers has borrowed before I<$date> and the borrowernumber.
2075 sub GetBorrowersNamesAndLatestIssue {
2076 my $dbh = C4::Context->dbh;
2077 my @borrowernumbers=@_;
2079 SELECT surname,lastname, phone, email,max(timestamp)
2081 LEFT JOIN issues ON borrowers.borrowernumber=issues.borrowernumber
2082 GROUP BY borrowernumber
2084 my $sth = $dbh->prepare($query);
2086 my $results = $sth->fetchall_arrayref({});
2092 my $success = ModPrivacy( $borrowernumber, $privacy );
2094 Update the privacy of a patron.
2097 true on success, false on failure
2102 my $borrowernumber = shift;
2103 my $privacy = shift;
2104 return unless defined $borrowernumber;
2105 return unless $borrowernumber =~ /^\d+$/;
2107 return ModMember( borrowernumber => $borrowernumber,
2108 privacy => $privacy );
2113 IssueSlip($branchcode, $borrowernumber, $quickslip)
2115 Returns letter hash ( see C4::Letters::GetPreparedLetter )
2117 $quickslip is boolean, to indicate whether we want a quick slip
2119 IssueSlip populates ISSUESLIP and ISSUEQSLIP, and will make the following expansions:
2155 NOTE: Not all table fields are available, pleasee see GetPendingIssues for a list of available fields.
2160 my ($branch, $borrowernumber, $quickslip) = @_;
2162 # FIXME Check callers before removing this statement
2163 #return unless $borrowernumber;
2165 my @issues = @{ GetPendingIssues($borrowernumber) };
2167 for my $issue (@issues) {
2168 $issue->{date_due} = $issue->{date_due_sql};
2170 my $today = output_pref({ dt => dt_from_string, dateformat => 'iso', dateonly => 1 });
2171 if ( substr( $issue->{issuedate}, 0, 10 ) eq $today
2172 or substr( $issue->{lastreneweddate}, 0, 10 ) eq $today ) {
2178 # Sort on timestamp then on issuedate (useful for tests and could be if modified in a batch
2180 my $s = $b->{timestamp} <=> $a->{timestamp};
2182 $b->{issuedate} <=> $a->{issuedate} : $s;
2185 my ($letter_code, %repeat);
2187 $letter_code = 'ISSUEQSLIP';
2189 'checkedout' => [ map {
2192 'biblioitems' => $_,
2194 }, grep { $_->{'now'} } @issues ],
2198 $letter_code = 'ISSUESLIP';
2200 'checkedout' => [ map {
2203 'biblioitems' => $_,
2205 }, grep { !$_->{'overdue'} } @issues ],
2207 'overdue' => [ map {
2210 'biblioitems' => $_,
2212 }, grep { $_->{'overdue'} } @issues ],
2215 $_->{'timestamp'} = $_->{'newdate'};
2217 } @{ GetNewsToDisplay("slip",$branch) } ],
2221 return C4::Letters::GetPreparedLetter (
2222 module => 'circulation',
2223 letter_code => $letter_code,
2224 branchcode => $branch,
2226 'branches' => $branch,
2227 'borrowers' => $borrowernumber,
2233 =head2 GetBorrowersWithEmail
2235 ([$borrnum,$userid], ...) = GetBorrowersWithEmail('me@example.com');
2237 This gets a list of users and their basic details from their email address.
2238 As it's possible for multiple user to have the same email address, it provides
2239 you with all of them. If there is no userid for the user, there will be an
2240 C<undef> there. An empty list will be returned if there are no matches.
2244 sub GetBorrowersWithEmail {
2247 my $dbh = C4::Context->dbh;
2249 my $query = "SELECT borrowernumber, userid FROM borrowers WHERE email=?";
2250 my $sth=$dbh->prepare($query);
2251 $sth->execute($email);
2253 while (my $ref = $sth->fetch) {
2256 die "Failure searching for borrowers by email address: $sth->errstr" if $sth->err;
2260 =head2 AddMember_Opac
2264 sub AddMember_Opac {
2265 my ( %borrower ) = @_;
2267 $borrower{'categorycode'} //= C4::Context->preference('PatronSelfRegistrationDefaultCategory');
2268 if (not defined $borrower{'password'}){
2269 my $sr = new String::Random;
2270 $sr->{'A'} = [ 'A'..'Z', 'a'..'z' ];
2271 my $password = $sr->randpattern("AAAAAAAAAA");
2272 $borrower{'password'} = $password;
2275 $borrower{'cardnumber'} = fixup_cardnumber( $borrower{'cardnumber'} );
2277 my $borrowernumber = AddMember(%borrower);
2279 return ( $borrowernumber, $borrower{'password'} );
2282 =head2 AddEnrolmentFeeIfNeeded
2284 AddEnrolmentFeeIfNeeded( $borrower->{categorycode}, $borrower->{borrowernumber} );
2286 Add enrolment fee for a patron if needed.
2290 sub AddEnrolmentFeeIfNeeded {
2291 my ( $categorycode, $borrowernumber ) = @_;
2292 # check for enrollment fee & add it if needed
2293 my $dbh = C4::Context->dbh;
2294 my $sth = $dbh->prepare(q{
2297 WHERE categorycode=?
2299 $sth->execute( $categorycode );
2301 warn sprintf('Database returned the following error: %s', $sth->errstr);
2304 my ($enrolmentfee) = $sth->fetchrow;
2305 if ($enrolmentfee && $enrolmentfee > 0) {
2306 # insert fee in patron debts
2307 C4::Accounts::manualinvoice( $borrowernumber, '', '', 'A', $enrolmentfee );
2316 my ( $borrowernumber ) = @_;
2318 my $sql = "SELECT COUNT(*) FROM issues WHERE date_due < NOW() AND borrowernumber = ?";
2319 my $sth = C4::Context->dbh->prepare( $sql );
2320 $sth->execute( $borrowernumber );
2321 my ( $count ) = $sth->fetchrow_array();
2326 =head2 DeleteExpiredOpacRegistrations
2328 Delete accounts that haven't been upgraded from the 'temporary' category
2329 Returns the number of removed patrons
2333 sub DeleteExpiredOpacRegistrations {
2335 my $delay = C4::Context->preference('PatronSelfRegistrationExpireTemporaryAccountsDelay');
2336 my $category_code = C4::Context->preference('PatronSelfRegistrationDefaultCategory');
2338 return 0 if not $category_code or not defined $delay or $delay eq q||;
2341 SELECT borrowernumber
2343 WHERE categorycode = ? AND DATEDIFF( NOW(), dateenrolled ) > ? |;
2345 my $dbh = C4::Context->dbh;
2346 my $sth = $dbh->prepare($query);
2347 $sth->execute( $category_code, $delay );
2349 while ( my ($borrowernumber) = $sth->fetchrow_array() ) {
2350 DelMember($borrowernumber);
2356 =head2 DeleteUnverifiedOpacRegistrations
2358 Delete all unverified self registrations in borrower_modifications,
2359 older than the specified number of days.
2363 sub DeleteUnverifiedOpacRegistrations {
2365 my $dbh = C4::Context->dbh;
2367 DELETE FROM borrower_modifications
2368 WHERE borrowernumber = 0 AND DATEDIFF( NOW(), timestamp ) > ?|;
2369 my $cnt=$dbh->do($sql, undef, ($days) );
2370 return $cnt eq '0E0'? 0: $cnt;
2373 sub GetOverduesForPatron {
2374 my ( $borrowernumber ) = @_;
2378 FROM issues, items, biblio, biblioitems
2379 WHERE items.itemnumber=issues.itemnumber
2380 AND biblio.biblionumber = items.biblionumber
2381 AND biblio.biblionumber = biblioitems.biblionumber
2382 AND issues.borrowernumber = ?
2383 AND date_due < NOW()
2386 my $sth = C4::Context->dbh->prepare( $sql );
2387 $sth->execute( $borrowernumber );
2389 return $sth->fetchall_arrayref({});
2392 END { } # module clean-up code here (global destructor)