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 Scalar::Util qw( looks_like_number );
28 use Date::Calc qw/Today Add_Delta_YM check_date Date_to_Days/;
29 use C4::Log; # logaction
35 use C4::Members::Attributes qw(SearchIdMatchingAttribute UpdateBorrowerAttribute);
36 use C4::NewsChannels; #get slip news
40 use Koha::Patron::Debarments qw(IsDebarred);
41 use Text::Unaccent qw( unac_string );
42 use Koha::AuthUtils qw(hash_password);
45 use Koha::List::Patron;
47 our (@ISA,@EXPORT,@EXPORT_OK,$debug);
49 use Module::Load::Conditional qw( can_load );
50 if ( ! can_load( modules => { 'Koha::NorwegianPatronDB' => undef } ) ) {
51 $debug && warn "Unable to load Koha::NorwegianPatronDB";
56 $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;
332 # Check the debt of the guarntees of this patron
333 my $no_issues_charge_guarantees = C4::Context->preference("NoIssuesChargeGuarantees");
334 $no_issues_charge_guarantees = undef unless looks_like_number( $no_issues_charge_guarantees );
335 if ( defined $no_issues_charge_guarantees ) {
336 my $p = Koha::Patrons->find( $patroninformation->{borrowernumber} );
337 my @guarantees = $p->guarantees();
338 my $guarantees_non_issues_charges;
339 foreach my $g ( @guarantees ) {
340 my ( $b, $n, $o ) = C4::Members::GetMemberAccountBalance( $g->id );
341 $guarantees_non_issues_charges += $n;
344 if ( $guarantees_non_issues_charges > $no_issues_charge_guarantees ) {
346 $flaginfo{'message'} = sprintf 'patron guarantees owe %.02f', $guarantees_non_issues_charges;
347 $flaginfo{'amount'} = $guarantees_non_issues_charges;
348 $flaginfo{'noissues'} = 1 unless C4::Context->preference("allowfineoverride");
349 $flags{'CHARGES_GUARANTEES'} = \%flaginfo;
353 if ( $patroninformation->{'gonenoaddress'}
354 && $patroninformation->{'gonenoaddress'} == 1 )
357 $flaginfo{'message'} = 'Borrower has no valid address.';
358 $flaginfo{'noissues'} = 1;
359 $flags{'GNA'} = \%flaginfo;
361 if ( $patroninformation->{'lost'} && $patroninformation->{'lost'} == 1 ) {
363 $flaginfo{'message'} = 'Borrower\'s card reported lost.';
364 $flaginfo{'noissues'} = 1;
365 $flags{'LOST'} = \%flaginfo;
367 if ( $patroninformation->{'debarred'} && check_date( split( /-/, $patroninformation->{'debarred'} ) ) ) {
368 if ( Date_to_Days(Date::Calc::Today) < Date_to_Days( split( /-/, $patroninformation->{'debarred'} ) ) ) {
370 $flaginfo{'debarredcomment'} = $patroninformation->{'debarredcomment'};
371 $flaginfo{'message'} = $patroninformation->{'debarredcomment'};
372 $flaginfo{'noissues'} = 1;
373 $flaginfo{'dateend'} = $patroninformation->{'debarred'};
374 $flags{'DBARRED'} = \%flaginfo;
377 if ( $patroninformation->{'borrowernotes'}
378 && $patroninformation->{'borrowernotes'} )
381 $flaginfo{'message'} = $patroninformation->{'borrowernotes'};
382 $flags{'NOTES'} = \%flaginfo;
384 my ( $odues, $itemsoverdue ) = C4::Overdues::checkoverdues($patroninformation->{'borrowernumber'});
385 if ( $odues && $odues > 0 ) {
387 $flaginfo{'message'} = "Yes";
388 $flaginfo{'itemlist'} = $itemsoverdue;
389 foreach ( sort { $a->{'date_due'} cmp $b->{'date_due'} }
392 $flaginfo{'itemlisttext'} .=
393 "$_->{'date_due'} $_->{'barcode'} $_->{'title'} \n"; # newline is display layer
395 $flags{'ODUES'} = \%flaginfo;
397 my @itemswaiting = C4::Reserves::GetReservesFromBorrowernumber( $patroninformation->{'borrowernumber'},'W' );
398 my $nowaiting = scalar @itemswaiting;
399 if ( $nowaiting > 0 ) {
401 $flaginfo{'message'} = "Reserved items available";
402 $flaginfo{'itemlist'} = \@itemswaiting;
403 $flags{'WAITING'} = \%flaginfo;
411 $borrower = &GetMember(%information);
413 Retrieve the first patron record meeting on criteria listed in the
414 C<%information> hash, which should contain one or more
415 pairs of borrowers column names and values, e.g.,
417 $borrower = GetMember(borrowernumber => id);
419 C<&GetBorrower> returns a reference-to-hash whose keys are the fields of
420 the C<borrowers> table in the Koha database.
422 FIXME: GetMember() is used throughout the code as a lookup
423 on a unique key such as the borrowernumber, but this meaning is not
424 enforced in the routine itself.
430 my ( %information ) = @_;
431 if (exists $information{borrowernumber} && !defined $information{borrowernumber}) {
432 #passing mysql's kohaadmin?? Makes no sense as a query
435 my $dbh = C4::Context->dbh;
437 q{SELECT borrowers.*, categories.category_type, categories.description
439 LEFT JOIN categories on borrowers.categorycode=categories.categorycode WHERE };
442 for (keys %information ) {
450 if (defined $information{$_}) {
452 push @values, $information{$_};
455 $select .= "$_ IS NULL";
458 $debug && warn $select, " ",values %information;
459 my $sth = $dbh->prepare("$select");
460 $sth->execute(@values);
461 my $data = $sth->fetchall_arrayref({});
462 #FIXME interface to this routine now allows generation of a result set
463 #so whole array should be returned but bowhere in the current code expects this
471 =head2 IsMemberBlocked
473 my ($block_status, $count) = IsMemberBlocked( $borrowernumber );
475 Returns whether a patron is restricted or has overdue items that may result
476 in a block of circulation privileges.
478 C<$block_status> can have the following values:
480 1 if the patron is currently restricted, in which case
481 C<$count> is the expiration date (9999-12-31 for indefinite)
483 -1 if the patron has overdue items, in which case C<$count> is the number of them
485 0 if the patron has no overdue items or outstanding fine days, in which case C<$count> is 0
487 Existing active restrictions are checked before current overdue items.
491 sub IsMemberBlocked {
492 my $borrowernumber = shift;
493 my $dbh = C4::Context->dbh;
495 my $blockeddate = Koha::Patron::Debarments::IsDebarred($borrowernumber);
497 return ( 1, $blockeddate ) if $blockeddate;
499 # if he have late issues
500 my $sth = $dbh->prepare(
501 "SELECT COUNT(*) as latedocs
503 WHERE borrowernumber = ?
504 AND date_due < now()"
506 $sth->execute($borrowernumber);
507 my $latedocs = $sth->fetchrow_hashref->{'latedocs'};
509 return ( -1, $latedocs ) if $latedocs > 0;
514 =head2 GetMemberIssuesAndFines
516 ($overdue_count, $issue_count, $total_fines) = &GetMemberIssuesAndFines($borrowernumber);
518 Returns aggregate data about items borrowed by the patron with the
519 given borrowernumber.
521 C<&GetMemberIssuesAndFines> returns a three-element array. C<$overdue_count> is the
522 number of overdue items the patron currently has borrowed. C<$issue_count> is the
523 number of books the patron currently has borrowed. C<$total_fines> is
524 the total fine currently due by the borrower.
529 sub GetMemberIssuesAndFines {
530 my ( $borrowernumber ) = @_;
531 my $dbh = C4::Context->dbh;
532 my $query = "SELECT COUNT(*) FROM issues WHERE borrowernumber = ?";
534 $debug and warn $query."\n";
535 my $sth = $dbh->prepare($query);
536 $sth->execute($borrowernumber);
537 my $issue_count = $sth->fetchrow_arrayref->[0];
539 $sth = $dbh->prepare(
540 "SELECT COUNT(*) FROM issues
541 WHERE borrowernumber = ?
542 AND date_due < now()"
544 $sth->execute($borrowernumber);
545 my $overdue_count = $sth->fetchrow_arrayref->[0];
547 $sth = $dbh->prepare("SELECT SUM(amountoutstanding) FROM accountlines WHERE borrowernumber = ?");
548 $sth->execute($borrowernumber);
549 my $total_fines = $sth->fetchrow_arrayref->[0];
551 return ($overdue_count, $issue_count, $total_fines);
557 my @columns = C4::Member::columns();
559 Returns an array of borrowers' table columns on success,
560 and an empty array on failure.
566 # Pure ANSI SQL goodness.
567 my $sql = 'SELECT * FROM borrowers WHERE 1=0;';
569 # Get the database handle.
570 my $dbh = C4::Context->dbh;
572 # Run the SQL statement to load STH's readonly properties.
573 my $sth = $dbh->prepare($sql);
574 my $rv = $sth->execute();
576 # This only fails if the table doesn't exist.
577 # This will always be called AFTER an install or upgrade,
578 # so borrowers will exist!
580 if ($sth->{NUM_OF_FIELDS}>0) {
581 @data = @{$sth->{NAME}};
592 my $success = ModMember(borrowernumber => $borrowernumber,
593 [ field => value ]... );
595 Modify borrower's data. All date fields should ALREADY be in ISO format.
598 true on success, or false on failure
604 # test to know if you must update or not the borrower password
605 if (exists $data{password}) {
606 if ($data{password} eq '****' or $data{password} eq '') {
607 delete $data{password};
609 if ( C4::Context->preference('NorwegianPatronDBEnable') && C4::Context->preference('NorwegianPatronDBEnable') == 1 ) {
610 # Update the hashed PIN in borrower_sync.hashed_pin, before Koha hashes it
611 Koha::NorwegianPatronDB::NLUpdateHashedPIN( $data{'borrowernumber'}, $data{password} );
613 $data{password} = hash_password($data{password});
617 my $old_categorycode = GetBorrowerCategorycode( $data{borrowernumber} );
619 # get only the columns of a borrower
620 my $schema = Koha::Database->new()->schema;
621 my @columns = $schema->source('Borrower')->columns;
622 my $new_borrower = { map { join(' ', @columns) =~ /$_/ ? ( $_ => $data{$_} ) : () } keys(%data) };
623 delete $new_borrower->{flags};
625 $new_borrower->{dateofbirth} ||= undef if exists $new_borrower->{dateofbirth};
626 $new_borrower->{dateenrolled} ||= undef if exists $new_borrower->{dateenrolled};
627 $new_borrower->{dateexpiry} ||= undef if exists $new_borrower->{dateexpiry};
628 $new_borrower->{debarred} ||= undef if exists $new_borrower->{debarred};
629 $new_borrower->{sms_provider_id} ||= undef if exists $new_borrower->{sms_provider_id};
631 my $rs = $schema->resultset('Borrower')->search({
632 borrowernumber => $new_borrower->{borrowernumber},
635 delete $new_borrower->{userid} if exists $new_borrower->{userid} and not $new_borrower->{userid};
637 my $execute_success = $rs->update($new_borrower);
638 if ($execute_success ne '0E0') { # only proceed if the update was a success
639 # If the patron changes to a category with enrollment fee, we add a fee
640 if ( $data{categorycode} and $data{categorycode} ne $old_categorycode ) {
641 if ( C4::Context->preference('FeeOnChangePatronCategory') ) {
642 AddEnrolmentFeeIfNeeded( $data{categorycode}, $data{borrowernumber} );
646 # If NorwegianPatronDBEnable is enabled, we set syncstatus to something that a
647 # cronjob will use for syncing with NL
648 if ( C4::Context->preference('NorwegianPatronDBEnable') && C4::Context->preference('NorwegianPatronDBEnable') == 1 ) {
649 my $borrowersync = Koha::Database->new->schema->resultset('BorrowerSync')->find({
650 'synctype' => 'norwegianpatrondb',
651 'borrowernumber' => $data{'borrowernumber'}
653 # Do not set to "edited" if syncstatus is "new". We need to sync as new before
654 # we can sync as changed. And the "new sync" will pick up all changes since
655 # the patron was created anyway.
656 if ( $borrowersync->syncstatus ne 'new' && $borrowersync->syncstatus ne 'delete' ) {
657 $borrowersync->update( { 'syncstatus' => 'edited' } );
659 # Set the value of 'sync'
660 $borrowersync->update( { 'sync' => $data{'sync'} } );
661 # Try to do the live sync
662 Koha::NorwegianPatronDB::NLSync({ 'borrowernumber' => $data{'borrowernumber'} });
665 logaction("MEMBERS", "MODIFY", $data{'borrowernumber'}, "UPDATE (executed w/ arg: $data{'borrowernumber'})") if C4::Context->preference("BorrowersLog");
667 return $execute_success;
672 $borrowernumber = &AddMember(%borrower);
674 insert new borrower into table
676 (%borrower keys are database columns. Database columns could be
677 different in different versions. Please look into database for correct
680 Returns the borrowernumber upon success
682 Returns as undef upon any db error without further processing
689 my $dbh = C4::Context->dbh;
690 my $schema = Koha::Database->new()->schema;
692 # generate a proper login if none provided
693 $data{'userid'} = Generate_Userid( $data{'borrowernumber'}, $data{'firstname'}, $data{'surname'} )
694 if ( $data{'userid'} eq '' || !Check_Userid( $data{'userid'} ) );
696 # add expiration date if it isn't already there
697 unless ( $data{'dateexpiry'} ) {
698 $data{'dateexpiry'} = GetExpiryDate( $data{'categorycode'}, output_pref( { dt => dt_from_string, dateonly => 1, dateformat => 'iso' } ) );
701 # add enrollment date if it isn't already there
702 unless ( $data{'dateenrolled'} ) {
703 $data{'dateenrolled'} = output_pref( { dt => dt_from_string, dateonly => 1, dateformat => 'iso' } );
706 my $patron_category = $schema->resultset('Category')->find( $data{'categorycode'} );
708 $patron_category->default_privacy() eq 'default' ? 1
709 : $patron_category->default_privacy() eq 'never' ? 2
710 : $patron_category->default_privacy() eq 'forever' ? 0
713 $data{'privacy_guarantor_checkouts'} = 0 unless defined( $data{'privacy_guarantor_checkouts'} );
715 # Make a copy of the plain text password for later use
716 my $plain_text_password = $data{'password'};
718 # create a disabled account if no password provided
719 $data{'password'} = ($data{'password'})? hash_password($data{'password'}) : '!';
721 # we don't want invalid dates in the db (mysql has a bad habit of inserting 0000-00-00
722 $data{'dateofbirth'} = undef if ( not $data{'dateofbirth'} );
723 $data{'debarred'} = undef if ( not $data{'debarred'} );
724 $data{'sms_provider_id'} = undef if ( not $data{'sms_provider_id'} );
726 # get only the columns of Borrower
727 my @columns = $schema->source('Borrower')->columns;
728 my $new_member = { map { join(' ',@columns) =~ /$_/ ? ( $_ => $data{$_} ) : () } keys(%data) } ;
729 delete $new_member->{borrowernumber};
731 my $rs = $schema->resultset('Borrower');
732 $data{borrowernumber} = $rs->create($new_member)->id;
734 # If NorwegianPatronDBEnable is enabled, we set syncstatus to something that a
735 # cronjob will use for syncing with NL
736 if ( exists $data{'borrowernumber'} && C4::Context->preference('NorwegianPatronDBEnable') && C4::Context->preference('NorwegianPatronDBEnable') == 1 ) {
737 Koha::Database->new->schema->resultset('BorrowerSync')->create({
738 'borrowernumber' => $data{'borrowernumber'},
739 'synctype' => 'norwegianpatrondb',
741 'syncstatus' => 'new',
742 'hashed_pin' => Koha::NorwegianPatronDB::NLEncryptPIN( $plain_text_password ),
746 # mysql_insertid is probably bad. not necessarily accurate and mysql-specific at best.
747 logaction("MEMBERS", "CREATE", $data{'borrowernumber'}, "") if C4::Context->preference("BorrowersLog");
749 AddEnrolmentFeeIfNeeded( $data{categorycode}, $data{borrowernumber} );
751 return $data{borrowernumber};
756 my $uniqueness = Check_Userid($userid,$borrowernumber);
758 $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 != '').
760 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.
763 0 for not unique (i.e. this $userid already exists)
764 1 for unique (i.e. this $userid does not exist, or this $userid/$borrowernumber combination already exists)
769 my ( $uid, $borrowernumber ) = @_;
771 return 0 unless ($uid); # userid is a unique column, we should assume NULL is not unique
773 return 0 if ( $uid eq C4::Context->config('user') );
775 my $rs = Koha::Database->new()->schema()->resultset('Borrower');
778 $params->{userid} = $uid;
779 $params->{borrowernumber} = { '!=' => $borrowernumber } if ($borrowernumber);
781 my $count = $rs->count( $params );
783 return $count ? 0 : 1;
786 =head2 Generate_Userid
788 my $newuid = Generate_Userid($borrowernumber, $firstname, $surname);
790 Generate a userid using the $surname and the $firstname (if there is a value in $firstname).
792 $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.
795 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).
799 sub Generate_Userid {
800 my ($borrowernumber, $firstname, $surname) = @_;
803 #The script will "do" the following code and increment the $offset until Check_Userid = 1 (i.e. until $newuid comes back as unique)
805 $firstname =~ s/[[:digit:][:space:][:blank:][:punct:][:cntrl:]]//g;
806 $surname =~ s/[[:digit:][:space:][:blank:][:punct:][:cntrl:]]//g;
807 $newuid = lc(($firstname)? "$firstname.$surname" : $surname);
808 $newuid = unac_string('utf-8',$newuid);
809 $newuid .= $offset unless $offset == 0;
812 } while (!Check_Userid($newuid,$borrowernumber));
818 my ( $uid, $member, $digest ) = @_;
819 my $dbh = C4::Context->dbh;
821 #Make sure the userid chosen is unique and not theirs if non-empty. If it is not,
822 #Then we need to tell the user and have them create a new one.
826 "SELECT * FROM borrowers WHERE userid=? AND borrowernumber != ?");
827 $sth->execute( $uid, $member );
828 if ( ( $uid ne '' ) && ( my $row = $sth->fetchrow_hashref ) ) {
832 #Everything is good so we can update the information.
835 "update borrowers set userid=?, password=? where borrowernumber=?");
836 $sth->execute( $uid, $digest, $member );
840 logaction("MEMBERS", "CHANGE PASS", $member, "") if C4::Context->preference("BorrowersLog");
846 =head2 fixup_cardnumber
848 Warning: The caller is responsible for locking the members table in write
849 mode, to avoid database corruption.
853 use vars qw( @weightings );
854 my @weightings = ( 8, 4, 6, 3, 5, 2, 1 );
856 sub fixup_cardnumber {
857 my ($cardnumber) = @_;
858 my $autonumber_members = C4::Context->boolean_preference('autoMemberNum') || 0;
860 # Find out whether member numbers should be generated
861 # automatically. Should be either "1" or something else.
862 # Defaults to "0", which is interpreted as "no".
864 # if ($cardnumber !~ /\S/ && $autonumber_members) {
865 ($autonumber_members) or return $cardnumber;
866 my $checkdigit = C4::Context->preference('checkdigit');
867 my $dbh = C4::Context->dbh;
868 if ( $checkdigit and $checkdigit eq 'katipo' ) {
870 # if checkdigit is selected, calculate katipo-style cardnumber.
871 # otherwise, just use the max()
872 # purpose: generate checksum'd member numbers.
873 # We'll assume we just got the max value of digits 2-8 of member #'s
874 # from the database and our job is to increment that by one,
875 # determine the 1st and 9th digits and return the full string.
876 my $sth = $dbh->prepare(
877 "select max(substring(borrowers.cardnumber,2,7)) as new_num from borrowers"
880 my $data = $sth->fetchrow_hashref;
881 $cardnumber = $data->{new_num};
882 if ( !$cardnumber ) { # If DB has no values,
883 $cardnumber = 1000000; # start at 1000000
889 for ( my $i = 0 ; $i < 8 ; $i += 1 ) {
890 # read weightings, left to right, 1 char at a time
891 my $temp1 = $weightings[$i];
893 # sequence left to right, 1 char at a time
894 my $temp2 = substr( $cardnumber, $i, 1 );
896 # mult each char 1-7 by its corresponding weighting
897 $sum += $temp1 * $temp2;
900 my $rem = ( $sum % 11 );
901 $rem = 'X' if $rem == 10;
903 return "V$cardnumber$rem";
906 my $sth = $dbh->prepare(
907 'SELECT MAX( CAST( cardnumber AS SIGNED ) ) FROM borrowers WHERE cardnumber REGEXP "^-?[0-9]+$"'
910 my ($result) = $sth->fetchrow;
913 return $cardnumber; # just here as a fallback/reminder
916 =head2 GetPendingIssues
918 my $issues = &GetPendingIssues(@borrowernumber);
920 Looks up what the patron with the given borrowernumber has borrowed.
922 C<&GetPendingIssues> returns a
923 reference-to-array where each element is a reference-to-hash; the
924 keys are the fields from the C<issues>, C<biblio>, and C<items> tables.
925 The keys include C<biblioitems> fields except marc and marcxml.
929 sub GetPendingIssues {
930 my @borrowernumbers = @_;
932 unless (@borrowernumbers ) { # return a ref_to_array
933 return \@borrowernumbers; # to not cause surprise to caller
936 # Borrowers part of the query
938 for (my $i = 0; $i < @borrowernumbers; $i++) {
939 $bquery .= ' issues.borrowernumber = ?';
940 if ($i < $#borrowernumbers ) {
945 # must avoid biblioitems.* to prevent large marc and marcxml fields from killing performance
946 # FIXME: namespace collision: each table has "timestamp" fields. Which one is "timestamp" ?
947 # FIXME: circ/ciculation.pl tries to sort by timestamp!
948 # FIXME: namespace collision: other collisions possible.
949 # FIXME: most of this data isn't really being used by callers.
956 biblioitems.itemtype,
959 biblioitems.publicationyear,
960 biblioitems.publishercode,
961 biblioitems.volumedate,
962 biblioitems.volumedesc,
967 borrowers.cardnumber,
968 issues.timestamp AS timestamp,
969 issues.renewals AS renewals,
970 issues.borrowernumber AS borrowernumber,
971 items.renewals AS totalrenewals
973 LEFT JOIN items ON items.itemnumber = issues.itemnumber
974 LEFT JOIN biblio ON items.biblionumber = biblio.biblionumber
975 LEFT JOIN biblioitems ON items.biblioitemnumber = biblioitems.biblioitemnumber
976 LEFT JOIN borrowers ON issues.borrowernumber = borrowers.borrowernumber
979 ORDER BY issues.issuedate"
982 my $sth = C4::Context->dbh->prepare($query);
983 $sth->execute(@borrowernumbers);
984 my $data = $sth->fetchall_arrayref({});
985 my $today = dt_from_string;
987 if ($_->{issuedate}) {
988 $_->{issuedate} = dt_from_string($_->{issuedate}, 'sql');
990 $_->{date_due_sql} = $_->{date_due};
991 # FIXME no need to have this value
992 $_->{date_due} or next;
993 $_->{date_due_sql} = $_->{date_due};
994 # FIXME no need to have this value
995 $_->{date_due} = dt_from_string($_->{date_due}, 'sql');
996 if ( DateTime->compare($_->{date_due}, $today) == -1 ) {
1005 $issues = &GetAllIssues($borrowernumber, $sortkey, $limit);
1007 Looks up what the patron with the given borrowernumber has borrowed,
1008 and sorts the results.
1010 C<$sortkey> is the name of a field on which to sort the results. This
1011 should be the name of a field in the C<issues>, C<biblio>,
1012 C<biblioitems>, or C<items> table in the Koha database.
1014 C<$limit> is the maximum number of results to return.
1016 C<&GetAllIssues> an arrayref, C<$issues>, of hashrefs, the keys of which
1017 are the fields from the C<issues>, C<biblio>, C<biblioitems>, and
1018 C<items> tables of the Koha database.
1024 my ( $borrowernumber, $order, $limit ) = @_;
1026 return unless $borrowernumber;
1027 $order = 'date_due desc' unless $order;
1029 my $dbh = C4::Context->dbh;
1031 'SELECT *, issues.timestamp as issuestimestamp, issues.renewals AS renewals,items.renewals AS totalrenewals,items.timestamp AS itemstimestamp
1033 LEFT JOIN items on items.itemnumber=issues.itemnumber
1034 LEFT JOIN biblio ON items.biblionumber=biblio.biblionumber
1035 LEFT JOIN biblioitems ON items.biblioitemnumber=biblioitems.biblioitemnumber
1036 WHERE borrowernumber=?
1038 SELECT *, old_issues.timestamp as issuestimestamp, old_issues.renewals AS renewals,items.renewals AS totalrenewals,items.timestamp AS itemstimestamp
1040 LEFT JOIN items on items.itemnumber=old_issues.itemnumber
1041 LEFT JOIN biblio ON items.biblionumber=biblio.biblionumber
1042 LEFT JOIN biblioitems ON items.biblioitemnumber=biblioitems.biblioitemnumber
1043 WHERE borrowernumber=? AND old_issues.itemnumber IS NOT NULL
1044 order by ' . $order;
1046 $query .= " limit $limit";
1049 my $sth = $dbh->prepare($query);
1050 $sth->execute( $borrowernumber, $borrowernumber );
1051 return $sth->fetchall_arrayref( {} );
1055 =head2 GetMemberAccountRecords
1057 ($total, $acctlines, $count) = &GetMemberAccountRecords($borrowernumber);
1059 Looks up accounting data for the patron with the given borrowernumber.
1061 C<&GetMemberAccountRecords> returns a three-element array. C<$acctlines> is a
1062 reference-to-array, where each element is a reference-to-hash; the
1063 keys are the fields of the C<accountlines> table in the Koha database.
1064 C<$count> is the number of elements in C<$acctlines>. C<$total> is the
1065 total amount outstanding for all of the account lines.
1069 sub GetMemberAccountRecords {
1070 my ($borrowernumber) = @_;
1071 my $dbh = C4::Context->dbh;
1077 WHERE borrowernumber=?);
1078 $strsth.=" ORDER BY accountlines_id desc";
1079 my $sth= $dbh->prepare( $strsth );
1080 $sth->execute( $borrowernumber );
1083 while ( my $data = $sth->fetchrow_hashref ) {
1084 if ( $data->{itemnumber} ) {
1085 my $biblio = GetBiblioFromItemNumber( $data->{itemnumber} );
1086 $data->{biblionumber} = $biblio->{biblionumber};
1087 $data->{title} = $biblio->{title};
1089 $acctlines[$numlines] = $data;
1091 $total += sprintf "%.0f", 1000*$data->{amountoutstanding}; # convert float to integer to avoid round-off errors
1094 return ( $total, \@acctlines,$numlines);
1097 =head2 GetMemberAccountBalance
1099 ($total_balance, $non_issue_balance, $other_charges) = &GetMemberAccountBalance($borrowernumber);
1101 Calculates amount immediately owing by the patron - non-issue charges.
1102 Based on GetMemberAccountRecords.
1103 Charges exempt from non-issue are:
1105 * Rent (rental) if RentalsInNoissuesCharge syspref is set to false
1106 * Manual invoices if ManInvInNoissuesCharge syspref is set to false
1110 sub GetMemberAccountBalance {
1111 my ($borrowernumber) = @_;
1113 my $ACCOUNT_TYPE_LENGTH = 5; # this is plain ridiculous...
1116 push @not_fines, 'Res' unless C4::Context->preference('HoldsInNoissuesCharge');
1117 push @not_fines, 'Rent' unless C4::Context->preference('RentalsInNoissuesCharge');
1118 unless ( C4::Context->preference('ManInvInNoissuesCharge') ) {
1119 my $dbh = C4::Context->dbh;
1120 my $man_inv_types = $dbh->selectcol_arrayref(qq{SELECT authorised_value FROM authorised_values WHERE category = 'MANUAL_INV'});
1121 push @not_fines, map substr($_, 0, $ACCOUNT_TYPE_LENGTH), @$man_inv_types;
1123 my %not_fine = map {$_ => 1} @not_fines;
1125 my ($total, $acctlines) = GetMemberAccountRecords($borrowernumber);
1126 my $other_charges = 0;
1127 foreach (@$acctlines) {
1128 $other_charges += $_->{amountoutstanding} if $not_fine{ substr($_->{accounttype}, 0, $ACCOUNT_TYPE_LENGTH) };
1131 return ( $total, $total - $other_charges, $other_charges);
1134 =head2 GetBorNotifyAcctRecord
1136 ($total, $acctlines, $count) = &GetBorNotifyAcctRecord($params,$notifyid);
1138 Looks up accounting data for the patron with the given borrowernumber per file number.
1140 C<&GetBorNotifyAcctRecord> returns a three-element array. C<$acctlines> is a
1141 reference-to-array, where each element is a reference-to-hash; the
1142 keys are the fields of the C<accountlines> table in the Koha database.
1143 C<$count> is the number of elements in C<$acctlines>. C<$total> is the
1144 total amount outstanding for all of the account lines.
1148 sub GetBorNotifyAcctRecord {
1149 my ( $borrowernumber, $notifyid ) = @_;
1150 my $dbh = C4::Context->dbh;
1153 my $sth = $dbh->prepare(
1156 WHERE borrowernumber=?
1158 AND amountoutstanding != '0'
1159 ORDER BY notify_id,accounttype
1162 $sth->execute( $borrowernumber, $notifyid );
1164 while ( my $data = $sth->fetchrow_hashref ) {
1165 if ( $data->{itemnumber} ) {
1166 my $biblio = GetBiblioFromItemNumber( $data->{itemnumber} );
1167 $data->{biblionumber} = $biblio->{biblionumber};
1168 $data->{title} = $biblio->{title};
1170 $acctlines[$numlines] = $data;
1172 $total += int(100 * $data->{'amountoutstanding'});
1175 return ( $total, \@acctlines, $numlines );
1178 =head2 checkuniquemember (OUEST-PROVENCE)
1180 ($result,$categorycode) = &checkuniquemember($collectivity,$surname,$firstname,$dateofbirth);
1182 Checks that a member exists or not in the database.
1184 C<&result> is nonzero (=exist) or 0 (=does not exist)
1185 C<&categorycode> is from categorycode table
1186 C<&collectivity> is 1 (= we add a collectivity) or 0 (= we add a physical member)
1187 C<&surname> is the surname
1188 C<&firstname> is the firstname (only if collectivity=0)
1189 C<&dateofbirth> is the date of birth in ISO format (only if collectivity=0)
1193 # FIXME: This function is not legitimate. Multiple patrons might have the same first/last name and birthdate.
1194 # This is especially true since first name is not even a required field.
1196 sub checkuniquemember {
1197 my ( $collectivity, $surname, $firstname, $dateofbirth ) = @_;
1198 my $dbh = C4::Context->dbh;
1199 my $request = ($collectivity) ?
1200 "SELECT borrowernumber,categorycode FROM borrowers WHERE surname=? " :
1202 "SELECT borrowernumber,categorycode FROM borrowers WHERE surname=? and firstname=? and dateofbirth=?" :
1203 "SELECT borrowernumber,categorycode FROM borrowers WHERE surname=? and firstname=?";
1204 my $sth = $dbh->prepare($request);
1205 if ($collectivity) {
1206 $sth->execute( uc($surname) );
1207 } elsif($dateofbirth){
1208 $sth->execute( uc($surname), ucfirst($firstname), $dateofbirth );
1210 $sth->execute( uc($surname), ucfirst($firstname));
1212 my @data = $sth->fetchrow;
1213 ( $data[0] ) and return $data[0], $data[1];
1217 sub checkcardnumber {
1218 my ( $cardnumber, $borrowernumber ) = @_;
1220 # If cardnumber is null, we assume they're allowed.
1221 return 0 unless defined $cardnumber;
1223 my $dbh = C4::Context->dbh;
1224 my $query = "SELECT * FROM borrowers WHERE cardnumber=?";
1225 $query .= " AND borrowernumber <> ?" if ($borrowernumber);
1226 my $sth = $dbh->prepare($query);
1229 ( $borrowernumber ? $borrowernumber : () )
1232 return 1 if $sth->fetchrow_hashref;
1234 my ( $min_length, $max_length ) = get_cardnumber_length();
1236 if length $cardnumber > $max_length
1237 or length $cardnumber < $min_length;
1242 =head2 get_cardnumber_length
1244 my ($min, $max) = C4::Members::get_cardnumber_length()
1246 Returns the minimum and maximum length for patron cardnumbers as
1247 determined by the CardnumberLength system preference, the
1248 BorrowerMandatoryField system preference, and the width of the
1253 sub get_cardnumber_length {
1254 my ( $min, $max ) = ( 0, 16 ); # borrowers.cardnumber is a nullable varchar(16)
1255 $min = 1 if C4::Context->preference('BorrowerMandatoryField') =~ /cardnumber/;
1256 if ( my $cardnumber_length = C4::Context->preference('CardnumberLength') ) {
1257 # Is integer and length match
1258 if ( $cardnumber_length =~ m|^\d+$| ) {
1259 $min = $max = $cardnumber_length
1260 if $cardnumber_length >= $min
1261 and $cardnumber_length <= $max;
1263 # Else assuming it is a range
1264 elsif ( $cardnumber_length =~ m|(\d*),(\d*)| ) {
1265 $min = $1 if $1 and $min < $1;
1266 $max = $2 if $2 and $max > $2;
1270 return ( $min, $max );
1273 =head2 GetFirstValidEmailAddress
1275 $email = GetFirstValidEmailAddress($borrowernumber);
1277 Return the first valid email address for a borrower, given the borrowernumber. For now, the order
1278 is defined as email, emailpro, B_email. Returns the empty string if the borrower has no email
1283 sub GetFirstValidEmailAddress {
1284 my $borrowernumber = shift;
1285 my $dbh = C4::Context->dbh;
1286 my $sth = $dbh->prepare( "SELECT email, emailpro, B_email FROM borrowers where borrowernumber = ? ");
1287 $sth->execute( $borrowernumber );
1288 my $data = $sth->fetchrow_hashref;
1290 if ($data->{'email'}) {
1291 return $data->{'email'};
1292 } elsif ($data->{'emailpro'}) {
1293 return $data->{'emailpro'};
1294 } elsif ($data->{'B_email'}) {
1295 return $data->{'B_email'};
1301 =head2 GetNoticeEmailAddress
1303 $email = GetNoticeEmailAddress($borrowernumber);
1305 Return the email address of borrower used for notices, given the borrowernumber.
1306 Returns the empty string if no email address.
1310 sub GetNoticeEmailAddress {
1311 my $borrowernumber = shift;
1313 my $which_address = C4::Context->preference("AutoEmailPrimaryAddress");
1314 # if syspref is set to 'first valid' (value == OFF), look up email address
1315 if ( $which_address eq 'OFF' ) {
1316 return GetFirstValidEmailAddress($borrowernumber);
1318 # specified email address field
1319 my $dbh = C4::Context->dbh;
1320 my $sth = $dbh->prepare( qq{
1321 SELECT $which_address AS primaryemail
1323 WHERE borrowernumber=?
1325 $sth->execute($borrowernumber);
1326 my $data = $sth->fetchrow_hashref;
1327 return $data->{'primaryemail'} || '';
1330 =head2 GetExpiryDate
1332 $expirydate = GetExpiryDate($categorycode, $dateenrolled);
1334 Calculate expiry date given a categorycode and starting date. Date argument must be in ISO format.
1335 Return date is also in ISO format.
1340 my ( $categorycode, $dateenrolled ) = @_;
1342 if ($categorycode) {
1343 my $dbh = C4::Context->dbh;
1344 my $sth = $dbh->prepare("SELECT enrolmentperiod,enrolmentperioddate FROM categories WHERE categorycode=?");
1345 $sth->execute($categorycode);
1346 $enrolments = $sth->fetchrow_hashref;
1348 # die "GetExpiryDate: for enrollmentperiod $enrolmentperiod (category '$categorycode') starting $dateenrolled.\n";
1349 my @date = split (/-/,$dateenrolled);
1350 if($enrolments->{enrolmentperiod}){
1351 return sprintf("%04d-%02d-%02d", Add_Delta_YM(@date,0,$enrolments->{enrolmentperiod}));
1353 return $enrolments->{enrolmentperioddate};
1357 =head2 GetUpcomingMembershipExpires
1359 my $expires = GetUpcomingMembershipExpires({
1360 branch => $branch, before => $before, after => $after,
1363 $branch is an optional branch code.
1364 $before/$after is an optional number of days before/after the date that
1365 is set by the preference MembershipExpiryDaysNotice.
1366 If the pref would be 14, before 2 and after 3, you will get all expires
1371 sub GetUpcomingMembershipExpires {
1372 my ( $params ) = @_;
1373 my $before = $params->{before} || 0;
1374 my $after = $params->{after} || 0;
1375 my $branch = $params->{branch};
1377 my $dbh = C4::Context->dbh;
1378 my $days = C4::Context->preference("MembershipExpiryDaysNotice") || 0;
1379 my $date1 = dt_from_string->add( days => $days - $before );
1380 my $date2 = dt_from_string->add( days => $days + $after );
1381 $date1= output_pref({ dt => $date1, dateformat => 'iso', dateonly => 1 });
1382 $date2= output_pref({ dt => $date2, dateformat => 'iso', dateonly => 1 });
1385 SELECT borrowers.*, categories.description,
1386 branches.branchname, branches.branchemail FROM borrowers
1387 LEFT JOIN branches USING (branchcode)
1388 LEFT JOIN categories USING (categorycode)
1391 $query.= 'WHERE branchcode=? AND dateexpiry BETWEEN ? AND ?';
1393 $query.= 'WHERE dateexpiry BETWEEN ? AND ?';
1396 my $sth = $dbh->prepare( $query );
1397 my @pars = $branch? ( $branch ): ();
1398 push @pars, $date1, $date2;
1399 $sth->execute( @pars );
1400 my $results = $sth->fetchall_arrayref( {} );
1404 =head2 GetborCatFromCatType
1406 ($codes_arrayref, $labels_hashref) = &GetborCatFromCatType();
1408 Looks up the different types of borrowers in the database. Returns two
1409 elements: a reference-to-array, which lists the borrower category
1410 codes, and a reference-to-hash, which maps the borrower category codes
1411 to category descriptions.
1416 sub GetborCatFromCatType {
1417 my ( $category_type, $action, $no_branch_limit ) = @_;
1419 my $branch_limit = $no_branch_limit
1421 : C4::Context->userenv ? C4::Context->userenv->{"branch"} : "";
1423 # FIXME - This API seems both limited and dangerous.
1424 my $dbh = C4::Context->dbh;
1427 SELECT categories.categorycode, categories.description
1431 LEFT JOIN categories_branches ON categories.categorycode = categories_branches.categorycode
1434 $request .= " $action ";
1435 $request .= " AND (branchcode = ? OR branchcode IS NULL) GROUP BY description" if $branch_limit;
1437 $request .= " WHERE branchcode = ? OR branchcode IS NULL GROUP BY description" if $branch_limit;
1439 $request .= " ORDER BY categorycode";
1441 my $sth = $dbh->prepare($request);
1443 $action ? $category_type : (),
1444 $branch_limit ? $branch_limit : ()
1450 while ( my $data = $sth->fetchrow_hashref ) {
1451 push @codes, $data->{'categorycode'};
1452 $labels{ $data->{'categorycode'} } = $data->{'description'};
1455 return ( \@codes, \%labels );
1458 =head2 GetBorrowercategory
1460 $hashref = &GetBorrowercategory($categorycode);
1462 Given the borrower's category code, the function returns the corresponding
1463 data hashref for a comprehensive information display.
1467 sub GetBorrowercategory {
1469 my $dbh = C4::Context->dbh;
1473 "SELECT description,dateofbirthrequired,upperagelimit,category_type
1475 WHERE categorycode = ?"
1477 $sth->execute($catcode);
1479 $sth->fetchrow_hashref;
1483 } # sub getborrowercategory
1486 =head2 GetBorrowerCategorycode
1488 $categorycode = &GetBorrowerCategoryCode( $borrowernumber );
1490 Given the borrowernumber, the function returns the corresponding categorycode
1494 sub GetBorrowerCategorycode {
1495 my ( $borrowernumber ) = @_;
1496 my $dbh = C4::Context->dbh;
1497 my $sth = $dbh->prepare( qq{
1500 WHERE borrowernumber = ?
1502 $sth->execute( $borrowernumber );
1503 return $sth->fetchrow;
1506 =head2 GetBorrowercategoryList
1508 $arrayref_hashref = &GetBorrowercategoryList;
1509 If no category code provided, the function returns all the categories.
1513 sub GetBorrowercategoryList {
1514 my $no_branch_limit = @_ ? shift : 0;
1515 my $branch_limit = $no_branch_limit
1517 : C4::Context->userenv ? C4::Context->userenv->{"branch"} : "";
1518 my $dbh = C4::Context->dbh;
1519 my $query = "SELECT categories.* FROM categories";
1521 LEFT JOIN categories_branches ON categories.categorycode = categories_branches.categorycode
1522 WHERE branchcode = ? OR branchcode IS NULL GROUP BY description
1524 $query .= " ORDER BY description";
1525 my $sth = $dbh->prepare( $query );
1526 $sth->execute( $branch_limit ? $branch_limit : () );
1527 my $data = $sth->fetchall_arrayref( {} );
1530 } # sub getborrowercategory
1534 $dateofbirth,$date = &GetAge($date);
1536 this function return the borrowers age with the value of dateofbirth
1542 my ( $date, $date_ref ) = @_;
1544 if ( not defined $date_ref ) {
1545 $date_ref = sprintf( '%04d-%02d-%02d', Today() );
1548 my ( $year1, $month1, $day1 ) = split /-/, $date;
1549 my ( $year2, $month2, $day2 ) = split /-/, $date_ref;
1551 my $age = $year2 - $year1;
1552 if ( $month1 . $day1 > $month2 . $day2 ) {
1561 $borrower = C4::Members::SetAge($borrower, $datetimeduration);
1562 $borrower = C4::Members::SetAge($borrower, '0015-12-10');
1563 $borrower = C4::Members::SetAge($borrower, $datetimeduration, $datetime_reference);
1565 eval { $borrower = C4::Members::SetAge($borrower, '015-1-10'); };
1566 if ($@) {print $@;} #Catch a bad ISO Date or kill your script!
1568 This function sets the borrower's dateofbirth to match the given age.
1569 Optionally relative to the given $datetime_reference.
1571 @PARAM1 koha.borrowers-object
1572 @PARAM2 DateTime::Duration-object as the desired age
1573 OR a ISO 8601 Date. (To make the API more pleasant)
1574 @PARAM3 DateTime-object as the relative date, defaults to now().
1575 RETURNS The given borrower reference @PARAM1.
1576 DIES If there was an error with the ISO Date handling.
1582 my ( $borrower, $datetimeduration, $datetime_ref ) = @_;
1583 $datetime_ref = DateTime->now() unless $datetime_ref;
1585 if ($datetimeduration && ref $datetimeduration ne 'DateTime::Duration') {
1586 if ($datetimeduration =~ /^(\d{4})-(\d{2})-(\d{2})/) {
1587 $datetimeduration = DateTime::Duration->new(years => $1, months => $2, days => $3);
1590 die "C4::Members::SetAge($borrower, $datetimeduration), datetimeduration not a valid ISO 8601 Date!\n";
1594 my $new_datetime_ref = $datetime_ref->clone();
1595 $new_datetime_ref->subtract_duration( $datetimeduration );
1597 $borrower->{dateofbirth} = $new_datetime_ref->ymd();
1602 =head2 GetSortDetails (OUEST-PROVENCE)
1604 ($lib) = &GetSortDetails($category,$sortvalue);
1606 Returns the authorized value details
1607 C<&$lib>return value of authorized value details
1608 C<&$sortvalue>this is the value of authorized value
1609 C<&$category>this is the value of authorized value category
1613 sub GetSortDetails {
1614 my ( $category, $sortvalue ) = @_;
1615 my $dbh = C4::Context->dbh;
1616 my $query = qq|SELECT lib
1617 FROM authorised_values
1619 AND authorised_value=? |;
1620 my $sth = $dbh->prepare($query);
1621 $sth->execute( $category, $sortvalue );
1622 my $lib = $sth->fetchrow;
1623 return ($lib) if ($lib);
1624 return ($sortvalue) unless ($lib);
1627 =head2 MoveMemberToDeleted
1629 $result = &MoveMemberToDeleted($borrowernumber);
1631 Copy the record from borrowers to deletedborrowers table.
1632 The routine returns 1 for success, undef for failure.
1636 sub MoveMemberToDeleted {
1637 my ($member) = shift or return;
1639 my $schema = Koha::Database->new()->schema();
1640 my $borrowers_rs = $schema->resultset('Borrower');
1641 $borrowers_rs->result_class('DBIx::Class::ResultClass::HashRefInflator');
1642 my $borrower = $borrowers_rs->find($member);
1643 return unless $borrower;
1645 my $deleted = $schema->resultset('Deletedborrower')->create($borrower);
1647 return $deleted ? 1 : undef;
1652 DelMember($borrowernumber);
1654 This function remove directly a borrower whitout writing it on deleteborrower.
1655 + Deletes reserves for the borrower
1660 my $dbh = C4::Context->dbh;
1661 my $borrowernumber = shift;
1662 #warn "in delmember with $borrowernumber";
1663 return unless $borrowernumber; # borrowernumber is mandatory.
1664 # Delete Patron's holds
1665 my @holds = Koha::Holds->search({ borrowernumber => $borrowernumber });
1666 $_->delete for @holds;
1671 WHERE borrowernumber = ?
1673 my $sth = $dbh->prepare($query);
1674 $sth->execute($borrowernumber);
1675 logaction("MEMBERS", "DELETE", $borrowernumber, "") if C4::Context->preference("BorrowersLog");
1679 =head2 HandleDelBorrower
1681 HandleDelBorrower($borrower);
1683 When a member is deleted (DelMember in Members.pm), you should call me first.
1684 This routine deletes/moves lists and entries for the deleted member/borrower.
1685 Lists owned by the borrower are deleted, but entries from the borrower to
1686 other lists are kept.
1690 sub HandleDelBorrower {
1693 my $dbh = C4::Context->dbh;
1695 #Delete all lists and all shares of this borrower
1696 #Consistent with the approach Koha uses on deleting individual lists
1697 #Note that entries in virtualshelfcontents added by this borrower to
1698 #lists of others will be handled by a table constraint: the borrower
1699 #is set to NULL in those entries.
1700 $query="DELETE FROM virtualshelves WHERE owner=?";
1701 $dbh->do($query,undef,($borrower));
1704 #We could handle the above deletes via a constraint too.
1705 #But a new BZ report 11889 has been opened to discuss another approach.
1706 #Instead of deleting we could also disown lists (based on a pref).
1707 #In that way we could save shared and public lists.
1708 #The current table constraints support that idea now.
1709 #This pref should then govern the results of other routines/methods such as
1710 #Koha::Virtualshelf->new->delete too.
1713 =head2 ExtendMemberSubscriptionTo (OUEST-PROVENCE)
1715 $date = ExtendMemberSubscriptionTo($borrowerid, $date);
1717 Extending the subscription to a given date or to the expiry date calculated on ISO date.
1722 sub ExtendMemberSubscriptionTo {
1723 my ( $borrowerid,$date) = @_;
1724 my $dbh = C4::Context->dbh;
1725 my $borrower = GetMember('borrowernumber'=>$borrowerid);
1727 $date = (C4::Context->preference('BorrowerRenewalPeriodBase') eq 'dateexpiry') ?
1728 eval { output_pref( { dt => dt_from_string( $borrower->{'dateexpiry'} ), dateonly => 1, dateformat => 'iso' } ); }
1730 output_pref( { dt => dt_from_string, dateonly => 1, dateformat => 'iso' } );
1731 $date = GetExpiryDate( $borrower->{'categorycode'}, $date );
1733 my $sth = $dbh->do(<<EOF);
1735 SET dateexpiry='$date'
1736 WHERE borrowernumber='$borrowerid'
1739 AddEnrolmentFeeIfNeeded( $borrower->{categorycode}, $borrower->{borrowernumber} );
1741 logaction("MEMBERS", "RENEW", $borrower->{'borrowernumber'}, "Membership renewed")if C4::Context->preference("BorrowersLog");
1742 return $date if ($sth);
1746 =head2 GetTitles (OUEST-PROVENCE)
1748 ($borrowertitle)= &GetTitles();
1750 Looks up the different title . Returns array with all borrowers title
1755 my @borrowerTitle = split (/,|\|/,C4::Context->preference('BorrowersTitles'));
1756 unshift( @borrowerTitle, "" );
1757 my $count=@borrowerTitle;
1762 return ( \@borrowerTitle);
1766 =head2 GetHideLostItemsPreference
1768 $hidelostitemspref = &GetHideLostItemsPreference($borrowernumber);
1770 Returns the HideLostItems preference for the patron category of the supplied borrowernumber
1771 C<&$hidelostitemspref>return value of function, 0 or 1
1775 sub GetHideLostItemsPreference {
1776 my ($borrowernumber) = @_;
1777 my $dbh = C4::Context->dbh;
1778 my $query = "SELECT hidelostitems FROM borrowers,categories WHERE borrowers.categorycode = categories.categorycode AND borrowernumber = ?";
1779 my $sth = $dbh->prepare($query);
1780 $sth->execute($borrowernumber);
1781 my $hidelostitems = $sth->fetchrow;
1782 return $hidelostitems;
1785 =head2 GetBorrowersToExpunge
1787 $borrowers = &GetBorrowersToExpunge(
1788 not_borrowed_since => $not_borrowed_since,
1789 expired_before => $expired_before,
1790 category_code => $category_code,
1791 patron_list_id => $patron_list_id,
1792 branchcode => $branchcode
1795 This function get all borrowers based on the given criteria.
1799 sub GetBorrowersToExpunge {
1802 my $filterdate = $params->{'not_borrowed_since'};
1803 my $filterexpiry = $params->{'expired_before'};
1804 my $filtercategory = $params->{'category_code'};
1805 my $filterbranch = $params->{'branchcode'} ||
1806 ((C4::Context->preference('IndependentBranches')
1807 && C4::Context->userenv
1808 && !C4::Context->IsSuperLibrarian()
1809 && C4::Context->userenv->{branch})
1810 ? C4::Context->userenv->{branch}
1812 my $filterpatronlist = $params->{'patron_list_id'};
1814 my $dbh = C4::Context->dbh;
1816 SELECT borrowers.borrowernumber,
1817 MAX(old_issues.timestamp) AS latestissue,
1818 MAX(issues.timestamp) AS currentissue
1820 JOIN categories USING (categorycode)
1824 WHERE guarantorid IS NOT NULL
1825 AND guarantorid <> 0
1826 ) as tmp ON borrowers.borrowernumber=tmp.guarantorid
1827 LEFT JOIN old_issues USING (borrowernumber)
1828 LEFT JOIN issues USING (borrowernumber)|;
1829 if ( $filterpatronlist ){
1830 $query .= q| LEFT JOIN patron_list_patrons USING (borrowernumber)|;
1832 $query .= q| WHERE category_type <> 'S'
1833 AND tmp.guarantorid IS NULL
1836 if ( $filterbranch && $filterbranch ne "" ) {
1837 $query.= " AND borrowers.branchcode = ? ";
1838 push( @query_params, $filterbranch );
1840 if ( $filterexpiry ) {
1841 $query .= " AND dateexpiry < ? ";
1842 push( @query_params, $filterexpiry );
1844 if ( $filtercategory ) {
1845 $query .= " AND categorycode = ? ";
1846 push( @query_params, $filtercategory );
1848 if ( $filterpatronlist ){
1849 $query.=" AND patron_list_id = ? ";
1850 push( @query_params, $filterpatronlist );
1852 $query.=" GROUP BY borrowers.borrowernumber HAVING currentissue IS NULL ";
1853 if ( $filterdate ) {
1854 $query.=" AND ( latestissue < ? OR latestissue IS NULL ) ";
1855 push @query_params,$filterdate;
1857 warn $query if $debug;
1859 my $sth = $dbh->prepare($query);
1860 if (scalar(@query_params)>0){
1861 $sth->execute(@query_params);
1868 while ( my $data = $sth->fetchrow_hashref ) {
1869 push @results, $data;
1874 =head2 GetBorrowersWhoHaveNeverBorrowed
1876 $results = &GetBorrowersWhoHaveNeverBorrowed
1878 This function get all borrowers who have never borrowed.
1880 I<$result> is a ref to an array which all elements are a hasref.
1884 sub GetBorrowersWhoHaveNeverBorrowed {
1885 my $filterbranch = shift ||
1886 ((C4::Context->preference('IndependentBranches')
1887 && C4::Context->userenv
1888 && !C4::Context->IsSuperLibrarian()
1889 && C4::Context->userenv->{branch})
1890 ? C4::Context->userenv->{branch}
1892 my $dbh = C4::Context->dbh;
1894 SELECT borrowers.borrowernumber,max(timestamp) as latestissue
1896 LEFT JOIN issues ON borrowers.borrowernumber = issues.borrowernumber
1897 WHERE issues.borrowernumber IS NULL
1900 if ($filterbranch && $filterbranch ne ""){
1901 $query.=" AND borrowers.branchcode= ?";
1902 push @query_params,$filterbranch;
1904 warn $query if $debug;
1906 my $sth = $dbh->prepare($query);
1907 if (scalar(@query_params)>0){
1908 $sth->execute(@query_params);
1915 while ( my $data = $sth->fetchrow_hashref ) {
1916 push @results, $data;
1921 =head2 GetBorrowersWithIssuesHistoryOlderThan
1923 $results = &GetBorrowersWithIssuesHistoryOlderThan($date)
1925 this function get all borrowers who has an issue history older than I<$date> given on input arg.
1927 I<$result> is a ref to an array which all elements are a hashref.
1928 This hashref is containt the number of time this borrowers has borrowed before I<$date> and the borrowernumber.
1932 sub GetBorrowersWithIssuesHistoryOlderThan {
1933 my $dbh = C4::Context->dbh;
1934 my $date = shift ||POSIX::strftime("%Y-%m-%d",localtime());
1935 my $filterbranch = shift ||
1936 ((C4::Context->preference('IndependentBranches')
1937 && C4::Context->userenv
1938 && !C4::Context->IsSuperLibrarian()
1939 && C4::Context->userenv->{branch})
1940 ? C4::Context->userenv->{branch}
1943 SELECT count(borrowernumber) as n,borrowernumber
1945 WHERE returndate < ?
1946 AND borrowernumber IS NOT NULL
1949 push @query_params, $date;
1951 $query.=" AND branchcode = ?";
1952 push @query_params, $filterbranch;
1954 $query.=" GROUP BY borrowernumber ";
1955 warn $query if $debug;
1956 my $sth = $dbh->prepare($query);
1957 $sth->execute(@query_params);
1960 while ( my $data = $sth->fetchrow_hashref ) {
1961 push @results, $data;
1966 =head2 GetBorrowersNamesAndLatestIssue
1968 $results = &GetBorrowersNamesAndLatestIssueList(@borrowernumbers)
1970 this function get borrowers Names and surnames and Issue information.
1972 I<@borrowernumbers> is an array which all elements are borrowernumbers.
1973 This hashref is containt the number of time this borrowers has borrowed before I<$date> and the borrowernumber.
1977 sub GetBorrowersNamesAndLatestIssue {
1978 my $dbh = C4::Context->dbh;
1979 my @borrowernumbers=@_;
1981 SELECT surname,lastname, phone, email,max(timestamp)
1983 LEFT JOIN issues ON borrowers.borrowernumber=issues.borrowernumber
1984 GROUP BY borrowernumber
1986 my $sth = $dbh->prepare($query);
1988 my $results = $sth->fetchall_arrayref({});
1994 my $success = ModPrivacy( $borrowernumber, $privacy );
1996 Update the privacy of a patron.
1999 true on success, false on failure
2004 my $borrowernumber = shift;
2005 my $privacy = shift;
2006 return unless defined $borrowernumber;
2007 return unless $borrowernumber =~ /^\d+$/;
2009 return ModMember( borrowernumber => $borrowernumber,
2010 privacy => $privacy );
2015 IssueSlip($branchcode, $borrowernumber, $quickslip)
2017 Returns letter hash ( see C4::Letters::GetPreparedLetter )
2019 $quickslip is boolean, to indicate whether we want a quick slip
2021 IssueSlip populates ISSUESLIP and ISSUEQSLIP, and will make the following expansions:
2057 NOTE: Not all table fields are available, pleasee see GetPendingIssues for a list of available fields.
2062 my ($branch, $borrowernumber, $quickslip) = @_;
2064 # FIXME Check callers before removing this statement
2065 #return unless $borrowernumber;
2067 my @issues = @{ GetPendingIssues($borrowernumber) };
2069 for my $issue (@issues) {
2070 $issue->{date_due} = $issue->{date_due_sql};
2072 my $today = output_pref({ dt => dt_from_string, dateformat => 'iso', dateonly => 1 });
2073 if ( substr( $issue->{issuedate}, 0, 10 ) eq $today
2074 or substr( $issue->{lastreneweddate}, 0, 10 ) eq $today ) {
2080 # Sort on timestamp then on issuedate (useful for tests and could be if modified in a batch
2082 my $s = $b->{timestamp} <=> $a->{timestamp};
2084 $b->{issuedate} <=> $a->{issuedate} : $s;
2087 my ($letter_code, %repeat);
2089 $letter_code = 'ISSUEQSLIP';
2091 'checkedout' => [ map {
2094 'biblioitems' => $_,
2096 }, grep { $_->{'now'} } @issues ],
2100 $letter_code = 'ISSUESLIP';
2102 'checkedout' => [ map {
2105 'biblioitems' => $_,
2107 }, grep { !$_->{'overdue'} } @issues ],
2109 'overdue' => [ map {
2112 'biblioitems' => $_,
2114 }, grep { $_->{'overdue'} } @issues ],
2117 $_->{'timestamp'} = $_->{'newdate'};
2119 } @{ GetNewsToDisplay("slip",$branch) } ],
2123 return C4::Letters::GetPreparedLetter (
2124 module => 'circulation',
2125 letter_code => $letter_code,
2126 branchcode => $branch,
2128 'branches' => $branch,
2129 'borrowers' => $borrowernumber,
2135 =head2 GetBorrowersWithEmail
2137 ([$borrnum,$userid], ...) = GetBorrowersWithEmail('me@example.com');
2139 This gets a list of users and their basic details from their email address.
2140 As it's possible for multiple user to have the same email address, it provides
2141 you with all of them. If there is no userid for the user, there will be an
2142 C<undef> there. An empty list will be returned if there are no matches.
2146 sub GetBorrowersWithEmail {
2149 my $dbh = C4::Context->dbh;
2151 my $query = "SELECT borrowernumber, userid FROM borrowers WHERE email=?";
2152 my $sth=$dbh->prepare($query);
2153 $sth->execute($email);
2155 while (my $ref = $sth->fetch) {
2158 die "Failure searching for borrowers by email address: $sth->errstr" if $sth->err;
2162 =head2 AddMember_Opac
2166 sub AddMember_Opac {
2167 my ( %borrower ) = @_;
2169 $borrower{'categorycode'} //= C4::Context->preference('PatronSelfRegistrationDefaultCategory');
2170 if (not defined $borrower{'password'}){
2171 my $sr = new String::Random;
2172 $sr->{'A'} = [ 'A'..'Z', 'a'..'z' ];
2173 my $password = $sr->randpattern("AAAAAAAAAA");
2174 $borrower{'password'} = $password;
2177 $borrower{'cardnumber'} = fixup_cardnumber( $borrower{'cardnumber'} );
2179 my $borrowernumber = AddMember(%borrower);
2181 return ( $borrowernumber, $borrower{'password'} );
2184 =head2 AddEnrolmentFeeIfNeeded
2186 AddEnrolmentFeeIfNeeded( $borrower->{categorycode}, $borrower->{borrowernumber} );
2188 Add enrolment fee for a patron if needed.
2192 sub AddEnrolmentFeeIfNeeded {
2193 my ( $categorycode, $borrowernumber ) = @_;
2194 # check for enrollment fee & add it if needed
2195 my $dbh = C4::Context->dbh;
2196 my $sth = $dbh->prepare(q{
2199 WHERE categorycode=?
2201 $sth->execute( $categorycode );
2203 warn sprintf('Database returned the following error: %s', $sth->errstr);
2206 my ($enrolmentfee) = $sth->fetchrow;
2207 if ($enrolmentfee && $enrolmentfee > 0) {
2208 # insert fee in patron debts
2209 C4::Accounts::manualinvoice( $borrowernumber, '', '', 'A', $enrolmentfee );
2218 my ( $borrowernumber ) = @_;
2220 my $sql = "SELECT COUNT(*) FROM issues WHERE date_due < NOW() AND borrowernumber = ?";
2221 my $sth = C4::Context->dbh->prepare( $sql );
2222 $sth->execute( $borrowernumber );
2223 my ( $count ) = $sth->fetchrow_array();
2228 =head2 DeleteExpiredOpacRegistrations
2230 Delete accounts that haven't been upgraded from the 'temporary' category
2231 Returns the number of removed patrons
2235 sub DeleteExpiredOpacRegistrations {
2237 my $delay = C4::Context->preference('PatronSelfRegistrationExpireTemporaryAccountsDelay');
2238 my $category_code = C4::Context->preference('PatronSelfRegistrationDefaultCategory');
2240 return 0 if not $category_code or not defined $delay or $delay eq q||;
2243 SELECT borrowernumber
2245 WHERE categorycode = ? AND DATEDIFF( NOW(), dateenrolled ) > ? |;
2247 my $dbh = C4::Context->dbh;
2248 my $sth = $dbh->prepare($query);
2249 $sth->execute( $category_code, $delay );
2251 while ( my ($borrowernumber) = $sth->fetchrow_array() ) {
2252 DelMember($borrowernumber);
2258 =head2 DeleteUnverifiedOpacRegistrations
2260 Delete all unverified self registrations in borrower_modifications,
2261 older than the specified number of days.
2265 sub DeleteUnverifiedOpacRegistrations {
2267 my $dbh = C4::Context->dbh;
2269 DELETE FROM borrower_modifications
2270 WHERE borrowernumber = 0 AND DATEDIFF( NOW(), timestamp ) > ?|;
2271 my $cnt=$dbh->do($sql, undef, ($days) );
2272 return $cnt eq '0E0'? 0: $cnt;
2275 sub GetOverduesForPatron {
2276 my ( $borrowernumber ) = @_;
2280 FROM issues, items, biblio, biblioitems
2281 WHERE items.itemnumber=issues.itemnumber
2282 AND biblio.biblionumber = items.biblionumber
2283 AND biblio.biblionumber = biblioitems.biblionumber
2284 AND issues.borrowernumber = ?
2285 AND date_due < NOW()
2288 my $sth = C4::Context->dbh->prepare( $sql );
2289 $sth->execute( $borrowernumber );
2291 return $sth->fetchall_arrayref({});
2294 END { } # module clean-up code here (global destructor)