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 under the
10 # terms of the GNU General Public License as published by the Free Software
11 # Foundation; either version 2 of the License, or (at your option) any later
14 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
15 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
16 # A PARTICULAR PURPOSE. See the GNU General Public License for more details.
18 # You should have received a copy of the GNU General Public License along
19 # with Koha; if not, write to the Free Software Foundation, Inc.,
20 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
24 #use warnings; FIXME - Bug 2505
26 use C4::Dates qw(format_date_in_iso format_date);
27 use String::Random qw( random_string );
28 use Date::Calc qw/Today Add_Delta_YM check_date Date_to_Days/;
29 use C4::Log; # logaction
35 use C4::SQLHelper qw(InsertInTable UpdateInTable SearchInTable);
36 use C4::Members::Attributes qw(SearchIdMatchingAttribute UpdateBorrowerAttribute);
37 use C4::NewsChannels; #get slip news
39 use DateTime::Format::DateParse;
42 use Koha::Borrower::Debarments qw(IsDebarred);
43 use Text::Unaccent qw( unac_string );
44 use Koha::AuthUtils qw(hash_password);
47 if ( C4::Context->preference('NorwegianPatronDBEnable') == 1 ) {
48 load Koha::NorwegianPatronDB, qw( NLUpdateHashedPIN NLEncryptPIN NLSync );
51 our ($VERSION,@ISA,@EXPORT,@EXPORT_OK,$debug);
54 $VERSION = 3.07.00.049;
55 $debug = $ENV{DEBUG} || 0;
67 &GetMemberIssuesAndFines
74 &GetFirstValidEmailAddress
75 &GetNoticeEmailAddress
86 &GetHideLostItemsPreference
89 &GetMemberAccountRecords
90 &GetBorNotifyAcctRecord
94 GetBorrowerCategorycode
95 &GetBorrowercategoryList
97 &GetBorrowersToExpunge
98 &GetBorrowersWhoHaveNeverBorrowed
99 &GetBorrowersWithIssuesHistoryOlderThan
109 GetBorrowersWithEmail
131 &ExtendMemberSubscriptionTo
149 C4::Members - Perl Module containing convenience functions for member handling
157 This module contains routines for adding, modifying and deleting members/patrons/borrowers
163 $borrowers_result_array_ref = &Search($filter,$orderby, $limit,
164 $columns_out, $search_on_fields,$searchtype);
166 Looks up patrons (borrowers) on filter. A wrapper for SearchInTable('borrowers').
168 For C<$filter>, C<$orderby>, C<$limit>, C<&columns_out>, C<&search_on_fields> and C<&searchtype>
169 refer to C4::SQLHelper:SearchInTable().
171 Special C<$filter> key '' is effectively expanded to search on surname firstname othernamescw
172 and cardnumber unless C<&search_on_fields> is defined
176 $borrowers = Search('abcd', 'cardnumber');
178 $borrowers = Search({''=>'abcd', category_type=>'I'}, 'surname');
182 sub _express_member_find {
185 # this is used by circulation everytime a new borrowers cardnumber is scanned
186 # so we can check an exact match first, if that works return, otherwise do the rest
187 my $dbh = C4::Context->dbh;
188 my $query = "SELECT borrowernumber FROM borrowers WHERE cardnumber = ?";
189 if ( my $borrowernumber = $dbh->selectrow_array($query, undef, $filter) ) {
190 return( {"borrowernumber"=>$borrowernumber} );
193 my ($search_on_fields, $searchtype);
194 if ( length($filter) == 1 ) {
195 $search_on_fields = [ qw(surname) ];
196 $searchtype = 'start_with';
198 $search_on_fields = [ qw(surname firstname othernames cardnumber) ];
199 $searchtype = 'contain';
202 return (undef, $search_on_fields, $searchtype);
206 my ( $filter, $orderby, $limit, $columns_out, $search_on_fields, $searchtype ) = @_;
211 if ( my $fr = ref $filter ) {
212 if ( $fr eq "HASH" ) {
213 if ( my $search_string = $filter->{''} ) {
214 my ($member_filter, $member_search_on_fields, $member_searchtype) = _express_member_find($search_string);
215 if ($member_filter) {
216 $filter = $member_filter;
219 $search_on_fields ||= $member_search_on_fields;
220 $searchtype ||= $member_searchtype;
225 $search_string = $filter;
229 $search_string = $filter;
230 my ($member_filter, $member_search_on_fields, $member_searchtype) = _express_member_find($search_string);
231 if ($member_filter) {
232 $filter = $member_filter;
235 $search_on_fields ||= $member_search_on_fields;
236 $searchtype ||= $member_searchtype;
240 if ( !$found_borrower && C4::Context->preference('ExtendedPatronAttributes') && $search_string ) {
241 my $matching_records = C4::Members::Attributes::SearchIdMatchingAttribute($search_string);
242 if(scalar(@$matching_records)>0) {
243 if ( my $fr = ref $filter ) {
244 if ( $fr eq "HASH" ) {
246 $filter = [ $filter ];
248 push @$filter, { %f, "borrowernumber"=>$$matching_records };
251 push @$filter, {"borrowernumber"=>$matching_records};
255 $filter = [ $filter ];
256 push @$filter, {"borrowernumber"=>$matching_records};
261 # $showallbranches was not used at the time SearchMember() was mainstreamed into Search().
262 # Mentioning for the reference
264 if ( C4::Context->preference("IndependentBranches") ) { # && !$showallbranches){
265 if ( my $userenv = C4::Context->userenv ) {
266 my $branch = $userenv->{'branch'};
267 if ( !C4::Context->IsSuperLibrarian() && $branch ){
268 if (my $fr = ref $filter) {
269 if ( $fr eq "HASH" ) {
270 $filter->{branchcode} = $branch;
274 $_ = { '' => $_ } unless ref $_;
275 $_->{branchcode} = $branch;
280 $filter = { '' => $filter, branchcode => $branch };
286 if ($found_borrower) {
287 $searchtype = "exact";
289 $searchtype ||= "start_with";
291 return SearchInTable( "borrowers", $filter, $orderby, $limit, $columns_out, $search_on_fields, $searchtype );
294 =head2 GetMemberDetails
296 ($borrower) = &GetMemberDetails($borrowernumber, $cardnumber);
298 Looks up a patron and returns information about him or her. If
299 C<$borrowernumber> is true (nonzero), C<&GetMemberDetails> looks
300 up the borrower by number; otherwise, it looks up the borrower by card
303 C<$borrower> is a reference-to-hash whose keys are the fields of the
304 borrowers table in the Koha database. In addition,
305 C<$borrower-E<gt>{flags}> is a hash giving more detailed information
306 about the patron. Its keys act as flags :
308 if $borrower->{flags}->{LOST} {
309 # Patron's card was reported lost
312 If the state of a flag means that the patron should not be
313 allowed to borrow any more books, then it will have a C<noissues> key
316 See patronflags for more details.
318 C<$borrower-E<gt>{authflags}> is a hash giving more detailed information
319 about the top-level permissions flags set for the borrower. For example,
320 if a user has the "editcatalogue" permission,
321 C<$borrower-E<gt>{authflags}-E<gt>{editcatalogue}> will exist and have
326 sub GetMemberDetails {
327 my ( $borrowernumber, $cardnumber ) = @_;
328 my $dbh = C4::Context->dbh;
331 if ($borrowernumber) {
332 $sth = $dbh->prepare("
335 categories.description,
336 categories.BlockExpiredPatronOpacActions,
340 LEFT JOIN categories ON borrowers.categorycode=categories.categorycode
341 WHERE borrowernumber = ?
343 $sth->execute($borrowernumber);
345 elsif ($cardnumber) {
346 $sth = $dbh->prepare("
349 categories.description,
350 categories.BlockExpiredPatronOpacActions,
354 LEFT JOIN categories ON borrowers.categorycode = categories.categorycode
357 $sth->execute($cardnumber);
362 my $borrower = $sth->fetchrow_hashref;
363 return unless $borrower;
364 my ($amount) = GetMemberAccountRecords( $borrowernumber);
365 $borrower->{'amountoutstanding'} = $amount;
366 # FIXME - patronflags calls GetMemberAccountRecords... just have patronflags return $amount
367 my $flags = patronflags( $borrower);
370 $sth = $dbh->prepare("select bit,flag from userflags");
372 while ( my ( $bit, $flag ) = $sth->fetchrow ) {
373 if ( $borrower->{'flags'} && $borrower->{'flags'} & 2**$bit ) {
374 $accessflagshash->{$flag} = 1;
377 $borrower->{'flags'} = $flags;
378 $borrower->{'authflags'} = $accessflagshash;
380 # For the purposes of making templates easier, we'll define a
381 # 'showname' which is the alternate form the user's first name if
382 # 'other name' is defined.
383 if ($borrower->{category_type} eq 'I') {
384 $borrower->{'showname'} = $borrower->{'othernames'};
385 $borrower->{'showname'} .= " $borrower->{'firstname'}" if $borrower->{'firstname'};
387 $borrower->{'showname'} = $borrower->{'firstname'};
390 # Handle setting the true behavior for BlockExpiredPatronOpacActions
391 $borrower->{'BlockExpiredPatronOpacActions'} =
392 C4::Context->preference('BlockExpiredPatronOpacActions')
393 if ( $borrower->{'BlockExpiredPatronOpacActions'} == -1 );
395 $borrower->{'is_expired'} = 0;
396 $borrower->{'is_expired'} = 1 if
397 defined($borrower->{dateexpiry}) &&
398 $borrower->{'dateexpiry'} ne '0000-00-00' &&
399 Date_to_Days( Today() ) >
400 Date_to_Days( split /-/, $borrower->{'dateexpiry'} );
402 return ($borrower); #, $flags, $accessflagshash);
407 $flags = &patronflags($patron);
409 This function is not exported.
411 The following will be set where applicable:
412 $flags->{CHARGES}->{amount} Amount of debt
413 $flags->{CHARGES}->{noissues} Set if debt amount >$5.00 (or syspref noissuescharge)
414 $flags->{CHARGES}->{message} Message -- deprecated
416 $flags->{CREDITS}->{amount} Amount of credit
417 $flags->{CREDITS}->{message} Message -- deprecated
419 $flags->{ GNA } Patron has no valid address
420 $flags->{ GNA }->{noissues} Set for each GNA
421 $flags->{ GNA }->{message} "Borrower has no valid address" -- deprecated
423 $flags->{ LOST } Patron's card reported lost
424 $flags->{ LOST }->{noissues} Set for each LOST
425 $flags->{ LOST }->{message} Message -- deprecated
427 $flags->{DBARRED} Set if patron debarred, no access
428 $flags->{DBARRED}->{noissues} Set for each DBARRED
429 $flags->{DBARRED}->{message} Message -- deprecated
432 $flags->{ NOTES }->{message} The note itself. NOT deprecated
434 $flags->{ ODUES } Set if patron has overdue books.
435 $flags->{ ODUES }->{message} "Yes" -- deprecated
436 $flags->{ ODUES }->{itemlist} ref-to-array: list of overdue books
437 $flags->{ ODUES }->{itemlisttext} Text list of overdue items -- deprecated
439 $flags->{WAITING} Set if any of patron's reserves are available
440 $flags->{WAITING}->{message} Message -- deprecated
441 $flags->{WAITING}->{itemlist} ref-to-array: list of available items
445 =item C<$flags-E<gt>{ODUES}-E<gt>{itemlist}> is a reference-to-array listing the
446 overdue items. Its elements are references-to-hash, each describing an
447 overdue item. The keys are selected fields from the issues, biblio,
448 biblioitems, and items tables of the Koha database.
450 =item C<$flags-E<gt>{ODUES}-E<gt>{itemlisttext}> is a string giving a text listing of
451 the overdue items, one per line. Deprecated.
453 =item C<$flags-E<gt>{WAITING}-E<gt>{itemlist}> is a reference-to-array listing the
454 available items. Each element is a reference-to-hash whose keys are
455 fields from the reserves table of the Koha database.
459 All the "message" fields that include language generated in this function are deprecated,
460 because such strings belong properly in the display layer.
462 The "message" field that comes from the DB is OK.
466 # TODO: use {anonymous => hashes} instead of a dozen %flaginfo
467 # FIXME rename this function.
470 my ( $patroninformation) = @_;
471 my $dbh=C4::Context->dbh;
472 my ($balance, $owing) = GetMemberAccountBalance( $patroninformation->{'borrowernumber'});
475 my $noissuescharge = C4::Context->preference("noissuescharge") || 5;
476 $flaginfo{'message'} = sprintf 'Patron owes %.02f', $owing;
477 $flaginfo{'amount'} = sprintf "%.02f", $owing;
478 if ( $owing > $noissuescharge && !C4::Context->preference("AllowFineOverride") ) {
479 $flaginfo{'noissues'} = 1;
481 $flags{'CHARGES'} = \%flaginfo;
483 elsif ( $balance < 0 ) {
485 $flaginfo{'message'} = sprintf 'Patron has credit of %.02f', -$balance;
486 $flaginfo{'amount'} = sprintf "%.02f", $balance;
487 $flags{'CREDITS'} = \%flaginfo;
489 if ( $patroninformation->{'gonenoaddress'}
490 && $patroninformation->{'gonenoaddress'} == 1 )
493 $flaginfo{'message'} = 'Borrower has no valid address.';
494 $flaginfo{'noissues'} = 1;
495 $flags{'GNA'} = \%flaginfo;
497 if ( $patroninformation->{'lost'} && $patroninformation->{'lost'} == 1 ) {
499 $flaginfo{'message'} = 'Borrower\'s card reported lost.';
500 $flaginfo{'noissues'} = 1;
501 $flags{'LOST'} = \%flaginfo;
503 if ( $patroninformation->{'debarred'} && check_date( split( /-/, $patroninformation->{'debarred'} ) ) ) {
504 if ( Date_to_Days(Date::Calc::Today) < Date_to_Days( split( /-/, $patroninformation->{'debarred'} ) ) ) {
506 $flaginfo{'debarredcomment'} = $patroninformation->{'debarredcomment'};
507 $flaginfo{'message'} = $patroninformation->{'debarredcomment'};
508 $flaginfo{'noissues'} = 1;
509 $flaginfo{'dateend'} = $patroninformation->{'debarred'};
510 $flags{'DBARRED'} = \%flaginfo;
513 if ( $patroninformation->{'borrowernotes'}
514 && $patroninformation->{'borrowernotes'} )
517 $flaginfo{'message'} = $patroninformation->{'borrowernotes'};
518 $flags{'NOTES'} = \%flaginfo;
520 my ( $odues, $itemsoverdue ) = C4::Overdues::checkoverdues($patroninformation->{'borrowernumber'});
521 if ( $odues && $odues > 0 ) {
523 $flaginfo{'message'} = "Yes";
524 $flaginfo{'itemlist'} = $itemsoverdue;
525 foreach ( sort { $a->{'date_due'} cmp $b->{'date_due'} }
528 $flaginfo{'itemlisttext'} .=
529 "$_->{'date_due'} $_->{'barcode'} $_->{'title'} \n"; # newline is display layer
531 $flags{'ODUES'} = \%flaginfo;
533 my @itemswaiting = C4::Reserves::GetReservesFromBorrowernumber( $patroninformation->{'borrowernumber'},'W' );
534 my $nowaiting = scalar @itemswaiting;
535 if ( $nowaiting > 0 ) {
537 $flaginfo{'message'} = "Reserved items available";
538 $flaginfo{'itemlist'} = \@itemswaiting;
539 $flags{'WAITING'} = \%flaginfo;
547 $borrower = &GetMember(%information);
549 Retrieve the first patron record meeting on criteria listed in the
550 C<%information> hash, which should contain one or more
551 pairs of borrowers column names and values, e.g.,
553 $borrower = GetMember(borrowernumber => id);
555 C<&GetBorrower> returns a reference-to-hash whose keys are the fields of
556 the C<borrowers> table in the Koha database.
558 FIXME: GetMember() is used throughout the code as a lookup
559 on a unique key such as the borrowernumber, but this meaning is not
560 enforced in the routine itself.
566 my ( %information ) = @_;
567 if (exists $information{borrowernumber} && !defined $information{borrowernumber}) {
568 #passing mysql's kohaadmin?? Makes no sense as a query
571 my $dbh = C4::Context->dbh;
573 q{SELECT borrowers.*, categories.category_type, categories.description
575 LEFT JOIN categories on borrowers.categorycode=categories.categorycode WHERE };
578 for (keys %information ) {
586 if (defined $information{$_}) {
588 push @values, $information{$_};
591 $select .= "$_ IS NULL";
594 $debug && warn $select, " ",values %information;
595 my $sth = $dbh->prepare("$select");
596 $sth->execute(map{$information{$_}} keys %information);
597 my $data = $sth->fetchall_arrayref({});
598 #FIXME interface to this routine now allows generation of a result set
599 #so whole array should be returned but bowhere in the current code expects this
607 =head2 GetMemberRelatives
609 @borrowernumbers = GetMemberRelatives($borrowernumber);
611 C<GetMemberRelatives> returns a borrowersnumber's list of guarantor/guarantees of the member given in parameter
614 sub GetMemberRelatives {
615 my $borrowernumber = shift;
616 my $dbh = C4::Context->dbh;
620 my $query = "SELECT guarantorid FROM borrowers WHERE borrowernumber=?";
621 my $sth = $dbh->prepare($query);
622 $sth->execute($borrowernumber);
623 my $data = $sth->fetchrow_arrayref();
624 push @glist, $data->[0] if $data->[0];
625 my $guarantor = $data->[0] ? $data->[0] : undef;
628 $query = "SELECT borrowernumber FROM borrowers WHERE guarantorid=?";
629 $sth = $dbh->prepare($query);
630 $sth->execute($borrowernumber);
631 while ($data = $sth->fetchrow_arrayref()) {
632 push @glist, $data->[0];
635 # Getting sibling guarantees
637 $query = "SELECT borrowernumber FROM borrowers WHERE guarantorid=?";
638 $sth = $dbh->prepare($query);
639 $sth->execute($guarantor);
640 while ($data = $sth->fetchrow_arrayref()) {
641 push @glist, $data->[0] if ($data->[0] != $borrowernumber);
648 =head2 IsMemberBlocked
650 my ($block_status, $count) = IsMemberBlocked( $borrowernumber );
652 Returns whether a patron has overdue items that may result
653 in a block or whether the patron has active fine days
654 that would block circulation privileges.
656 C<$block_status> can have the following values:
658 1 if the patron has outstanding fine days or a manual debarment, in which case
659 C<$count> is the expiration date (9999-12-31 for indefinite)
661 -1 if the patron has overdue items, in which case C<$count> is the number of them
663 0 if the patron has no overdue items or outstanding fine days, in which case C<$count> is 0
665 Outstanding fine days are checked before current overdue items
668 FIXME: this needs to be split into two functions; a potential block
669 based on the number of current overdue items could be orthogonal
670 to a block based on whether the patron has any fine days accrued.
674 sub IsMemberBlocked {
675 my $borrowernumber = shift;
676 my $dbh = C4::Context->dbh;
678 my $blockeddate = Koha::Borrower::Debarments::IsDebarred($borrowernumber);
680 return ( 1, $blockeddate ) if $blockeddate;
682 # if he have late issues
683 my $sth = $dbh->prepare(
684 "SELECT COUNT(*) as latedocs
686 WHERE borrowernumber = ?
687 AND date_due < now()"
689 $sth->execute($borrowernumber);
690 my $latedocs = $sth->fetchrow_hashref->{'latedocs'};
692 return ( -1, $latedocs ) if $latedocs > 0;
697 =head2 GetMemberIssuesAndFines
699 ($overdue_count, $issue_count, $total_fines) = &GetMemberIssuesAndFines($borrowernumber);
701 Returns aggregate data about items borrowed by the patron with the
702 given borrowernumber.
704 C<&GetMemberIssuesAndFines> returns a three-element array. C<$overdue_count> is the
705 number of overdue items the patron currently has borrowed. C<$issue_count> is the
706 number of books the patron currently has borrowed. C<$total_fines> is
707 the total fine currently due by the borrower.
712 sub GetMemberIssuesAndFines {
713 my ( $borrowernumber ) = @_;
714 my $dbh = C4::Context->dbh;
715 my $query = "SELECT COUNT(*) FROM issues WHERE borrowernumber = ?";
717 $debug and warn $query."\n";
718 my $sth = $dbh->prepare($query);
719 $sth->execute($borrowernumber);
720 my $issue_count = $sth->fetchrow_arrayref->[0];
722 $sth = $dbh->prepare(
723 "SELECT COUNT(*) FROM issues
724 WHERE borrowernumber = ?
725 AND date_due < now()"
727 $sth->execute($borrowernumber);
728 my $overdue_count = $sth->fetchrow_arrayref->[0];
730 $sth = $dbh->prepare("SELECT SUM(amountoutstanding) FROM accountlines WHERE borrowernumber = ?");
731 $sth->execute($borrowernumber);
732 my $total_fines = $sth->fetchrow_arrayref->[0];
734 return ($overdue_count, $issue_count, $total_fines);
740 my @columns = C4::Member::columns();
742 Returns an array of borrowers' table columns on success,
743 and an empty array on failure.
749 # Pure ANSI SQL goodness.
750 my $sql = 'SELECT * FROM borrowers WHERE 1=0;';
752 # Get the database handle.
753 my $dbh = C4::Context->dbh;
755 # Run the SQL statement to load STH's readonly properties.
756 my $sth = $dbh->prepare($sql);
757 my $rv = $sth->execute();
759 # This only fails if the table doesn't exist.
760 # This will always be called AFTER an install or upgrade,
761 # so borrowers will exist!
763 if ($sth->{NUM_OF_FIELDS}>0) {
764 @data = @{$sth->{NAME}};
775 my $success = ModMember(borrowernumber => $borrowernumber,
776 [ field => value ]... );
778 Modify borrower's data. All date fields should ALREADY be in ISO format.
781 true on success, or false on failure
787 # test to know if you must update or not the borrower password
788 if (exists $data{password}) {
789 if ($data{password} eq '****' or $data{password} eq '') {
790 delete $data{password};
792 if ( C4::Context->preference('NorwegianPatronDBEnable') == 1 ) {
793 # Update the hashed PIN in borrower_sync.hashed_pin, before Koha hashes it
794 NLUpdateHashedPIN( $data{'borrowernumber'}, $data{password} );
796 $data{password} = hash_password($data{password});
799 my $old_categorycode = GetBorrowerCategorycode( $data{borrowernumber} );
800 my $execute_success=UpdateInTable("borrowers",\%data);
801 if ($execute_success) { # only proceed if the update was a success
802 # ok if its an adult (type) it may have borrowers that depend on it as a guarantor
803 # so when we update information for an adult we should check for guarantees and update the relevant part
804 # of their records, ie addresses and phone numbers
805 my $borrowercategory= GetBorrowercategory( $data{'category_type'} );
806 if ( exists $borrowercategory->{'category_type'} && $borrowercategory->{'category_type'} eq ('A' || 'S') ) {
807 # is adult check guarantees;
808 UpdateGuarantees(%data);
811 # If the patron changes to a category with enrollment fee, we add a fee
812 if ( $data{categorycode} and $data{categorycode} ne $old_categorycode ) {
813 AddEnrolmentFeeIfNeeded( $data{categorycode}, $data{borrowernumber} );
816 # If NorwegianPatronDBEnable is enabled, we set syncstatus to something that a
817 # cronjob will use for syncing with NL
818 if ( C4::Context->preference('NorwegianPatronDBEnable') == 1 ) {
819 my $borrowersync = Koha::Database->new->schema->resultset('BorrowerSync')->find({
820 'synctype' => 'norwegianpatrondb',
821 'borrowernumber' => $data{'borrowernumber'}
823 # Do not set to "edited" if syncstatus is "new". We need to sync as new before
824 # we can sync as changed. And the "new sync" will pick up all changes since
825 # the patron was created anyway.
826 if ( $borrowersync->syncstatus ne 'new' && $borrowersync->syncstatus ne 'delete' ) {
827 $borrowersync->update( { 'syncstatus' => 'edited' } );
829 # Set the value of 'sync'
830 $borrowersync->update( { 'sync' => $data{'sync'} } );
831 # Try to do the live sync
832 NLSync({ 'borrowernumber' => $data{'borrowernumber'} });
835 logaction("MEMBERS", "MODIFY", $data{'borrowernumber'}, "UPDATE (executed w/ arg: $data{'borrowernumber'})") if C4::Context->preference("BorrowersLog");
837 return $execute_success;
842 $borrowernumber = &AddMember(%borrower);
844 insert new borrower into table
845 Returns the borrowernumber upon success
847 Returns as undef upon any db error without further processing
854 my $dbh = C4::Context->dbh;
856 # generate a proper login if none provided
857 $data{'userid'} = Generate_Userid($data{'borrowernumber'}, $data{'firstname'}, $data{'surname'}) if $data{'userid'} eq '';
859 # add expiration date if it isn't already there
860 unless ( $data{'dateexpiry'} ) {
861 $data{'dateexpiry'} = GetExpiryDate( $data{'categorycode'}, C4::Dates->new()->output("iso") );
864 # add enrollment date if it isn't already there
865 unless ( $data{'dateenrolled'} ) {
866 $data{'dateenrolled'} = C4::Dates->new()->output("iso");
869 my $patron_category =
870 Koha::Database->new()->schema()->resultset('Category')
871 ->find( $data{'categorycode'} );
873 $patron_category->default_privacy() eq 'default' ? 1
874 : $patron_category->default_privacy() eq 'never' ? 2
875 : $patron_category->default_privacy() eq 'forever' ? 0
877 # Make a copy of the plain text password for later use
878 my $plain_text_password = $data{'password'};
880 # create a disabled account if no password provided
881 $data{'password'} = ($data{'password'})? hash_password($data{'password'}) : '!';
882 $data{'borrowernumber'}=InsertInTable("borrowers",\%data);
884 # If NorwegianPatronDBEnable is enabled, we set syncstatus to something that a
885 # cronjob will use for syncing with NL
886 if ( exists $data{'borrowernumber'} && C4::Context->preference('NorwegianPatronDBEnable') == 1 ) {
887 Koha::Database->new->schema->resultset('BorrowerSync')->create({
888 'borrowernumber' => $data{'borrowernumber'},
889 'synctype' => 'norwegianpatrondb',
891 'syncstatus' => 'new',
892 'hashed_pin' => NLEncryptPIN( $plain_text_password ),
896 # mysql_insertid is probably bad. not necessarily accurate and mysql-specific at best.
897 logaction("MEMBERS", "CREATE", $data{'borrowernumber'}, "") if C4::Context->preference("BorrowersLog");
899 AddEnrolmentFeeIfNeeded( $data{categorycode}, $data{borrowernumber} );
901 return $data{'borrowernumber'};
906 my $uniqueness = Check_Userid($userid,$borrowernumber);
908 $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 != '').
910 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.
913 0 for not unique (i.e. this $userid already exists)
914 1 for unique (i.e. this $userid does not exist, or this $userid/$borrowernumber combination already exists)
919 my ($uid,$member) = @_;
920 my $dbh = C4::Context->dbh;
923 "SELECT * FROM borrowers WHERE userid=? AND borrowernumber != ?");
924 $sth->execute( $uid, $member );
925 if ( (( $uid ne '' ) && ( my $row = $sth->fetchrow_hashref )) or
926 (( $uid ne '' ) && ( $uid eq C4::Context->config('user') )) ) {
934 =head2 Generate_Userid
936 my $newuid = Generate_Userid($borrowernumber, $firstname, $surname);
938 Generate a userid using the $surname and the $firstname (if there is a value in $firstname).
940 $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.
943 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).
947 sub Generate_Userid {
948 my ($borrowernumber, $firstname, $surname) = @_;
951 #The script will "do" the following code and increment the $offset until Check_Userid = 1 (i.e. until $newuid comes back as unique)
953 $firstname =~ s/[[:digit:][:space:][:blank:][:punct:][:cntrl:]]//g;
954 $surname =~ s/[[:digit:][:space:][:blank:][:punct:][:cntrl:]]//g;
955 $newuid = lc(($firstname)? "$firstname.$surname" : $surname);
956 $newuid = unac_string('utf-8',$newuid);
957 $newuid .= $offset unless $offset == 0;
960 } while (!Check_Userid($newuid,$borrowernumber));
966 my ( $uid, $member, $digest ) = @_;
967 my $dbh = C4::Context->dbh;
969 #Make sure the userid chosen is unique and not theirs if non-empty. If it is not,
970 #Then we need to tell the user and have them create a new one.
974 "SELECT * FROM borrowers WHERE userid=? AND borrowernumber != ?");
975 $sth->execute( $uid, $member );
976 if ( ( $uid ne '' ) && ( my $row = $sth->fetchrow_hashref ) ) {
980 #Everything is good so we can update the information.
983 "update borrowers set userid=?, password=? where borrowernumber=?");
984 $sth->execute( $uid, $digest, $member );
988 logaction("MEMBERS", "CHANGE PASS", $member, "") if C4::Context->preference("BorrowersLog");
994 =head2 fixup_cardnumber
996 Warning: The caller is responsible for locking the members table in write
997 mode, to avoid database corruption.
1001 use vars qw( @weightings );
1002 my @weightings = ( 8, 4, 6, 3, 5, 2, 1 );
1004 sub fixup_cardnumber {
1005 my ($cardnumber) = @_;
1006 my $autonumber_members = C4::Context->boolean_preference('autoMemberNum') || 0;
1008 # Find out whether member numbers should be generated
1009 # automatically. Should be either "1" or something else.
1010 # Defaults to "0", which is interpreted as "no".
1012 # if ($cardnumber !~ /\S/ && $autonumber_members) {
1013 ($autonumber_members) or return $cardnumber;
1014 my $checkdigit = C4::Context->preference('checkdigit');
1015 my $dbh = C4::Context->dbh;
1016 if ( $checkdigit and $checkdigit eq 'katipo' ) {
1018 # if checkdigit is selected, calculate katipo-style cardnumber.
1019 # otherwise, just use the max()
1020 # purpose: generate checksum'd member numbers.
1021 # We'll assume we just got the max value of digits 2-8 of member #'s
1022 # from the database and our job is to increment that by one,
1023 # determine the 1st and 9th digits and return the full string.
1024 my $sth = $dbh->prepare(
1025 "select max(substring(borrowers.cardnumber,2,7)) as new_num from borrowers"
1028 my $data = $sth->fetchrow_hashref;
1029 $cardnumber = $data->{new_num};
1030 if ( !$cardnumber ) { # If DB has no values,
1031 $cardnumber = 1000000; # start at 1000000
1037 for ( my $i = 0 ; $i < 8 ; $i += 1 ) {
1038 # read weightings, left to right, 1 char at a time
1039 my $temp1 = $weightings[$i];
1041 # sequence left to right, 1 char at a time
1042 my $temp2 = substr( $cardnumber, $i, 1 );
1044 # mult each char 1-7 by its corresponding weighting
1045 $sum += $temp1 * $temp2;
1048 my $rem = ( $sum % 11 );
1049 $rem = 'X' if $rem == 10;
1051 return "V$cardnumber$rem";
1054 my $sth = $dbh->prepare(
1055 'SELECT MAX( CAST( cardnumber AS SIGNED ) ) FROM borrowers WHERE cardnumber REGEXP "^-?[0-9]+$"'
1058 my ($result) = $sth->fetchrow;
1061 return $cardnumber; # just here as a fallback/reminder
1064 =head2 GetGuarantees
1066 ($num_children, $children_arrayref) = &GetGuarantees($parent_borrno);
1067 $child0_cardno = $children_arrayref->[0]{"cardnumber"};
1068 $child0_borrno = $children_arrayref->[0]{"borrowernumber"};
1070 C<&GetGuarantees> takes a borrower number (e.g., that of a patron
1071 with children) and looks up the borrowers who are guaranteed by that
1072 borrower (i.e., the patron's children).
1074 C<&GetGuarantees> returns two values: an integer giving the number of
1075 borrowers guaranteed by C<$parent_borrno>, and a reference to an array
1076 of references to hash, which gives the actual results.
1082 my ($borrowernumber) = @_;
1083 my $dbh = C4::Context->dbh;
1086 "select cardnumber,borrowernumber, firstname, surname from borrowers where guarantorid=?"
1088 $sth->execute($borrowernumber);
1091 my $data = $sth->fetchall_arrayref({});
1092 return ( scalar(@$data), $data );
1095 =head2 UpdateGuarantees
1097 &UpdateGuarantees($parent_borrno);
1100 C<&UpdateGuarantees> borrower data for an adult and updates all the guarantees
1101 with the modified information
1106 sub UpdateGuarantees {
1108 my $dbh = C4::Context->dbh;
1109 my ( $count, $guarantees ) = GetGuarantees( $data{'borrowernumber'} );
1110 foreach my $guarantee (@$guarantees){
1111 my $guaquery = qq|UPDATE borrowers
1112 SET address=?,fax=?,B_city=?,mobile=?,city=?,phone=?
1113 WHERE borrowernumber=?
1115 my $sth = $dbh->prepare($guaquery);
1116 $sth->execute($data{'address'},$data{'fax'},$data{'B_city'},$data{'mobile'},$data{'city'},$data{'phone'},$guarantee->{'borrowernumber'});
1119 =head2 GetPendingIssues
1121 my $issues = &GetPendingIssues(@borrowernumber);
1123 Looks up what the patron with the given borrowernumber has borrowed.
1125 C<&GetPendingIssues> returns a
1126 reference-to-array where each element is a reference-to-hash; the
1127 keys are the fields from the C<issues>, C<biblio>, and C<items> tables.
1128 The keys include C<biblioitems> fields except marc and marcxml.
1133 sub GetPendingIssues {
1134 my @borrowernumbers = @_;
1136 unless (@borrowernumbers ) { # return a ref_to_array
1137 return \@borrowernumbers; # to not cause surprise to caller
1140 # Borrowers part of the query
1142 for (my $i = 0; $i < @borrowernumbers; $i++) {
1143 $bquery .= ' issues.borrowernumber = ?';
1144 if ($i < $#borrowernumbers ) {
1149 # must avoid biblioitems.* to prevent large marc and marcxml fields from killing performance
1150 # FIXME: namespace collision: each table has "timestamp" fields. Which one is "timestamp" ?
1151 # FIXME: circ/ciculation.pl tries to sort by timestamp!
1152 # FIXME: namespace collision: other collisions possible.
1153 # FIXME: most of this data isn't really being used by callers.
1160 biblioitems.itemtype,
1163 biblioitems.publicationyear,
1164 biblioitems.publishercode,
1165 biblioitems.volumedate,
1166 biblioitems.volumedesc,
1169 borrowers.firstname,
1171 borrowers.cardnumber,
1172 issues.timestamp AS timestamp,
1173 issues.renewals AS renewals,
1174 issues.borrowernumber AS borrowernumber,
1175 items.renewals AS totalrenewals
1177 LEFT JOIN items ON items.itemnumber = issues.itemnumber
1178 LEFT JOIN biblio ON items.biblionumber = biblio.biblionumber
1179 LEFT JOIN biblioitems ON items.biblioitemnumber = biblioitems.biblioitemnumber
1180 LEFT JOIN borrowers ON issues.borrowernumber = borrowers.borrowernumber
1183 ORDER BY issues.issuedate"
1186 my $sth = C4::Context->dbh->prepare($query);
1187 $sth->execute(@borrowernumbers);
1188 my $data = $sth->fetchall_arrayref({});
1189 my $tz = C4::Context->tz();
1190 my $today = DateTime->now( time_zone => $tz);
1191 foreach (@{$data}) {
1192 if ($_->{issuedate}) {
1193 $_->{issuedate} = dt_from_string($_->{issuedate}, 'sql');
1195 $_->{date_due} or next;
1196 $_->{date_due} = DateTime::Format::DateParse->parse_datetime($_->{date_due}, $tz->name());
1197 if ( DateTime->compare($_->{date_due}, $today) == -1 ) {
1206 $issues = &GetAllIssues($borrowernumber, $sortkey, $limit);
1208 Looks up what the patron with the given borrowernumber has borrowed,
1209 and sorts the results.
1211 C<$sortkey> is the name of a field on which to sort the results. This
1212 should be the name of a field in the C<issues>, C<biblio>,
1213 C<biblioitems>, or C<items> table in the Koha database.
1215 C<$limit> is the maximum number of results to return.
1217 C<&GetAllIssues> an arrayref, C<$issues>, of hashrefs, the keys of which
1218 are the fields from the C<issues>, C<biblio>, C<biblioitems>, and
1219 C<items> tables of the Koha database.
1225 my ( $borrowernumber, $order, $limit ) = @_;
1227 return unless $borrowernumber;
1228 $order = 'date_due desc' unless $order;
1230 my $dbh = C4::Context->dbh;
1232 'SELECT *, issues.timestamp as issuestimestamp, issues.renewals AS renewals,items.renewals AS totalrenewals,items.timestamp AS itemstimestamp
1234 LEFT JOIN items on items.itemnumber=issues.itemnumber
1235 LEFT JOIN biblio ON items.biblionumber=biblio.biblionumber
1236 LEFT JOIN biblioitems ON items.biblioitemnumber=biblioitems.biblioitemnumber
1237 WHERE borrowernumber=?
1239 SELECT *, old_issues.timestamp as issuestimestamp, old_issues.renewals AS renewals,items.renewals AS totalrenewals,items.timestamp AS itemstimestamp
1241 LEFT JOIN items on items.itemnumber=old_issues.itemnumber
1242 LEFT JOIN biblio ON items.biblionumber=biblio.biblionumber
1243 LEFT JOIN biblioitems ON items.biblioitemnumber=biblioitems.biblioitemnumber
1244 WHERE borrowernumber=? AND old_issues.itemnumber IS NOT NULL
1245 order by ' . $order;
1247 $query .= " limit $limit";
1250 my $sth = $dbh->prepare($query);
1251 $sth->execute( $borrowernumber, $borrowernumber );
1252 return $sth->fetchall_arrayref( {} );
1256 =head2 GetMemberAccountRecords
1258 ($total, $acctlines, $count) = &GetMemberAccountRecords($borrowernumber);
1260 Looks up accounting data for the patron with the given borrowernumber.
1262 C<&GetMemberAccountRecords> returns a three-element array. C<$acctlines> is a
1263 reference-to-array, where each element is a reference-to-hash; the
1264 keys are the fields of the C<accountlines> table in the Koha database.
1265 C<$count> is the number of elements in C<$acctlines>. C<$total> is the
1266 total amount outstanding for all of the account lines.
1270 sub GetMemberAccountRecords {
1271 my ($borrowernumber) = @_;
1272 my $dbh = C4::Context->dbh;
1278 WHERE borrowernumber=?);
1279 $strsth.=" ORDER BY date desc,timestamp DESC";
1280 my $sth= $dbh->prepare( $strsth );
1281 $sth->execute( $borrowernumber );
1284 while ( my $data = $sth->fetchrow_hashref ) {
1285 if ( $data->{itemnumber} ) {
1286 my $biblio = GetBiblioFromItemNumber( $data->{itemnumber} );
1287 $data->{biblionumber} = $biblio->{biblionumber};
1288 $data->{title} = $biblio->{title};
1290 $acctlines[$numlines] = $data;
1292 $total += int(1000 * $data->{'amountoutstanding'}); # convert float to integer to avoid round-off errors
1295 return ( $total, \@acctlines,$numlines);
1298 =head2 GetMemberAccountBalance
1300 ($total_balance, $non_issue_balance, $other_charges) = &GetMemberAccountBalance($borrowernumber);
1302 Calculates amount immediately owing by the patron - non-issue charges.
1303 Based on GetMemberAccountRecords.
1304 Charges exempt from non-issue are:
1306 * Rent (rental) if RentalsInNoissuesCharge syspref is set to false
1307 * Manual invoices if ManInvInNoissuesCharge syspref is set to false
1311 sub GetMemberAccountBalance {
1312 my ($borrowernumber) = @_;
1314 my $ACCOUNT_TYPE_LENGTH = 5; # this is plain ridiculous...
1317 push @not_fines, 'Res' unless C4::Context->preference('HoldsInNoissuesCharge');
1318 push @not_fines, 'Rent' unless C4::Context->preference('RentalsInNoissuesCharge');
1319 unless ( C4::Context->preference('ManInvInNoissuesCharge') ) {
1320 my $dbh = C4::Context->dbh;
1321 my $man_inv_types = $dbh->selectcol_arrayref(qq{SELECT authorised_value FROM authorised_values WHERE category = 'MANUAL_INV'});
1322 push @not_fines, map substr($_, 0, $ACCOUNT_TYPE_LENGTH), @$man_inv_types;
1324 my %not_fine = map {$_ => 1} @not_fines;
1326 my ($total, $acctlines) = GetMemberAccountRecords($borrowernumber);
1327 my $other_charges = 0;
1328 foreach (@$acctlines) {
1329 $other_charges += $_->{amountoutstanding} if $not_fine{ substr($_->{accounttype}, 0, $ACCOUNT_TYPE_LENGTH) };
1332 return ( $total, $total - $other_charges, $other_charges);
1335 =head2 GetBorNotifyAcctRecord
1337 ($total, $acctlines, $count) = &GetBorNotifyAcctRecord($params,$notifyid);
1339 Looks up accounting data for the patron with the given borrowernumber per file number.
1341 C<&GetBorNotifyAcctRecord> returns a three-element array. C<$acctlines> is a
1342 reference-to-array, where each element is a reference-to-hash; the
1343 keys are the fields of the C<accountlines> table in the Koha database.
1344 C<$count> is the number of elements in C<$acctlines>. C<$total> is the
1345 total amount outstanding for all of the account lines.
1349 sub GetBorNotifyAcctRecord {
1350 my ( $borrowernumber, $notifyid ) = @_;
1351 my $dbh = C4::Context->dbh;
1354 my $sth = $dbh->prepare(
1357 WHERE borrowernumber=?
1359 AND amountoutstanding != '0'
1360 ORDER BY notify_id,accounttype
1363 $sth->execute( $borrowernumber, $notifyid );
1365 while ( my $data = $sth->fetchrow_hashref ) {
1366 if ( $data->{itemnumber} ) {
1367 my $biblio = GetBiblioFromItemNumber( $data->{itemnumber} );
1368 $data->{biblionumber} = $biblio->{biblionumber};
1369 $data->{title} = $biblio->{title};
1371 $acctlines[$numlines] = $data;
1373 $total += int(100 * $data->{'amountoutstanding'});
1376 return ( $total, \@acctlines, $numlines );
1379 =head2 checkuniquemember (OUEST-PROVENCE)
1381 ($result,$categorycode) = &checkuniquemember($collectivity,$surname,$firstname,$dateofbirth);
1383 Checks that a member exists or not in the database.
1385 C<&result> is nonzero (=exist) or 0 (=does not exist)
1386 C<&categorycode> is from categorycode table
1387 C<&collectivity> is 1 (= we add a collectivity) or 0 (= we add a physical member)
1388 C<&surname> is the surname
1389 C<&firstname> is the firstname (only if collectivity=0)
1390 C<&dateofbirth> is the date of birth in ISO format (only if collectivity=0)
1394 # FIXME: This function is not legitimate. Multiple patrons might have the same first/last name and birthdate.
1395 # This is especially true since first name is not even a required field.
1397 sub checkuniquemember {
1398 my ( $collectivity, $surname, $firstname, $dateofbirth ) = @_;
1399 my $dbh = C4::Context->dbh;
1400 my $request = ($collectivity) ?
1401 "SELECT borrowernumber,categorycode FROM borrowers WHERE surname=? " :
1403 "SELECT borrowernumber,categorycode FROM borrowers WHERE surname=? and firstname=? and dateofbirth=?" :
1404 "SELECT borrowernumber,categorycode FROM borrowers WHERE surname=? and firstname=?";
1405 my $sth = $dbh->prepare($request);
1406 if ($collectivity) {
1407 $sth->execute( uc($surname) );
1408 } elsif($dateofbirth){
1409 $sth->execute( uc($surname), ucfirst($firstname), $dateofbirth );
1411 $sth->execute( uc($surname), ucfirst($firstname));
1413 my @data = $sth->fetchrow;
1414 ( $data[0] ) and return $data[0], $data[1];
1418 sub checkcardnumber {
1419 my ( $cardnumber, $borrowernumber ) = @_;
1421 # If cardnumber is null, we assume they're allowed.
1422 return 0 unless defined $cardnumber;
1424 my $dbh = C4::Context->dbh;
1425 my $query = "SELECT * FROM borrowers WHERE cardnumber=?";
1426 $query .= " AND borrowernumber <> ?" if ($borrowernumber);
1427 my $sth = $dbh->prepare($query);
1430 ( $borrowernumber ? $borrowernumber : () )
1433 return 1 if $sth->fetchrow_hashref;
1435 my ( $min_length, $max_length ) = get_cardnumber_length();
1437 if length $cardnumber > $max_length
1438 or length $cardnumber < $min_length;
1443 =head2 get_cardnumber_length
1445 my ($min, $max) = C4::Members::get_cardnumber_length()
1447 Returns the minimum and maximum length for patron cardnumbers as
1448 determined by the CardnumberLength system preference, the
1449 BorrowerMandatoryField system preference, and the width of the
1454 sub get_cardnumber_length {
1455 my ( $min, $max ) = ( 0, 16 ); # borrowers.cardnumber is a nullable varchar(16)
1456 $min = 1 if C4::Context->preference('BorrowerMandatoryField') =~ /cardnumber/;
1457 if ( my $cardnumber_length = C4::Context->preference('CardnumberLength') ) {
1458 # Is integer and length match
1459 if ( $cardnumber_length =~ m|^\d+$| ) {
1460 $min = $max = $cardnumber_length
1461 if $cardnumber_length >= $min
1462 and $cardnumber_length <= $max;
1464 # Else assuming it is a range
1465 elsif ( $cardnumber_length =~ m|(\d*),(\d*)| ) {
1466 $min = $1 if $1 and $min < $1;
1467 $max = $2 if $2 and $max > $2;
1471 return ( $min, $max );
1474 =head2 getzipnamecity (OUEST-PROVENCE)
1476 take all info from table city for the fields city and zip
1477 check for the name and the zip code of the city selected
1481 sub getzipnamecity {
1483 my $dbh = C4::Context->dbh;
1486 "select city_name,city_state,city_zipcode,city_country from cities where cityid=? ");
1487 $sth->execute($cityid);
1488 my @data = $sth->fetchrow;
1489 return $data[0], $data[1], $data[2], $data[3];
1493 =head2 getdcity (OUEST-PROVENCE)
1495 recover cityid with city_name condition
1500 my ($city_name) = @_;
1501 my $dbh = C4::Context->dbh;
1502 my $sth = $dbh->prepare("select cityid from cities where city_name=? ");
1503 $sth->execute($city_name);
1504 my $data = $sth->fetchrow;
1508 =head2 GetFirstValidEmailAddress
1510 $email = GetFirstValidEmailAddress($borrowernumber);
1512 Return the first valid email address for a borrower, given the borrowernumber. For now, the order
1513 is defined as email, emailpro, B_email. Returns the empty string if the borrower has no email
1518 sub GetFirstValidEmailAddress {
1519 my $borrowernumber = shift;
1520 my $dbh = C4::Context->dbh;
1521 my $sth = $dbh->prepare( "SELECT email, emailpro, B_email FROM borrowers where borrowernumber = ? ");
1522 $sth->execute( $borrowernumber );
1523 my $data = $sth->fetchrow_hashref;
1525 if ($data->{'email'}) {
1526 return $data->{'email'};
1527 } elsif ($data->{'emailpro'}) {
1528 return $data->{'emailpro'};
1529 } elsif ($data->{'B_email'}) {
1530 return $data->{'B_email'};
1536 =head2 GetNoticeEmailAddress
1538 $email = GetNoticeEmailAddress($borrowernumber);
1540 Return the email address of borrower used for notices, given the borrowernumber.
1541 Returns the empty string if no email address.
1545 sub GetNoticeEmailAddress {
1546 my $borrowernumber = shift;
1548 my $which_address = C4::Context->preference("AutoEmailPrimaryAddress");
1549 # if syspref is set to 'first valid' (value == OFF), look up email address
1550 if ( $which_address eq 'OFF' ) {
1551 return GetFirstValidEmailAddress($borrowernumber);
1553 # specified email address field
1554 my $dbh = C4::Context->dbh;
1555 my $sth = $dbh->prepare( qq{
1556 SELECT $which_address AS primaryemail
1558 WHERE borrowernumber=?
1560 $sth->execute($borrowernumber);
1561 my $data = $sth->fetchrow_hashref;
1562 return $data->{'primaryemail'} || '';
1565 =head2 GetExpiryDate
1567 $expirydate = GetExpiryDate($categorycode, $dateenrolled);
1569 Calculate expiry date given a categorycode and starting date. Date argument must be in ISO format.
1570 Return date is also in ISO format.
1575 my ( $categorycode, $dateenrolled ) = @_;
1577 if ($categorycode) {
1578 my $dbh = C4::Context->dbh;
1579 my $sth = $dbh->prepare("SELECT enrolmentperiod,enrolmentperioddate FROM categories WHERE categorycode=?");
1580 $sth->execute($categorycode);
1581 $enrolments = $sth->fetchrow_hashref;
1583 # die "GetExpiryDate: for enrollmentperiod $enrolmentperiod (category '$categorycode') starting $dateenrolled.\n";
1584 my @date = split (/-/,$dateenrolled);
1585 if($enrolments->{enrolmentperiod}){
1586 return sprintf("%04d-%02d-%02d", Add_Delta_YM(@date,0,$enrolments->{enrolmentperiod}));
1588 return $enrolments->{enrolmentperioddate};
1592 =head2 GetborCatFromCatType
1594 ($codes_arrayref, $labels_hashref) = &GetborCatFromCatType();
1596 Looks up the different types of borrowers in the database. Returns two
1597 elements: a reference-to-array, which lists the borrower category
1598 codes, and a reference-to-hash, which maps the borrower category codes
1599 to category descriptions.
1604 sub GetborCatFromCatType {
1605 my ( $category_type, $action, $no_branch_limit ) = @_;
1607 my $branch_limit = $no_branch_limit
1609 : C4::Context->userenv ? C4::Context->userenv->{"branch"} : "";
1611 # FIXME - This API seems both limited and dangerous.
1612 my $dbh = C4::Context->dbh;
1615 SELECT categories.categorycode, categories.description
1619 LEFT JOIN categories_branches ON categories.categorycode = categories_branches.categorycode
1622 $request .= " $action ";
1623 $request .= " AND (branchcode = ? OR branchcode IS NULL) GROUP BY description" if $branch_limit;
1625 $request .= " WHERE branchcode = ? OR branchcode IS NULL GROUP BY description" if $branch_limit;
1627 $request .= " ORDER BY categorycode";
1629 my $sth = $dbh->prepare($request);
1631 $action ? $category_type : (),
1632 $branch_limit ? $branch_limit : ()
1638 while ( my $data = $sth->fetchrow_hashref ) {
1639 push @codes, $data->{'categorycode'};
1640 $labels{ $data->{'categorycode'} } = $data->{'description'};
1643 return ( \@codes, \%labels );
1646 =head2 GetBorrowercategory
1648 $hashref = &GetBorrowercategory($categorycode);
1650 Given the borrower's category code, the function returns the corresponding
1651 data hashref for a comprehensive information display.
1655 sub GetBorrowercategory {
1657 my $dbh = C4::Context->dbh;
1661 "SELECT description,dateofbirthrequired,upperagelimit,category_type
1663 WHERE categorycode = ?"
1665 $sth->execute($catcode);
1667 $sth->fetchrow_hashref;
1671 } # sub getborrowercategory
1674 =head2 GetBorrowerCategorycode
1676 $categorycode = &GetBorrowerCategoryCode( $borrowernumber );
1678 Given the borrowernumber, the function returns the corresponding categorycode
1681 sub GetBorrowerCategorycode {
1682 my ( $borrowernumber ) = @_;
1683 my $dbh = C4::Context->dbh;
1684 my $sth = $dbh->prepare( qq{
1687 WHERE borrowernumber = ?
1689 $sth->execute( $borrowernumber );
1690 return $sth->fetchrow;
1693 =head2 GetBorrowercategoryList
1695 $arrayref_hashref = &GetBorrowercategoryList;
1696 If no category code provided, the function returns all the categories.
1700 sub GetBorrowercategoryList {
1701 my $no_branch_limit = @_ ? shift : 0;
1702 my $branch_limit = $no_branch_limit
1704 : C4::Context->userenv ? C4::Context->userenv->{"branch"} : "";
1705 my $dbh = C4::Context->dbh;
1706 my $query = "SELECT categories.* FROM categories";
1708 LEFT JOIN categories_branches ON categories.categorycode = categories_branches.categorycode
1709 WHERE branchcode = ? OR branchcode IS NULL GROUP BY description
1711 $query .= " ORDER BY description";
1712 my $sth = $dbh->prepare( $query );
1713 $sth->execute( $branch_limit ? $branch_limit : () );
1714 my $data = $sth->fetchall_arrayref( {} );
1717 } # sub getborrowercategory
1719 =head2 ethnicitycategories
1721 ($codes_arrayref, $labels_hashref) = ðnicitycategories();
1723 Looks up the different ethnic types in the database. Returns two
1724 elements: a reference-to-array, which lists the ethnicity codes, and a
1725 reference-to-hash, which maps the ethnicity codes to ethnicity
1732 sub ethnicitycategories {
1733 my $dbh = C4::Context->dbh;
1734 my $sth = $dbh->prepare("Select code,name from ethnicity order by name");
1738 while ( my $data = $sth->fetchrow_hashref ) {
1739 push @codes, $data->{'code'};
1740 $labels{ $data->{'code'} } = $data->{'name'};
1742 return ( \@codes, \%labels );
1747 $ethn_name = &fixEthnicity($ethn_code);
1749 Takes an ethnicity code (e.g., "european" or "pi") and returns the
1750 corresponding descriptive name from the C<ethnicity> table in the
1751 Koha database ("European" or "Pacific Islander").
1758 my $ethnicity = shift;
1759 return unless $ethnicity;
1760 my $dbh = C4::Context->dbh;
1761 my $sth = $dbh->prepare("Select name from ethnicity where code = ?");
1762 $sth->execute($ethnicity);
1763 my $data = $sth->fetchrow_hashref;
1764 return $data->{'name'};
1765 } # sub fixEthnicity
1769 $dateofbirth,$date = &GetAge($date);
1771 this function return the borrowers age with the value of dateofbirth
1777 my ( $date, $date_ref ) = @_;
1779 if ( not defined $date_ref ) {
1780 $date_ref = sprintf( '%04d-%02d-%02d', Today() );
1783 my ( $year1, $month1, $day1 ) = split /-/, $date;
1784 my ( $year2, $month2, $day2 ) = split /-/, $date_ref;
1786 my $age = $year2 - $year1;
1787 if ( $month1 . $day1 > $month2 . $day2 ) {
1796 $borrower = C4::Members::SetAge($borrower, $datetimeduration);
1797 $borrower = C4::Members::SetAge($borrower, '0015-12-10');
1798 $borrower = C4::Members::SetAge($borrower, $datetimeduration, $datetime_reference);
1800 eval { $borrower = C4::Members::SetAge($borrower, '015-1-10'); };
1801 if ($@) {print $@;} #Catch a bad ISO Date or kill your script!
1803 This function sets the borrower's dateofbirth to match the given age.
1804 Optionally relative to the given $datetime_reference.
1806 @PARAM1 koha.borrowers-object
1807 @PARAM2 DateTime::Duration-object as the desired age
1808 OR a ISO 8601 Date. (To make the API more pleasant)
1809 @PARAM3 DateTime-object as the relative date, defaults to now().
1810 RETURNS The given borrower reference @PARAM1.
1811 DIES If there was an error with the ISO Date handling.
1817 my ( $borrower, $datetimeduration, $datetime_ref ) = @_;
1818 $datetime_ref = DateTime->now() unless $datetime_ref;
1820 if ($datetimeduration && ref $datetimeduration ne 'DateTime::Duration') {
1821 if ($datetimeduration =~ /^(\d{4})-(\d{2})-(\d{2})/) {
1822 $datetimeduration = DateTime::Duration->new(years => $1, months => $2, days => $3);
1825 die "C4::Members::SetAge($borrower, $datetimeduration), datetimeduration not a valid ISO 8601 Date!\n";
1829 my $new_datetime_ref = $datetime_ref->clone();
1830 $new_datetime_ref->subtract_duration( $datetimeduration );
1832 $borrower->{dateofbirth} = $new_datetime_ref->ymd();
1839 $cityarrayref = GetCities();
1841 Returns an array_ref of the entries in the cities table
1842 If there are entries in the table an empty row is returned
1843 This is currently only used to populate a popup in memberentry
1849 my $dbh = C4::Context->dbh;
1850 my $city_arr = $dbh->selectall_arrayref(
1851 q|SELECT cityid,city_zipcode,city_name,city_state,city_country FROM cities ORDER BY city_name|,
1853 if ( @{$city_arr} ) {
1854 unshift @{$city_arr}, {
1855 city_zipcode => q{},
1859 city_country => q{},
1866 =head2 GetSortDetails (OUEST-PROVENCE)
1868 ($lib) = &GetSortDetails($category,$sortvalue);
1870 Returns the authorized value details
1871 C<&$lib>return value of authorized value details
1872 C<&$sortvalue>this is the value of authorized value
1873 C<&$category>this is the value of authorized value category
1877 sub GetSortDetails {
1878 my ( $category, $sortvalue ) = @_;
1879 my $dbh = C4::Context->dbh;
1880 my $query = qq|SELECT lib
1881 FROM authorised_values
1883 AND authorised_value=? |;
1884 my $sth = $dbh->prepare($query);
1885 $sth->execute( $category, $sortvalue );
1886 my $lib = $sth->fetchrow;
1887 return ($lib) if ($lib);
1888 return ($sortvalue) unless ($lib);
1891 =head2 MoveMemberToDeleted
1893 $result = &MoveMemberToDeleted($borrowernumber);
1895 Copy the record from borrowers to deletedborrowers table.
1896 The routine returns 1 for success, undef for failure.
1900 sub MoveMemberToDeleted {
1901 my ($member) = shift or return;
1903 my $schema = Koha::Database->new()->schema();
1904 my $borrowers_rs = $schema->resultset('Borrower');
1905 $borrowers_rs->result_class('DBIx::Class::ResultClass::HashRefInflator');
1906 my $borrower = $borrowers_rs->find($member);
1907 return unless $borrower;
1909 my $deleted = $schema->resultset('Deletedborrower')->create($borrower);
1911 return $deleted ? 1 : undef;
1916 DelMember($borrowernumber);
1918 This function remove directly a borrower whitout writing it on deleteborrower.
1919 + Deletes reserves for the borrower
1924 my $dbh = C4::Context->dbh;
1925 my $borrowernumber = shift;
1926 #warn "in delmember with $borrowernumber";
1927 return unless $borrowernumber; # borrowernumber is mandatory.
1929 my $query = qq|DELETE
1931 WHERE borrowernumber=?|;
1932 my $sth = $dbh->prepare($query);
1933 $sth->execute($borrowernumber);
1937 WHERE borrowernumber = ?
1939 $sth = $dbh->prepare($query);
1940 $sth->execute($borrowernumber);
1941 logaction("MEMBERS", "DELETE", $borrowernumber, "") if C4::Context->preference("BorrowersLog");
1945 =head2 ExtendMemberSubscriptionTo (OUEST-PROVENCE)
1947 $date = ExtendMemberSubscriptionTo($borrowerid, $date);
1949 Extending the subscription to a given date or to the expiry date calculated on ISO date.
1954 sub ExtendMemberSubscriptionTo {
1955 my ( $borrowerid,$date) = @_;
1956 my $dbh = C4::Context->dbh;
1957 my $borrower = GetMember('borrowernumber'=>$borrowerid);
1959 $date = (C4::Context->preference('BorrowerRenewalPeriodBase') eq 'dateexpiry') ?
1960 C4::Dates->new($borrower->{'dateexpiry'}, 'iso')->output("iso") :
1961 C4::Dates->new()->output("iso");
1962 $date = GetExpiryDate( $borrower->{'categorycode'}, $date );
1964 my $sth = $dbh->do(<<EOF);
1966 SET dateexpiry='$date'
1967 WHERE borrowernumber='$borrowerid'
1970 AddEnrolmentFeeIfNeeded( $borrower->{categorycode}, $borrower->{borrowernumber} );
1972 logaction("MEMBERS", "RENEW", $borrower->{'borrowernumber'}, "Membership renewed")if C4::Context->preference("BorrowersLog");
1973 return $date if ($sth);
1977 =head2 GetTitles (OUEST-PROVENCE)
1979 ($borrowertitle)= &GetTitles();
1981 Looks up the different title . Returns array with all borrowers title
1986 my @borrowerTitle = split (/,|\|/,C4::Context->preference('BorrowersTitles'));
1987 unshift( @borrowerTitle, "" );
1988 my $count=@borrowerTitle;
1993 return ( \@borrowerTitle);
1997 =head2 GetPatronImage
1999 my ($imagedata, $dberror) = GetPatronImage($borrowernumber);
2001 Returns the mimetype and binary image data of the image for the patron with the supplied borrowernumber.
2005 sub GetPatronImage {
2006 my ($borrowernumber) = @_;
2007 warn "Borrowernumber passed to GetPatronImage is $borrowernumber" if $debug;
2008 my $dbh = C4::Context->dbh;
2009 my $query = 'SELECT mimetype, imagefile FROM patronimage WHERE borrowernumber = ?';
2010 my $sth = $dbh->prepare($query);
2011 $sth->execute($borrowernumber);
2012 my $imagedata = $sth->fetchrow_hashref;
2013 warn "Database error!" if $sth->errstr;
2014 return $imagedata, $sth->errstr;
2017 =head2 PutPatronImage
2019 PutPatronImage($cardnumber, $mimetype, $imgfile);
2021 Stores patron binary image data and mimetype in database.
2022 NOTE: This function is good for updating images as well as inserting new images in the database.
2026 sub PutPatronImage {
2027 my ($cardnumber, $mimetype, $imgfile) = @_;
2028 warn "Parameters passed in: Cardnumber=$cardnumber, Mimetype=$mimetype, " . ($imgfile ? "Imagefile" : "No Imagefile") if $debug;
2029 my $dbh = C4::Context->dbh;
2030 my $query = "INSERT INTO patronimage (borrowernumber, mimetype, imagefile) VALUES ( ( SELECT borrowernumber from borrowers WHERE cardnumber = ? ),?,?) ON DUPLICATE KEY UPDATE imagefile = ?;";
2031 my $sth = $dbh->prepare($query);
2032 $sth->execute($cardnumber,$mimetype,$imgfile,$imgfile);
2033 warn "Error returned inserting $cardnumber.$mimetype." if $sth->errstr;
2034 return $sth->errstr;
2037 =head2 RmPatronImage
2039 my ($dberror) = RmPatronImage($borrowernumber);
2041 Removes the image for the patron with the supplied borrowernumber.
2046 my ($borrowernumber) = @_;
2047 warn "Borrowernumber passed to GetPatronImage is $borrowernumber" if $debug;
2048 my $dbh = C4::Context->dbh;
2049 my $query = "DELETE FROM patronimage WHERE borrowernumber = ?;";
2050 my $sth = $dbh->prepare($query);
2051 $sth->execute($borrowernumber);
2052 my $dberror = $sth->errstr;
2053 warn "Database error!" if $sth->errstr;
2057 =head2 GetHideLostItemsPreference
2059 $hidelostitemspref = &GetHideLostItemsPreference($borrowernumber);
2061 Returns the HideLostItems preference for the patron category of the supplied borrowernumber
2062 C<&$hidelostitemspref>return value of function, 0 or 1
2066 sub GetHideLostItemsPreference {
2067 my ($borrowernumber) = @_;
2068 my $dbh = C4::Context->dbh;
2069 my $query = "SELECT hidelostitems FROM borrowers,categories WHERE borrowers.categorycode = categories.categorycode AND borrowernumber = ?";
2070 my $sth = $dbh->prepare($query);
2071 $sth->execute($borrowernumber);
2072 my $hidelostitems = $sth->fetchrow;
2073 return $hidelostitems;
2076 =head2 GetBorrowersToExpunge
2078 $borrowers = &GetBorrowersToExpunge(
2079 not_borrowered_since => $not_borrowered_since,
2080 expired_before => $expired_before,
2081 category_code => $category_code,
2082 branchcode => $branchcode
2085 This function get all borrowers based on the given criteria.
2089 sub GetBorrowersToExpunge {
2092 my $filterdate = $params->{'not_borrowered_since'};
2093 my $filterexpiry = $params->{'expired_before'};
2094 my $filtercategory = $params->{'category_code'};
2095 my $filterbranch = $params->{'branchcode'} ||
2096 ((C4::Context->preference('IndependentBranches')
2097 && C4::Context->userenv
2098 && !C4::Context->IsSuperLibrarian()
2099 && C4::Context->userenv->{branch})
2100 ? C4::Context->userenv->{branch}
2103 my $dbh = C4::Context->dbh;
2105 SELECT borrowers.borrowernumber,
2106 MAX(old_issues.timestamp) AS latestissue,
2107 MAX(issues.timestamp) AS currentissue
2109 JOIN categories USING (categorycode)
2110 LEFT JOIN old_issues USING (borrowernumber)
2111 LEFT JOIN issues USING (borrowernumber)
2112 WHERE category_type <> 'S'
2113 AND borrowernumber NOT IN (SELECT guarantorid FROM borrowers WHERE guarantorid IS NOT NULL AND guarantorid <> 0)
2116 if ( $filterbranch && $filterbranch ne "" ) {
2117 $query.= " AND borrowers.branchcode = ? ";
2118 push( @query_params, $filterbranch );
2120 if ( $filterexpiry ) {
2121 $query .= " AND dateexpiry < ? ";
2122 push( @query_params, $filterexpiry );
2124 if ( $filtercategory ) {
2125 $query .= " AND categorycode = ? ";
2126 push( @query_params, $filtercategory );
2128 $query.=" GROUP BY borrowers.borrowernumber HAVING currentissue IS NULL ";
2129 if ( $filterdate ) {
2130 $query.=" AND ( latestissue < ? OR latestissue IS NULL ) ";
2131 push @query_params,$filterdate;
2133 warn $query if $debug;
2135 my $sth = $dbh->prepare($query);
2136 if (scalar(@query_params)>0){
2137 $sth->execute(@query_params);
2144 while ( my $data = $sth->fetchrow_hashref ) {
2145 push @results, $data;
2150 =head2 GetBorrowersWhoHaveNeverBorrowed
2152 $results = &GetBorrowersWhoHaveNeverBorrowed
2154 This function get all borrowers who have never borrowed.
2156 I<$result> is a ref to an array which all elements are a hasref.
2160 sub GetBorrowersWhoHaveNeverBorrowed {
2161 my $filterbranch = shift ||
2162 ((C4::Context->preference('IndependentBranches')
2163 && C4::Context->userenv
2164 && !C4::Context->IsSuperLibrarian()
2165 && C4::Context->userenv->{branch})
2166 ? C4::Context->userenv->{branch}
2168 my $dbh = C4::Context->dbh;
2170 SELECT borrowers.borrowernumber,max(timestamp) as latestissue
2172 LEFT JOIN issues ON borrowers.borrowernumber = issues.borrowernumber
2173 WHERE issues.borrowernumber IS NULL
2176 if ($filterbranch && $filterbranch ne ""){
2177 $query.=" AND borrowers.branchcode= ?";
2178 push @query_params,$filterbranch;
2180 warn $query if $debug;
2182 my $sth = $dbh->prepare($query);
2183 if (scalar(@query_params)>0){
2184 $sth->execute(@query_params);
2191 while ( my $data = $sth->fetchrow_hashref ) {
2192 push @results, $data;
2197 =head2 GetBorrowersWithIssuesHistoryOlderThan
2199 $results = &GetBorrowersWithIssuesHistoryOlderThan($date)
2201 this function get all borrowers who has an issue history older than I<$date> given on input arg.
2203 I<$result> is a ref to an array which all elements are a hashref.
2204 This hashref is containt the number of time this borrowers has borrowed before I<$date> and the borrowernumber.
2208 sub GetBorrowersWithIssuesHistoryOlderThan {
2209 my $dbh = C4::Context->dbh;
2210 my $date = shift ||POSIX::strftime("%Y-%m-%d",localtime());
2211 my $filterbranch = shift ||
2212 ((C4::Context->preference('IndependentBranches')
2213 && C4::Context->userenv
2214 && !C4::Context->IsSuperLibrarian()
2215 && C4::Context->userenv->{branch})
2216 ? C4::Context->userenv->{branch}
2219 SELECT count(borrowernumber) as n,borrowernumber
2221 WHERE returndate < ?
2222 AND borrowernumber IS NOT NULL
2225 push @query_params, $date;
2227 $query.=" AND branchcode = ?";
2228 push @query_params, $filterbranch;
2230 $query.=" GROUP BY borrowernumber ";
2231 warn $query if $debug;
2232 my $sth = $dbh->prepare($query);
2233 $sth->execute(@query_params);
2236 while ( my $data = $sth->fetchrow_hashref ) {
2237 push @results, $data;
2242 =head2 GetBorrowersNamesAndLatestIssue
2244 $results = &GetBorrowersNamesAndLatestIssueList(@borrowernumbers)
2246 this function get borrowers Names and surnames and Issue information.
2248 I<@borrowernumbers> is an array which all elements are borrowernumbers.
2249 This hashref is containt the number of time this borrowers has borrowed before I<$date> and the borrowernumber.
2253 sub GetBorrowersNamesAndLatestIssue {
2254 my $dbh = C4::Context->dbh;
2255 my @borrowernumbers=@_;
2257 SELECT surname,lastname, phone, email,max(timestamp)
2259 LEFT JOIN issues ON borrowers.borrowernumber=issues.borrowernumber
2260 GROUP BY borrowernumber
2262 my $sth = $dbh->prepare($query);
2264 my $results = $sth->fetchall_arrayref({});
2272 my $success = ModPrivacy( $borrowernumber, $privacy );
2274 Update the privacy of a patron.
2277 true on success, false on failure
2284 my $borrowernumber = shift;
2285 my $privacy = shift;
2286 return unless defined $borrowernumber;
2287 return unless $borrowernumber =~ /^\d+$/;
2289 return ModMember( borrowernumber => $borrowernumber,
2290 privacy => $privacy );
2295 AddMessage( $borrowernumber, $message_type, $message, $branchcode );
2297 Adds a message to the messages table for the given borrower.
2306 my ( $borrowernumber, $message_type, $message, $branchcode ) = @_;
2308 my $dbh = C4::Context->dbh;
2310 if ( ! ( $borrowernumber && $message_type && $message && $branchcode ) ) {
2314 my $query = "INSERT INTO messages ( borrowernumber, branchcode, message_type, message ) VALUES ( ?, ?, ?, ? )";
2315 my $sth = $dbh->prepare($query);
2316 $sth->execute( $borrowernumber, $branchcode, $message_type, $message );
2317 logaction("MEMBERS", "ADDCIRCMESSAGE", $borrowernumber, $message) if C4::Context->preference("BorrowersLog");
2323 GetMessages( $borrowernumber, $type );
2325 $type is message type, B for borrower, or L for Librarian.
2326 Empty type returns all messages of any type.
2328 Returns all messages for the given borrowernumber
2333 my ( $borrowernumber, $type, $branchcode ) = @_;
2339 my $dbh = C4::Context->dbh;
2342 branches.branchname,
2345 messages.branchcode LIKE '$branchcode' AS can_delete
2346 FROM messages, branches
2347 WHERE borrowernumber = ?
2348 AND message_type LIKE ?
2349 AND messages.branchcode = branches.branchcode
2350 ORDER BY message_date DESC";
2351 my $sth = $dbh->prepare($query);
2352 $sth->execute( $borrowernumber, $type ) ;
2355 while ( my $data = $sth->fetchrow_hashref ) {
2356 my $d = C4::Dates->new( $data->{message_date}, 'iso' );
2357 $data->{message_date_formatted} = $d->output;
2358 push @results, $data;
2366 GetMessagesCount( $borrowernumber, $type );
2368 $type is message type, B for borrower, or L for Librarian.
2369 Empty type returns all messages of any type.
2371 Returns the number of messages for the given borrowernumber
2375 sub GetMessagesCount {
2376 my ( $borrowernumber, $type, $branchcode ) = @_;
2382 my $dbh = C4::Context->dbh;
2384 my $query = "SELECT COUNT(*) as MsgCount FROM messages WHERE borrowernumber = ? AND message_type LIKE ?";
2385 my $sth = $dbh->prepare($query);
2386 $sth->execute( $borrowernumber, $type ) ;
2389 my $data = $sth->fetchrow_hashref;
2390 my $count = $data->{'MsgCount'};
2397 =head2 DeleteMessage
2399 DeleteMessage( $message_id );
2404 my ( $message_id ) = @_;
2406 my $dbh = C4::Context->dbh;
2407 my $query = "SELECT * FROM messages WHERE message_id = ?";
2408 my $sth = $dbh->prepare($query);
2409 $sth->execute( $message_id );
2410 my $message = $sth->fetchrow_hashref();
2412 $query = "DELETE FROM messages WHERE message_id = ?";
2413 $sth = $dbh->prepare($query);
2414 $sth->execute( $message_id );
2415 logaction("MEMBERS", "DELCIRCMESSAGE", $message->{'borrowernumber'}, $message->{'message'}) if C4::Context->preference("BorrowersLog");
2420 IssueSlip($branchcode, $borrowernumber, $quickslip)
2422 Returns letter hash ( see C4::Letters::GetPreparedLetter )
2424 $quickslip is boolean, to indicate whether we want a quick slip
2429 my ($branch, $borrowernumber, $quickslip) = @_;
2431 # return unless ( C4::Context->boolean_preference('printcirculationslips') );
2433 my $now = POSIX::strftime("%Y-%m-%d", localtime);
2435 my $issueslist = GetPendingIssues($borrowernumber);
2436 foreach my $it (@$issueslist){
2437 if ((substr $it->{'issuedate'}, 0, 10) eq $now || (substr $it->{'lastreneweddate'}, 0, 10) eq $now) {
2440 elsif ((substr $it->{'date_due'}, 0, 10) le $now) {
2441 $it->{'overdue'} = 1;
2443 my $dt = dt_from_string( $it->{'date_due'} );
2444 $it->{'date_due'} = output_pref( $dt );;
2446 my @issues = sort { $b->{'timestamp'} <=> $a->{'timestamp'} } @$issueslist;
2448 my ($letter_code, %repeat);
2450 $letter_code = 'ISSUEQSLIP';
2452 'checkedout' => [ map {
2456 }, grep { $_->{'now'} } @issues ],
2460 $letter_code = 'ISSUESLIP';
2462 'checkedout' => [ map {
2466 }, grep { !$_->{'overdue'} } @issues ],
2468 'overdue' => [ map {
2472 }, grep { $_->{'overdue'} } @issues ],
2475 $_->{'timestamp'} = $_->{'newdate'};
2477 } @{ GetNewsToDisplay("slip",$branch) } ],
2481 return C4::Letters::GetPreparedLetter (
2482 module => 'circulation',
2483 letter_code => $letter_code,
2484 branchcode => $branch,
2486 'branches' => $branch,
2487 'borrowers' => $borrowernumber,
2493 =head2 GetBorrowersWithEmail
2495 ([$borrnum,$userid], ...) = GetBorrowersWithEmail('me@example.com');
2497 This gets a list of users and their basic details from their email address.
2498 As it's possible for multiple user to have the same email address, it provides
2499 you with all of them. If there is no userid for the user, there will be an
2500 C<undef> there. An empty list will be returned if there are no matches.
2504 sub GetBorrowersWithEmail {
2507 my $dbh = C4::Context->dbh;
2509 my $query = "SELECT borrowernumber, userid FROM borrowers WHERE email=?";
2510 my $sth=$dbh->prepare($query);
2511 $sth->execute($email);
2513 while (my $ref = $sth->fetch) {
2516 die "Failure searching for borrowers by email address: $sth->errstr" if $sth->err;
2520 sub AddMember_Opac {
2521 my ( %borrower ) = @_;
2523 $borrower{'categorycode'} = C4::Context->preference('PatronSelfRegistrationDefaultCategory');
2525 my $sr = new String::Random;
2526 $sr->{'A'} = [ 'A'..'Z', 'a'..'z' ];
2527 my $password = $sr->randpattern("AAAAAAAAAA");
2528 $borrower{'password'} = $password;
2530 $borrower{'cardnumber'} = fixup_cardnumber();
2532 my $borrowernumber = AddMember(%borrower);
2534 return ( $borrowernumber, $password );
2537 =head2 AddEnrolmentFeeIfNeeded
2539 AddEnrolmentFeeIfNeeded( $borrower->{categorycode}, $borrower->{borrowernumber} );
2541 Add enrolment fee for a patron if needed.
2545 sub AddEnrolmentFeeIfNeeded {
2546 my ( $categorycode, $borrowernumber ) = @_;
2547 # check for enrollment fee & add it if needed
2548 my $dbh = C4::Context->dbh;
2549 my $sth = $dbh->prepare(q{
2552 WHERE categorycode=?
2554 $sth->execute( $categorycode );
2556 warn sprintf('Database returned the following error: %s', $sth->errstr);
2559 my ($enrolmentfee) = $sth->fetchrow;
2560 if ($enrolmentfee && $enrolmentfee > 0) {
2561 # insert fee in patron debts
2562 C4::Accounts::manualinvoice( $borrowernumber, '', '', 'A', $enrolmentfee );
2567 my ( $borrowernumber ) = @_;
2569 my $sql = "SELECT COUNT(*) FROM issues WHERE date_due < NOW() AND borrowernumber = ?";
2570 my $sth = C4::Context->dbh->prepare( $sql );
2571 $sth->execute( $borrowernumber );
2572 my ( $count ) = $sth->fetchrow_array();
2577 END { } # module clean-up code here (global destructor)