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 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
41 use Koha::Borrower::Debarments qw(IsDebarred);
42 use Text::Unaccent qw( unac_string );
43 use Koha::AuthUtils qw(hash_password);
46 if ( C4::Context->preference('NorwegianPatronDBEnable') && C4::Context->preference('NorwegianPatronDBEnable') == 1 ) {
47 load Koha::NorwegianPatronDB, qw( NLUpdateHashedPIN NLEncryptPIN NLSync );
50 our ($VERSION,@ISA,@EXPORT,@EXPORT_OK,$debug);
53 $VERSION = 3.07.00.049;
54 $debug = $ENV{DEBUG} || 0;
66 &GetMemberIssuesAndFines
73 &GetFirstValidEmailAddress
74 &GetNoticeEmailAddress
85 &GetHideLostItemsPreference
88 &GetMemberAccountRecords
89 &GetBorNotifyAcctRecord
93 GetBorrowerCategorycode
94 &GetBorrowercategoryList
96 &GetBorrowersToExpunge
97 &GetBorrowersWhoHaveNeverBorrowed
98 &GetBorrowersWithIssuesHistoryOlderThan
108 GetBorrowersWithEmail
130 &ExtendMemberSubscriptionTo
148 C4::Members - Perl Module containing convenience functions for member handling
156 This module contains routines for adding, modifying and deleting members/patrons/borrowers
162 $borrowers_result_array_ref = &Search($filter,$orderby, $limit,
163 $columns_out, $search_on_fields,$searchtype);
165 Looks up patrons (borrowers) on filter. A wrapper for SearchInTable('borrowers').
167 For C<$filter>, C<$orderby>, C<$limit>, C<&columns_out>, C<&search_on_fields> and C<&searchtype>
168 refer to C4::SQLHelper:SearchInTable().
170 Special C<$filter> key '' is effectively expanded to search on surname firstname othernamescw
171 and cardnumber unless C<&search_on_fields> is defined
175 $borrowers = Search('abcd', 'cardnumber');
177 $borrowers = Search({''=>'abcd', category_type=>'I'}, 'surname');
181 sub _express_member_find {
184 # this is used by circulation everytime a new borrowers cardnumber is scanned
185 # so we can check an exact match first, if that works return, otherwise do the rest
186 my $dbh = C4::Context->dbh;
187 my $query = "SELECT borrowernumber FROM borrowers WHERE cardnumber = ?";
188 if ( my $borrowernumber = $dbh->selectrow_array($query, undef, $filter) ) {
189 return( {"borrowernumber"=>$borrowernumber} );
192 my ($search_on_fields, $searchtype);
193 if ( length($filter) == 1 ) {
194 $search_on_fields = [ qw(surname) ];
195 $searchtype = 'start_with';
197 $search_on_fields = [ qw(surname firstname othernames cardnumber) ];
198 $searchtype = 'contain';
201 return (undef, $search_on_fields, $searchtype);
205 my ( $filter, $orderby, $limit, $columns_out, $search_on_fields, $searchtype, $not_attributes ) = @_;
210 if ( my $fr = ref $filter ) {
211 if ( $fr eq "HASH" ) {
212 if ( my $search_string = $filter->{''} ) {
213 my ($member_filter, $member_search_on_fields, $member_searchtype) = _express_member_find($search_string);
214 if ($member_filter) {
215 $filter = $member_filter;
218 $search_on_fields ||= $member_search_on_fields;
219 $searchtype ||= $member_searchtype;
224 $search_string = $filter;
228 $search_string = $filter;
229 my ($member_filter, $member_search_on_fields, $member_searchtype) = _express_member_find($search_string);
230 if ($member_filter) {
231 $filter = $member_filter;
234 $search_on_fields ||= $member_search_on_fields;
235 $searchtype ||= $member_searchtype;
239 if ( !$found_borrower && C4::Context->preference('ExtendedPatronAttributes') && $search_string && !$not_attributes ) {
240 my $matching_records = C4::Members::Attributes::SearchIdMatchingAttribute($search_string);
241 if(scalar(@$matching_records)>0) {
242 if ( my $fr = ref $filter ) {
243 if ( $fr eq "HASH" ) {
245 $filter = [ $filter ];
247 push @$filter, { %f, "borrowernumber"=>$$matching_records };
250 push @$filter, {"borrowernumber"=>$matching_records};
254 $filter = [ $filter ];
255 push @$filter, {"borrowernumber"=>$matching_records};
260 # $showallbranches was not used at the time SearchMember() was mainstreamed into Search().
261 # Mentioning for the reference
263 if ( C4::Context->preference("IndependentBranches") ) { # && !$showallbranches){
264 if ( my $userenv = C4::Context->userenv ) {
265 my $branch = $userenv->{'branch'};
266 if ( !C4::Context->IsSuperLibrarian() && $branch ){
267 if (my $fr = ref $filter) {
268 if ( $fr eq "HASH" ) {
269 $filter->{branchcode} = $branch;
273 $_ = { '' => $_ } unless ref $_;
274 $_->{branchcode} = $branch;
279 $filter = { '' => $filter, branchcode => $branch };
285 if ($found_borrower) {
286 $searchtype = "exact";
288 $searchtype ||= "start_with";
290 return SearchInTable( "borrowers", $filter, $orderby, $limit, $columns_out, $search_on_fields, $searchtype );
293 =head2 GetMemberDetails
295 ($borrower) = &GetMemberDetails($borrowernumber, $cardnumber);
297 Looks up a patron and returns information about him or her. If
298 C<$borrowernumber> is true (nonzero), C<&GetMemberDetails> looks
299 up the borrower by number; otherwise, it looks up the borrower by card
302 C<$borrower> is a reference-to-hash whose keys are the fields of the
303 borrowers table in the Koha database. In addition,
304 C<$borrower-E<gt>{flags}> is a hash giving more detailed information
305 about the patron. Its keys act as flags :
307 if $borrower->{flags}->{LOST} {
308 # Patron's card was reported lost
311 If the state of a flag means that the patron should not be
312 allowed to borrow any more books, then it will have a C<noissues> key
315 See patronflags for more details.
317 C<$borrower-E<gt>{authflags}> is a hash giving more detailed information
318 about the top-level permissions flags set for the borrower. For example,
319 if a user has the "editcatalogue" permission,
320 C<$borrower-E<gt>{authflags}-E<gt>{editcatalogue}> will exist and have
325 sub GetMemberDetails {
326 my ( $borrowernumber, $cardnumber ) = @_;
327 my $dbh = C4::Context->dbh;
330 if ($borrowernumber) {
331 $sth = $dbh->prepare("
334 categories.description,
335 categories.BlockExpiredPatronOpacActions,
339 LEFT JOIN categories ON borrowers.categorycode=categories.categorycode
340 WHERE borrowernumber = ?
342 $sth->execute($borrowernumber);
344 elsif ($cardnumber) {
345 $sth = $dbh->prepare("
348 categories.description,
349 categories.BlockExpiredPatronOpacActions,
353 LEFT JOIN categories ON borrowers.categorycode = categories.categorycode
356 $sth->execute($cardnumber);
361 my $borrower = $sth->fetchrow_hashref;
362 return unless $borrower;
363 my ($amount) = GetMemberAccountRecords($borrower->{borrowernumber});
364 $borrower->{'amountoutstanding'} = $amount;
365 # FIXME - patronflags calls GetMemberAccountRecords... just have patronflags return $amount
366 my $flags = patronflags( $borrower);
369 $sth = $dbh->prepare("select bit,flag from userflags");
371 while ( my ( $bit, $flag ) = $sth->fetchrow ) {
372 if ( $borrower->{'flags'} && $borrower->{'flags'} & 2**$bit ) {
373 $accessflagshash->{$flag} = 1;
376 $borrower->{'flags'} = $flags;
377 $borrower->{'authflags'} = $accessflagshash;
379 # For the purposes of making templates easier, we'll define a
380 # 'showname' which is the alternate form the user's first name if
381 # 'other name' is defined.
382 if ($borrower->{category_type} eq 'I') {
383 $borrower->{'showname'} = $borrower->{'othernames'};
384 $borrower->{'showname'} .= " $borrower->{'firstname'}" if $borrower->{'firstname'};
386 $borrower->{'showname'} = $borrower->{'firstname'};
389 # Handle setting the true behavior for BlockExpiredPatronOpacActions
390 $borrower->{'BlockExpiredPatronOpacActions'} =
391 C4::Context->preference('BlockExpiredPatronOpacActions')
392 if ( $borrower->{'BlockExpiredPatronOpacActions'} == -1 );
394 $borrower->{'is_expired'} = 0;
395 $borrower->{'is_expired'} = 1 if
396 defined($borrower->{dateexpiry}) &&
397 $borrower->{'dateexpiry'} ne '0000-00-00' &&
398 Date_to_Days( Today() ) >
399 Date_to_Days( split /-/, $borrower->{'dateexpiry'} );
401 return ($borrower); #, $flags, $accessflagshash);
406 $flags = &patronflags($patron);
408 This function is not exported.
410 The following will be set where applicable:
411 $flags->{CHARGES}->{amount} Amount of debt
412 $flags->{CHARGES}->{noissues} Set if debt amount >$5.00 (or syspref noissuescharge)
413 $flags->{CHARGES}->{message} Message -- deprecated
415 $flags->{CREDITS}->{amount} Amount of credit
416 $flags->{CREDITS}->{message} Message -- deprecated
418 $flags->{ GNA } Patron has no valid address
419 $flags->{ GNA }->{noissues} Set for each GNA
420 $flags->{ GNA }->{message} "Borrower has no valid address" -- deprecated
422 $flags->{ LOST } Patron's card reported lost
423 $flags->{ LOST }->{noissues} Set for each LOST
424 $flags->{ LOST }->{message} Message -- deprecated
426 $flags->{DBARRED} Set if patron debarred, no access
427 $flags->{DBARRED}->{noissues} Set for each DBARRED
428 $flags->{DBARRED}->{message} Message -- deprecated
431 $flags->{ NOTES }->{message} The note itself. NOT deprecated
433 $flags->{ ODUES } Set if patron has overdue books.
434 $flags->{ ODUES }->{message} "Yes" -- deprecated
435 $flags->{ ODUES }->{itemlist} ref-to-array: list of overdue books
436 $flags->{ ODUES }->{itemlisttext} Text list of overdue items -- deprecated
438 $flags->{WAITING} Set if any of patron's reserves are available
439 $flags->{WAITING}->{message} Message -- deprecated
440 $flags->{WAITING}->{itemlist} ref-to-array: list of available items
444 =item C<$flags-E<gt>{ODUES}-E<gt>{itemlist}> is a reference-to-array listing the
445 overdue items. Its elements are references-to-hash, each describing an
446 overdue item. The keys are selected fields from the issues, biblio,
447 biblioitems, and items tables of the Koha database.
449 =item C<$flags-E<gt>{ODUES}-E<gt>{itemlisttext}> is a string giving a text listing of
450 the overdue items, one per line. Deprecated.
452 =item C<$flags-E<gt>{WAITING}-E<gt>{itemlist}> is a reference-to-array listing the
453 available items. Each element is a reference-to-hash whose keys are
454 fields from the reserves table of the Koha database.
458 All the "message" fields that include language generated in this function are deprecated,
459 because such strings belong properly in the display layer.
461 The "message" field that comes from the DB is OK.
465 # TODO: use {anonymous => hashes} instead of a dozen %flaginfo
466 # FIXME rename this function.
469 my ( $patroninformation) = @_;
470 my $dbh=C4::Context->dbh;
471 my ($balance, $owing) = GetMemberAccountBalance( $patroninformation->{'borrowernumber'});
474 my $noissuescharge = C4::Context->preference("noissuescharge") || 5;
475 $flaginfo{'message'} = sprintf 'Patron owes %.02f', $owing;
476 $flaginfo{'amount'} = sprintf "%.02f", $owing;
477 if ( $owing > $noissuescharge && !C4::Context->preference("AllowFineOverride") ) {
478 $flaginfo{'noissues'} = 1;
480 $flags{'CHARGES'} = \%flaginfo;
482 elsif ( $balance < 0 ) {
484 $flaginfo{'message'} = sprintf 'Patron has credit of %.02f', -$balance;
485 $flaginfo{'amount'} = sprintf "%.02f", $balance;
486 $flags{'CREDITS'} = \%flaginfo;
488 if ( $patroninformation->{'gonenoaddress'}
489 && $patroninformation->{'gonenoaddress'} == 1 )
492 $flaginfo{'message'} = 'Borrower has no valid address.';
493 $flaginfo{'noissues'} = 1;
494 $flags{'GNA'} = \%flaginfo;
496 if ( $patroninformation->{'lost'} && $patroninformation->{'lost'} == 1 ) {
498 $flaginfo{'message'} = 'Borrower\'s card reported lost.';
499 $flaginfo{'noissues'} = 1;
500 $flags{'LOST'} = \%flaginfo;
502 if ( $patroninformation->{'debarred'} && check_date( split( /-/, $patroninformation->{'debarred'} ) ) ) {
503 if ( Date_to_Days(Date::Calc::Today) < Date_to_Days( split( /-/, $patroninformation->{'debarred'} ) ) ) {
505 $flaginfo{'debarredcomment'} = $patroninformation->{'debarredcomment'};
506 $flaginfo{'message'} = $patroninformation->{'debarredcomment'};
507 $flaginfo{'noissues'} = 1;
508 $flaginfo{'dateend'} = $patroninformation->{'debarred'};
509 $flags{'DBARRED'} = \%flaginfo;
512 if ( $patroninformation->{'borrowernotes'}
513 && $patroninformation->{'borrowernotes'} )
516 $flaginfo{'message'} = $patroninformation->{'borrowernotes'};
517 $flags{'NOTES'} = \%flaginfo;
519 my ( $odues, $itemsoverdue ) = C4::Overdues::checkoverdues($patroninformation->{'borrowernumber'});
520 if ( $odues && $odues > 0 ) {
522 $flaginfo{'message'} = "Yes";
523 $flaginfo{'itemlist'} = $itemsoverdue;
524 foreach ( sort { $a->{'date_due'} cmp $b->{'date_due'} }
527 $flaginfo{'itemlisttext'} .=
528 "$_->{'date_due'} $_->{'barcode'} $_->{'title'} \n"; # newline is display layer
530 $flags{'ODUES'} = \%flaginfo;
532 my @itemswaiting = C4::Reserves::GetReservesFromBorrowernumber( $patroninformation->{'borrowernumber'},'W' );
533 my $nowaiting = scalar @itemswaiting;
534 if ( $nowaiting > 0 ) {
536 $flaginfo{'message'} = "Reserved items available";
537 $flaginfo{'itemlist'} = \@itemswaiting;
538 $flags{'WAITING'} = \%flaginfo;
546 $borrower = &GetMember(%information);
548 Retrieve the first patron record meeting on criteria listed in the
549 C<%information> hash, which should contain one or more
550 pairs of borrowers column names and values, e.g.,
552 $borrower = GetMember(borrowernumber => id);
554 C<&GetBorrower> returns a reference-to-hash whose keys are the fields of
555 the C<borrowers> table in the Koha database.
557 FIXME: GetMember() is used throughout the code as a lookup
558 on a unique key such as the borrowernumber, but this meaning is not
559 enforced in the routine itself.
565 my ( %information ) = @_;
566 if (exists $information{borrowernumber} && !defined $information{borrowernumber}) {
567 #passing mysql's kohaadmin?? Makes no sense as a query
570 my $dbh = C4::Context->dbh;
572 q{SELECT borrowers.*, categories.category_type, categories.description
574 LEFT JOIN categories on borrowers.categorycode=categories.categorycode WHERE };
577 for (keys %information ) {
585 if (defined $information{$_}) {
587 push @values, $information{$_};
590 $select .= "$_ IS NULL";
593 $debug && warn $select, " ",values %information;
594 my $sth = $dbh->prepare("$select");
595 $sth->execute(map{$information{$_}} keys %information);
596 my $data = $sth->fetchall_arrayref({});
597 #FIXME interface to this routine now allows generation of a result set
598 #so whole array should be returned but bowhere in the current code expects this
606 =head2 GetMemberRelatives
608 @borrowernumbers = GetMemberRelatives($borrowernumber);
610 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') && 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') && 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
846 (%borrower keys are database columns. Database columns could be
847 different in different versions. Please look into database for correct
850 Returns the borrowernumber upon success
852 Returns as undef upon any db error without further processing
859 my $dbh = C4::Context->dbh;
861 # generate a proper login if none provided
862 $data{'userid'} = Generate_Userid( $data{'borrowernumber'}, $data{'firstname'}, $data{'surname'} )
863 if ( $data{'userid'} eq '' || !Check_Userid( $data{'userid'} ) );
865 # add expiration date if it isn't already there
866 unless ( $data{'dateexpiry'} ) {
867 $data{'dateexpiry'} = GetExpiryDate( $data{'categorycode'}, C4::Dates->new()->output("iso") );
870 # add enrollment date if it isn't already there
871 unless ( $data{'dateenrolled'} ) {
872 $data{'dateenrolled'} = C4::Dates->new()->output("iso");
875 my $patron_category =
876 Koha::Database->new()->schema()->resultset('Category')
877 ->find( $data{'categorycode'} );
879 $patron_category->default_privacy() eq 'default' ? 1
880 : $patron_category->default_privacy() eq 'never' ? 2
881 : $patron_category->default_privacy() eq 'forever' ? 0
883 # Make a copy of the plain text password for later use
884 my $plain_text_password = $data{'password'};
886 # create a disabled account if no password provided
887 $data{'password'} = ($data{'password'})? hash_password($data{'password'}) : '!';
888 $data{'borrowernumber'}=InsertInTable("borrowers",\%data);
890 # If NorwegianPatronDBEnable is enabled, we set syncstatus to something that a
891 # cronjob will use for syncing with NL
892 if ( exists $data{'borrowernumber'} && C4::Context->preference('NorwegianPatronDBEnable') && C4::Context->preference('NorwegianPatronDBEnable') == 1 ) {
893 Koha::Database->new->schema->resultset('BorrowerSync')->create({
894 'borrowernumber' => $data{'borrowernumber'},
895 'synctype' => 'norwegianpatrondb',
897 'syncstatus' => 'new',
898 'hashed_pin' => NLEncryptPIN( $plain_text_password ),
902 # mysql_insertid is probably bad. not necessarily accurate and mysql-specific at best.
903 logaction("MEMBERS", "CREATE", $data{'borrowernumber'}, "") if C4::Context->preference("BorrowersLog");
905 AddEnrolmentFeeIfNeeded( $data{categorycode}, $data{borrowernumber} );
907 return $data{'borrowernumber'};
912 my $uniqueness = Check_Userid($userid,$borrowernumber);
914 $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 != '').
916 If $borrowernumber is provided, the database will be checked for every instance of that userid coupled with a different borrower(number) than the one provided.
919 0 for not unique (i.e. this $userid already exists)
920 1 for unique (i.e. this $userid does not exist, or this $userid/$borrowernumber combination already exists)
925 my ( $uid, $borrowernumber ) = @_;
927 return 0 unless ($uid); # userid is a unique column, we should assume NULL is not unique
929 return 0 if ( $uid eq C4::Context->config('user') );
931 my $rs = Koha::Database->new()->schema()->resultset('Borrower');
934 $params->{userid} = $uid;
935 $params->{borrowernumber} = { '!=' => $borrowernumber } if ($borrowernumber);
937 my $count = $rs->count( $params );
939 return $count ? 0 : 1;
942 =head2 Generate_Userid
944 my $newuid = Generate_Userid($borrowernumber, $firstname, $surname);
946 Generate a userid using the $surname and the $firstname (if there is a value in $firstname).
948 $borrowernumber is optional (i.e. it can contain a blank value). A value is passed when generating a new userid for an existing borrower. When a new userid is created for a new borrower, a blank value is passed to this sub.
951 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).
955 sub Generate_Userid {
956 my ($borrowernumber, $firstname, $surname) = @_;
959 #The script will "do" the following code and increment the $offset until Check_Userid = 1 (i.e. until $newuid comes back as unique)
961 $firstname =~ s/[[:digit:][:space:][:blank:][:punct:][:cntrl:]]//g;
962 $surname =~ s/[[:digit:][:space:][:blank:][:punct:][:cntrl:]]//g;
963 $newuid = lc(($firstname)? "$firstname.$surname" : $surname);
964 $newuid = unac_string('utf-8',$newuid);
965 $newuid .= $offset unless $offset == 0;
968 } while (!Check_Userid($newuid,$borrowernumber));
974 my ( $uid, $member, $digest ) = @_;
975 my $dbh = C4::Context->dbh;
977 #Make sure the userid chosen is unique and not theirs if non-empty. If it is not,
978 #Then we need to tell the user and have them create a new one.
982 "SELECT * FROM borrowers WHERE userid=? AND borrowernumber != ?");
983 $sth->execute( $uid, $member );
984 if ( ( $uid ne '' ) && ( my $row = $sth->fetchrow_hashref ) ) {
988 #Everything is good so we can update the information.
991 "update borrowers set userid=?, password=? where borrowernumber=?");
992 $sth->execute( $uid, $digest, $member );
996 logaction("MEMBERS", "CHANGE PASS", $member, "") if C4::Context->preference("BorrowersLog");
1002 =head2 fixup_cardnumber
1004 Warning: The caller is responsible for locking the members table in write
1005 mode, to avoid database corruption.
1009 use vars qw( @weightings );
1010 my @weightings = ( 8, 4, 6, 3, 5, 2, 1 );
1012 sub fixup_cardnumber {
1013 my ($cardnumber) = @_;
1014 my $autonumber_members = C4::Context->boolean_preference('autoMemberNum') || 0;
1016 # Find out whether member numbers should be generated
1017 # automatically. Should be either "1" or something else.
1018 # Defaults to "0", which is interpreted as "no".
1020 # if ($cardnumber !~ /\S/ && $autonumber_members) {
1021 ($autonumber_members) or return $cardnumber;
1022 my $checkdigit = C4::Context->preference('checkdigit');
1023 my $dbh = C4::Context->dbh;
1024 if ( $checkdigit and $checkdigit eq 'katipo' ) {
1026 # if checkdigit is selected, calculate katipo-style cardnumber.
1027 # otherwise, just use the max()
1028 # purpose: generate checksum'd member numbers.
1029 # We'll assume we just got the max value of digits 2-8 of member #'s
1030 # from the database and our job is to increment that by one,
1031 # determine the 1st and 9th digits and return the full string.
1032 my $sth = $dbh->prepare(
1033 "select max(substring(borrowers.cardnumber,2,7)) as new_num from borrowers"
1036 my $data = $sth->fetchrow_hashref;
1037 $cardnumber = $data->{new_num};
1038 if ( !$cardnumber ) { # If DB has no values,
1039 $cardnumber = 1000000; # start at 1000000
1045 for ( my $i = 0 ; $i < 8 ; $i += 1 ) {
1046 # read weightings, left to right, 1 char at a time
1047 my $temp1 = $weightings[$i];
1049 # sequence left to right, 1 char at a time
1050 my $temp2 = substr( $cardnumber, $i, 1 );
1052 # mult each char 1-7 by its corresponding weighting
1053 $sum += $temp1 * $temp2;
1056 my $rem = ( $sum % 11 );
1057 $rem = 'X' if $rem == 10;
1059 return "V$cardnumber$rem";
1062 my $sth = $dbh->prepare(
1063 'SELECT MAX( CAST( cardnumber AS SIGNED ) ) FROM borrowers WHERE cardnumber REGEXP "^-?[0-9]+$"'
1066 my ($result) = $sth->fetchrow;
1069 return $cardnumber; # just here as a fallback/reminder
1072 =head2 GetGuarantees
1074 ($num_children, $children_arrayref) = &GetGuarantees($parent_borrno);
1075 $child0_cardno = $children_arrayref->[0]{"cardnumber"};
1076 $child0_borrno = $children_arrayref->[0]{"borrowernumber"};
1078 C<&GetGuarantees> takes a borrower number (e.g., that of a patron
1079 with children) and looks up the borrowers who are guaranteed by that
1080 borrower (i.e., the patron's children).
1082 C<&GetGuarantees> returns two values: an integer giving the number of
1083 borrowers guaranteed by C<$parent_borrno>, and a reference to an array
1084 of references to hash, which gives the actual results.
1090 my ($borrowernumber) = @_;
1091 my $dbh = C4::Context->dbh;
1094 "select cardnumber,borrowernumber, firstname, surname from borrowers where guarantorid=?"
1096 $sth->execute($borrowernumber);
1099 my $data = $sth->fetchall_arrayref({});
1100 return ( scalar(@$data), $data );
1103 =head2 UpdateGuarantees
1105 &UpdateGuarantees($parent_borrno);
1108 C<&UpdateGuarantees> borrower data for an adult and updates all the guarantees
1109 with the modified information
1114 sub UpdateGuarantees {
1116 my $dbh = C4::Context->dbh;
1117 my ( $count, $guarantees ) = GetGuarantees( $data{'borrowernumber'} );
1118 foreach my $guarantee (@$guarantees){
1119 my $guaquery = qq|UPDATE borrowers
1120 SET address=?,fax=?,B_city=?,mobile=?,city=?,phone=?
1121 WHERE borrowernumber=?
1123 my $sth = $dbh->prepare($guaquery);
1124 $sth->execute($data{'address'},$data{'fax'},$data{'B_city'},$data{'mobile'},$data{'city'},$data{'phone'},$guarantee->{'borrowernumber'});
1127 =head2 GetPendingIssues
1129 my $issues = &GetPendingIssues(@borrowernumber);
1131 Looks up what the patron with the given borrowernumber has borrowed.
1133 C<&GetPendingIssues> returns a
1134 reference-to-array where each element is a reference-to-hash; the
1135 keys are the fields from the C<issues>, C<biblio>, and C<items> tables.
1136 The keys include C<biblioitems> fields except marc and marcxml.
1141 sub GetPendingIssues {
1142 my @borrowernumbers = @_;
1144 unless (@borrowernumbers ) { # return a ref_to_array
1145 return \@borrowernumbers; # to not cause surprise to caller
1148 # Borrowers part of the query
1150 for (my $i = 0; $i < @borrowernumbers; $i++) {
1151 $bquery .= ' issues.borrowernumber = ?';
1152 if ($i < $#borrowernumbers ) {
1157 # must avoid biblioitems.* to prevent large marc and marcxml fields from killing performance
1158 # FIXME: namespace collision: each table has "timestamp" fields. Which one is "timestamp" ?
1159 # FIXME: circ/ciculation.pl tries to sort by timestamp!
1160 # FIXME: namespace collision: other collisions possible.
1161 # FIXME: most of this data isn't really being used by callers.
1168 biblioitems.itemtype,
1171 biblioitems.publicationyear,
1172 biblioitems.publishercode,
1173 biblioitems.volumedate,
1174 biblioitems.volumedesc,
1177 borrowers.firstname,
1179 borrowers.cardnumber,
1180 issues.timestamp AS timestamp,
1181 issues.renewals AS renewals,
1182 issues.borrowernumber AS borrowernumber,
1183 items.renewals AS totalrenewals
1185 LEFT JOIN items ON items.itemnumber = issues.itemnumber
1186 LEFT JOIN biblio ON items.biblionumber = biblio.biblionumber
1187 LEFT JOIN biblioitems ON items.biblioitemnumber = biblioitems.biblioitemnumber
1188 LEFT JOIN borrowers ON issues.borrowernumber = borrowers.borrowernumber
1191 ORDER BY issues.issuedate"
1194 my $sth = C4::Context->dbh->prepare($query);
1195 $sth->execute(@borrowernumbers);
1196 my $data = $sth->fetchall_arrayref({});
1197 my $today = dt_from_string;
1198 foreach (@{$data}) {
1199 if ($_->{issuedate}) {
1200 $_->{issuedate} = dt_from_string($_->{issuedate}, 'sql');
1202 $_->{date_due} or next;
1203 $_->{date_due_sql} = $_->{date_due};
1204 # FIXME no need to have this value
1205 $_->{date_due} = dt_from_string($_->{date_due}, 'sql');
1206 if ( DateTime->compare($_->{date_due}, $today) == -1 ) {
1215 $issues = &GetAllIssues($borrowernumber, $sortkey, $limit);
1217 Looks up what the patron with the given borrowernumber has borrowed,
1218 and sorts the results.
1220 C<$sortkey> is the name of a field on which to sort the results. This
1221 should be the name of a field in the C<issues>, C<biblio>,
1222 C<biblioitems>, or C<items> table in the Koha database.
1224 C<$limit> is the maximum number of results to return.
1226 C<&GetAllIssues> an arrayref, C<$issues>, of hashrefs, the keys of which
1227 are the fields from the C<issues>, C<biblio>, C<biblioitems>, and
1228 C<items> tables of the Koha database.
1234 my ( $borrowernumber, $order, $limit ) = @_;
1236 return unless $borrowernumber;
1237 $order = 'date_due desc' unless $order;
1239 my $dbh = C4::Context->dbh;
1241 'SELECT *, issues.timestamp as issuestimestamp, issues.renewals AS renewals,items.renewals AS totalrenewals,items.timestamp AS itemstimestamp
1243 LEFT JOIN items on items.itemnumber=issues.itemnumber
1244 LEFT JOIN biblio ON items.biblionumber=biblio.biblionumber
1245 LEFT JOIN biblioitems ON items.biblioitemnumber=biblioitems.biblioitemnumber
1246 WHERE borrowernumber=?
1248 SELECT *, old_issues.timestamp as issuestimestamp, old_issues.renewals AS renewals,items.renewals AS totalrenewals,items.timestamp AS itemstimestamp
1250 LEFT JOIN items on items.itemnumber=old_issues.itemnumber
1251 LEFT JOIN biblio ON items.biblionumber=biblio.biblionumber
1252 LEFT JOIN biblioitems ON items.biblioitemnumber=biblioitems.biblioitemnumber
1253 WHERE borrowernumber=? AND old_issues.itemnumber IS NOT NULL
1254 order by ' . $order;
1256 $query .= " limit $limit";
1259 my $sth = $dbh->prepare($query);
1260 $sth->execute( $borrowernumber, $borrowernumber );
1261 return $sth->fetchall_arrayref( {} );
1265 =head2 GetMemberAccountRecords
1267 ($total, $acctlines, $count) = &GetMemberAccountRecords($borrowernumber);
1269 Looks up accounting data for the patron with the given borrowernumber.
1271 C<&GetMemberAccountRecords> returns a three-element array. C<$acctlines> is a
1272 reference-to-array, where each element is a reference-to-hash; the
1273 keys are the fields of the C<accountlines> table in the Koha database.
1274 C<$count> is the number of elements in C<$acctlines>. C<$total> is the
1275 total amount outstanding for all of the account lines.
1279 sub GetMemberAccountRecords {
1280 my ($borrowernumber) = @_;
1281 my $dbh = C4::Context->dbh;
1287 WHERE borrowernumber=?);
1288 $strsth.=" ORDER BY date desc,timestamp DESC";
1289 my $sth= $dbh->prepare( $strsth );
1290 $sth->execute( $borrowernumber );
1293 while ( my $data = $sth->fetchrow_hashref ) {
1294 if ( $data->{itemnumber} ) {
1295 my $biblio = GetBiblioFromItemNumber( $data->{itemnumber} );
1296 $data->{biblionumber} = $biblio->{biblionumber};
1297 $data->{title} = $biblio->{title};
1299 $acctlines[$numlines] = $data;
1301 $total += int(1000 * $data->{'amountoutstanding'}); # convert float to integer to avoid round-off errors
1304 return ( $total, \@acctlines,$numlines);
1307 =head2 GetMemberAccountBalance
1309 ($total_balance, $non_issue_balance, $other_charges) = &GetMemberAccountBalance($borrowernumber);
1311 Calculates amount immediately owing by the patron - non-issue charges.
1312 Based on GetMemberAccountRecords.
1313 Charges exempt from non-issue are:
1315 * Rent (rental) if RentalsInNoissuesCharge syspref is set to false
1316 * Manual invoices if ManInvInNoissuesCharge syspref is set to false
1320 sub GetMemberAccountBalance {
1321 my ($borrowernumber) = @_;
1323 my $ACCOUNT_TYPE_LENGTH = 5; # this is plain ridiculous...
1326 push @not_fines, 'Res' unless C4::Context->preference('HoldsInNoissuesCharge');
1327 push @not_fines, 'Rent' unless C4::Context->preference('RentalsInNoissuesCharge');
1328 unless ( C4::Context->preference('ManInvInNoissuesCharge') ) {
1329 my $dbh = C4::Context->dbh;
1330 my $man_inv_types = $dbh->selectcol_arrayref(qq{SELECT authorised_value FROM authorised_values WHERE category = 'MANUAL_INV'});
1331 push @not_fines, map substr($_, 0, $ACCOUNT_TYPE_LENGTH), @$man_inv_types;
1333 my %not_fine = map {$_ => 1} @not_fines;
1335 my ($total, $acctlines) = GetMemberAccountRecords($borrowernumber);
1336 my $other_charges = 0;
1337 foreach (@$acctlines) {
1338 $other_charges += $_->{amountoutstanding} if $not_fine{ substr($_->{accounttype}, 0, $ACCOUNT_TYPE_LENGTH) };
1341 return ( $total, $total - $other_charges, $other_charges);
1344 =head2 GetBorNotifyAcctRecord
1346 ($total, $acctlines, $count) = &GetBorNotifyAcctRecord($params,$notifyid);
1348 Looks up accounting data for the patron with the given borrowernumber per file number.
1350 C<&GetBorNotifyAcctRecord> returns a three-element array. C<$acctlines> is a
1351 reference-to-array, where each element is a reference-to-hash; the
1352 keys are the fields of the C<accountlines> table in the Koha database.
1353 C<$count> is the number of elements in C<$acctlines>. C<$total> is the
1354 total amount outstanding for all of the account lines.
1358 sub GetBorNotifyAcctRecord {
1359 my ( $borrowernumber, $notifyid ) = @_;
1360 my $dbh = C4::Context->dbh;
1363 my $sth = $dbh->prepare(
1366 WHERE borrowernumber=?
1368 AND amountoutstanding != '0'
1369 ORDER BY notify_id,accounttype
1372 $sth->execute( $borrowernumber, $notifyid );
1374 while ( my $data = $sth->fetchrow_hashref ) {
1375 if ( $data->{itemnumber} ) {
1376 my $biblio = GetBiblioFromItemNumber( $data->{itemnumber} );
1377 $data->{biblionumber} = $biblio->{biblionumber};
1378 $data->{title} = $biblio->{title};
1380 $acctlines[$numlines] = $data;
1382 $total += int(100 * $data->{'amountoutstanding'});
1385 return ( $total, \@acctlines, $numlines );
1388 =head2 checkuniquemember (OUEST-PROVENCE)
1390 ($result,$categorycode) = &checkuniquemember($collectivity,$surname,$firstname,$dateofbirth);
1392 Checks that a member exists or not in the database.
1394 C<&result> is nonzero (=exist) or 0 (=does not exist)
1395 C<&categorycode> is from categorycode table
1396 C<&collectivity> is 1 (= we add a collectivity) or 0 (= we add a physical member)
1397 C<&surname> is the surname
1398 C<&firstname> is the firstname (only if collectivity=0)
1399 C<&dateofbirth> is the date of birth in ISO format (only if collectivity=0)
1403 # FIXME: This function is not legitimate. Multiple patrons might have the same first/last name and birthdate.
1404 # This is especially true since first name is not even a required field.
1406 sub checkuniquemember {
1407 my ( $collectivity, $surname, $firstname, $dateofbirth ) = @_;
1408 my $dbh = C4::Context->dbh;
1409 my $request = ($collectivity) ?
1410 "SELECT borrowernumber,categorycode FROM borrowers WHERE surname=? " :
1412 "SELECT borrowernumber,categorycode FROM borrowers WHERE surname=? and firstname=? and dateofbirth=?" :
1413 "SELECT borrowernumber,categorycode FROM borrowers WHERE surname=? and firstname=?";
1414 my $sth = $dbh->prepare($request);
1415 if ($collectivity) {
1416 $sth->execute( uc($surname) );
1417 } elsif($dateofbirth){
1418 $sth->execute( uc($surname), ucfirst($firstname), $dateofbirth );
1420 $sth->execute( uc($surname), ucfirst($firstname));
1422 my @data = $sth->fetchrow;
1423 ( $data[0] ) and return $data[0], $data[1];
1427 sub checkcardnumber {
1428 my ( $cardnumber, $borrowernumber ) = @_;
1430 # If cardnumber is null, we assume they're allowed.
1431 return 0 unless defined $cardnumber;
1433 my $dbh = C4::Context->dbh;
1434 my $query = "SELECT * FROM borrowers WHERE cardnumber=?";
1435 $query .= " AND borrowernumber <> ?" if ($borrowernumber);
1436 my $sth = $dbh->prepare($query);
1439 ( $borrowernumber ? $borrowernumber : () )
1442 return 1 if $sth->fetchrow_hashref;
1444 my ( $min_length, $max_length ) = get_cardnumber_length();
1446 if length $cardnumber > $max_length
1447 or length $cardnumber < $min_length;
1452 =head2 get_cardnumber_length
1454 my ($min, $max) = C4::Members::get_cardnumber_length()
1456 Returns the minimum and maximum length for patron cardnumbers as
1457 determined by the CardnumberLength system preference, the
1458 BorrowerMandatoryField system preference, and the width of the
1463 sub get_cardnumber_length {
1464 my ( $min, $max ) = ( 0, 16 ); # borrowers.cardnumber is a nullable varchar(16)
1465 $min = 1 if C4::Context->preference('BorrowerMandatoryField') =~ /cardnumber/;
1466 if ( my $cardnumber_length = C4::Context->preference('CardnumberLength') ) {
1467 # Is integer and length match
1468 if ( $cardnumber_length =~ m|^\d+$| ) {
1469 $min = $max = $cardnumber_length
1470 if $cardnumber_length >= $min
1471 and $cardnumber_length <= $max;
1473 # Else assuming it is a range
1474 elsif ( $cardnumber_length =~ m|(\d*),(\d*)| ) {
1475 $min = $1 if $1 and $min < $1;
1476 $max = $2 if $2 and $max > $2;
1480 return ( $min, $max );
1483 =head2 getzipnamecity (OUEST-PROVENCE)
1485 take all info from table city for the fields city and zip
1486 check for the name and the zip code of the city selected
1490 sub getzipnamecity {
1492 my $dbh = C4::Context->dbh;
1495 "select city_name,city_state,city_zipcode,city_country from cities where cityid=? ");
1496 $sth->execute($cityid);
1497 my @data = $sth->fetchrow;
1498 return $data[0], $data[1], $data[2], $data[3];
1502 =head2 getdcity (OUEST-PROVENCE)
1504 recover cityid with city_name condition
1509 my ($city_name) = @_;
1510 my $dbh = C4::Context->dbh;
1511 my $sth = $dbh->prepare("select cityid from cities where city_name=? ");
1512 $sth->execute($city_name);
1513 my $data = $sth->fetchrow;
1517 =head2 GetFirstValidEmailAddress
1519 $email = GetFirstValidEmailAddress($borrowernumber);
1521 Return the first valid email address for a borrower, given the borrowernumber. For now, the order
1522 is defined as email, emailpro, B_email. Returns the empty string if the borrower has no email
1527 sub GetFirstValidEmailAddress {
1528 my $borrowernumber = shift;
1529 my $dbh = C4::Context->dbh;
1530 my $sth = $dbh->prepare( "SELECT email, emailpro, B_email FROM borrowers where borrowernumber = ? ");
1531 $sth->execute( $borrowernumber );
1532 my $data = $sth->fetchrow_hashref;
1534 if ($data->{'email'}) {
1535 return $data->{'email'};
1536 } elsif ($data->{'emailpro'}) {
1537 return $data->{'emailpro'};
1538 } elsif ($data->{'B_email'}) {
1539 return $data->{'B_email'};
1545 =head2 GetNoticeEmailAddress
1547 $email = GetNoticeEmailAddress($borrowernumber);
1549 Return the email address of borrower used for notices, given the borrowernumber.
1550 Returns the empty string if no email address.
1554 sub GetNoticeEmailAddress {
1555 my $borrowernumber = shift;
1557 my $which_address = C4::Context->preference("AutoEmailPrimaryAddress");
1558 # if syspref is set to 'first valid' (value == OFF), look up email address
1559 if ( $which_address eq 'OFF' ) {
1560 return GetFirstValidEmailAddress($borrowernumber);
1562 # specified email address field
1563 my $dbh = C4::Context->dbh;
1564 my $sth = $dbh->prepare( qq{
1565 SELECT $which_address AS primaryemail
1567 WHERE borrowernumber=?
1569 $sth->execute($borrowernumber);
1570 my $data = $sth->fetchrow_hashref;
1571 return $data->{'primaryemail'} || '';
1574 =head2 GetExpiryDate
1576 $expirydate = GetExpiryDate($categorycode, $dateenrolled);
1578 Calculate expiry date given a categorycode and starting date. Date argument must be in ISO format.
1579 Return date is also in ISO format.
1584 my ( $categorycode, $dateenrolled ) = @_;
1586 if ($categorycode) {
1587 my $dbh = C4::Context->dbh;
1588 my $sth = $dbh->prepare("SELECT enrolmentperiod,enrolmentperioddate FROM categories WHERE categorycode=?");
1589 $sth->execute($categorycode);
1590 $enrolments = $sth->fetchrow_hashref;
1592 # die "GetExpiryDate: for enrollmentperiod $enrolmentperiod (category '$categorycode') starting $dateenrolled.\n";
1593 my @date = split (/-/,$dateenrolled);
1594 if($enrolments->{enrolmentperiod}){
1595 return sprintf("%04d-%02d-%02d", Add_Delta_YM(@date,0,$enrolments->{enrolmentperiod}));
1597 return $enrolments->{enrolmentperioddate};
1601 =head2 GetborCatFromCatType
1603 ($codes_arrayref, $labels_hashref) = &GetborCatFromCatType();
1605 Looks up the different types of borrowers in the database. Returns two
1606 elements: a reference-to-array, which lists the borrower category
1607 codes, and a reference-to-hash, which maps the borrower category codes
1608 to category descriptions.
1613 sub GetborCatFromCatType {
1614 my ( $category_type, $action, $no_branch_limit ) = @_;
1616 my $branch_limit = $no_branch_limit
1618 : C4::Context->userenv ? C4::Context->userenv->{"branch"} : "";
1620 # FIXME - This API seems both limited and dangerous.
1621 my $dbh = C4::Context->dbh;
1624 SELECT categories.categorycode, categories.description
1628 LEFT JOIN categories_branches ON categories.categorycode = categories_branches.categorycode
1631 $request .= " $action ";
1632 $request .= " AND (branchcode = ? OR branchcode IS NULL) GROUP BY description" if $branch_limit;
1634 $request .= " WHERE branchcode = ? OR branchcode IS NULL GROUP BY description" if $branch_limit;
1636 $request .= " ORDER BY categorycode";
1638 my $sth = $dbh->prepare($request);
1640 $action ? $category_type : (),
1641 $branch_limit ? $branch_limit : ()
1647 while ( my $data = $sth->fetchrow_hashref ) {
1648 push @codes, $data->{'categorycode'};
1649 $labels{ $data->{'categorycode'} } = $data->{'description'};
1652 return ( \@codes, \%labels );
1655 =head2 GetBorrowercategory
1657 $hashref = &GetBorrowercategory($categorycode);
1659 Given the borrower's category code, the function returns the corresponding
1660 data hashref for a comprehensive information display.
1664 sub GetBorrowercategory {
1666 my $dbh = C4::Context->dbh;
1670 "SELECT description,dateofbirthrequired,upperagelimit,category_type
1672 WHERE categorycode = ?"
1674 $sth->execute($catcode);
1676 $sth->fetchrow_hashref;
1680 } # sub getborrowercategory
1683 =head2 GetBorrowerCategorycode
1685 $categorycode = &GetBorrowerCategoryCode( $borrowernumber );
1687 Given the borrowernumber, the function returns the corresponding categorycode
1691 sub GetBorrowerCategorycode {
1692 my ( $borrowernumber ) = @_;
1693 my $dbh = C4::Context->dbh;
1694 my $sth = $dbh->prepare( qq{
1697 WHERE borrowernumber = ?
1699 $sth->execute( $borrowernumber );
1700 return $sth->fetchrow;
1703 =head2 GetBorrowercategoryList
1705 $arrayref_hashref = &GetBorrowercategoryList;
1706 If no category code provided, the function returns all the categories.
1710 sub GetBorrowercategoryList {
1711 my $no_branch_limit = @_ ? shift : 0;
1712 my $branch_limit = $no_branch_limit
1714 : C4::Context->userenv ? C4::Context->userenv->{"branch"} : "";
1715 my $dbh = C4::Context->dbh;
1716 my $query = "SELECT categories.* FROM categories";
1718 LEFT JOIN categories_branches ON categories.categorycode = categories_branches.categorycode
1719 WHERE branchcode = ? OR branchcode IS NULL GROUP BY description
1721 $query .= " ORDER BY description";
1722 my $sth = $dbh->prepare( $query );
1723 $sth->execute( $branch_limit ? $branch_limit : () );
1724 my $data = $sth->fetchall_arrayref( {} );
1727 } # sub getborrowercategory
1729 =head2 ethnicitycategories
1731 ($codes_arrayref, $labels_hashref) = ðnicitycategories();
1733 Looks up the different ethnic types in the database. Returns two
1734 elements: a reference-to-array, which lists the ethnicity codes, and a
1735 reference-to-hash, which maps the ethnicity codes to ethnicity
1742 sub ethnicitycategories {
1743 my $dbh = C4::Context->dbh;
1744 my $sth = $dbh->prepare("Select code,name from ethnicity order by name");
1748 while ( my $data = $sth->fetchrow_hashref ) {
1749 push @codes, $data->{'code'};
1750 $labels{ $data->{'code'} } = $data->{'name'};
1752 return ( \@codes, \%labels );
1757 $ethn_name = &fixEthnicity($ethn_code);
1759 Takes an ethnicity code (e.g., "european" or "pi") and returns the
1760 corresponding descriptive name from the C<ethnicity> table in the
1761 Koha database ("European" or "Pacific Islander").
1768 my $ethnicity = shift;
1769 return unless $ethnicity;
1770 my $dbh = C4::Context->dbh;
1771 my $sth = $dbh->prepare("Select name from ethnicity where code = ?");
1772 $sth->execute($ethnicity);
1773 my $data = $sth->fetchrow_hashref;
1774 return $data->{'name'};
1775 } # sub fixEthnicity
1779 $dateofbirth,$date = &GetAge($date);
1781 this function return the borrowers age with the value of dateofbirth
1787 my ( $date, $date_ref ) = @_;
1789 if ( not defined $date_ref ) {
1790 $date_ref = sprintf( '%04d-%02d-%02d', Today() );
1793 my ( $year1, $month1, $day1 ) = split /-/, $date;
1794 my ( $year2, $month2, $day2 ) = split /-/, $date_ref;
1796 my $age = $year2 - $year1;
1797 if ( $month1 . $day1 > $month2 . $day2 ) {
1806 $borrower = C4::Members::SetAge($borrower, $datetimeduration);
1807 $borrower = C4::Members::SetAge($borrower, '0015-12-10');
1808 $borrower = C4::Members::SetAge($borrower, $datetimeduration, $datetime_reference);
1810 eval { $borrower = C4::Members::SetAge($borrower, '015-1-10'); };
1811 if ($@) {print $@;} #Catch a bad ISO Date or kill your script!
1813 This function sets the borrower's dateofbirth to match the given age.
1814 Optionally relative to the given $datetime_reference.
1816 @PARAM1 koha.borrowers-object
1817 @PARAM2 DateTime::Duration-object as the desired age
1818 OR a ISO 8601 Date. (To make the API more pleasant)
1819 @PARAM3 DateTime-object as the relative date, defaults to now().
1820 RETURNS The given borrower reference @PARAM1.
1821 DIES If there was an error with the ISO Date handling.
1827 my ( $borrower, $datetimeduration, $datetime_ref ) = @_;
1828 $datetime_ref = DateTime->now() unless $datetime_ref;
1830 if ($datetimeduration && ref $datetimeduration ne 'DateTime::Duration') {
1831 if ($datetimeduration =~ /^(\d{4})-(\d{2})-(\d{2})/) {
1832 $datetimeduration = DateTime::Duration->new(years => $1, months => $2, days => $3);
1835 die "C4::Members::SetAge($borrower, $datetimeduration), datetimeduration not a valid ISO 8601 Date!\n";
1839 my $new_datetime_ref = $datetime_ref->clone();
1840 $new_datetime_ref->subtract_duration( $datetimeduration );
1842 $borrower->{dateofbirth} = $new_datetime_ref->ymd();
1849 $cityarrayref = GetCities();
1851 Returns an array_ref of the entries in the cities table
1852 If there are entries in the table an empty row is returned
1853 This is currently only used to populate a popup in memberentry
1859 my $dbh = C4::Context->dbh;
1860 my $city_arr = $dbh->selectall_arrayref(
1861 q|SELECT cityid,city_zipcode,city_name,city_state,city_country FROM cities ORDER BY city_name|,
1863 if ( @{$city_arr} ) {
1864 unshift @{$city_arr}, {
1865 city_zipcode => q{},
1869 city_country => q{},
1876 =head2 GetSortDetails (OUEST-PROVENCE)
1878 ($lib) = &GetSortDetails($category,$sortvalue);
1880 Returns the authorized value details
1881 C<&$lib>return value of authorized value details
1882 C<&$sortvalue>this is the value of authorized value
1883 C<&$category>this is the value of authorized value category
1887 sub GetSortDetails {
1888 my ( $category, $sortvalue ) = @_;
1889 my $dbh = C4::Context->dbh;
1890 my $query = qq|SELECT lib
1891 FROM authorised_values
1893 AND authorised_value=? |;
1894 my $sth = $dbh->prepare($query);
1895 $sth->execute( $category, $sortvalue );
1896 my $lib = $sth->fetchrow;
1897 return ($lib) if ($lib);
1898 return ($sortvalue) unless ($lib);
1901 =head2 MoveMemberToDeleted
1903 $result = &MoveMemberToDeleted($borrowernumber);
1905 Copy the record from borrowers to deletedborrowers table.
1906 The routine returns 1 for success, undef for failure.
1910 sub MoveMemberToDeleted {
1911 my ($member) = shift or return;
1913 my $schema = Koha::Database->new()->schema();
1914 my $borrowers_rs = $schema->resultset('Borrower');
1915 $borrowers_rs->result_class('DBIx::Class::ResultClass::HashRefInflator');
1916 my $borrower = $borrowers_rs->find($member);
1917 return unless $borrower;
1919 my $deleted = $schema->resultset('Deletedborrower')->create($borrower);
1921 return $deleted ? 1 : undef;
1926 DelMember($borrowernumber);
1928 This function remove directly a borrower whitout writing it on deleteborrower.
1929 + Deletes reserves for the borrower
1934 my $dbh = C4::Context->dbh;
1935 my $borrowernumber = shift;
1936 #warn "in delmember with $borrowernumber";
1937 return unless $borrowernumber; # borrowernumber is mandatory.
1939 my $query = qq|DELETE
1941 WHERE borrowernumber=?|;
1942 my $sth = $dbh->prepare($query);
1943 $sth->execute($borrowernumber);
1947 WHERE borrowernumber = ?
1949 $sth = $dbh->prepare($query);
1950 $sth->execute($borrowernumber);
1951 logaction("MEMBERS", "DELETE", $borrowernumber, "") if C4::Context->preference("BorrowersLog");
1955 =head2 ExtendMemberSubscriptionTo (OUEST-PROVENCE)
1957 $date = ExtendMemberSubscriptionTo($borrowerid, $date);
1959 Extending the subscription to a given date or to the expiry date calculated on ISO date.
1964 sub ExtendMemberSubscriptionTo {
1965 my ( $borrowerid,$date) = @_;
1966 my $dbh = C4::Context->dbh;
1967 my $borrower = GetMember('borrowernumber'=>$borrowerid);
1969 $date = (C4::Context->preference('BorrowerRenewalPeriodBase') eq 'dateexpiry') ?
1970 C4::Dates->new($borrower->{'dateexpiry'}, 'iso')->output("iso") :
1971 C4::Dates->new()->output("iso");
1972 $date = GetExpiryDate( $borrower->{'categorycode'}, $date );
1974 my $sth = $dbh->do(<<EOF);
1976 SET dateexpiry='$date'
1977 WHERE borrowernumber='$borrowerid'
1980 AddEnrolmentFeeIfNeeded( $borrower->{categorycode}, $borrower->{borrowernumber} );
1982 logaction("MEMBERS", "RENEW", $borrower->{'borrowernumber'}, "Membership renewed")if C4::Context->preference("BorrowersLog");
1983 return $date if ($sth);
1987 =head2 GetTitles (OUEST-PROVENCE)
1989 ($borrowertitle)= &GetTitles();
1991 Looks up the different title . Returns array with all borrowers title
1996 my @borrowerTitle = split (/,|\|/,C4::Context->preference('BorrowersTitles'));
1997 unshift( @borrowerTitle, "" );
1998 my $count=@borrowerTitle;
2003 return ( \@borrowerTitle);
2007 =head2 GetPatronImage
2009 my ($imagedata, $dberror) = GetPatronImage($borrowernumber);
2011 Returns the mimetype and binary image data of the image for the patron with the supplied borrowernumber.
2015 sub GetPatronImage {
2016 my ($borrowernumber) = @_;
2017 warn "Borrowernumber passed to GetPatronImage is $borrowernumber" if $debug;
2018 my $dbh = C4::Context->dbh;
2019 my $query = 'SELECT mimetype, imagefile FROM patronimage WHERE borrowernumber = ?';
2020 my $sth = $dbh->prepare($query);
2021 $sth->execute($borrowernumber);
2022 my $imagedata = $sth->fetchrow_hashref;
2023 warn "Database error!" if $sth->errstr;
2024 return $imagedata, $sth->errstr;
2027 =head2 PutPatronImage
2029 PutPatronImage($cardnumber, $mimetype, $imgfile);
2031 Stores patron binary image data and mimetype in database.
2032 NOTE: This function is good for updating images as well as inserting new images in the database.
2036 sub PutPatronImage {
2037 my ($cardnumber, $mimetype, $imgfile) = @_;
2038 warn "Parameters passed in: Cardnumber=$cardnumber, Mimetype=$mimetype, " . ($imgfile ? "Imagefile" : "No Imagefile") if $debug;
2039 my $dbh = C4::Context->dbh;
2040 my $query = "INSERT INTO patronimage (borrowernumber, mimetype, imagefile) VALUES ( ( SELECT borrowernumber from borrowers WHERE cardnumber = ? ),?,?) ON DUPLICATE KEY UPDATE imagefile = ?;";
2041 my $sth = $dbh->prepare($query);
2042 $sth->execute($cardnumber,$mimetype,$imgfile,$imgfile);
2043 warn "Error returned inserting $cardnumber.$mimetype." if $sth->errstr;
2044 return $sth->errstr;
2047 =head2 RmPatronImage
2049 my ($dberror) = RmPatronImage($borrowernumber);
2051 Removes the image for the patron with the supplied borrowernumber.
2056 my ($borrowernumber) = @_;
2057 warn "Borrowernumber passed to GetPatronImage is $borrowernumber" if $debug;
2058 my $dbh = C4::Context->dbh;
2059 my $query = "DELETE FROM patronimage WHERE borrowernumber = ?;";
2060 my $sth = $dbh->prepare($query);
2061 $sth->execute($borrowernumber);
2062 my $dberror = $sth->errstr;
2063 warn "Database error!" if $sth->errstr;
2067 =head2 GetHideLostItemsPreference
2069 $hidelostitemspref = &GetHideLostItemsPreference($borrowernumber);
2071 Returns the HideLostItems preference for the patron category of the supplied borrowernumber
2072 C<&$hidelostitemspref>return value of function, 0 or 1
2076 sub GetHideLostItemsPreference {
2077 my ($borrowernumber) = @_;
2078 my $dbh = C4::Context->dbh;
2079 my $query = "SELECT hidelostitems FROM borrowers,categories WHERE borrowers.categorycode = categories.categorycode AND borrowernumber = ?";
2080 my $sth = $dbh->prepare($query);
2081 $sth->execute($borrowernumber);
2082 my $hidelostitems = $sth->fetchrow;
2083 return $hidelostitems;
2086 =head2 GetBorrowersToExpunge
2088 $borrowers = &GetBorrowersToExpunge(
2089 not_borrowered_since => $not_borrowered_since,
2090 expired_before => $expired_before,
2091 category_code => $category_code,
2092 branchcode => $branchcode
2095 This function get all borrowers based on the given criteria.
2099 sub GetBorrowersToExpunge {
2102 my $filterdate = $params->{'not_borrowered_since'};
2103 my $filterexpiry = $params->{'expired_before'};
2104 my $filtercategory = $params->{'category_code'};
2105 my $filterbranch = $params->{'branchcode'} ||
2106 ((C4::Context->preference('IndependentBranches')
2107 && C4::Context->userenv
2108 && !C4::Context->IsSuperLibrarian()
2109 && C4::Context->userenv->{branch})
2110 ? C4::Context->userenv->{branch}
2113 my $dbh = C4::Context->dbh;
2115 SELECT borrowers.borrowernumber,
2116 MAX(old_issues.timestamp) AS latestissue,
2117 MAX(issues.timestamp) AS currentissue
2119 JOIN categories USING (categorycode)
2123 WHERE guarantorid IS NOT NULL
2124 AND guarantorid <> 0
2125 ) as tmp ON borrowers.borrowernumber=tmp.guarantorid
2126 LEFT JOIN old_issues USING (borrowernumber)
2127 LEFT JOIN issues USING (borrowernumber)
2128 WHERE category_type <> 'S'
2129 AND tmp.guarantorid IS NULL
2133 if ( $filterbranch && $filterbranch ne "" ) {
2134 $query.= " AND borrowers.branchcode = ? ";
2135 push( @query_params, $filterbranch );
2137 if ( $filterexpiry ) {
2138 $query .= " AND dateexpiry < ? ";
2139 push( @query_params, $filterexpiry );
2141 if ( $filtercategory ) {
2142 $query .= " AND categorycode = ? ";
2143 push( @query_params, $filtercategory );
2145 $query.=" GROUP BY borrowers.borrowernumber HAVING currentissue IS NULL ";
2146 if ( $filterdate ) {
2147 $query.=" AND ( latestissue < ? OR latestissue IS NULL ) ";
2148 push @query_params,$filterdate;
2150 warn $query if $debug;
2152 my $sth = $dbh->prepare($query);
2153 if (scalar(@query_params)>0){
2154 $sth->execute(@query_params);
2161 while ( my $data = $sth->fetchrow_hashref ) {
2162 push @results, $data;
2167 =head2 GetBorrowersWhoHaveNeverBorrowed
2169 $results = &GetBorrowersWhoHaveNeverBorrowed
2171 This function get all borrowers who have never borrowed.
2173 I<$result> is a ref to an array which all elements are a hasref.
2177 sub GetBorrowersWhoHaveNeverBorrowed {
2178 my $filterbranch = shift ||
2179 ((C4::Context->preference('IndependentBranches')
2180 && C4::Context->userenv
2181 && !C4::Context->IsSuperLibrarian()
2182 && C4::Context->userenv->{branch})
2183 ? C4::Context->userenv->{branch}
2185 my $dbh = C4::Context->dbh;
2187 SELECT borrowers.borrowernumber,max(timestamp) as latestissue
2189 LEFT JOIN issues ON borrowers.borrowernumber = issues.borrowernumber
2190 WHERE issues.borrowernumber IS NULL
2193 if ($filterbranch && $filterbranch ne ""){
2194 $query.=" AND borrowers.branchcode= ?";
2195 push @query_params,$filterbranch;
2197 warn $query if $debug;
2199 my $sth = $dbh->prepare($query);
2200 if (scalar(@query_params)>0){
2201 $sth->execute(@query_params);
2208 while ( my $data = $sth->fetchrow_hashref ) {
2209 push @results, $data;
2214 =head2 GetBorrowersWithIssuesHistoryOlderThan
2216 $results = &GetBorrowersWithIssuesHistoryOlderThan($date)
2218 this function get all borrowers who has an issue history older than I<$date> given on input arg.
2220 I<$result> is a ref to an array which all elements are a hashref.
2221 This hashref is containt the number of time this borrowers has borrowed before I<$date> and the borrowernumber.
2225 sub GetBorrowersWithIssuesHistoryOlderThan {
2226 my $dbh = C4::Context->dbh;
2227 my $date = shift ||POSIX::strftime("%Y-%m-%d",localtime());
2228 my $filterbranch = shift ||
2229 ((C4::Context->preference('IndependentBranches')
2230 && C4::Context->userenv
2231 && !C4::Context->IsSuperLibrarian()
2232 && C4::Context->userenv->{branch})
2233 ? C4::Context->userenv->{branch}
2236 SELECT count(borrowernumber) as n,borrowernumber
2238 WHERE returndate < ?
2239 AND borrowernumber IS NOT NULL
2242 push @query_params, $date;
2244 $query.=" AND branchcode = ?";
2245 push @query_params, $filterbranch;
2247 $query.=" GROUP BY borrowernumber ";
2248 warn $query if $debug;
2249 my $sth = $dbh->prepare($query);
2250 $sth->execute(@query_params);
2253 while ( my $data = $sth->fetchrow_hashref ) {
2254 push @results, $data;
2259 =head2 GetBorrowersNamesAndLatestIssue
2261 $results = &GetBorrowersNamesAndLatestIssueList(@borrowernumbers)
2263 this function get borrowers Names and surnames and Issue information.
2265 I<@borrowernumbers> is an array which all elements are borrowernumbers.
2266 This hashref is containt the number of time this borrowers has borrowed before I<$date> and the borrowernumber.
2270 sub GetBorrowersNamesAndLatestIssue {
2271 my $dbh = C4::Context->dbh;
2272 my @borrowernumbers=@_;
2274 SELECT surname,lastname, phone, email,max(timestamp)
2276 LEFT JOIN issues ON borrowers.borrowernumber=issues.borrowernumber
2277 GROUP BY borrowernumber
2279 my $sth = $dbh->prepare($query);
2281 my $results = $sth->fetchall_arrayref({});
2287 my $success = ModPrivacy( $borrowernumber, $privacy );
2289 Update the privacy of a patron.
2292 true on success, false on failure
2297 my $borrowernumber = shift;
2298 my $privacy = shift;
2299 return unless defined $borrowernumber;
2300 return unless $borrowernumber =~ /^\d+$/;
2302 return ModMember( borrowernumber => $borrowernumber,
2303 privacy => $privacy );
2308 AddMessage( $borrowernumber, $message_type, $message, $branchcode );
2310 Adds a message to the messages table for the given borrower.
2319 my ( $borrowernumber, $message_type, $message, $branchcode ) = @_;
2321 my $dbh = C4::Context->dbh;
2323 if ( ! ( $borrowernumber && $message_type && $message && $branchcode ) ) {
2327 my $query = "INSERT INTO messages ( borrowernumber, branchcode, message_type, message ) VALUES ( ?, ?, ?, ? )";
2328 my $sth = $dbh->prepare($query);
2329 $sth->execute( $borrowernumber, $branchcode, $message_type, $message );
2330 logaction("MEMBERS", "ADDCIRCMESSAGE", $borrowernumber, $message) if C4::Context->preference("BorrowersLog");
2336 GetMessages( $borrowernumber, $type );
2338 $type is message type, B for borrower, or L for Librarian.
2339 Empty type returns all messages of any type.
2341 Returns all messages for the given borrowernumber
2346 my ( $borrowernumber, $type, $branchcode ) = @_;
2352 my $dbh = C4::Context->dbh;
2355 branches.branchname,
2358 messages.branchcode LIKE '$branchcode' AS can_delete
2359 FROM messages, branches
2360 WHERE borrowernumber = ?
2361 AND message_type LIKE ?
2362 AND messages.branchcode = branches.branchcode
2363 ORDER BY message_date DESC";
2364 my $sth = $dbh->prepare($query);
2365 $sth->execute( $borrowernumber, $type ) ;
2368 while ( my $data = $sth->fetchrow_hashref ) {
2369 my $d = C4::Dates->new( $data->{message_date}, 'iso' );
2370 $data->{message_date_formatted} = $d->output;
2371 push @results, $data;
2379 GetMessagesCount( $borrowernumber, $type );
2381 $type is message type, B for borrower, or L for Librarian.
2382 Empty type returns all messages of any type.
2384 Returns the number of messages for the given borrowernumber
2388 sub GetMessagesCount {
2389 my ( $borrowernumber, $type, $branchcode ) = @_;
2395 my $dbh = C4::Context->dbh;
2397 my $query = "SELECT COUNT(*) as MsgCount FROM messages WHERE borrowernumber = ? AND message_type LIKE ?";
2398 my $sth = $dbh->prepare($query);
2399 $sth->execute( $borrowernumber, $type ) ;
2402 my $data = $sth->fetchrow_hashref;
2403 my $count = $data->{'MsgCount'};
2410 =head2 DeleteMessage
2412 DeleteMessage( $message_id );
2417 my ( $message_id ) = @_;
2419 my $dbh = C4::Context->dbh;
2420 my $query = "SELECT * FROM messages WHERE message_id = ?";
2421 my $sth = $dbh->prepare($query);
2422 $sth->execute( $message_id );
2423 my $message = $sth->fetchrow_hashref();
2425 $query = "DELETE FROM messages WHERE message_id = ?";
2426 $sth = $dbh->prepare($query);
2427 $sth->execute( $message_id );
2428 logaction("MEMBERS", "DELCIRCMESSAGE", $message->{'borrowernumber'}, $message->{'message'}) if C4::Context->preference("BorrowersLog");
2433 IssueSlip($branchcode, $borrowernumber, $quickslip)
2435 Returns letter hash ( see C4::Letters::GetPreparedLetter )
2437 $quickslip is boolean, to indicate whether we want a quick slip
2439 IssueSlip populates ISSUESLIP and ISSUEQSLIP, and will make the following expansions:
2475 NOTE: Not all table fields are available, pleasee see GetPendingIssues for a list of available fields.
2480 my ($branch, $borrowernumber, $quickslip) = @_;
2482 # FIXME Check callers before removing this statement
2483 #return unless $borrowernumber;
2485 my @issues = @{ GetPendingIssues($borrowernumber) };
2487 for my $issue (@issues) {
2488 $issue->{date_due} = $issue->{date_due_sql};
2490 my $today = output_pref({ dt => dt_from_string, dateformat => 'iso', dateonly => 1 });
2491 if ( substr( $issue->{issuedate}, 0, 10 ) eq $today
2492 or substr( $issue->{lastreneweddate}, 0, 10 ) eq $today ) {
2498 # Sort on timestamp then on issuedate (useful for tests and could be if modified in a batch
2500 my $s = $b->{timestamp} <=> $a->{timestamp};
2502 $b->{issuedate} <=> $a->{issuedate} : $s;
2505 my ($letter_code, %repeat);
2507 $letter_code = 'ISSUEQSLIP';
2509 'checkedout' => [ map {
2512 'biblioitems' => $_,
2514 }, grep { $_->{'now'} } @issues ],
2518 $letter_code = 'ISSUESLIP';
2520 'checkedout' => [ map {
2523 'biblioitems' => $_,
2525 }, grep { !$_->{'overdue'} } @issues ],
2527 'overdue' => [ map {
2530 'biblioitems' => $_,
2532 }, grep { $_->{'overdue'} } @issues ],
2535 $_->{'timestamp'} = $_->{'newdate'};
2537 } @{ GetNewsToDisplay("slip",$branch) } ],
2541 return C4::Letters::GetPreparedLetter (
2542 module => 'circulation',
2543 letter_code => $letter_code,
2544 branchcode => $branch,
2546 'branches' => $branch,
2547 'borrowers' => $borrowernumber,
2553 =head2 GetBorrowersWithEmail
2555 ([$borrnum,$userid], ...) = GetBorrowersWithEmail('me@example.com');
2557 This gets a list of users and their basic details from their email address.
2558 As it's possible for multiple user to have the same email address, it provides
2559 you with all of them. If there is no userid for the user, there will be an
2560 C<undef> there. An empty list will be returned if there are no matches.
2564 sub GetBorrowersWithEmail {
2567 my $dbh = C4::Context->dbh;
2569 my $query = "SELECT borrowernumber, userid FROM borrowers WHERE email=?";
2570 my $sth=$dbh->prepare($query);
2571 $sth->execute($email);
2573 while (my $ref = $sth->fetch) {
2576 die "Failure searching for borrowers by email address: $sth->errstr" if $sth->err;
2580 sub AddMember_Opac {
2581 my ( %borrower ) = @_;
2583 $borrower{'categorycode'} = C4::Context->preference('PatronSelfRegistrationDefaultCategory');
2585 my $sr = new String::Random;
2586 $sr->{'A'} = [ 'A'..'Z', 'a'..'z' ];
2587 my $password = $sr->randpattern("AAAAAAAAAA");
2588 $borrower{'password'} = $password;
2590 $borrower{'cardnumber'} = fixup_cardnumber();
2592 my $borrowernumber = AddMember(%borrower);
2594 return ( $borrowernumber, $password );
2597 =head2 AddEnrolmentFeeIfNeeded
2599 AddEnrolmentFeeIfNeeded( $borrower->{categorycode}, $borrower->{borrowernumber} );
2601 Add enrolment fee for a patron if needed.
2605 sub AddEnrolmentFeeIfNeeded {
2606 my ( $categorycode, $borrowernumber ) = @_;
2607 # check for enrollment fee & add it if needed
2608 my $dbh = C4::Context->dbh;
2609 my $sth = $dbh->prepare(q{
2612 WHERE categorycode=?
2614 $sth->execute( $categorycode );
2616 warn sprintf('Database returned the following error: %s', $sth->errstr);
2619 my ($enrolmentfee) = $sth->fetchrow;
2620 if ($enrolmentfee && $enrolmentfee > 0) {
2621 # insert fee in patron debts
2622 C4::Accounts::manualinvoice( $borrowernumber, '', '', 'A', $enrolmentfee );
2627 my ( $borrowernumber ) = @_;
2629 my $sql = "SELECT COUNT(*) FROM issues WHERE date_due < NOW() AND borrowernumber = ?";
2630 my $sth = C4::Context->dbh->prepare( $sql );
2631 $sth->execute( $borrowernumber );
2632 my ( $count ) = $sth->fetchrow_array();
2637 END { } # module clean-up code here (global destructor)