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
77 &GetHideLostItemsPreference
80 &GetMemberAccountRecords
81 &GetBorNotifyAcctRecord
85 GetBorrowerCategorycode
86 &GetBorrowercategoryList
88 &GetBorrowersToExpunge
89 &GetBorrowersWhoHaveNeverBorrowed
90 &GetBorrowersWithIssuesHistoryOlderThan
93 &GetUpcomingMembershipExpires
118 &ExtendMemberSubscriptionTo
134 C4::Members - Perl Module containing convenience functions for member handling
142 This module contains routines for adding, modifying and deleting members/patrons/borrowers
146 =head2 GetMemberDetails
148 ($borrower) = &GetMemberDetails($borrowernumber, $cardnumber);
150 Looks up a patron and returns information about him or her. If
151 C<$borrowernumber> is true (nonzero), C<&GetMemberDetails> looks
152 up the borrower by number; otherwise, it looks up the borrower by card
155 C<$borrower> is a reference-to-hash whose keys are the fields of the
156 borrowers table in the Koha database. In addition,
157 C<$borrower-E<gt>{flags}> is a hash giving more detailed information
158 about the patron. Its keys act as flags :
160 if $borrower->{flags}->{LOST} {
161 # Patron's card was reported lost
164 If the state of a flag means that the patron should not be
165 allowed to borrow any more books, then it will have a C<noissues> key
168 See patronflags for more details.
170 C<$borrower-E<gt>{authflags}> is a hash giving more detailed information
171 about the top-level permissions flags set for the borrower. For example,
172 if a user has the "editcatalogue" permission,
173 C<$borrower-E<gt>{authflags}-E<gt>{editcatalogue}> will exist and have
178 sub GetMemberDetails {
179 my ( $borrowernumber, $cardnumber ) = @_;
180 my $dbh = C4::Context->dbh;
183 if ($borrowernumber) {
184 $sth = $dbh->prepare("
187 categories.description,
188 categories.BlockExpiredPatronOpacActions,
192 LEFT JOIN categories ON borrowers.categorycode=categories.categorycode
193 WHERE borrowernumber = ?
195 $sth->execute($borrowernumber);
197 elsif ($cardnumber) {
198 $sth = $dbh->prepare("
201 categories.description,
202 categories.BlockExpiredPatronOpacActions,
206 LEFT JOIN categories ON borrowers.categorycode = categories.categorycode
209 $sth->execute($cardnumber);
214 my $borrower = $sth->fetchrow_hashref;
215 return unless $borrower;
216 my ($amount) = GetMemberAccountRecords($borrower->{borrowernumber});
217 $borrower->{'amountoutstanding'} = $amount;
218 # FIXME - patronflags calls GetMemberAccountRecords... just have patronflags return $amount
219 my $flags = patronflags( $borrower);
222 $sth = $dbh->prepare("select bit,flag from userflags");
224 while ( my ( $bit, $flag ) = $sth->fetchrow ) {
225 if ( $borrower->{'flags'} && $borrower->{'flags'} & 2**$bit ) {
226 $accessflagshash->{$flag} = 1;
229 $borrower->{'flags'} = $flags;
230 $borrower->{'authflags'} = $accessflagshash;
232 # Handle setting the true behavior for BlockExpiredPatronOpacActions
233 $borrower->{'BlockExpiredPatronOpacActions'} =
234 C4::Context->preference('BlockExpiredPatronOpacActions')
235 if ( $borrower->{'BlockExpiredPatronOpacActions'} == -1 );
237 $borrower->{'is_expired'} = 0;
238 $borrower->{'is_expired'} = 1 if
239 defined($borrower->{dateexpiry}) &&
240 $borrower->{'dateexpiry'} ne '0000-00-00' &&
241 Date_to_Days( Today() ) >
242 Date_to_Days( split /-/, $borrower->{'dateexpiry'} );
244 return ($borrower); #, $flags, $accessflagshash);
249 $flags = &patronflags($patron);
251 This function is not exported.
253 The following will be set where applicable:
254 $flags->{CHARGES}->{amount} Amount of debt
255 $flags->{CHARGES}->{noissues} Set if debt amount >$5.00 (or syspref noissuescharge)
256 $flags->{CHARGES}->{message} Message -- deprecated
258 $flags->{CREDITS}->{amount} Amount of credit
259 $flags->{CREDITS}->{message} Message -- deprecated
261 $flags->{ GNA } Patron has no valid address
262 $flags->{ GNA }->{noissues} Set for each GNA
263 $flags->{ GNA }->{message} "Borrower has no valid address" -- deprecated
265 $flags->{ LOST } Patron's card reported lost
266 $flags->{ LOST }->{noissues} Set for each LOST
267 $flags->{ LOST }->{message} Message -- deprecated
269 $flags->{DBARRED} Set if patron debarred, no access
270 $flags->{DBARRED}->{noissues} Set for each DBARRED
271 $flags->{DBARRED}->{message} Message -- deprecated
274 $flags->{ NOTES }->{message} The note itself. NOT deprecated
276 $flags->{ ODUES } Set if patron has overdue books.
277 $flags->{ ODUES }->{message} "Yes" -- deprecated
278 $flags->{ ODUES }->{itemlist} ref-to-array: list of overdue books
279 $flags->{ ODUES }->{itemlisttext} Text list of overdue items -- deprecated
281 $flags->{WAITING} Set if any of patron's reserves are available
282 $flags->{WAITING}->{message} Message -- deprecated
283 $flags->{WAITING}->{itemlist} ref-to-array: list of available items
287 =item C<$flags-E<gt>{ODUES}-E<gt>{itemlist}> is a reference-to-array listing the
288 overdue items. Its elements are references-to-hash, each describing an
289 overdue item. The keys are selected fields from the issues, biblio,
290 biblioitems, and items tables of the Koha database.
292 =item C<$flags-E<gt>{ODUES}-E<gt>{itemlisttext}> is a string giving a text listing of
293 the overdue items, one per line. Deprecated.
295 =item C<$flags-E<gt>{WAITING}-E<gt>{itemlist}> is a reference-to-array listing the
296 available items. Each element is a reference-to-hash whose keys are
297 fields from the reserves table of the Koha database.
301 All the "message" fields that include language generated in this function are deprecated,
302 because such strings belong properly in the display layer.
304 The "message" field that comes from the DB is OK.
308 # TODO: use {anonymous => hashes} instead of a dozen %flaginfo
309 # FIXME rename this function.
312 my ( $patroninformation) = @_;
313 my $dbh=C4::Context->dbh;
314 my ($balance, $owing) = GetMemberAccountBalance( $patroninformation->{'borrowernumber'});
317 my $noissuescharge = C4::Context->preference("noissuescharge") || 5;
318 $flaginfo{'message'} = sprintf 'Patron owes %.02f', $owing;
319 $flaginfo{'amount'} = sprintf "%.02f", $owing;
320 if ( $owing > $noissuescharge && !C4::Context->preference("AllowFineOverride") ) {
321 $flaginfo{'noissues'} = 1;
323 $flags{'CHARGES'} = \%flaginfo;
325 elsif ( $balance < 0 ) {
327 $flaginfo{'message'} = sprintf 'Patron has credit of %.02f', -$balance;
328 $flaginfo{'amount'} = sprintf "%.02f", $balance;
329 $flags{'CREDITS'} = \%flaginfo;
331 if ( $patroninformation->{'gonenoaddress'}
332 && $patroninformation->{'gonenoaddress'} == 1 )
335 $flaginfo{'message'} = 'Borrower has no valid address.';
336 $flaginfo{'noissues'} = 1;
337 $flags{'GNA'} = \%flaginfo;
339 if ( $patroninformation->{'lost'} && $patroninformation->{'lost'} == 1 ) {
341 $flaginfo{'message'} = 'Borrower\'s card reported lost.';
342 $flaginfo{'noissues'} = 1;
343 $flags{'LOST'} = \%flaginfo;
345 if ( $patroninformation->{'debarred'} && check_date( split( /-/, $patroninformation->{'debarred'} ) ) ) {
346 if ( Date_to_Days(Date::Calc::Today) < Date_to_Days( split( /-/, $patroninformation->{'debarred'} ) ) ) {
348 $flaginfo{'debarredcomment'} = $patroninformation->{'debarredcomment'};
349 $flaginfo{'message'} = $patroninformation->{'debarredcomment'};
350 $flaginfo{'noissues'} = 1;
351 $flaginfo{'dateend'} = $patroninformation->{'debarred'};
352 $flags{'DBARRED'} = \%flaginfo;
355 if ( $patroninformation->{'borrowernotes'}
356 && $patroninformation->{'borrowernotes'} )
359 $flaginfo{'message'} = $patroninformation->{'borrowernotes'};
360 $flags{'NOTES'} = \%flaginfo;
362 my ( $odues, $itemsoverdue ) = C4::Overdues::checkoverdues($patroninformation->{'borrowernumber'});
363 if ( $odues && $odues > 0 ) {
365 $flaginfo{'message'} = "Yes";
366 $flaginfo{'itemlist'} = $itemsoverdue;
367 foreach ( sort { $a->{'date_due'} cmp $b->{'date_due'} }
370 $flaginfo{'itemlisttext'} .=
371 "$_->{'date_due'} $_->{'barcode'} $_->{'title'} \n"; # newline is display layer
373 $flags{'ODUES'} = \%flaginfo;
375 my @itemswaiting = C4::Reserves::GetReservesFromBorrowernumber( $patroninformation->{'borrowernumber'},'W' );
376 my $nowaiting = scalar @itemswaiting;
377 if ( $nowaiting > 0 ) {
379 $flaginfo{'message'} = "Reserved items available";
380 $flaginfo{'itemlist'} = \@itemswaiting;
381 $flags{'WAITING'} = \%flaginfo;
389 $borrower = &GetMember(%information);
391 Retrieve the first patron record meeting on criteria listed in the
392 C<%information> hash, which should contain one or more
393 pairs of borrowers column names and values, e.g.,
395 $borrower = GetMember(borrowernumber => id);
397 C<&GetBorrower> returns a reference-to-hash whose keys are the fields of
398 the C<borrowers> table in the Koha database.
400 FIXME: GetMember() is used throughout the code as a lookup
401 on a unique key such as the borrowernumber, but this meaning is not
402 enforced in the routine itself.
408 my ( %information ) = @_;
409 if (exists $information{borrowernumber} && !defined $information{borrowernumber}) {
410 #passing mysql's kohaadmin?? Makes no sense as a query
413 my $dbh = C4::Context->dbh;
415 q{SELECT borrowers.*, categories.category_type, categories.description
417 LEFT JOIN categories on borrowers.categorycode=categories.categorycode WHERE };
420 for (keys %information ) {
428 if (defined $information{$_}) {
430 push @values, $information{$_};
433 $select .= "$_ IS NULL";
436 $debug && warn $select, " ",values %information;
437 my $sth = $dbh->prepare("$select");
438 $sth->execute(@values);
439 my $data = $sth->fetchall_arrayref({});
440 #FIXME interface to this routine now allows generation of a result set
441 #so whole array should be returned but bowhere in the current code expects this
449 =head2 GetMemberRelatives
451 @borrowernumbers = GetMemberRelatives($borrowernumber);
453 C<GetMemberRelatives> returns a borrowersnumber's list of guarantor/guarantees of the member given in parameter
457 sub GetMemberRelatives {
458 my $borrowernumber = shift;
459 my $dbh = C4::Context->dbh;
463 my $query = "SELECT guarantorid FROM borrowers WHERE borrowernumber=?";
464 my $sth = $dbh->prepare($query);
465 $sth->execute($borrowernumber);
466 my $data = $sth->fetchrow_arrayref();
467 push @glist, $data->[0] if $data->[0];
468 my $guarantor = $data->[0] ? $data->[0] : undef;
471 $query = "SELECT borrowernumber FROM borrowers WHERE guarantorid=?";
472 $sth = $dbh->prepare($query);
473 $sth->execute($borrowernumber);
474 while ($data = $sth->fetchrow_arrayref()) {
475 push @glist, $data->[0];
478 # Getting sibling guarantees
480 $query = "SELECT borrowernumber FROM borrowers WHERE guarantorid=?";
481 $sth = $dbh->prepare($query);
482 $sth->execute($guarantor);
483 while ($data = $sth->fetchrow_arrayref()) {
484 push @glist, $data->[0] if ($data->[0] != $borrowernumber);
491 =head2 IsMemberBlocked
493 my ($block_status, $count) = IsMemberBlocked( $borrowernumber );
495 Returns whether a patron is restricted or has overdue items that may result
496 in a block of circulation privileges.
498 C<$block_status> can have the following values:
500 1 if the patron is currently restricted, in which case
501 C<$count> is the expiration date (9999-12-31 for indefinite)
503 -1 if the patron has overdue items, in which case C<$count> is the number of them
505 0 if the patron has no overdue items or outstanding fine days, in which case C<$count> is 0
507 Existing active restrictions are checked before current overdue items.
511 sub IsMemberBlocked {
512 my $borrowernumber = shift;
513 my $dbh = C4::Context->dbh;
515 my $blockeddate = Koha::Patron::Debarments::IsDebarred($borrowernumber);
517 return ( 1, $blockeddate ) if $blockeddate;
519 # if he have late issues
520 my $sth = $dbh->prepare(
521 "SELECT COUNT(*) as latedocs
523 WHERE borrowernumber = ?
524 AND date_due < now()"
526 $sth->execute($borrowernumber);
527 my $latedocs = $sth->fetchrow_hashref->{'latedocs'};
529 return ( -1, $latedocs ) if $latedocs > 0;
534 =head2 GetMemberIssuesAndFines
536 ($overdue_count, $issue_count, $total_fines) = &GetMemberIssuesAndFines($borrowernumber);
538 Returns aggregate data about items borrowed by the patron with the
539 given borrowernumber.
541 C<&GetMemberIssuesAndFines> returns a three-element array. C<$overdue_count> is the
542 number of overdue items the patron currently has borrowed. C<$issue_count> is the
543 number of books the patron currently has borrowed. C<$total_fines> is
544 the total fine currently due by the borrower.
549 sub GetMemberIssuesAndFines {
550 my ( $borrowernumber ) = @_;
551 my $dbh = C4::Context->dbh;
552 my $query = "SELECT COUNT(*) FROM issues WHERE borrowernumber = ?";
554 $debug and warn $query."\n";
555 my $sth = $dbh->prepare($query);
556 $sth->execute($borrowernumber);
557 my $issue_count = $sth->fetchrow_arrayref->[0];
559 $sth = $dbh->prepare(
560 "SELECT COUNT(*) FROM issues
561 WHERE borrowernumber = ?
562 AND date_due < now()"
564 $sth->execute($borrowernumber);
565 my $overdue_count = $sth->fetchrow_arrayref->[0];
567 $sth = $dbh->prepare("SELECT SUM(amountoutstanding) FROM accountlines WHERE borrowernumber = ?");
568 $sth->execute($borrowernumber);
569 my $total_fines = $sth->fetchrow_arrayref->[0];
571 return ($overdue_count, $issue_count, $total_fines);
577 my @columns = C4::Member::columns();
579 Returns an array of borrowers' table columns on success,
580 and an empty array on failure.
586 # Pure ANSI SQL goodness.
587 my $sql = 'SELECT * FROM borrowers WHERE 1=0;';
589 # Get the database handle.
590 my $dbh = C4::Context->dbh;
592 # Run the SQL statement to load STH's readonly properties.
593 my $sth = $dbh->prepare($sql);
594 my $rv = $sth->execute();
596 # This only fails if the table doesn't exist.
597 # This will always be called AFTER an install or upgrade,
598 # so borrowers will exist!
600 if ($sth->{NUM_OF_FIELDS}>0) {
601 @data = @{$sth->{NAME}};
612 my $success = ModMember(borrowernumber => $borrowernumber,
613 [ field => value ]... );
615 Modify borrower's data. All date fields should ALREADY be in ISO format.
618 true on success, or false on failure
624 # test to know if you must update or not the borrower password
625 if (exists $data{password}) {
626 if ($data{password} eq '****' or $data{password} eq '') {
627 delete $data{password};
629 if ( C4::Context->preference('NorwegianPatronDBEnable') && C4::Context->preference('NorwegianPatronDBEnable') == 1 ) {
630 # Update the hashed PIN in borrower_sync.hashed_pin, before Koha hashes it
631 Koha::NorwegianPatronDB::NLUpdateHashedPIN( $data{'borrowernumber'}, $data{password} );
633 $data{password} = hash_password($data{password});
637 my $old_categorycode = GetBorrowerCategorycode( $data{borrowernumber} );
639 # get only the columns of a borrower
640 my $schema = Koha::Database->new()->schema;
641 my @columns = $schema->source('Borrower')->columns;
642 my $new_borrower = { map { join(' ', @columns) =~ /$_/ ? ( $_ => $data{$_} ) : () } keys(%data) };
643 delete $new_borrower->{flags};
645 $new_borrower->{dateofbirth} ||= undef if exists $new_borrower->{dateofbirth};
646 $new_borrower->{dateenrolled} ||= undef if exists $new_borrower->{dateenrolled};
647 $new_borrower->{dateexpiry} ||= undef if exists $new_borrower->{dateexpiry};
648 $new_borrower->{debarred} ||= undef if exists $new_borrower->{debarred};
649 $new_borrower->{sms_provider_id} ||= undef if exists $new_borrower->{sms_provider_id};
651 my $rs = $schema->resultset('Borrower')->search({
652 borrowernumber => $new_borrower->{borrowernumber},
655 my $execute_success = $rs->update($new_borrower);
656 if ($execute_success ne '0E0') { # only proceed if the update was a success
658 # ok if its an adult (type) it may have borrowers that depend on it as a guarantor
659 # so when we update information for an adult we should check for guarantees and update the relevant part
660 # of their records, ie addresses and phone numbers
661 my $borrowercategory= GetBorrowercategory( $data{'category_type'} );
662 if ( exists $borrowercategory->{'category_type'} && $borrowercategory->{'category_type'} eq ('A' || 'S') ) {
663 # is adult check guarantees;
664 UpdateGuarantees(%data);
667 # If the patron changes to a category with enrollment fee, we add a fee
668 if ( $data{categorycode} and $data{categorycode} ne $old_categorycode ) {
669 if ( C4::Context->preference('FeeOnChangePatronCategory') ) {
670 AddEnrolmentFeeIfNeeded( $data{categorycode}, $data{borrowernumber} );
674 # If NorwegianPatronDBEnable is enabled, we set syncstatus to something that a
675 # cronjob will use for syncing with NL
676 if ( C4::Context->preference('NorwegianPatronDBEnable') && C4::Context->preference('NorwegianPatronDBEnable') == 1 ) {
677 my $borrowersync = Koha::Database->new->schema->resultset('BorrowerSync')->find({
678 'synctype' => 'norwegianpatrondb',
679 'borrowernumber' => $data{'borrowernumber'}
681 # Do not set to "edited" if syncstatus is "new". We need to sync as new before
682 # we can sync as changed. And the "new sync" will pick up all changes since
683 # the patron was created anyway.
684 if ( $borrowersync->syncstatus ne 'new' && $borrowersync->syncstatus ne 'delete' ) {
685 $borrowersync->update( { 'syncstatus' => 'edited' } );
687 # Set the value of 'sync'
688 $borrowersync->update( { 'sync' => $data{'sync'} } );
689 # Try to do the live sync
690 Koha::NorwegianPatronDB::NLSync({ 'borrowernumber' => $data{'borrowernumber'} });
693 logaction("MEMBERS", "MODIFY", $data{'borrowernumber'}, "UPDATE (executed w/ arg: $data{'borrowernumber'})") if C4::Context->preference("BorrowersLog");
695 return $execute_success;
700 $borrowernumber = &AddMember(%borrower);
702 insert new borrower into table
704 (%borrower keys are database columns. Database columns could be
705 different in different versions. Please look into database for correct
708 Returns the borrowernumber upon success
710 Returns as undef upon any db error without further processing
717 my $dbh = C4::Context->dbh;
718 my $schema = Koha::Database->new()->schema;
720 # generate a proper login if none provided
721 $data{'userid'} = Generate_Userid( $data{'borrowernumber'}, $data{'firstname'}, $data{'surname'} )
722 if ( $data{'userid'} eq '' || !Check_Userid( $data{'userid'} ) );
724 # add expiration date if it isn't already there
725 unless ( $data{'dateexpiry'} ) {
726 $data{'dateexpiry'} = GetExpiryDate( $data{'categorycode'}, output_pref( { dt => dt_from_string, dateonly => 1, dateformat => 'iso' } ) );
729 # add enrollment date if it isn't already there
730 unless ( $data{'dateenrolled'} ) {
731 $data{'dateenrolled'} = output_pref( { dt => dt_from_string, dateonly => 1, dateformat => 'iso' } );
734 my $patron_category = $schema->resultset('Category')->find( $data{'categorycode'} );
736 $patron_category->default_privacy() eq 'default' ? 1
737 : $patron_category->default_privacy() eq 'never' ? 2
738 : $patron_category->default_privacy() eq 'forever' ? 0
741 $data{'privacy_guarantor_checkouts'} = 0 unless defined( $data{'privacy_guarantor_checkouts'} );
743 # Make a copy of the plain text password for later use
744 my $plain_text_password = $data{'password'};
746 # create a disabled account if no password provided
747 $data{'password'} = ($data{'password'})? hash_password($data{'password'}) : '!';
749 # we don't want invalid dates in the db (mysql has a bad habit of inserting 0000-00-00
750 $data{'dateofbirth'} = undef if ( not $data{'dateofbirth'} );
751 $data{'debarred'} = undef if ( not $data{'debarred'} );
752 $data{'sms_provider_id'} = undef if ( not $data{'sms_provider_id'} );
754 # get only the columns of Borrower
755 my @columns = $schema->source('Borrower')->columns;
756 my $new_member = { map { join(' ',@columns) =~ /$_/ ? ( $_ => $data{$_} ) : () } keys(%data) } ;
757 delete $new_member->{borrowernumber};
759 my $rs = $schema->resultset('Borrower');
760 $data{borrowernumber} = $rs->create($new_member)->id;
762 # If NorwegianPatronDBEnable is enabled, we set syncstatus to something that a
763 # cronjob will use for syncing with NL
764 if ( exists $data{'borrowernumber'} && C4::Context->preference('NorwegianPatronDBEnable') && C4::Context->preference('NorwegianPatronDBEnable') == 1 ) {
765 Koha::Database->new->schema->resultset('BorrowerSync')->create({
766 'borrowernumber' => $data{'borrowernumber'},
767 'synctype' => 'norwegianpatrondb',
769 'syncstatus' => 'new',
770 'hashed_pin' => Koha::NorwegianPatronDB::NLEncryptPIN( $plain_text_password ),
774 # mysql_insertid is probably bad. not necessarily accurate and mysql-specific at best.
775 logaction("MEMBERS", "CREATE", $data{'borrowernumber'}, "") if C4::Context->preference("BorrowersLog");
777 AddEnrolmentFeeIfNeeded( $data{categorycode}, $data{borrowernumber} );
779 return $data{borrowernumber};
784 my $uniqueness = Check_Userid($userid,$borrowernumber);
786 $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 != '').
788 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.
791 0 for not unique (i.e. this $userid already exists)
792 1 for unique (i.e. this $userid does not exist, or this $userid/$borrowernumber combination already exists)
797 my ( $uid, $borrowernumber ) = @_;
799 return 0 unless ($uid); # userid is a unique column, we should assume NULL is not unique
801 return 0 if ( $uid eq C4::Context->config('user') );
803 my $rs = Koha::Database->new()->schema()->resultset('Borrower');
806 $params->{userid} = $uid;
807 $params->{borrowernumber} = { '!=' => $borrowernumber } if ($borrowernumber);
809 my $count = $rs->count( $params );
811 return $count ? 0 : 1;
814 =head2 Generate_Userid
816 my $newuid = Generate_Userid($borrowernumber, $firstname, $surname);
818 Generate a userid using the $surname and the $firstname (if there is a value in $firstname).
820 $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.
823 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).
827 sub Generate_Userid {
828 my ($borrowernumber, $firstname, $surname) = @_;
831 #The script will "do" the following code and increment the $offset until Check_Userid = 1 (i.e. until $newuid comes back as unique)
833 $firstname =~ s/[[:digit:][:space:][:blank:][:punct:][:cntrl:]]//g;
834 $surname =~ s/[[:digit:][:space:][:blank:][:punct:][:cntrl:]]//g;
835 $newuid = lc(($firstname)? "$firstname.$surname" : $surname);
836 $newuid = unac_string('utf-8',$newuid);
837 $newuid .= $offset unless $offset == 0;
840 } while (!Check_Userid($newuid,$borrowernumber));
846 my ( $uid, $member, $digest ) = @_;
847 my $dbh = C4::Context->dbh;
849 #Make sure the userid chosen is unique and not theirs if non-empty. If it is not,
850 #Then we need to tell the user and have them create a new one.
854 "SELECT * FROM borrowers WHERE userid=? AND borrowernumber != ?");
855 $sth->execute( $uid, $member );
856 if ( ( $uid ne '' ) && ( my $row = $sth->fetchrow_hashref ) ) {
860 #Everything is good so we can update the information.
863 "update borrowers set userid=?, password=? where borrowernumber=?");
864 $sth->execute( $uid, $digest, $member );
868 logaction("MEMBERS", "CHANGE PASS", $member, "") if C4::Context->preference("BorrowersLog");
874 =head2 fixup_cardnumber
876 Warning: The caller is responsible for locking the members table in write
877 mode, to avoid database corruption.
881 use vars qw( @weightings );
882 my @weightings = ( 8, 4, 6, 3, 5, 2, 1 );
884 sub fixup_cardnumber {
885 my ($cardnumber) = @_;
886 my $autonumber_members = C4::Context->boolean_preference('autoMemberNum') || 0;
888 # Find out whether member numbers should be generated
889 # automatically. Should be either "1" or something else.
890 # Defaults to "0", which is interpreted as "no".
892 # if ($cardnumber !~ /\S/ && $autonumber_members) {
893 ($autonumber_members) or return $cardnumber;
894 my $checkdigit = C4::Context->preference('checkdigit');
895 my $dbh = C4::Context->dbh;
896 if ( $checkdigit and $checkdigit eq 'katipo' ) {
898 # if checkdigit is selected, calculate katipo-style cardnumber.
899 # otherwise, just use the max()
900 # purpose: generate checksum'd member numbers.
901 # We'll assume we just got the max value of digits 2-8 of member #'s
902 # from the database and our job is to increment that by one,
903 # determine the 1st and 9th digits and return the full string.
904 my $sth = $dbh->prepare(
905 "select max(substring(borrowers.cardnumber,2,7)) as new_num from borrowers"
908 my $data = $sth->fetchrow_hashref;
909 $cardnumber = $data->{new_num};
910 if ( !$cardnumber ) { # If DB has no values,
911 $cardnumber = 1000000; # start at 1000000
917 for ( my $i = 0 ; $i < 8 ; $i += 1 ) {
918 # read weightings, left to right, 1 char at a time
919 my $temp1 = $weightings[$i];
921 # sequence left to right, 1 char at a time
922 my $temp2 = substr( $cardnumber, $i, 1 );
924 # mult each char 1-7 by its corresponding weighting
925 $sum += $temp1 * $temp2;
928 my $rem = ( $sum % 11 );
929 $rem = 'X' if $rem == 10;
931 return "V$cardnumber$rem";
934 my $sth = $dbh->prepare(
935 'SELECT MAX( CAST( cardnumber AS SIGNED ) ) FROM borrowers WHERE cardnumber REGEXP "^-?[0-9]+$"'
938 my ($result) = $sth->fetchrow;
941 return $cardnumber; # just here as a fallback/reminder
946 ($num_children, $children_arrayref) = &GetGuarantees($parent_borrno);
947 $child0_cardno = $children_arrayref->[0]{"cardnumber"};
948 $child0_borrno = $children_arrayref->[0]{"borrowernumber"};
950 C<&GetGuarantees> takes a borrower number (e.g., that of a patron
951 with children) and looks up the borrowers who are guaranteed by that
952 borrower (i.e., the patron's children).
954 C<&GetGuarantees> returns two values: an integer giving the number of
955 borrowers guaranteed by C<$parent_borrno>, and a reference to an array
956 of references to hash, which gives the actual results.
962 my ($borrowernumber) = @_;
963 my $dbh = C4::Context->dbh;
966 "select cardnumber,borrowernumber, firstname, surname from borrowers where guarantorid=?"
968 $sth->execute($borrowernumber);
971 my $data = $sth->fetchall_arrayref({});
972 return ( scalar(@$data), $data );
975 =head2 UpdateGuarantees
977 &UpdateGuarantees($parent_borrno);
980 C<&UpdateGuarantees> borrower data for an adult and updates all the guarantees
981 with the modified information
986 sub UpdateGuarantees {
988 my $dbh = C4::Context->dbh;
989 my ( $count, $guarantees ) = GetGuarantees( $data{'borrowernumber'} );
990 foreach my $guarantee (@$guarantees){
991 my $guaquery = qq|UPDATE borrowers
992 SET address=?,fax=?,B_city=?,mobile=?,city=?,phone=?
993 WHERE borrowernumber=?
995 my $sth = $dbh->prepare($guaquery);
996 $sth->execute($data{'address'},$data{'fax'},$data{'B_city'},$data{'mobile'},$data{'city'},$data{'phone'},$guarantee->{'borrowernumber'});
1000 =head2 GetPendingIssues
1002 my $issues = &GetPendingIssues(@borrowernumber);
1004 Looks up what the patron with the given borrowernumber has borrowed.
1006 C<&GetPendingIssues> returns a
1007 reference-to-array where each element is a reference-to-hash; the
1008 keys are the fields from the C<issues>, C<biblio>, and C<items> tables.
1009 The keys include C<biblioitems> fields except marc and marcxml.
1013 sub GetPendingIssues {
1014 my @borrowernumbers = @_;
1016 unless (@borrowernumbers ) { # return a ref_to_array
1017 return \@borrowernumbers; # to not cause surprise to caller
1020 # Borrowers part of the query
1022 for (my $i = 0; $i < @borrowernumbers; $i++) {
1023 $bquery .= ' issues.borrowernumber = ?';
1024 if ($i < $#borrowernumbers ) {
1029 # must avoid biblioitems.* to prevent large marc and marcxml fields from killing performance
1030 # FIXME: namespace collision: each table has "timestamp" fields. Which one is "timestamp" ?
1031 # FIXME: circ/ciculation.pl tries to sort by timestamp!
1032 # FIXME: namespace collision: other collisions possible.
1033 # FIXME: most of this data isn't really being used by callers.
1040 biblioitems.itemtype,
1043 biblioitems.publicationyear,
1044 biblioitems.publishercode,
1045 biblioitems.volumedate,
1046 biblioitems.volumedesc,
1049 borrowers.firstname,
1051 borrowers.cardnumber,
1052 issues.timestamp AS timestamp,
1053 issues.renewals AS renewals,
1054 issues.borrowernumber AS borrowernumber,
1055 items.renewals AS totalrenewals
1057 LEFT JOIN items ON items.itemnumber = issues.itemnumber
1058 LEFT JOIN biblio ON items.biblionumber = biblio.biblionumber
1059 LEFT JOIN biblioitems ON items.biblioitemnumber = biblioitems.biblioitemnumber
1060 LEFT JOIN borrowers ON issues.borrowernumber = borrowers.borrowernumber
1063 ORDER BY issues.issuedate"
1066 my $sth = C4::Context->dbh->prepare($query);
1067 $sth->execute(@borrowernumbers);
1068 my $data = $sth->fetchall_arrayref({});
1069 my $today = dt_from_string;
1070 foreach (@{$data}) {
1071 if ($_->{issuedate}) {
1072 $_->{issuedate} = dt_from_string($_->{issuedate}, 'sql');
1074 $_->{date_due_sql} = $_->{date_due};
1075 # FIXME no need to have this value
1076 $_->{date_due} or next;
1077 $_->{date_due_sql} = $_->{date_due};
1078 # FIXME no need to have this value
1079 $_->{date_due} = dt_from_string($_->{date_due}, 'sql');
1080 if ( DateTime->compare($_->{date_due}, $today) == -1 ) {
1089 $issues = &GetAllIssues($borrowernumber, $sortkey, $limit);
1091 Looks up what the patron with the given borrowernumber has borrowed,
1092 and sorts the results.
1094 C<$sortkey> is the name of a field on which to sort the results. This
1095 should be the name of a field in the C<issues>, C<biblio>,
1096 C<biblioitems>, or C<items> table in the Koha database.
1098 C<$limit> is the maximum number of results to return.
1100 C<&GetAllIssues> an arrayref, C<$issues>, of hashrefs, the keys of which
1101 are the fields from the C<issues>, C<biblio>, C<biblioitems>, and
1102 C<items> tables of the Koha database.
1108 my ( $borrowernumber, $order, $limit ) = @_;
1110 return unless $borrowernumber;
1111 $order = 'date_due desc' unless $order;
1113 my $dbh = C4::Context->dbh;
1115 'SELECT *, issues.timestamp as issuestimestamp, issues.renewals AS renewals,items.renewals AS totalrenewals,items.timestamp AS itemstimestamp
1117 LEFT JOIN items on items.itemnumber=issues.itemnumber
1118 LEFT JOIN biblio ON items.biblionumber=biblio.biblionumber
1119 LEFT JOIN biblioitems ON items.biblioitemnumber=biblioitems.biblioitemnumber
1120 WHERE borrowernumber=?
1122 SELECT *, old_issues.timestamp as issuestimestamp, old_issues.renewals AS renewals,items.renewals AS totalrenewals,items.timestamp AS itemstimestamp
1124 LEFT JOIN items on items.itemnumber=old_issues.itemnumber
1125 LEFT JOIN biblio ON items.biblionumber=biblio.biblionumber
1126 LEFT JOIN biblioitems ON items.biblioitemnumber=biblioitems.biblioitemnumber
1127 WHERE borrowernumber=? AND old_issues.itemnumber IS NOT NULL
1128 order by ' . $order;
1130 $query .= " limit $limit";
1133 my $sth = $dbh->prepare($query);
1134 $sth->execute( $borrowernumber, $borrowernumber );
1135 return $sth->fetchall_arrayref( {} );
1139 =head2 GetMemberAccountRecords
1141 ($total, $acctlines, $count) = &GetMemberAccountRecords($borrowernumber);
1143 Looks up accounting data for the patron with the given borrowernumber.
1145 C<&GetMemberAccountRecords> returns a three-element array. C<$acctlines> is a
1146 reference-to-array, where each element is a reference-to-hash; the
1147 keys are the fields of the C<accountlines> table in the Koha database.
1148 C<$count> is the number of elements in C<$acctlines>. C<$total> is the
1149 total amount outstanding for all of the account lines.
1153 sub GetMemberAccountRecords {
1154 my ($borrowernumber) = @_;
1155 my $dbh = C4::Context->dbh;
1161 WHERE borrowernumber=?);
1162 $strsth.=" ORDER BY accountlines_id desc";
1163 my $sth= $dbh->prepare( $strsth );
1164 $sth->execute( $borrowernumber );
1167 while ( my $data = $sth->fetchrow_hashref ) {
1168 if ( $data->{itemnumber} ) {
1169 my $biblio = GetBiblioFromItemNumber( $data->{itemnumber} );
1170 $data->{biblionumber} = $biblio->{biblionumber};
1171 $data->{title} = $biblio->{title};
1173 $acctlines[$numlines] = $data;
1175 $total += int(1000 * $data->{'amountoutstanding'}); # convert float to integer to avoid round-off errors
1178 return ( $total, \@acctlines,$numlines);
1181 =head2 GetMemberAccountBalance
1183 ($total_balance, $non_issue_balance, $other_charges) = &GetMemberAccountBalance($borrowernumber);
1185 Calculates amount immediately owing by the patron - non-issue charges.
1186 Based on GetMemberAccountRecords.
1187 Charges exempt from non-issue are:
1189 * Rent (rental) if RentalsInNoissuesCharge syspref is set to false
1190 * Manual invoices if ManInvInNoissuesCharge syspref is set to false
1194 sub GetMemberAccountBalance {
1195 my ($borrowernumber) = @_;
1197 my $ACCOUNT_TYPE_LENGTH = 5; # this is plain ridiculous...
1200 push @not_fines, 'Res' unless C4::Context->preference('HoldsInNoissuesCharge');
1201 push @not_fines, 'Rent' unless C4::Context->preference('RentalsInNoissuesCharge');
1202 unless ( C4::Context->preference('ManInvInNoissuesCharge') ) {
1203 my $dbh = C4::Context->dbh;
1204 my $man_inv_types = $dbh->selectcol_arrayref(qq{SELECT authorised_value FROM authorised_values WHERE category = 'MANUAL_INV'});
1205 push @not_fines, map substr($_, 0, $ACCOUNT_TYPE_LENGTH), @$man_inv_types;
1207 my %not_fine = map {$_ => 1} @not_fines;
1209 my ($total, $acctlines) = GetMemberAccountRecords($borrowernumber);
1210 my $other_charges = 0;
1211 foreach (@$acctlines) {
1212 $other_charges += $_->{amountoutstanding} if $not_fine{ substr($_->{accounttype}, 0, $ACCOUNT_TYPE_LENGTH) };
1215 return ( $total, $total - $other_charges, $other_charges);
1218 =head2 GetBorNotifyAcctRecord
1220 ($total, $acctlines, $count) = &GetBorNotifyAcctRecord($params,$notifyid);
1222 Looks up accounting data for the patron with the given borrowernumber per file number.
1224 C<&GetBorNotifyAcctRecord> returns a three-element array. C<$acctlines> is a
1225 reference-to-array, where each element is a reference-to-hash; the
1226 keys are the fields of the C<accountlines> table in the Koha database.
1227 C<$count> is the number of elements in C<$acctlines>. C<$total> is the
1228 total amount outstanding for all of the account lines.
1232 sub GetBorNotifyAcctRecord {
1233 my ( $borrowernumber, $notifyid ) = @_;
1234 my $dbh = C4::Context->dbh;
1237 my $sth = $dbh->prepare(
1240 WHERE borrowernumber=?
1242 AND amountoutstanding != '0'
1243 ORDER BY notify_id,accounttype
1246 $sth->execute( $borrowernumber, $notifyid );
1248 while ( my $data = $sth->fetchrow_hashref ) {
1249 if ( $data->{itemnumber} ) {
1250 my $biblio = GetBiblioFromItemNumber( $data->{itemnumber} );
1251 $data->{biblionumber} = $biblio->{biblionumber};
1252 $data->{title} = $biblio->{title};
1254 $acctlines[$numlines] = $data;
1256 $total += int(100 * $data->{'amountoutstanding'});
1259 return ( $total, \@acctlines, $numlines );
1262 =head2 checkuniquemember (OUEST-PROVENCE)
1264 ($result,$categorycode) = &checkuniquemember($collectivity,$surname,$firstname,$dateofbirth);
1266 Checks that a member exists or not in the database.
1268 C<&result> is nonzero (=exist) or 0 (=does not exist)
1269 C<&categorycode> is from categorycode table
1270 C<&collectivity> is 1 (= we add a collectivity) or 0 (= we add a physical member)
1271 C<&surname> is the surname
1272 C<&firstname> is the firstname (only if collectivity=0)
1273 C<&dateofbirth> is the date of birth in ISO format (only if collectivity=0)
1277 # FIXME: This function is not legitimate. Multiple patrons might have the same first/last name and birthdate.
1278 # This is especially true since first name is not even a required field.
1280 sub checkuniquemember {
1281 my ( $collectivity, $surname, $firstname, $dateofbirth ) = @_;
1282 my $dbh = C4::Context->dbh;
1283 my $request = ($collectivity) ?
1284 "SELECT borrowernumber,categorycode FROM borrowers WHERE surname=? " :
1286 "SELECT borrowernumber,categorycode FROM borrowers WHERE surname=? and firstname=? and dateofbirth=?" :
1287 "SELECT borrowernumber,categorycode FROM borrowers WHERE surname=? and firstname=?";
1288 my $sth = $dbh->prepare($request);
1289 if ($collectivity) {
1290 $sth->execute( uc($surname) );
1291 } elsif($dateofbirth){
1292 $sth->execute( uc($surname), ucfirst($firstname), $dateofbirth );
1294 $sth->execute( uc($surname), ucfirst($firstname));
1296 my @data = $sth->fetchrow;
1297 ( $data[0] ) and return $data[0], $data[1];
1301 sub checkcardnumber {
1302 my ( $cardnumber, $borrowernumber ) = @_;
1304 # If cardnumber is null, we assume they're allowed.
1305 return 0 unless defined $cardnumber;
1307 my $dbh = C4::Context->dbh;
1308 my $query = "SELECT * FROM borrowers WHERE cardnumber=?";
1309 $query .= " AND borrowernumber <> ?" if ($borrowernumber);
1310 my $sth = $dbh->prepare($query);
1313 ( $borrowernumber ? $borrowernumber : () )
1316 return 1 if $sth->fetchrow_hashref;
1318 my ( $min_length, $max_length ) = get_cardnumber_length();
1320 if length $cardnumber > $max_length
1321 or length $cardnumber < $min_length;
1326 =head2 get_cardnumber_length
1328 my ($min, $max) = C4::Members::get_cardnumber_length()
1330 Returns the minimum and maximum length for patron cardnumbers as
1331 determined by the CardnumberLength system preference, the
1332 BorrowerMandatoryField system preference, and the width of the
1337 sub get_cardnumber_length {
1338 my ( $min, $max ) = ( 0, 16 ); # borrowers.cardnumber is a nullable varchar(16)
1339 $min = 1 if C4::Context->preference('BorrowerMandatoryField') =~ /cardnumber/;
1340 if ( my $cardnumber_length = C4::Context->preference('CardnumberLength') ) {
1341 # Is integer and length match
1342 if ( $cardnumber_length =~ m|^\d+$| ) {
1343 $min = $max = $cardnumber_length
1344 if $cardnumber_length >= $min
1345 and $cardnumber_length <= $max;
1347 # Else assuming it is a range
1348 elsif ( $cardnumber_length =~ m|(\d*),(\d*)| ) {
1349 $min = $1 if $1 and $min < $1;
1350 $max = $2 if $2 and $max > $2;
1354 return ( $min, $max );
1357 =head2 GetFirstValidEmailAddress
1359 $email = GetFirstValidEmailAddress($borrowernumber);
1361 Return the first valid email address for a borrower, given the borrowernumber. For now, the order
1362 is defined as email, emailpro, B_email. Returns the empty string if the borrower has no email
1367 sub GetFirstValidEmailAddress {
1368 my $borrowernumber = shift;
1369 my $dbh = C4::Context->dbh;
1370 my $sth = $dbh->prepare( "SELECT email, emailpro, B_email FROM borrowers where borrowernumber = ? ");
1371 $sth->execute( $borrowernumber );
1372 my $data = $sth->fetchrow_hashref;
1374 if ($data->{'email'}) {
1375 return $data->{'email'};
1376 } elsif ($data->{'emailpro'}) {
1377 return $data->{'emailpro'};
1378 } elsif ($data->{'B_email'}) {
1379 return $data->{'B_email'};
1385 =head2 GetNoticeEmailAddress
1387 $email = GetNoticeEmailAddress($borrowernumber);
1389 Return the email address of borrower used for notices, given the borrowernumber.
1390 Returns the empty string if no email address.
1394 sub GetNoticeEmailAddress {
1395 my $borrowernumber = shift;
1397 my $which_address = C4::Context->preference("AutoEmailPrimaryAddress");
1398 # if syspref is set to 'first valid' (value == OFF), look up email address
1399 if ( $which_address eq 'OFF' ) {
1400 return GetFirstValidEmailAddress($borrowernumber);
1402 # specified email address field
1403 my $dbh = C4::Context->dbh;
1404 my $sth = $dbh->prepare( qq{
1405 SELECT $which_address AS primaryemail
1407 WHERE borrowernumber=?
1409 $sth->execute($borrowernumber);
1410 my $data = $sth->fetchrow_hashref;
1411 return $data->{'primaryemail'} || '';
1414 =head2 GetExpiryDate
1416 $expirydate = GetExpiryDate($categorycode, $dateenrolled);
1418 Calculate expiry date given a categorycode and starting date. Date argument must be in ISO format.
1419 Return date is also in ISO format.
1424 my ( $categorycode, $dateenrolled ) = @_;
1426 if ($categorycode) {
1427 my $dbh = C4::Context->dbh;
1428 my $sth = $dbh->prepare("SELECT enrolmentperiod,enrolmentperioddate FROM categories WHERE categorycode=?");
1429 $sth->execute($categorycode);
1430 $enrolments = $sth->fetchrow_hashref;
1432 # die "GetExpiryDate: for enrollmentperiod $enrolmentperiod (category '$categorycode') starting $dateenrolled.\n";
1433 my @date = split (/-/,$dateenrolled);
1434 if($enrolments->{enrolmentperiod}){
1435 return sprintf("%04d-%02d-%02d", Add_Delta_YM(@date,0,$enrolments->{enrolmentperiod}));
1437 return $enrolments->{enrolmentperioddate};
1441 =head2 GetUpcomingMembershipExpires
1443 my $upcoming_mem_expires = GetUpcomingMembershipExpires();
1447 sub GetUpcomingMembershipExpires {
1448 my $dbh = C4::Context->dbh;
1449 my $days = C4::Context->preference("MembershipExpiryDaysNotice") || 0;
1450 my $dateexpiry = output_pref({ dt => (dt_from_string()->add( days => $days)), dateformat => 'iso', dateonly => 1 });
1453 SELECT borrowers.*, categories.description,
1454 branches.branchname, branches.branchemail FROM borrowers
1455 LEFT JOIN branches on borrowers.branchcode = branches.branchcode
1456 LEFT JOIN categories on borrowers.categorycode = categories.categorycode
1457 WHERE dateexpiry = ?;
1459 my $sth = $dbh->prepare($query);
1460 $sth->execute($dateexpiry);
1461 my $results = $sth->fetchall_arrayref({});
1465 =head2 GetborCatFromCatType
1467 ($codes_arrayref, $labels_hashref) = &GetborCatFromCatType();
1469 Looks up the different types of borrowers in the database. Returns two
1470 elements: a reference-to-array, which lists the borrower category
1471 codes, and a reference-to-hash, which maps the borrower category codes
1472 to category descriptions.
1477 sub GetborCatFromCatType {
1478 my ( $category_type, $action, $no_branch_limit ) = @_;
1480 my $branch_limit = $no_branch_limit
1482 : C4::Context->userenv ? C4::Context->userenv->{"branch"} : "";
1484 # FIXME - This API seems both limited and dangerous.
1485 my $dbh = C4::Context->dbh;
1488 SELECT categories.categorycode, categories.description
1492 LEFT JOIN categories_branches ON categories.categorycode = categories_branches.categorycode
1495 $request .= " $action ";
1496 $request .= " AND (branchcode = ? OR branchcode IS NULL) GROUP BY description" if $branch_limit;
1498 $request .= " WHERE branchcode = ? OR branchcode IS NULL GROUP BY description" if $branch_limit;
1500 $request .= " ORDER BY categorycode";
1502 my $sth = $dbh->prepare($request);
1504 $action ? $category_type : (),
1505 $branch_limit ? $branch_limit : ()
1511 while ( my $data = $sth->fetchrow_hashref ) {
1512 push @codes, $data->{'categorycode'};
1513 $labels{ $data->{'categorycode'} } = $data->{'description'};
1516 return ( \@codes, \%labels );
1519 =head2 GetBorrowercategory
1521 $hashref = &GetBorrowercategory($categorycode);
1523 Given the borrower's category code, the function returns the corresponding
1524 data hashref for a comprehensive information display.
1528 sub GetBorrowercategory {
1530 my $dbh = C4::Context->dbh;
1534 "SELECT description,dateofbirthrequired,upperagelimit,category_type
1536 WHERE categorycode = ?"
1538 $sth->execute($catcode);
1540 $sth->fetchrow_hashref;
1544 } # sub getborrowercategory
1547 =head2 GetBorrowerCategorycode
1549 $categorycode = &GetBorrowerCategoryCode( $borrowernumber );
1551 Given the borrowernumber, the function returns the corresponding categorycode
1555 sub GetBorrowerCategorycode {
1556 my ( $borrowernumber ) = @_;
1557 my $dbh = C4::Context->dbh;
1558 my $sth = $dbh->prepare( qq{
1561 WHERE borrowernumber = ?
1563 $sth->execute( $borrowernumber );
1564 return $sth->fetchrow;
1567 =head2 GetBorrowercategoryList
1569 $arrayref_hashref = &GetBorrowercategoryList;
1570 If no category code provided, the function returns all the categories.
1574 sub GetBorrowercategoryList {
1575 my $no_branch_limit = @_ ? shift : 0;
1576 my $branch_limit = $no_branch_limit
1578 : C4::Context->userenv ? C4::Context->userenv->{"branch"} : "";
1579 my $dbh = C4::Context->dbh;
1580 my $query = "SELECT categories.* FROM categories";
1582 LEFT JOIN categories_branches ON categories.categorycode = categories_branches.categorycode
1583 WHERE branchcode = ? OR branchcode IS NULL GROUP BY description
1585 $query .= " ORDER BY description";
1586 my $sth = $dbh->prepare( $query );
1587 $sth->execute( $branch_limit ? $branch_limit : () );
1588 my $data = $sth->fetchall_arrayref( {} );
1591 } # sub getborrowercategory
1595 $dateofbirth,$date = &GetAge($date);
1597 this function return the borrowers age with the value of dateofbirth
1603 my ( $date, $date_ref ) = @_;
1605 if ( not defined $date_ref ) {
1606 $date_ref = sprintf( '%04d-%02d-%02d', Today() );
1609 my ( $year1, $month1, $day1 ) = split /-/, $date;
1610 my ( $year2, $month2, $day2 ) = split /-/, $date_ref;
1612 my $age = $year2 - $year1;
1613 if ( $month1 . $day1 > $month2 . $day2 ) {
1622 $borrower = C4::Members::SetAge($borrower, $datetimeduration);
1623 $borrower = C4::Members::SetAge($borrower, '0015-12-10');
1624 $borrower = C4::Members::SetAge($borrower, $datetimeduration, $datetime_reference);
1626 eval { $borrower = C4::Members::SetAge($borrower, '015-1-10'); };
1627 if ($@) {print $@;} #Catch a bad ISO Date or kill your script!
1629 This function sets the borrower's dateofbirth to match the given age.
1630 Optionally relative to the given $datetime_reference.
1632 @PARAM1 koha.borrowers-object
1633 @PARAM2 DateTime::Duration-object as the desired age
1634 OR a ISO 8601 Date. (To make the API more pleasant)
1635 @PARAM3 DateTime-object as the relative date, defaults to now().
1636 RETURNS The given borrower reference @PARAM1.
1637 DIES If there was an error with the ISO Date handling.
1643 my ( $borrower, $datetimeduration, $datetime_ref ) = @_;
1644 $datetime_ref = DateTime->now() unless $datetime_ref;
1646 if ($datetimeduration && ref $datetimeduration ne 'DateTime::Duration') {
1647 if ($datetimeduration =~ /^(\d{4})-(\d{2})-(\d{2})/) {
1648 $datetimeduration = DateTime::Duration->new(years => $1, months => $2, days => $3);
1651 die "C4::Members::SetAge($borrower, $datetimeduration), datetimeduration not a valid ISO 8601 Date!\n";
1655 my $new_datetime_ref = $datetime_ref->clone();
1656 $new_datetime_ref->subtract_duration( $datetimeduration );
1658 $borrower->{dateofbirth} = $new_datetime_ref->ymd();
1663 =head2 GetSortDetails (OUEST-PROVENCE)
1665 ($lib) = &GetSortDetails($category,$sortvalue);
1667 Returns the authorized value details
1668 C<&$lib>return value of authorized value details
1669 C<&$sortvalue>this is the value of authorized value
1670 C<&$category>this is the value of authorized value category
1674 sub GetSortDetails {
1675 my ( $category, $sortvalue ) = @_;
1676 my $dbh = C4::Context->dbh;
1677 my $query = qq|SELECT lib
1678 FROM authorised_values
1680 AND authorised_value=? |;
1681 my $sth = $dbh->prepare($query);
1682 $sth->execute( $category, $sortvalue );
1683 my $lib = $sth->fetchrow;
1684 return ($lib) if ($lib);
1685 return ($sortvalue) unless ($lib);
1688 =head2 MoveMemberToDeleted
1690 $result = &MoveMemberToDeleted($borrowernumber);
1692 Copy the record from borrowers to deletedborrowers table.
1693 The routine returns 1 for success, undef for failure.
1697 sub MoveMemberToDeleted {
1698 my ($member) = shift or return;
1700 my $schema = Koha::Database->new()->schema();
1701 my $borrowers_rs = $schema->resultset('Borrower');
1702 $borrowers_rs->result_class('DBIx::Class::ResultClass::HashRefInflator');
1703 my $borrower = $borrowers_rs->find($member);
1704 return unless $borrower;
1706 my $deleted = $schema->resultset('Deletedborrower')->create($borrower);
1708 return $deleted ? 1 : undef;
1713 DelMember($borrowernumber);
1715 This function remove directly a borrower whitout writing it on deleteborrower.
1716 + Deletes reserves for the borrower
1721 my $dbh = C4::Context->dbh;
1722 my $borrowernumber = shift;
1723 #warn "in delmember with $borrowernumber";
1724 return unless $borrowernumber; # borrowernumber is mandatory.
1726 my $query = qq|DELETE
1728 WHERE borrowernumber=?|;
1729 my $sth = $dbh->prepare($query);
1730 $sth->execute($borrowernumber);
1734 WHERE borrowernumber = ?
1736 $sth = $dbh->prepare($query);
1737 $sth->execute($borrowernumber);
1738 logaction("MEMBERS", "DELETE", $borrowernumber, "") if C4::Context->preference("BorrowersLog");
1742 =head2 HandleDelBorrower
1744 HandleDelBorrower($borrower);
1746 When a member is deleted (DelMember in Members.pm), you should call me first.
1747 This routine deletes/moves lists and entries for the deleted member/borrower.
1748 Lists owned by the borrower are deleted, but entries from the borrower to
1749 other lists are kept.
1753 sub HandleDelBorrower {
1756 my $dbh = C4::Context->dbh;
1758 #Delete all lists and all shares of this borrower
1759 #Consistent with the approach Koha uses on deleting individual lists
1760 #Note that entries in virtualshelfcontents added by this borrower to
1761 #lists of others will be handled by a table constraint: the borrower
1762 #is set to NULL in those entries.
1763 $query="DELETE FROM virtualshelves WHERE owner=?";
1764 $dbh->do($query,undef,($borrower));
1767 #We could handle the above deletes via a constraint too.
1768 #But a new BZ report 11889 has been opened to discuss another approach.
1769 #Instead of deleting we could also disown lists (based on a pref).
1770 #In that way we could save shared and public lists.
1771 #The current table constraints support that idea now.
1772 #This pref should then govern the results of other routines/methods such as
1773 #Koha::Virtualshelf->new->delete too.
1776 =head2 ExtendMemberSubscriptionTo (OUEST-PROVENCE)
1778 $date = ExtendMemberSubscriptionTo($borrowerid, $date);
1780 Extending the subscription to a given date or to the expiry date calculated on ISO date.
1785 sub ExtendMemberSubscriptionTo {
1786 my ( $borrowerid,$date) = @_;
1787 my $dbh = C4::Context->dbh;
1788 my $borrower = GetMember('borrowernumber'=>$borrowerid);
1790 $date = (C4::Context->preference('BorrowerRenewalPeriodBase') eq 'dateexpiry') ?
1791 eval { output_pref( { dt => dt_from_string( $borrower->{'dateexpiry'} ), dateonly => 1, dateformat => 'iso' } ); }
1793 output_pref( { dt => dt_from_string, dateonly => 1, dateformat => 'iso' } );
1794 $date = GetExpiryDate( $borrower->{'categorycode'}, $date );
1796 my $sth = $dbh->do(<<EOF);
1798 SET dateexpiry='$date'
1799 WHERE borrowernumber='$borrowerid'
1802 AddEnrolmentFeeIfNeeded( $borrower->{categorycode}, $borrower->{borrowernumber} );
1804 logaction("MEMBERS", "RENEW", $borrower->{'borrowernumber'}, "Membership renewed")if C4::Context->preference("BorrowersLog");
1805 return $date if ($sth);
1809 =head2 GetTitles (OUEST-PROVENCE)
1811 ($borrowertitle)= &GetTitles();
1813 Looks up the different title . Returns array with all borrowers title
1818 my @borrowerTitle = split (/,|\|/,C4::Context->preference('BorrowersTitles'));
1819 unshift( @borrowerTitle, "" );
1820 my $count=@borrowerTitle;
1825 return ( \@borrowerTitle);
1829 =head2 GetHideLostItemsPreference
1831 $hidelostitemspref = &GetHideLostItemsPreference($borrowernumber);
1833 Returns the HideLostItems preference for the patron category of the supplied borrowernumber
1834 C<&$hidelostitemspref>return value of function, 0 or 1
1838 sub GetHideLostItemsPreference {
1839 my ($borrowernumber) = @_;
1840 my $dbh = C4::Context->dbh;
1841 my $query = "SELECT hidelostitems FROM borrowers,categories WHERE borrowers.categorycode = categories.categorycode AND borrowernumber = ?";
1842 my $sth = $dbh->prepare($query);
1843 $sth->execute($borrowernumber);
1844 my $hidelostitems = $sth->fetchrow;
1845 return $hidelostitems;
1848 =head2 GetBorrowersToExpunge
1850 $borrowers = &GetBorrowersToExpunge(
1851 not_borrowered_since => $not_borrowered_since,
1852 expired_before => $expired_before,
1853 category_code => $category_code,
1854 branchcode => $branchcode
1857 This function get all borrowers based on the given criteria.
1861 sub GetBorrowersToExpunge {
1864 my $filterdate = $params->{'not_borrowered_since'};
1865 my $filterexpiry = $params->{'expired_before'};
1866 my $filtercategory = $params->{'category_code'};
1867 my $filterbranch = $params->{'branchcode'} ||
1868 ((C4::Context->preference('IndependentBranches')
1869 && C4::Context->userenv
1870 && !C4::Context->IsSuperLibrarian()
1871 && C4::Context->userenv->{branch})
1872 ? C4::Context->userenv->{branch}
1875 my $dbh = C4::Context->dbh;
1877 SELECT borrowers.borrowernumber,
1878 MAX(old_issues.timestamp) AS latestissue,
1879 MAX(issues.timestamp) AS currentissue
1881 JOIN categories USING (categorycode)
1885 WHERE guarantorid IS NOT NULL
1886 AND guarantorid <> 0
1887 ) as tmp ON borrowers.borrowernumber=tmp.guarantorid
1888 LEFT JOIN old_issues USING (borrowernumber)
1889 LEFT JOIN issues USING (borrowernumber)
1890 WHERE category_type <> 'S'
1891 AND tmp.guarantorid IS NULL
1895 if ( $filterbranch && $filterbranch ne "" ) {
1896 $query.= " AND borrowers.branchcode = ? ";
1897 push( @query_params, $filterbranch );
1899 if ( $filterexpiry ) {
1900 $query .= " AND dateexpiry < ? ";
1901 push( @query_params, $filterexpiry );
1903 if ( $filtercategory ) {
1904 $query .= " AND categorycode = ? ";
1905 push( @query_params, $filtercategory );
1907 $query.=" GROUP BY borrowers.borrowernumber HAVING currentissue IS NULL ";
1908 if ( $filterdate ) {
1909 $query.=" AND ( latestissue < ? OR latestissue IS NULL ) ";
1910 push @query_params,$filterdate;
1912 warn $query if $debug;
1914 my $sth = $dbh->prepare($query);
1915 if (scalar(@query_params)>0){
1916 $sth->execute(@query_params);
1923 while ( my $data = $sth->fetchrow_hashref ) {
1924 push @results, $data;
1929 =head2 GetBorrowersWhoHaveNeverBorrowed
1931 $results = &GetBorrowersWhoHaveNeverBorrowed
1933 This function get all borrowers who have never borrowed.
1935 I<$result> is a ref to an array which all elements are a hasref.
1939 sub GetBorrowersWhoHaveNeverBorrowed {
1940 my $filterbranch = shift ||
1941 ((C4::Context->preference('IndependentBranches')
1942 && C4::Context->userenv
1943 && !C4::Context->IsSuperLibrarian()
1944 && C4::Context->userenv->{branch})
1945 ? C4::Context->userenv->{branch}
1947 my $dbh = C4::Context->dbh;
1949 SELECT borrowers.borrowernumber,max(timestamp) as latestissue
1951 LEFT JOIN issues ON borrowers.borrowernumber = issues.borrowernumber
1952 WHERE issues.borrowernumber IS NULL
1955 if ($filterbranch && $filterbranch ne ""){
1956 $query.=" AND borrowers.branchcode= ?";
1957 push @query_params,$filterbranch;
1959 warn $query if $debug;
1961 my $sth = $dbh->prepare($query);
1962 if (scalar(@query_params)>0){
1963 $sth->execute(@query_params);
1970 while ( my $data = $sth->fetchrow_hashref ) {
1971 push @results, $data;
1976 =head2 GetBorrowersWithIssuesHistoryOlderThan
1978 $results = &GetBorrowersWithIssuesHistoryOlderThan($date)
1980 this function get all borrowers who has an issue history older than I<$date> given on input arg.
1982 I<$result> is a ref to an array which all elements are a hashref.
1983 This hashref is containt the number of time this borrowers has borrowed before I<$date> and the borrowernumber.
1987 sub GetBorrowersWithIssuesHistoryOlderThan {
1988 my $dbh = C4::Context->dbh;
1989 my $date = shift ||POSIX::strftime("%Y-%m-%d",localtime());
1990 my $filterbranch = shift ||
1991 ((C4::Context->preference('IndependentBranches')
1992 && C4::Context->userenv
1993 && !C4::Context->IsSuperLibrarian()
1994 && C4::Context->userenv->{branch})
1995 ? C4::Context->userenv->{branch}
1998 SELECT count(borrowernumber) as n,borrowernumber
2000 WHERE returndate < ?
2001 AND borrowernumber IS NOT NULL
2004 push @query_params, $date;
2006 $query.=" AND branchcode = ?";
2007 push @query_params, $filterbranch;
2009 $query.=" GROUP BY borrowernumber ";
2010 warn $query if $debug;
2011 my $sth = $dbh->prepare($query);
2012 $sth->execute(@query_params);
2015 while ( my $data = $sth->fetchrow_hashref ) {
2016 push @results, $data;
2021 =head2 GetBorrowersNamesAndLatestIssue
2023 $results = &GetBorrowersNamesAndLatestIssueList(@borrowernumbers)
2025 this function get borrowers Names and surnames and Issue information.
2027 I<@borrowernumbers> is an array which all elements are borrowernumbers.
2028 This hashref is containt the number of time this borrowers has borrowed before I<$date> and the borrowernumber.
2032 sub GetBorrowersNamesAndLatestIssue {
2033 my $dbh = C4::Context->dbh;
2034 my @borrowernumbers=@_;
2036 SELECT surname,lastname, phone, email,max(timestamp)
2038 LEFT JOIN issues ON borrowers.borrowernumber=issues.borrowernumber
2039 GROUP BY borrowernumber
2041 my $sth = $dbh->prepare($query);
2043 my $results = $sth->fetchall_arrayref({});
2049 my $success = ModPrivacy( $borrowernumber, $privacy );
2051 Update the privacy of a patron.
2054 true on success, false on failure
2059 my $borrowernumber = shift;
2060 my $privacy = shift;
2061 return unless defined $borrowernumber;
2062 return unless $borrowernumber =~ /^\d+$/;
2064 return ModMember( borrowernumber => $borrowernumber,
2065 privacy => $privacy );
2070 IssueSlip($branchcode, $borrowernumber, $quickslip)
2072 Returns letter hash ( see C4::Letters::GetPreparedLetter )
2074 $quickslip is boolean, to indicate whether we want a quick slip
2076 IssueSlip populates ISSUESLIP and ISSUEQSLIP, and will make the following expansions:
2112 NOTE: Not all table fields are available, pleasee see GetPendingIssues for a list of available fields.
2117 my ($branch, $borrowernumber, $quickslip) = @_;
2119 # FIXME Check callers before removing this statement
2120 #return unless $borrowernumber;
2122 my @issues = @{ GetPendingIssues($borrowernumber) };
2124 for my $issue (@issues) {
2125 $issue->{date_due} = $issue->{date_due_sql};
2127 my $today = output_pref({ dt => dt_from_string, dateformat => 'iso', dateonly => 1 });
2128 if ( substr( $issue->{issuedate}, 0, 10 ) eq $today
2129 or substr( $issue->{lastreneweddate}, 0, 10 ) eq $today ) {
2135 # Sort on timestamp then on issuedate (useful for tests and could be if modified in a batch
2137 my $s = $b->{timestamp} <=> $a->{timestamp};
2139 $b->{issuedate} <=> $a->{issuedate} : $s;
2142 my ($letter_code, %repeat);
2144 $letter_code = 'ISSUEQSLIP';
2146 'checkedout' => [ map {
2149 'biblioitems' => $_,
2151 }, grep { $_->{'now'} } @issues ],
2155 $letter_code = 'ISSUESLIP';
2157 'checkedout' => [ map {
2160 'biblioitems' => $_,
2162 }, grep { !$_->{'overdue'} } @issues ],
2164 'overdue' => [ map {
2167 'biblioitems' => $_,
2169 }, grep { $_->{'overdue'} } @issues ],
2172 $_->{'timestamp'} = $_->{'newdate'};
2174 } @{ GetNewsToDisplay("slip",$branch) } ],
2178 return C4::Letters::GetPreparedLetter (
2179 module => 'circulation',
2180 letter_code => $letter_code,
2181 branchcode => $branch,
2183 'branches' => $branch,
2184 'borrowers' => $borrowernumber,
2190 =head2 GetBorrowersWithEmail
2192 ([$borrnum,$userid], ...) = GetBorrowersWithEmail('me@example.com');
2194 This gets a list of users and their basic details from their email address.
2195 As it's possible for multiple user to have the same email address, it provides
2196 you with all of them. If there is no userid for the user, there will be an
2197 C<undef> there. An empty list will be returned if there are no matches.
2201 sub GetBorrowersWithEmail {
2204 my $dbh = C4::Context->dbh;
2206 my $query = "SELECT borrowernumber, userid FROM borrowers WHERE email=?";
2207 my $sth=$dbh->prepare($query);
2208 $sth->execute($email);
2210 while (my $ref = $sth->fetch) {
2213 die "Failure searching for borrowers by email address: $sth->errstr" if $sth->err;
2217 =head2 AddMember_Opac
2221 sub AddMember_Opac {
2222 my ( %borrower ) = @_;
2224 $borrower{'categorycode'} //= C4::Context->preference('PatronSelfRegistrationDefaultCategory');
2225 if (not defined $borrower{'password'}){
2226 my $sr = new String::Random;
2227 $sr->{'A'} = [ 'A'..'Z', 'a'..'z' ];
2228 my $password = $sr->randpattern("AAAAAAAAAA");
2229 $borrower{'password'} = $password;
2232 $borrower{'cardnumber'} = fixup_cardnumber( $borrower{'cardnumber'} );
2234 my $borrowernumber = AddMember(%borrower);
2236 return ( $borrowernumber, $borrower{'password'} );
2239 =head2 AddEnrolmentFeeIfNeeded
2241 AddEnrolmentFeeIfNeeded( $borrower->{categorycode}, $borrower->{borrowernumber} );
2243 Add enrolment fee for a patron if needed.
2247 sub AddEnrolmentFeeIfNeeded {
2248 my ( $categorycode, $borrowernumber ) = @_;
2249 # check for enrollment fee & add it if needed
2250 my $dbh = C4::Context->dbh;
2251 my $sth = $dbh->prepare(q{
2254 WHERE categorycode=?
2256 $sth->execute( $categorycode );
2258 warn sprintf('Database returned the following error: %s', $sth->errstr);
2261 my ($enrolmentfee) = $sth->fetchrow;
2262 if ($enrolmentfee && $enrolmentfee > 0) {
2263 # insert fee in patron debts
2264 C4::Accounts::manualinvoice( $borrowernumber, '', '', 'A', $enrolmentfee );
2273 my ( $borrowernumber ) = @_;
2275 my $sql = "SELECT COUNT(*) FROM issues WHERE date_due < NOW() AND borrowernumber = ?";
2276 my $sth = C4::Context->dbh->prepare( $sql );
2277 $sth->execute( $borrowernumber );
2278 my ( $count ) = $sth->fetchrow_array();
2283 =head2 DeleteExpiredOpacRegistrations
2285 Delete accounts that haven't been upgraded from the 'temporary' category
2286 Returns the number of removed patrons
2290 sub DeleteExpiredOpacRegistrations {
2292 my $delay = C4::Context->preference('PatronSelfRegistrationExpireTemporaryAccountsDelay');
2293 my $category_code = C4::Context->preference('PatronSelfRegistrationDefaultCategory');
2295 return 0 if not $category_code or not defined $delay or $delay eq q||;
2298 SELECT borrowernumber
2300 WHERE categorycode = ? AND DATEDIFF( NOW(), dateenrolled ) > ? |;
2302 my $dbh = C4::Context->dbh;
2303 my $sth = $dbh->prepare($query);
2304 $sth->execute( $category_code, $delay );
2306 while ( my ($borrowernumber) = $sth->fetchrow_array() ) {
2307 DelMember($borrowernumber);
2313 =head2 DeleteUnverifiedOpacRegistrations
2315 Delete all unverified self registrations in borrower_modifications,
2316 older than the specified number of days.
2320 sub DeleteUnverifiedOpacRegistrations {
2322 my $dbh = C4::Context->dbh;
2324 DELETE FROM borrower_modifications
2325 WHERE borrowernumber = 0 AND DATEDIFF( NOW(), timestamp ) > ?|;
2326 my $cnt=$dbh->do($sql, undef, ($days) );
2327 return $cnt eq '0E0'? 0: $cnt;
2330 sub GetOverduesForPatron {
2331 my ( $borrowernumber ) = @_;
2335 FROM issues, items, biblio, biblioitems
2336 WHERE items.itemnumber=issues.itemnumber
2337 AND biblio.biblionumber = items.biblionumber
2338 AND biblio.biblionumber = biblioitems.biblionumber
2339 AND issues.borrowernumber = ?
2340 AND date_due < NOW()
2343 my $sth = C4::Context->dbh->prepare( $sql );
2344 $sth->execute( $borrowernumber );
2346 return $sth->fetchall_arrayref({});
2349 END { } # module clean-up code here (global destructor)