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);
37 use C4::NewsChannels; #get slip news
39 use DateTime::Format::DateParse;
41 use Koha::Borrower::Debarments qw(IsDebarred);
42 use Text::Unaccent qw( unac_string );
43 use Koha::AuthUtils qw(hash_password);
45 our ($VERSION,@ISA,@EXPORT,@EXPORT_OK,$debug);
48 $VERSION = 3.07.00.049;
49 $debug = $ENV{DEBUG} || 0;
61 &GetMemberIssuesAndFines
69 &GetFirstValidEmailAddress
70 &GetNoticeEmailAddress
81 &GetHideLostItemsPreference
84 &GetMemberAccountRecords
85 &GetBorNotifyAcctRecord
89 GetBorrowerCategorycode
90 &GetBorrowercategoryList
92 &GetBorrowersToExpunge
93 &GetBorrowersWhoHaveNeverBorrowed
94 &GetBorrowersWithIssuesHistoryOlderThan
104 GetBorrowersWithEmail
127 &ExtendMemberSubscriptionTo
145 C4::Members - Perl Module containing convenience functions for member handling
153 This module contains routines for adding, modifying and deleting members/patrons/borrowers
159 $borrowers_result_array_ref = &Search($filter,$orderby, $limit,
160 $columns_out, $search_on_fields,$searchtype);
162 Looks up patrons (borrowers) on filter. A wrapper for SearchInTable('borrowers').
164 For C<$filter>, C<$orderby>, C<$limit>, C<&columns_out>, C<&search_on_fields> and C<&searchtype>
165 refer to C4::SQLHelper:SearchInTable().
167 Special C<$filter> key '' is effectively expanded to search on surname firstname othernamescw
168 and cardnumber unless C<&search_on_fields> is defined
172 $borrowers = Search('abcd', 'cardnumber');
174 $borrowers = Search({''=>'abcd', category_type=>'I'}, 'surname');
178 sub _express_member_find {
181 # this is used by circulation everytime a new borrowers cardnumber is scanned
182 # so we can check an exact match first, if that works return, otherwise do the rest
183 my $dbh = C4::Context->dbh;
184 my $query = "SELECT borrowernumber FROM borrowers WHERE cardnumber = ?";
185 if ( my $borrowernumber = $dbh->selectrow_array($query, undef, $filter) ) {
186 return( {"borrowernumber"=>$borrowernumber} );
189 my ($search_on_fields, $searchtype);
190 if ( length($filter) == 1 ) {
191 $search_on_fields = [ qw(surname) ];
192 $searchtype = 'start_with';
194 $search_on_fields = [ qw(surname firstname othernames cardnumber) ];
195 $searchtype = 'contain';
198 return (undef, $search_on_fields, $searchtype);
202 my ( $filter, $orderby, $limit, $columns_out, $search_on_fields, $searchtype ) = @_;
207 if ( my $fr = ref $filter ) {
208 if ( $fr eq "HASH" ) {
209 if ( my $search_string = $filter->{''} ) {
210 my ($member_filter, $member_search_on_fields, $member_searchtype) = _express_member_find($search_string);
211 if ($member_filter) {
212 $filter = $member_filter;
215 $search_on_fields ||= $member_search_on_fields;
216 $searchtype ||= $member_searchtype;
221 $search_string = $filter;
225 $search_string = $filter;
226 my ($member_filter, $member_search_on_fields, $member_searchtype) = _express_member_find($search_string);
227 if ($member_filter) {
228 $filter = $member_filter;
231 $search_on_fields ||= $member_search_on_fields;
232 $searchtype ||= $member_searchtype;
236 if ( !$found_borrower && C4::Context->preference('ExtendedPatronAttributes') && $search_string ) {
237 my $matching_records = C4::Members::Attributes::SearchIdMatchingAttribute($search_string);
238 if(scalar(@$matching_records)>0) {
239 if ( my $fr = ref $filter ) {
240 if ( $fr eq "HASH" ) {
242 $filter = [ $filter ];
244 push @$filter, { %f, "borrowernumber"=>$$matching_records };
247 push @$filter, {"borrowernumber"=>$matching_records};
251 $filter = [ $filter ];
252 push @$filter, {"borrowernumber"=>$matching_records};
257 # $showallbranches was not used at the time SearchMember() was mainstreamed into Search().
258 # Mentioning for the reference
260 if ( C4::Context->preference("IndependentBranches") ) { # && !$showallbranches){
261 if ( my $userenv = C4::Context->userenv ) {
262 my $branch = $userenv->{'branch'};
263 if ( !C4::Context->IsSuperLibrarian() && $branch ){
264 if (my $fr = ref $filter) {
265 if ( $fr eq "HASH" ) {
266 $filter->{branchcode} = $branch;
270 $_ = { '' => $_ } unless ref $_;
271 $_->{branchcode} = $branch;
276 $filter = { '' => $filter, branchcode => $branch };
282 if ($found_borrower) {
283 $searchtype = "exact";
285 $searchtype ||= "start_with";
287 return SearchInTable( "borrowers", $filter, $orderby, $limit, $columns_out, $search_on_fields, $searchtype );
290 =head2 GetMemberDetails
292 ($borrower) = &GetMemberDetails($borrowernumber, $cardnumber);
294 Looks up a patron and returns information about him or her. If
295 C<$borrowernumber> is true (nonzero), C<&GetMemberDetails> looks
296 up the borrower by number; otherwise, it looks up the borrower by card
299 C<$borrower> is a reference-to-hash whose keys are the fields of the
300 borrowers table in the Koha database. In addition,
301 C<$borrower-E<gt>{flags}> is a hash giving more detailed information
302 about the patron. Its keys act as flags :
304 if $borrower->{flags}->{LOST} {
305 # Patron's card was reported lost
308 If the state of a flag means that the patron should not be
309 allowed to borrow any more books, then it will have a C<noissues> key
312 See patronflags for more details.
314 C<$borrower-E<gt>{authflags}> is a hash giving more detailed information
315 about the top-level permissions flags set for the borrower. For example,
316 if a user has the "editcatalogue" permission,
317 C<$borrower-E<gt>{authflags}-E<gt>{editcatalogue}> will exist and have
322 sub GetMemberDetails {
323 my ( $borrowernumber, $cardnumber ) = @_;
324 my $dbh = C4::Context->dbh;
327 if ($borrowernumber) {
328 $sth = $dbh->prepare("SELECT borrowers.*,category_type,categories.description,reservefee,enrolmentperiod FROM borrowers LEFT JOIN categories ON borrowers.categorycode=categories.categorycode WHERE borrowernumber=?");
329 $sth->execute($borrowernumber);
331 elsif ($cardnumber) {
332 $sth = $dbh->prepare("SELECT borrowers.*,category_type,categories.description,reservefee,enrolmentperiod FROM borrowers LEFT JOIN categories ON borrowers.categorycode=categories.categorycode WHERE cardnumber=?");
333 $sth->execute($cardnumber);
338 my $borrower = $sth->fetchrow_hashref;
339 my ($amount) = GetMemberAccountRecords( $borrowernumber);
340 $borrower->{'amountoutstanding'} = $amount;
341 # FIXME - patronflags calls GetMemberAccountRecords... just have patronflags return $amount
342 my $flags = patronflags( $borrower);
345 $sth = $dbh->prepare("select bit,flag from userflags");
347 while ( my ( $bit, $flag ) = $sth->fetchrow ) {
348 if ( $borrower->{'flags'} && $borrower->{'flags'} & 2**$bit ) {
349 $accessflagshash->{$flag} = 1;
352 $borrower->{'flags'} = $flags;
353 $borrower->{'authflags'} = $accessflagshash;
355 # For the purposes of making templates easier, we'll define a
356 # 'showname' which is the alternate form the user's first name if
357 # 'other name' is defined.
358 if ($borrower->{category_type} eq 'I') {
359 $borrower->{'showname'} = $borrower->{'othernames'};
360 $borrower->{'showname'} .= " $borrower->{'firstname'}" if $borrower->{'firstname'};
362 $borrower->{'showname'} = $borrower->{'firstname'};
365 return ($borrower); #, $flags, $accessflagshash);
370 $flags = &patronflags($patron);
372 This function is not exported.
374 The following will be set where applicable:
375 $flags->{CHARGES}->{amount} Amount of debt
376 $flags->{CHARGES}->{noissues} Set if debt amount >$5.00 (or syspref noissuescharge)
377 $flags->{CHARGES}->{message} Message -- deprecated
379 $flags->{CREDITS}->{amount} Amount of credit
380 $flags->{CREDITS}->{message} Message -- deprecated
382 $flags->{ GNA } Patron has no valid address
383 $flags->{ GNA }->{noissues} Set for each GNA
384 $flags->{ GNA }->{message} "Borrower has no valid address" -- deprecated
386 $flags->{ LOST } Patron's card reported lost
387 $flags->{ LOST }->{noissues} Set for each LOST
388 $flags->{ LOST }->{message} Message -- deprecated
390 $flags->{DBARRED} Set if patron debarred, no access
391 $flags->{DBARRED}->{noissues} Set for each DBARRED
392 $flags->{DBARRED}->{message} Message -- deprecated
395 $flags->{ NOTES }->{message} The note itself. NOT deprecated
397 $flags->{ ODUES } Set if patron has overdue books.
398 $flags->{ ODUES }->{message} "Yes" -- deprecated
399 $flags->{ ODUES }->{itemlist} ref-to-array: list of overdue books
400 $flags->{ ODUES }->{itemlisttext} Text list of overdue items -- deprecated
402 $flags->{WAITING} Set if any of patron's reserves are available
403 $flags->{WAITING}->{message} Message -- deprecated
404 $flags->{WAITING}->{itemlist} ref-to-array: list of available items
408 =item C<$flags-E<gt>{ODUES}-E<gt>{itemlist}> is a reference-to-array listing the
409 overdue items. Its elements are references-to-hash, each describing an
410 overdue item. The keys are selected fields from the issues, biblio,
411 biblioitems, and items tables of the Koha database.
413 =item C<$flags-E<gt>{ODUES}-E<gt>{itemlisttext}> is a string giving a text listing of
414 the overdue items, one per line. Deprecated.
416 =item C<$flags-E<gt>{WAITING}-E<gt>{itemlist}> is a reference-to-array listing the
417 available items. Each element is a reference-to-hash whose keys are
418 fields from the reserves table of the Koha database.
422 All the "message" fields that include language generated in this function are deprecated,
423 because such strings belong properly in the display layer.
425 The "message" field that comes from the DB is OK.
429 # TODO: use {anonymous => hashes} instead of a dozen %flaginfo
430 # FIXME rename this function.
433 my ( $patroninformation) = @_;
434 my $dbh=C4::Context->dbh;
435 my ($balance, $owing) = GetMemberAccountBalance( $patroninformation->{'borrowernumber'});
438 my $noissuescharge = C4::Context->preference("noissuescharge") || 5;
439 $flaginfo{'message'} = sprintf 'Patron owes %.02f', $owing;
440 $flaginfo{'amount'} = sprintf "%.02f", $owing;
441 if ( $owing > $noissuescharge && !C4::Context->preference("AllowFineOverride") ) {
442 $flaginfo{'noissues'} = 1;
444 $flags{'CHARGES'} = \%flaginfo;
446 elsif ( $balance < 0 ) {
448 $flaginfo{'message'} = sprintf 'Patron has credit of %.02f', -$balance;
449 $flaginfo{'amount'} = sprintf "%.02f", $balance;
450 $flags{'CREDITS'} = \%flaginfo;
452 if ( $patroninformation->{'gonenoaddress'}
453 && $patroninformation->{'gonenoaddress'} == 1 )
456 $flaginfo{'message'} = 'Borrower has no valid address.';
457 $flaginfo{'noissues'} = 1;
458 $flags{'GNA'} = \%flaginfo;
460 if ( $patroninformation->{'lost'} && $patroninformation->{'lost'} == 1 ) {
462 $flaginfo{'message'} = 'Borrower\'s card reported lost.';
463 $flaginfo{'noissues'} = 1;
464 $flags{'LOST'} = \%flaginfo;
466 if ( $patroninformation->{'debarred'} && check_date( split( /-/, $patroninformation->{'debarred'} ) ) ) {
467 if ( Date_to_Days(Date::Calc::Today) < Date_to_Days( split( /-/, $patroninformation->{'debarred'} ) ) ) {
469 $flaginfo{'debarredcomment'} = $patroninformation->{'debarredcomment'};
470 $flaginfo{'message'} = $patroninformation->{'debarredcomment'};
471 $flaginfo{'noissues'} = 1;
472 $flaginfo{'dateend'} = $patroninformation->{'debarred'};
473 $flags{'DBARRED'} = \%flaginfo;
476 if ( $patroninformation->{'borrowernotes'}
477 && $patroninformation->{'borrowernotes'} )
480 $flaginfo{'message'} = $patroninformation->{'borrowernotes'};
481 $flags{'NOTES'} = \%flaginfo;
483 my ( $odues, $itemsoverdue ) = C4::Overdues::checkoverdues($patroninformation->{'borrowernumber'});
484 if ( $odues && $odues > 0 ) {
486 $flaginfo{'message'} = "Yes";
487 $flaginfo{'itemlist'} = $itemsoverdue;
488 foreach ( sort { $a->{'date_due'} cmp $b->{'date_due'} }
491 $flaginfo{'itemlisttext'} .=
492 "$_->{'date_due'} $_->{'barcode'} $_->{'title'} \n"; # newline is display layer
494 $flags{'ODUES'} = \%flaginfo;
496 my @itemswaiting = C4::Reserves::GetReservesFromBorrowernumber( $patroninformation->{'borrowernumber'},'W' );
497 my $nowaiting = scalar @itemswaiting;
498 if ( $nowaiting > 0 ) {
500 $flaginfo{'message'} = "Reserved items available";
501 $flaginfo{'itemlist'} = \@itemswaiting;
502 $flags{'WAITING'} = \%flaginfo;
510 $borrower = &GetMember(%information);
512 Retrieve the first patron record meeting on criteria listed in the
513 C<%information> hash, which should contain one or more
514 pairs of borrowers column names and values, e.g.,
516 $borrower = GetMember(borrowernumber => id);
518 C<&GetBorrower> returns a reference-to-hash whose keys are the fields of
519 the C<borrowers> table in the Koha database.
521 FIXME: GetMember() is used throughout the code as a lookup
522 on a unique key such as the borrowernumber, but this meaning is not
523 enforced in the routine itself.
529 my ( %information ) = @_;
530 if (exists $information{borrowernumber} && !defined $information{borrowernumber}) {
531 #passing mysql's kohaadmin?? Makes no sense as a query
534 my $dbh = C4::Context->dbh;
536 q{SELECT borrowers.*, categories.category_type, categories.description
538 LEFT JOIN categories on borrowers.categorycode=categories.categorycode WHERE };
541 for (keys %information ) {
549 if (defined $information{$_}) {
551 push @values, $information{$_};
554 $select .= "$_ IS NULL";
557 $debug && warn $select, " ",values %information;
558 my $sth = $dbh->prepare("$select");
559 $sth->execute(map{$information{$_}} keys %information);
560 my $data = $sth->fetchall_arrayref({});
561 #FIXME interface to this routine now allows generation of a result set
562 #so whole array should be returned but bowhere in the current code expects this
570 =head2 GetMemberRelatives
572 @borrowernumbers = GetMemberRelatives($borrowernumber);
574 C<GetMemberRelatives> returns a borrowersnumber's list of guarantor/guarantees of the member given in parameter
577 sub GetMemberRelatives {
578 my $borrowernumber = shift;
579 my $dbh = C4::Context->dbh;
583 my $query = "SELECT guarantorid FROM borrowers WHERE borrowernumber=?";
584 my $sth = $dbh->prepare($query);
585 $sth->execute($borrowernumber);
586 my $data = $sth->fetchrow_arrayref();
587 push @glist, $data->[0] if $data->[0];
588 my $guarantor = $data->[0] ? $data->[0] : undef;
591 $query = "SELECT borrowernumber FROM borrowers WHERE guarantorid=?";
592 $sth = $dbh->prepare($query);
593 $sth->execute($borrowernumber);
594 while ($data = $sth->fetchrow_arrayref()) {
595 push @glist, $data->[0];
598 # Getting sibling guarantees
600 $query = "SELECT borrowernumber FROM borrowers WHERE guarantorid=?";
601 $sth = $dbh->prepare($query);
602 $sth->execute($guarantor);
603 while ($data = $sth->fetchrow_arrayref()) {
604 push @glist, $data->[0] if ($data->[0] != $borrowernumber);
611 =head2 IsMemberBlocked
613 my ($block_status, $count) = IsMemberBlocked( $borrowernumber );
615 Returns whether a patron has overdue items that may result
616 in a block or whether the patron has active fine days
617 that would block circulation privileges.
619 C<$block_status> can have the following values:
621 1 if the patron has outstanding fine days, in which case C<$count> is the number of them
623 -1 if the patron has overdue items, in which case C<$count> is the number of them
625 0 if the patron has no overdue items or outstanding fine days, in which case C<$count> is 0
627 Outstanding fine days are checked before current overdue items
630 FIXME: this needs to be split into two functions; a potential block
631 based on the number of current overdue items could be orthogonal
632 to a block based on whether the patron has any fine days accrued.
636 sub IsMemberBlocked {
637 my $borrowernumber = shift;
638 my $dbh = C4::Context->dbh;
640 my $blockeddate = Koha::Borrower::Debarments::IsDebarred($borrowernumber);
642 return ( 1, $blockeddate ) if $blockeddate;
644 # if he have late issues
645 my $sth = $dbh->prepare(
646 "SELECT COUNT(*) as latedocs
648 WHERE borrowernumber = ?
649 AND date_due < now()"
651 $sth->execute($borrowernumber);
652 my $latedocs = $sth->fetchrow_hashref->{'latedocs'};
654 return ( -1, $latedocs ) if $latedocs > 0;
659 =head2 GetMemberIssuesAndFines
661 ($overdue_count, $issue_count, $total_fines) = &GetMemberIssuesAndFines($borrowernumber);
663 Returns aggregate data about items borrowed by the patron with the
664 given borrowernumber.
666 C<&GetMemberIssuesAndFines> returns a three-element array. C<$overdue_count> is the
667 number of overdue items the patron currently has borrowed. C<$issue_count> is the
668 number of books the patron currently has borrowed. C<$total_fines> is
669 the total fine currently due by the borrower.
674 sub GetMemberIssuesAndFines {
675 my ( $borrowernumber ) = @_;
676 my $dbh = C4::Context->dbh;
677 my $query = "SELECT COUNT(*) FROM issues WHERE borrowernumber = ?";
679 $debug and warn $query."\n";
680 my $sth = $dbh->prepare($query);
681 $sth->execute($borrowernumber);
682 my $issue_count = $sth->fetchrow_arrayref->[0];
684 $sth = $dbh->prepare(
685 "SELECT COUNT(*) FROM issues
686 WHERE borrowernumber = ?
687 AND date_due < now()"
689 $sth->execute($borrowernumber);
690 my $overdue_count = $sth->fetchrow_arrayref->[0];
692 $sth = $dbh->prepare("SELECT SUM(amountoutstanding) FROM accountlines WHERE borrowernumber = ?");
693 $sth->execute($borrowernumber);
694 my $total_fines = $sth->fetchrow_arrayref->[0];
696 return ($overdue_count, $issue_count, $total_fines);
702 my @columns = C4::Member::columns();
704 Returns an array of borrowers' table columns on success,
705 and an empty array on failure.
711 # Pure ANSI SQL goodness.
712 my $sql = 'SELECT * FROM borrowers WHERE 1=0;';
714 # Get the database handle.
715 my $dbh = C4::Context->dbh;
717 # Run the SQL statement to load STH's readonly properties.
718 my $sth = $dbh->prepare($sql);
719 my $rv = $sth->execute();
721 # This only fails if the table doesn't exist.
722 # This will always be called AFTER an install or upgrade,
723 # so borrowers will exist!
725 if ($sth->{NUM_OF_FIELDS}>0) {
726 @data = @{$sth->{NAME}};
737 my $success = ModMember(borrowernumber => $borrowernumber,
738 [ field => value ]... );
740 Modify borrower's data. All date fields should ALREADY be in ISO format.
743 true on success, or false on failure
749 # test to know if you must update or not the borrower password
750 if (exists $data{password}) {
751 if ($data{password} eq '****' or $data{password} eq '') {
752 delete $data{password};
754 $data{password} = hash_password($data{password});
757 my $old_categorycode = GetBorrowerCategorycode( $data{borrowernumber} );
758 my $execute_success=UpdateInTable("borrowers",\%data);
759 if ($execute_success) { # only proceed if the update was a success
760 # ok if its an adult (type) it may have borrowers that depend on it as a guarantor
761 # so when we update information for an adult we should check for guarantees and update the relevant part
762 # of their records, ie addresses and phone numbers
763 my $borrowercategory= GetBorrowercategory( $data{'category_type'} );
764 if ( exists $borrowercategory->{'category_type'} && $borrowercategory->{'category_type'} eq ('A' || 'S') ) {
765 # is adult check guarantees;
766 UpdateGuarantees(%data);
769 # If the patron changes to a category with enrollment fee, we add a fee
770 if ( $data{categorycode} and $data{categorycode} ne $old_categorycode ) {
771 AddEnrolmentFeeIfNeeded( $data{categorycode}, $data{borrowernumber} );
774 logaction("MEMBERS", "MODIFY", $data{'borrowernumber'}, "UPDATE (executed w/ arg: $data{'borrowernumber'})") if C4::Context->preference("BorrowersLog");
776 return $execute_success;
781 $borrowernumber = &AddMember(%borrower);
783 insert new borrower into table
784 Returns the borrowernumber upon success
786 Returns as undef upon any db error without further processing
793 my $dbh = C4::Context->dbh;
795 # generate a proper login if none provided
796 $data{'userid'} = Generate_Userid($data{'borrowernumber'}, $data{'firstname'}, $data{'surname'}) if $data{'userid'} eq '';
798 # add expiration date if it isn't already there
799 unless ( $data{'dateexpiry'} ) {
800 $data{'dateexpiry'} = GetExpiryDate( $data{'categorycode'}, C4::Dates->new()->output("iso") );
803 # add enrollment date if it isn't already there
804 unless ( $data{'dateenrolled'} ) {
805 $data{'dateenrolled'} = C4::Dates->new()->output("iso");
808 # create a disabled account if no password provided
809 $data{'password'} = ($data{'password'})? hash_password($data{'password'}) : '!';
810 $data{'borrowernumber'}=InsertInTable("borrowers",\%data);
812 # mysql_insertid is probably bad. not necessarily accurate and mysql-specific at best.
813 logaction("MEMBERS", "CREATE", $data{'borrowernumber'}, "") if C4::Context->preference("BorrowersLog");
815 AddEnrolmentFeeIfNeeded( $data{categorycode}, $data{borrowernumber} );
817 return $data{'borrowernumber'};
822 my $uniqueness = Check_Userid($userid,$borrowernumber);
824 $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 != '').
826 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.
829 0 for not unique (i.e. this $userid already exists)
830 1 for unique (i.e. this $userid does not exist, or this $userid/$borrowernumber combination already exists)
835 my ($uid,$member) = @_;
836 my $dbh = C4::Context->dbh;
839 "SELECT * FROM borrowers WHERE userid=? AND borrowernumber != ?");
840 $sth->execute( $uid, $member );
841 if ( ( $uid ne '' ) && ( my $row = $sth->fetchrow_hashref ) ) {
849 =head2 Generate_Userid
851 my $newuid = Generate_Userid($borrowernumber, $firstname, $surname);
853 Generate a userid using the $surname and the $firstname (if there is a value in $firstname).
855 $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.
858 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).
862 sub Generate_Userid {
863 my ($borrowernumber, $firstname, $surname) = @_;
866 #The script will "do" the following code and increment the $offset until Check_Userid = 1 (i.e. until $newuid comes back as unique)
868 $firstname =~ s/[[:digit:][:space:][:blank:][:punct:][:cntrl:]]//g;
869 $surname =~ s/[[:digit:][:space:][:blank:][:punct:][:cntrl:]]//g;
870 $newuid = lc(($firstname)? "$firstname.$surname" : $surname);
871 $newuid = unac_string('utf-8',$newuid);
872 $newuid .= $offset unless $offset == 0;
875 } while (!Check_Userid($newuid,$borrowernumber));
881 my ( $uid, $member, $digest ) = @_;
882 my $dbh = C4::Context->dbh;
884 #Make sure the userid chosen is unique and not theirs if non-empty. If it is not,
885 #Then we need to tell the user and have them create a new one.
889 "SELECT * FROM borrowers WHERE userid=? AND borrowernumber != ?");
890 $sth->execute( $uid, $member );
891 if ( ( $uid ne '' ) && ( my $row = $sth->fetchrow_hashref ) ) {
895 #Everything is good so we can update the information.
898 "update borrowers set userid=?, password=? where borrowernumber=?");
899 $sth->execute( $uid, $digest, $member );
903 logaction("MEMBERS", "CHANGE PASS", $member, "") if C4::Context->preference("BorrowersLog");
909 =head2 fixup_cardnumber
911 Warning: The caller is responsible for locking the members table in write
912 mode, to avoid database corruption.
916 use vars qw( @weightings );
917 my @weightings = ( 8, 4, 6, 3, 5, 2, 1 );
919 sub fixup_cardnumber {
920 my ($cardnumber) = @_;
921 my $autonumber_members = C4::Context->boolean_preference('autoMemberNum') || 0;
923 # Find out whether member numbers should be generated
924 # automatically. Should be either "1" or something else.
925 # Defaults to "0", which is interpreted as "no".
927 # if ($cardnumber !~ /\S/ && $autonumber_members) {
928 ($autonumber_members) or return $cardnumber;
929 my $checkdigit = C4::Context->preference('checkdigit');
930 my $dbh = C4::Context->dbh;
931 if ( $checkdigit and $checkdigit eq 'katipo' ) {
933 # if checkdigit is selected, calculate katipo-style cardnumber.
934 # otherwise, just use the max()
935 # purpose: generate checksum'd member numbers.
936 # We'll assume we just got the max value of digits 2-8 of member #'s
937 # from the database and our job is to increment that by one,
938 # determine the 1st and 9th digits and return the full string.
939 my $sth = $dbh->prepare(
940 "select max(substring(borrowers.cardnumber,2,7)) as new_num from borrowers"
943 my $data = $sth->fetchrow_hashref;
944 $cardnumber = $data->{new_num};
945 if ( !$cardnumber ) { # If DB has no values,
946 $cardnumber = 1000000; # start at 1000000
952 for ( my $i = 0 ; $i < 8 ; $i += 1 ) {
953 # read weightings, left to right, 1 char at a time
954 my $temp1 = $weightings[$i];
956 # sequence left to right, 1 char at a time
957 my $temp2 = substr( $cardnumber, $i, 1 );
959 # mult each char 1-7 by its corresponding weighting
960 $sum += $temp1 * $temp2;
963 my $rem = ( $sum % 11 );
964 $rem = 'X' if $rem == 10;
966 return "V$cardnumber$rem";
969 my $sth = $dbh->prepare(
970 'SELECT MAX( CAST( cardnumber AS SIGNED ) ) FROM borrowers WHERE cardnumber REGEXP "^-?[0-9]+$"'
973 my ($result) = $sth->fetchrow;
976 return $cardnumber; # just here as a fallback/reminder
981 ($num_children, $children_arrayref) = &GetGuarantees($parent_borrno);
982 $child0_cardno = $children_arrayref->[0]{"cardnumber"};
983 $child0_borrno = $children_arrayref->[0]{"borrowernumber"};
985 C<&GetGuarantees> takes a borrower number (e.g., that of a patron
986 with children) and looks up the borrowers who are guaranteed by that
987 borrower (i.e., the patron's children).
989 C<&GetGuarantees> returns two values: an integer giving the number of
990 borrowers guaranteed by C<$parent_borrno>, and a reference to an array
991 of references to hash, which gives the actual results.
997 my ($borrowernumber) = @_;
998 my $dbh = C4::Context->dbh;
1001 "select cardnumber,borrowernumber, firstname, surname from borrowers where guarantorid=?"
1003 $sth->execute($borrowernumber);
1006 my $data = $sth->fetchall_arrayref({});
1007 return ( scalar(@$data), $data );
1010 =head2 UpdateGuarantees
1012 &UpdateGuarantees($parent_borrno);
1015 C<&UpdateGuarantees> borrower data for an adult and updates all the guarantees
1016 with the modified information
1021 sub UpdateGuarantees {
1023 my $dbh = C4::Context->dbh;
1024 my ( $count, $guarantees ) = GetGuarantees( $data{'borrowernumber'} );
1025 foreach my $guarantee (@$guarantees){
1026 my $guaquery = qq|UPDATE borrowers
1027 SET address=?,fax=?,B_city=?,mobile=?,city=?,phone=?
1028 WHERE borrowernumber=?
1030 my $sth = $dbh->prepare($guaquery);
1031 $sth->execute($data{'address'},$data{'fax'},$data{'B_city'},$data{'mobile'},$data{'city'},$data{'phone'},$guarantee->{'borrowernumber'});
1034 =head2 GetPendingIssues
1036 my $issues = &GetPendingIssues(@borrowernumber);
1038 Looks up what the patron with the given borrowernumber has borrowed.
1040 C<&GetPendingIssues> returns a
1041 reference-to-array where each element is a reference-to-hash; the
1042 keys are the fields from the C<issues>, C<biblio>, and C<items> tables.
1043 The keys include C<biblioitems> fields except marc and marcxml.
1048 sub GetPendingIssues {
1049 my @borrowernumbers = @_;
1051 unless (@borrowernumbers ) { # return a ref_to_array
1052 return \@borrowernumbers; # to not cause surprise to caller
1055 # Borrowers part of the query
1057 for (my $i = 0; $i < @borrowernumbers; $i++) {
1058 $bquery .= ' issues.borrowernumber = ?';
1059 if ($i < $#borrowernumbers ) {
1064 # must avoid biblioitems.* to prevent large marc and marcxml fields from killing performance
1065 # FIXME: namespace collision: each table has "timestamp" fields. Which one is "timestamp" ?
1066 # FIXME: circ/ciculation.pl tries to sort by timestamp!
1067 # FIXME: namespace collision: other collisions possible.
1068 # FIXME: most of this data isn't really being used by callers.
1075 biblioitems.itemtype,
1078 biblioitems.publicationyear,
1079 biblioitems.publishercode,
1080 biblioitems.volumedate,
1081 biblioitems.volumedesc,
1084 borrowers.firstname,
1086 borrowers.cardnumber,
1087 issues.timestamp AS timestamp,
1088 issues.renewals AS renewals,
1089 issues.borrowernumber AS borrowernumber,
1090 items.renewals AS totalrenewals
1092 LEFT JOIN items ON items.itemnumber = issues.itemnumber
1093 LEFT JOIN biblio ON items.biblionumber = biblio.biblionumber
1094 LEFT JOIN biblioitems ON items.biblioitemnumber = biblioitems.biblioitemnumber
1095 LEFT JOIN borrowers ON issues.borrowernumber = borrowers.borrowernumber
1098 ORDER BY issues.issuedate"
1101 my $sth = C4::Context->dbh->prepare($query);
1102 $sth->execute(@borrowernumbers);
1103 my $data = $sth->fetchall_arrayref({});
1104 my $tz = C4::Context->tz();
1105 my $today = DateTime->now( time_zone => $tz);
1106 foreach (@{$data}) {
1107 if ($_->{issuedate}) {
1108 $_->{issuedate} = dt_from_string($_->{issuedate}, 'sql');
1110 $_->{date_due} or next;
1111 $_->{date_due} = DateTime::Format::DateParse->parse_datetime($_->{date_due}, $tz->name());
1112 if ( DateTime->compare($_->{date_due}, $today) == -1 ) {
1121 $issues = &GetAllIssues($borrowernumber, $sortkey, $limit);
1123 Looks up what the patron with the given borrowernumber has borrowed,
1124 and sorts the results.
1126 C<$sortkey> is the name of a field on which to sort the results. This
1127 should be the name of a field in the C<issues>, C<biblio>,
1128 C<biblioitems>, or C<items> table in the Koha database.
1130 C<$limit> is the maximum number of results to return.
1132 C<&GetAllIssues> an arrayref, C<$issues>, of hashrefs, the keys of which
1133 are the fields from the C<issues>, C<biblio>, C<biblioitems>, and
1134 C<items> tables of the Koha database.
1140 my ( $borrowernumber, $order, $limit ) = @_;
1142 my $dbh = C4::Context->dbh;
1144 'SELECT *, issues.timestamp as issuestimestamp, issues.renewals AS renewals,items.renewals AS totalrenewals,items.timestamp AS itemstimestamp
1146 LEFT JOIN items on items.itemnumber=issues.itemnumber
1147 LEFT JOIN biblio ON items.biblionumber=biblio.biblionumber
1148 LEFT JOIN biblioitems ON items.biblioitemnumber=biblioitems.biblioitemnumber
1149 WHERE borrowernumber=?
1151 SELECT *, old_issues.timestamp as issuestimestamp, old_issues.renewals AS renewals,items.renewals AS totalrenewals,items.timestamp AS itemstimestamp
1153 LEFT JOIN items on items.itemnumber=old_issues.itemnumber
1154 LEFT JOIN biblio ON items.biblionumber=biblio.biblionumber
1155 LEFT JOIN biblioitems ON items.biblioitemnumber=biblioitems.biblioitemnumber
1156 WHERE borrowernumber=? AND old_issues.itemnumber IS NOT NULL
1157 order by ' . $order;
1159 $query .= " limit $limit";
1162 my $sth = $dbh->prepare($query);
1163 $sth->execute( $borrowernumber, $borrowernumber );
1164 return $sth->fetchall_arrayref( {} );
1168 =head2 GetMemberAccountRecords
1170 ($total, $acctlines, $count) = &GetMemberAccountRecords($borrowernumber);
1172 Looks up accounting data for the patron with the given borrowernumber.
1174 C<&GetMemberAccountRecords> returns a three-element array. C<$acctlines> is a
1175 reference-to-array, where each element is a reference-to-hash; the
1176 keys are the fields of the C<accountlines> table in the Koha database.
1177 C<$count> is the number of elements in C<$acctlines>. C<$total> is the
1178 total amount outstanding for all of the account lines.
1182 sub GetMemberAccountRecords {
1183 my ($borrowernumber) = @_;
1184 my $dbh = C4::Context->dbh;
1190 WHERE borrowernumber=?);
1191 $strsth.=" ORDER BY date desc,timestamp DESC";
1192 my $sth= $dbh->prepare( $strsth );
1193 $sth->execute( $borrowernumber );
1196 while ( my $data = $sth->fetchrow_hashref ) {
1197 if ( $data->{itemnumber} ) {
1198 my $biblio = GetBiblioFromItemNumber( $data->{itemnumber} );
1199 $data->{biblionumber} = $biblio->{biblionumber};
1200 $data->{title} = $biblio->{title};
1202 $acctlines[$numlines] = $data;
1204 $total += int(1000 * $data->{'amountoutstanding'}); # convert float to integer to avoid round-off errors
1207 return ( $total, \@acctlines,$numlines);
1210 =head2 GetMemberAccountBalance
1212 ($total_balance, $non_issue_balance, $other_charges) = &GetMemberAccountBalance($borrowernumber);
1214 Calculates amount immediately owing by the patron - non-issue charges.
1215 Based on GetMemberAccountRecords.
1216 Charges exempt from non-issue are:
1218 * Rent (rental) if RentalsInNoissuesCharge syspref is set to false
1219 * Manual invoices if ManInvInNoissuesCharge syspref is set to false
1223 sub GetMemberAccountBalance {
1224 my ($borrowernumber) = @_;
1226 my $ACCOUNT_TYPE_LENGTH = 5; # this is plain ridiculous...
1228 my @not_fines = ('Res');
1229 push @not_fines, 'Rent' unless C4::Context->preference('RentalsInNoissuesCharge');
1230 unless ( C4::Context->preference('ManInvInNoissuesCharge') ) {
1231 my $dbh = C4::Context->dbh;
1232 my $man_inv_types = $dbh->selectcol_arrayref(qq{SELECT authorised_value FROM authorised_values WHERE category = 'MANUAL_INV'});
1233 push @not_fines, map substr($_, 0, $ACCOUNT_TYPE_LENGTH), @$man_inv_types;
1235 my %not_fine = map {$_ => 1} @not_fines;
1237 my ($total, $acctlines) = GetMemberAccountRecords($borrowernumber);
1238 my $other_charges = 0;
1239 foreach (@$acctlines) {
1240 $other_charges += $_->{amountoutstanding} if $not_fine{ substr($_->{accounttype}, 0, $ACCOUNT_TYPE_LENGTH) };
1243 return ( $total, $total - $other_charges, $other_charges);
1246 =head2 GetBorNotifyAcctRecord
1248 ($total, $acctlines, $count) = &GetBorNotifyAcctRecord($params,$notifyid);
1250 Looks up accounting data for the patron with the given borrowernumber per file number.
1252 C<&GetBorNotifyAcctRecord> returns a three-element array. C<$acctlines> is a
1253 reference-to-array, where each element is a reference-to-hash; the
1254 keys are the fields of the C<accountlines> table in the Koha database.
1255 C<$count> is the number of elements in C<$acctlines>. C<$total> is the
1256 total amount outstanding for all of the account lines.
1260 sub GetBorNotifyAcctRecord {
1261 my ( $borrowernumber, $notifyid ) = @_;
1262 my $dbh = C4::Context->dbh;
1265 my $sth = $dbh->prepare(
1268 WHERE borrowernumber=?
1270 AND amountoutstanding != '0'
1271 ORDER BY notify_id,accounttype
1274 $sth->execute( $borrowernumber, $notifyid );
1276 while ( my $data = $sth->fetchrow_hashref ) {
1277 if ( $data->{itemnumber} ) {
1278 my $biblio = GetBiblioFromItemNumber( $data->{itemnumber} );
1279 $data->{biblionumber} = $biblio->{biblionumber};
1280 $data->{title} = $biblio->{title};
1282 $acctlines[$numlines] = $data;
1284 $total += int(100 * $data->{'amountoutstanding'});
1287 return ( $total, \@acctlines, $numlines );
1290 =head2 checkuniquemember (OUEST-PROVENCE)
1292 ($result,$categorycode) = &checkuniquemember($collectivity,$surname,$firstname,$dateofbirth);
1294 Checks that a member exists or not in the database.
1296 C<&result> is nonzero (=exist) or 0 (=does not exist)
1297 C<&categorycode> is from categorycode table
1298 C<&collectivity> is 1 (= we add a collectivity) or 0 (= we add a physical member)
1299 C<&surname> is the surname
1300 C<&firstname> is the firstname (only if collectivity=0)
1301 C<&dateofbirth> is the date of birth in ISO format (only if collectivity=0)
1305 # FIXME: This function is not legitimate. Multiple patrons might have the same first/last name and birthdate.
1306 # This is especially true since first name is not even a required field.
1308 sub checkuniquemember {
1309 my ( $collectivity, $surname, $firstname, $dateofbirth ) = @_;
1310 my $dbh = C4::Context->dbh;
1311 my $request = ($collectivity) ?
1312 "SELECT borrowernumber,categorycode FROM borrowers WHERE surname=? " :
1314 "SELECT borrowernumber,categorycode FROM borrowers WHERE surname=? and firstname=? and dateofbirth=?" :
1315 "SELECT borrowernumber,categorycode FROM borrowers WHERE surname=? and firstname=?";
1316 my $sth = $dbh->prepare($request);
1317 if ($collectivity) {
1318 $sth->execute( uc($surname) );
1319 } elsif($dateofbirth){
1320 $sth->execute( uc($surname), ucfirst($firstname), $dateofbirth );
1322 $sth->execute( uc($surname), ucfirst($firstname));
1324 my @data = $sth->fetchrow;
1325 ( $data[0] ) and return $data[0], $data[1];
1329 sub checkcardnumber {
1330 my ($cardnumber,$borrowernumber) = @_;
1331 # If cardnumber is null, we assume they're allowed.
1332 return 0 if !defined($cardnumber);
1333 my $dbh = C4::Context->dbh;
1334 my $query = "SELECT * FROM borrowers WHERE cardnumber=?";
1335 $query .= " AND borrowernumber <> ?" if ($borrowernumber);
1336 my $sth = $dbh->prepare($query);
1337 if ($borrowernumber) {
1338 $sth->execute($cardnumber,$borrowernumber);
1340 $sth->execute($cardnumber);
1342 if (my $data= $sth->fetchrow_hashref()){
1351 =head2 getzipnamecity (OUEST-PROVENCE)
1353 take all info from table city for the fields city and zip
1354 check for the name and the zip code of the city selected
1358 sub getzipnamecity {
1360 my $dbh = C4::Context->dbh;
1363 "select city_name,city_state,city_zipcode,city_country from cities where cityid=? ");
1364 $sth->execute($cityid);
1365 my @data = $sth->fetchrow;
1366 return $data[0], $data[1], $data[2], $data[3];
1370 =head2 getdcity (OUEST-PROVENCE)
1372 recover cityid with city_name condition
1377 my ($city_name) = @_;
1378 my $dbh = C4::Context->dbh;
1379 my $sth = $dbh->prepare("select cityid from cities where city_name=? ");
1380 $sth->execute($city_name);
1381 my $data = $sth->fetchrow;
1385 =head2 GetFirstValidEmailAddress
1387 $email = GetFirstValidEmailAddress($borrowernumber);
1389 Return the first valid email address for a borrower, given the borrowernumber. For now, the order
1390 is defined as email, emailpro, B_email. Returns the empty string if the borrower has no email
1395 sub GetFirstValidEmailAddress {
1396 my $borrowernumber = shift;
1397 my $dbh = C4::Context->dbh;
1398 my $sth = $dbh->prepare( "SELECT email, emailpro, B_email FROM borrowers where borrowernumber = ? ");
1399 $sth->execute( $borrowernumber );
1400 my $data = $sth->fetchrow_hashref;
1402 if ($data->{'email'}) {
1403 return $data->{'email'};
1404 } elsif ($data->{'emailpro'}) {
1405 return $data->{'emailpro'};
1406 } elsif ($data->{'B_email'}) {
1407 return $data->{'B_email'};
1413 =head2 GetNoticeEmailAddress
1415 $email = GetNoticeEmailAddress($borrowernumber);
1417 Return the email address of borrower used for notices, given the borrowernumber.
1418 Returns the empty string if no email address.
1422 sub GetNoticeEmailAddress {
1423 my $borrowernumber = shift;
1425 my $which_address = C4::Context->preference("AutoEmailPrimaryAddress");
1426 # if syspref is set to 'first valid' (value == OFF), look up email address
1427 if ( $which_address eq 'OFF' ) {
1428 return GetFirstValidEmailAddress($borrowernumber);
1430 # specified email address field
1431 my $dbh = C4::Context->dbh;
1432 my $sth = $dbh->prepare( qq{
1433 SELECT $which_address AS primaryemail
1435 WHERE borrowernumber=?
1437 $sth->execute($borrowernumber);
1438 my $data = $sth->fetchrow_hashref;
1439 return $data->{'primaryemail'} || '';
1442 =head2 GetExpiryDate
1444 $expirydate = GetExpiryDate($categorycode, $dateenrolled);
1446 Calculate expiry date given a categorycode and starting date. Date argument must be in ISO format.
1447 Return date is also in ISO format.
1452 my ( $categorycode, $dateenrolled ) = @_;
1454 if ($categorycode) {
1455 my $dbh = C4::Context->dbh;
1456 my $sth = $dbh->prepare("SELECT enrolmentperiod,enrolmentperioddate FROM categories WHERE categorycode=?");
1457 $sth->execute($categorycode);
1458 $enrolments = $sth->fetchrow_hashref;
1460 # die "GetExpiryDate: for enrollmentperiod $enrolmentperiod (category '$categorycode') starting $dateenrolled.\n";
1461 my @date = split (/-/,$dateenrolled);
1462 if($enrolments->{enrolmentperiod}){
1463 return sprintf("%04d-%02d-%02d", Add_Delta_YM(@date,0,$enrolments->{enrolmentperiod}));
1465 return $enrolments->{enrolmentperioddate};
1469 =head2 GetborCatFromCatType
1471 ($codes_arrayref, $labels_hashref) = &GetborCatFromCatType();
1473 Looks up the different types of borrowers in the database. Returns two
1474 elements: a reference-to-array, which lists the borrower category
1475 codes, and a reference-to-hash, which maps the borrower category codes
1476 to category descriptions.
1481 sub GetborCatFromCatType {
1482 my ( $category_type, $action, $no_branch_limit ) = @_;
1484 my $branch_limit = $no_branch_limit
1486 : C4::Context->userenv ? C4::Context->userenv->{"branch"} : "";
1488 # FIXME - This API seems both limited and dangerous.
1489 my $dbh = C4::Context->dbh;
1492 SELECT categories.categorycode, categories.description
1496 LEFT JOIN categories_branches ON categories.categorycode = categories_branches.categorycode
1499 $request .= " $action ";
1500 $request .= " AND (branchcode = ? OR branchcode IS NULL) GROUP BY description" if $branch_limit;
1502 $request .= " WHERE branchcode = ? OR branchcode IS NULL GROUP BY description" if $branch_limit;
1504 $request .= " ORDER BY categorycode";
1506 my $sth = $dbh->prepare($request);
1508 $action ? $category_type : (),
1509 $branch_limit ? $branch_limit : ()
1515 while ( my $data = $sth->fetchrow_hashref ) {
1516 push @codes, $data->{'categorycode'};
1517 $labels{ $data->{'categorycode'} } = $data->{'description'};
1520 return ( \@codes, \%labels );
1523 =head2 GetBorrowercategory
1525 $hashref = &GetBorrowercategory($categorycode);
1527 Given the borrower's category code, the function returns the corresponding
1528 data hashref for a comprehensive information display.
1532 sub GetBorrowercategory {
1534 my $dbh = C4::Context->dbh;
1538 "SELECT description,dateofbirthrequired,upperagelimit,category_type
1540 WHERE categorycode = ?"
1542 $sth->execute($catcode);
1544 $sth->fetchrow_hashref;
1548 } # sub getborrowercategory
1551 =head2 GetBorrowerCategorycode
1553 $categorycode = &GetBorrowerCategoryCode( $borrowernumber );
1555 Given the borrowernumber, the function returns the corresponding categorycode
1558 sub GetBorrowerCategorycode {
1559 my ( $borrowernumber ) = @_;
1560 my $dbh = C4::Context->dbh;
1561 my $sth = $dbh->prepare( qq{
1564 WHERE borrowernumber = ?
1566 $sth->execute( $borrowernumber );
1567 return $sth->fetchrow;
1570 =head2 GetBorrowercategoryList
1572 $arrayref_hashref = &GetBorrowercategoryList;
1573 If no category code provided, the function returns all the categories.
1577 sub GetBorrowercategoryList {
1578 my $no_branch_limit = @_ ? shift : 0;
1579 my $branch_limit = $no_branch_limit
1581 : C4::Context->userenv ? C4::Context->userenv->{"branch"} : "";
1582 my $dbh = C4::Context->dbh;
1583 my $query = "SELECT categories.* FROM categories";
1585 LEFT JOIN categories_branches ON categories.categorycode = categories_branches.categorycode
1586 WHERE branchcode = ? OR branchcode IS NULL GROUP BY description
1588 $query .= " ORDER BY description";
1589 my $sth = $dbh->prepare( $query );
1590 $sth->execute( $branch_limit ? $branch_limit : () );
1591 my $data = $sth->fetchall_arrayref( {} );
1594 } # sub getborrowercategory
1596 =head2 ethnicitycategories
1598 ($codes_arrayref, $labels_hashref) = ðnicitycategories();
1600 Looks up the different ethnic types in the database. Returns two
1601 elements: a reference-to-array, which lists the ethnicity codes, and a
1602 reference-to-hash, which maps the ethnicity codes to ethnicity
1609 sub ethnicitycategories {
1610 my $dbh = C4::Context->dbh;
1611 my $sth = $dbh->prepare("Select code,name from ethnicity order by name");
1615 while ( my $data = $sth->fetchrow_hashref ) {
1616 push @codes, $data->{'code'};
1617 $labels{ $data->{'code'} } = $data->{'name'};
1619 return ( \@codes, \%labels );
1624 $ethn_name = &fixEthnicity($ethn_code);
1626 Takes an ethnicity code (e.g., "european" or "pi") and returns the
1627 corresponding descriptive name from the C<ethnicity> table in the
1628 Koha database ("European" or "Pacific Islander").
1635 my $ethnicity = shift;
1636 return unless $ethnicity;
1637 my $dbh = C4::Context->dbh;
1638 my $sth = $dbh->prepare("Select name from ethnicity where code = ?");
1639 $sth->execute($ethnicity);
1640 my $data = $sth->fetchrow_hashref;
1641 return $data->{'name'};
1642 } # sub fixEthnicity
1646 $dateofbirth,$date = &GetAge($date);
1648 this function return the borrowers age with the value of dateofbirth
1654 my ( $date, $date_ref ) = @_;
1656 if ( not defined $date_ref ) {
1657 $date_ref = sprintf( '%04d-%02d-%02d', Today() );
1660 my ( $year1, $month1, $day1 ) = split /-/, $date;
1661 my ( $year2, $month2, $day2 ) = split /-/, $date_ref;
1663 my $age = $year2 - $year1;
1664 if ( $month1 . $day1 > $month2 . $day2 ) {
1671 =head2 get_institutions
1673 $insitutions = get_institutions();
1675 Just returns a list of all the borrowers of type I, borrownumber and name
1680 sub get_institutions {
1681 my $dbh = C4::Context->dbh();
1684 "SELECT borrowernumber,surname FROM borrowers WHERE categorycode=? ORDER BY surname"
1688 while ( my $data = $sth->fetchrow_hashref() ) {
1689 $orgs{ $data->{'borrowernumber'} } = $data;
1693 } # sub get_institutions
1695 =head2 add_member_orgs
1697 add_member_orgs($borrowernumber,$borrowernumbers);
1699 Takes a borrowernumber and a list of other borrowernumbers and inserts them into the borrowers_to_borrowers table
1704 sub add_member_orgs {
1705 my ( $borrowernumber, $otherborrowers ) = @_;
1706 my $dbh = C4::Context->dbh();
1708 "INSERT INTO borrowers_to_borrowers (borrower1,borrower2) VALUES (?,?)";
1709 my $sth = $dbh->prepare($query);
1710 foreach my $otherborrowernumber (@$otherborrowers) {
1711 $sth->execute( $borrowernumber, $otherborrowernumber );
1714 } # sub add_member_orgs
1718 $cityarrayref = GetCities();
1720 Returns an array_ref of the entries in the cities table
1721 If there are entries in the table an empty row is returned
1722 This is currently only used to populate a popup in memberentry
1728 my $dbh = C4::Context->dbh;
1729 my $city_arr = $dbh->selectall_arrayref(
1730 q|SELECT cityid,city_zipcode,city_name,city_state,city_country FROM cities ORDER BY city_name|,
1732 if ( @{$city_arr} ) {
1733 unshift @{$city_arr}, {
1734 city_zipcode => q{},
1738 city_country => q{},
1745 =head2 GetSortDetails (OUEST-PROVENCE)
1747 ($lib) = &GetSortDetails($category,$sortvalue);
1749 Returns the authorized value details
1750 C<&$lib>return value of authorized value details
1751 C<&$sortvalue>this is the value of authorized value
1752 C<&$category>this is the value of authorized value category
1756 sub GetSortDetails {
1757 my ( $category, $sortvalue ) = @_;
1758 my $dbh = C4::Context->dbh;
1759 my $query = qq|SELECT lib
1760 FROM authorised_values
1762 AND authorised_value=? |;
1763 my $sth = $dbh->prepare($query);
1764 $sth->execute( $category, $sortvalue );
1765 my $lib = $sth->fetchrow;
1766 return ($lib) if ($lib);
1767 return ($sortvalue) unless ($lib);
1770 =head2 MoveMemberToDeleted
1772 $result = &MoveMemberToDeleted($borrowernumber);
1774 Copy the record from borrowers to deletedborrowers table.
1778 # FIXME: should do it in one SQL statement w/ subquery
1779 # Otherwise, we should return the @data on success
1781 sub MoveMemberToDeleted {
1782 my ($member) = shift or return;
1783 my $dbh = C4::Context->dbh;
1784 my $query = qq|SELECT *
1786 WHERE borrowernumber=?|;
1787 my $sth = $dbh->prepare($query);
1788 $sth->execute($member);
1789 my @data = $sth->fetchrow_array;
1790 (@data) or return; # if we got a bad borrowernumber, there's nothing to insert
1792 $dbh->prepare( "INSERT INTO deletedborrowers VALUES ("
1793 . ( "?," x ( scalar(@data) - 1 ) )
1795 $sth->execute(@data);
1800 DelMember($borrowernumber);
1802 This function remove directly a borrower whitout writing it on deleteborrower.
1803 + Deletes reserves for the borrower
1808 my $dbh = C4::Context->dbh;
1809 my $borrowernumber = shift;
1810 #warn "in delmember with $borrowernumber";
1811 return unless $borrowernumber; # borrowernumber is mandatory.
1813 my $query = qq|DELETE
1815 WHERE borrowernumber=?|;
1816 my $sth = $dbh->prepare($query);
1817 $sth->execute($borrowernumber);
1821 WHERE borrowernumber = ?
1823 $sth = $dbh->prepare($query);
1824 $sth->execute($borrowernumber);
1825 logaction("MEMBERS", "DELETE", $borrowernumber, "") if C4::Context->preference("BorrowersLog");
1829 =head2 ExtendMemberSubscriptionTo (OUEST-PROVENCE)
1831 $date = ExtendMemberSubscriptionTo($borrowerid, $date);
1833 Extending the subscription to a given date or to the expiry date calculated on ISO date.
1838 sub ExtendMemberSubscriptionTo {
1839 my ( $borrowerid,$date) = @_;
1840 my $dbh = C4::Context->dbh;
1841 my $borrower = GetMember('borrowernumber'=>$borrowerid);
1843 $date = (C4::Context->preference('BorrowerRenewalPeriodBase') eq 'dateexpiry') ?
1844 C4::Dates->new($borrower->{'dateexpiry'}, 'iso')->output("iso") :
1845 C4::Dates->new()->output("iso");
1846 $date = GetExpiryDate( $borrower->{'categorycode'}, $date );
1848 my $sth = $dbh->do(<<EOF);
1850 SET dateexpiry='$date'
1851 WHERE borrowernumber='$borrowerid'
1854 AddEnrolmentFeeIfNeeded( $borrower->{categorycode}, $borrower->{borrowernumber} );
1856 logaction("MEMBERS", "RENEW", $borrower->{'borrowernumber'}, "Membership renewed")if C4::Context->preference("BorrowersLog");
1857 return $date if ($sth);
1861 =head2 GetTitles (OUEST-PROVENCE)
1863 ($borrowertitle)= &GetTitles();
1865 Looks up the different title . Returns array with all borrowers title
1870 my @borrowerTitle = split (/,|\|/,C4::Context->preference('BorrowersTitles'));
1871 unshift( @borrowerTitle, "" );
1872 my $count=@borrowerTitle;
1877 return ( \@borrowerTitle);
1881 =head2 GetPatronImage
1883 my ($imagedata, $dberror) = GetPatronImage($borrowernumber);
1885 Returns the mimetype and binary image data of the image for the patron with the supplied borrowernumber.
1889 sub GetPatronImage {
1890 my ($borrowernumber) = @_;
1891 warn "Borrowernumber passed to GetPatronImage is $borrowernumber" if $debug;
1892 my $dbh = C4::Context->dbh;
1893 my $query = 'SELECT mimetype, imagefile FROM patronimage WHERE borrowernumber = ?';
1894 my $sth = $dbh->prepare($query);
1895 $sth->execute($borrowernumber);
1896 my $imagedata = $sth->fetchrow_hashref;
1897 warn "Database error!" if $sth->errstr;
1898 return $imagedata, $sth->errstr;
1901 =head2 PutPatronImage
1903 PutPatronImage($cardnumber, $mimetype, $imgfile);
1905 Stores patron binary image data and mimetype in database.
1906 NOTE: This function is good for updating images as well as inserting new images in the database.
1910 sub PutPatronImage {
1911 my ($cardnumber, $mimetype, $imgfile) = @_;
1912 warn "Parameters passed in: Cardnumber=$cardnumber, Mimetype=$mimetype, " . ($imgfile ? "Imagefile" : "No Imagefile") if $debug;
1913 my $dbh = C4::Context->dbh;
1914 my $query = "INSERT INTO patronimage (borrowernumber, mimetype, imagefile) VALUES ( ( SELECT borrowernumber from borrowers WHERE cardnumber = ? ),?,?) ON DUPLICATE KEY UPDATE imagefile = ?;";
1915 my $sth = $dbh->prepare($query);
1916 $sth->execute($cardnumber,$mimetype,$imgfile,$imgfile);
1917 warn "Error returned inserting $cardnumber.$mimetype." if $sth->errstr;
1918 return $sth->errstr;
1921 =head2 RmPatronImage
1923 my ($dberror) = RmPatronImage($borrowernumber);
1925 Removes the image for the patron with the supplied borrowernumber.
1930 my ($borrowernumber) = @_;
1931 warn "Borrowernumber passed to GetPatronImage is $borrowernumber" if $debug;
1932 my $dbh = C4::Context->dbh;
1933 my $query = "DELETE FROM patronimage WHERE borrowernumber = ?;";
1934 my $sth = $dbh->prepare($query);
1935 $sth->execute($borrowernumber);
1936 my $dberror = $sth->errstr;
1937 warn "Database error!" if $sth->errstr;
1941 =head2 GetHideLostItemsPreference
1943 $hidelostitemspref = &GetHideLostItemsPreference($borrowernumber);
1945 Returns the HideLostItems preference for the patron category of the supplied borrowernumber
1946 C<&$hidelostitemspref>return value of function, 0 or 1
1950 sub GetHideLostItemsPreference {
1951 my ($borrowernumber) = @_;
1952 my $dbh = C4::Context->dbh;
1953 my $query = "SELECT hidelostitems FROM borrowers,categories WHERE borrowers.categorycode = categories.categorycode AND borrowernumber = ?";
1954 my $sth = $dbh->prepare($query);
1955 $sth->execute($borrowernumber);
1956 my $hidelostitems = $sth->fetchrow;
1957 return $hidelostitems;
1960 =head2 GetBorrowersToExpunge
1962 $borrowers = &GetBorrowersToExpunge(
1963 not_borrowered_since => $not_borrowered_since,
1964 expired_before => $expired_before,
1965 category_code => $category_code,
1966 branchcode => $branchcode
1969 This function get all borrowers based on the given criteria.
1973 sub GetBorrowersToExpunge {
1976 my $filterdate = $params->{'not_borrowered_since'};
1977 my $filterexpiry = $params->{'expired_before'};
1978 my $filtercategory = $params->{'category_code'};
1979 my $filterbranch = $params->{'branchcode'} ||
1980 ((C4::Context->preference('IndependentBranches')
1981 && C4::Context->userenv
1982 && !C4::Context->IsSuperLibrarian()
1983 && C4::Context->userenv->{branch})
1984 ? C4::Context->userenv->{branch}
1987 my $dbh = C4::Context->dbh;
1989 SELECT borrowers.borrowernumber,
1990 MAX(old_issues.timestamp) AS latestissue,
1991 MAX(issues.timestamp) AS currentissue
1993 JOIN categories USING (categorycode)
1994 LEFT JOIN old_issues USING (borrowernumber)
1995 LEFT JOIN issues USING (borrowernumber)
1996 WHERE category_type <> 'S'
1997 AND borrowernumber NOT IN (SELECT guarantorid FROM borrowers WHERE guarantorid IS NOT NULL AND guarantorid <> 0)
2000 if ( $filterbranch && $filterbranch ne "" ) {
2001 $query.= " AND borrowers.branchcode = ? ";
2002 push( @query_params, $filterbranch );
2004 if ( $filterexpiry ) {
2005 $query .= " AND dateexpiry < ? ";
2006 push( @query_params, $filterexpiry );
2008 if ( $filtercategory ) {
2009 $query .= " AND categorycode = ? ";
2010 push( @query_params, $filtercategory );
2012 $query.=" GROUP BY borrowers.borrowernumber HAVING currentissue IS NULL ";
2013 if ( $filterdate ) {
2014 $query.=" AND ( latestissue < ? OR latestissue IS NULL ) ";
2015 push @query_params,$filterdate;
2017 warn $query if $debug;
2019 my $sth = $dbh->prepare($query);
2020 if (scalar(@query_params)>0){
2021 $sth->execute(@query_params);
2028 while ( my $data = $sth->fetchrow_hashref ) {
2029 push @results, $data;
2034 =head2 GetBorrowersWhoHaveNeverBorrowed
2036 $results = &GetBorrowersWhoHaveNeverBorrowed
2038 This function get all borrowers who have never borrowed.
2040 I<$result> is a ref to an array which all elements are a hasref.
2044 sub GetBorrowersWhoHaveNeverBorrowed {
2045 my $filterbranch = shift ||
2046 ((C4::Context->preference('IndependentBranches')
2047 && C4::Context->userenv
2048 && !C4::Context->IsSuperLibrarian()
2049 && C4::Context->userenv->{branch})
2050 ? C4::Context->userenv->{branch}
2052 my $dbh = C4::Context->dbh;
2054 SELECT borrowers.borrowernumber,max(timestamp) as latestissue
2056 LEFT JOIN issues ON borrowers.borrowernumber = issues.borrowernumber
2057 WHERE issues.borrowernumber IS NULL
2060 if ($filterbranch && $filterbranch ne ""){
2061 $query.=" AND borrowers.branchcode= ?";
2062 push @query_params,$filterbranch;
2064 warn $query if $debug;
2066 my $sth = $dbh->prepare($query);
2067 if (scalar(@query_params)>0){
2068 $sth->execute(@query_params);
2075 while ( my $data = $sth->fetchrow_hashref ) {
2076 push @results, $data;
2081 =head2 GetBorrowersWithIssuesHistoryOlderThan
2083 $results = &GetBorrowersWithIssuesHistoryOlderThan($date)
2085 this function get all borrowers who has an issue history older than I<$date> given on input arg.
2087 I<$result> is a ref to an array which all elements are a hashref.
2088 This hashref is containt the number of time this borrowers has borrowed before I<$date> and the borrowernumber.
2092 sub GetBorrowersWithIssuesHistoryOlderThan {
2093 my $dbh = C4::Context->dbh;
2094 my $date = shift ||POSIX::strftime("%Y-%m-%d",localtime());
2095 my $filterbranch = shift ||
2096 ((C4::Context->preference('IndependentBranches')
2097 && C4::Context->userenv
2098 && !C4::Context->IsSuperLibrarian()
2099 && C4::Context->userenv->{branch})
2100 ? C4::Context->userenv->{branch}
2103 SELECT count(borrowernumber) as n,borrowernumber
2105 WHERE returndate < ?
2106 AND borrowernumber IS NOT NULL
2109 push @query_params, $date;
2111 $query.=" AND branchcode = ?";
2112 push @query_params, $filterbranch;
2114 $query.=" GROUP BY borrowernumber ";
2115 warn $query if $debug;
2116 my $sth = $dbh->prepare($query);
2117 $sth->execute(@query_params);
2120 while ( my $data = $sth->fetchrow_hashref ) {
2121 push @results, $data;
2126 =head2 GetBorrowersNamesAndLatestIssue
2128 $results = &GetBorrowersNamesAndLatestIssueList(@borrowernumbers)
2130 this function get borrowers Names and surnames and Issue information.
2132 I<@borrowernumbers> is an array which all elements are borrowernumbers.
2133 This hashref is containt the number of time this borrowers has borrowed before I<$date> and the borrowernumber.
2137 sub GetBorrowersNamesAndLatestIssue {
2138 my $dbh = C4::Context->dbh;
2139 my @borrowernumbers=@_;
2141 SELECT surname,lastname, phone, email,max(timestamp)
2143 LEFT JOIN issues ON borrowers.borrowernumber=issues.borrowernumber
2144 GROUP BY borrowernumber
2146 my $sth = $dbh->prepare($query);
2148 my $results = $sth->fetchall_arrayref({});
2156 my $success = ModPrivacy( $borrowernumber, $privacy );
2158 Update the privacy of a patron.
2161 true on success, false on failure
2168 my $borrowernumber = shift;
2169 my $privacy = shift;
2170 return unless defined $borrowernumber;
2171 return unless $borrowernumber =~ /^\d+$/;
2173 return ModMember( borrowernumber => $borrowernumber,
2174 privacy => $privacy );
2179 AddMessage( $borrowernumber, $message_type, $message, $branchcode );
2181 Adds a message to the messages table for the given borrower.
2190 my ( $borrowernumber, $message_type, $message, $branchcode ) = @_;
2192 my $dbh = C4::Context->dbh;
2194 if ( ! ( $borrowernumber && $message_type && $message && $branchcode ) ) {
2198 my $query = "INSERT INTO messages ( borrowernumber, branchcode, message_type, message ) VALUES ( ?, ?, ?, ? )";
2199 my $sth = $dbh->prepare($query);
2200 $sth->execute( $borrowernumber, $branchcode, $message_type, $message );
2201 logaction("MEMBERS", "ADDCIRCMESSAGE", $borrowernumber, $message) if C4::Context->preference("BorrowersLog");
2207 GetMessages( $borrowernumber, $type );
2209 $type is message type, B for borrower, or L for Librarian.
2210 Empty type returns all messages of any type.
2212 Returns all messages for the given borrowernumber
2217 my ( $borrowernumber, $type, $branchcode ) = @_;
2223 my $dbh = C4::Context->dbh;
2226 branches.branchname,
2229 messages.branchcode LIKE '$branchcode' AS can_delete
2230 FROM messages, branches
2231 WHERE borrowernumber = ?
2232 AND message_type LIKE ?
2233 AND messages.branchcode = branches.branchcode
2234 ORDER BY message_date DESC";
2235 my $sth = $dbh->prepare($query);
2236 $sth->execute( $borrowernumber, $type ) ;
2239 while ( my $data = $sth->fetchrow_hashref ) {
2240 my $d = C4::Dates->new( $data->{message_date}, 'iso' );
2241 $data->{message_date_formatted} = $d->output;
2242 push @results, $data;
2250 GetMessagesCount( $borrowernumber, $type );
2252 $type is message type, B for borrower, or L for Librarian.
2253 Empty type returns all messages of any type.
2255 Returns the number of messages for the given borrowernumber
2259 sub GetMessagesCount {
2260 my ( $borrowernumber, $type, $branchcode ) = @_;
2266 my $dbh = C4::Context->dbh;
2268 my $query = "SELECT COUNT(*) as MsgCount FROM messages WHERE borrowernumber = ? AND message_type LIKE ?";
2269 my $sth = $dbh->prepare($query);
2270 $sth->execute( $borrowernumber, $type ) ;
2273 my $data = $sth->fetchrow_hashref;
2274 my $count = $data->{'MsgCount'};
2281 =head2 DeleteMessage
2283 DeleteMessage( $message_id );
2288 my ( $message_id ) = @_;
2290 my $dbh = C4::Context->dbh;
2291 my $query = "SELECT * FROM messages WHERE message_id = ?";
2292 my $sth = $dbh->prepare($query);
2293 $sth->execute( $message_id );
2294 my $message = $sth->fetchrow_hashref();
2296 $query = "DELETE FROM messages WHERE message_id = ?";
2297 $sth = $dbh->prepare($query);
2298 $sth->execute( $message_id );
2299 logaction("MEMBERS", "DELCIRCMESSAGE", $message->{'borrowernumber'}, $message->{'message'}) if C4::Context->preference("BorrowersLog");
2304 IssueSlip($branchcode, $borrowernumber, $quickslip)
2306 Returns letter hash ( see C4::Letters::GetPreparedLetter )
2308 $quickslip is boolean, to indicate whether we want a quick slip
2313 my ($branch, $borrowernumber, $quickslip) = @_;
2315 # return unless ( C4::Context->boolean_preference('printcirculationslips') );
2317 my $now = POSIX::strftime("%Y-%m-%d", localtime);
2319 my $issueslist = GetPendingIssues($borrowernumber);
2320 foreach my $it (@$issueslist){
2321 if ((substr $it->{'issuedate'}, 0, 10) eq $now || (substr $it->{'lastreneweddate'}, 0, 10) eq $now) {
2324 elsif ((substr $it->{'date_due'}, 0, 10) le $now) {
2325 $it->{'overdue'} = 1;
2327 my $dt = dt_from_string( $it->{'date_due'} );
2328 $it->{'date_due'} = output_pref( $dt );;
2330 my @issues = sort { $b->{'timestamp'} <=> $a->{'timestamp'} } @$issueslist;
2332 my ($letter_code, %repeat);
2334 $letter_code = 'ISSUEQSLIP';
2336 'checkedout' => [ map {
2340 }, grep { $_->{'now'} } @issues ],
2344 $letter_code = 'ISSUESLIP';
2346 'checkedout' => [ map {
2350 }, grep { !$_->{'overdue'} } @issues ],
2352 'overdue' => [ map {
2356 }, grep { $_->{'overdue'} } @issues ],
2359 $_->{'timestamp'} = $_->{'newdate'};
2361 } @{ GetNewsToDisplay("slip") } ],
2365 return C4::Letters::GetPreparedLetter (
2366 module => 'circulation',
2367 letter_code => $letter_code,
2368 branchcode => $branch,
2370 'branches' => $branch,
2371 'borrowers' => $borrowernumber,
2377 =head2 GetBorrowersWithEmail
2379 ([$borrnum,$userid], ...) = GetBorrowersWithEmail('me@example.com');
2381 This gets a list of users and their basic details from their email address.
2382 As it's possible for multiple user to have the same email address, it provides
2383 you with all of them. If there is no userid for the user, there will be an
2384 C<undef> there. An empty list will be returned if there are no matches.
2388 sub GetBorrowersWithEmail {
2391 my $dbh = C4::Context->dbh;
2393 my $query = "SELECT borrowernumber, userid FROM borrowers WHERE email=?";
2394 my $sth=$dbh->prepare($query);
2395 $sth->execute($email);
2397 while (my $ref = $sth->fetch) {
2400 die "Failure searching for borrowers by email address: $sth->errstr" if $sth->err;
2404 sub AddMember_Opac {
2405 my ( %borrower ) = @_;
2407 $borrower{'categorycode'} = C4::Context->preference('PatronSelfRegistrationDefaultCategory');
2409 my $sr = new String::Random;
2410 $sr->{'A'} = [ 'A'..'Z', 'a'..'z' ];
2411 my $password = $sr->randpattern("AAAAAAAAAA");
2412 $borrower{'password'} = $password;
2414 $borrower{'cardnumber'} = fixup_cardnumber();
2416 my $borrowernumber = AddMember(%borrower);
2418 return ( $borrowernumber, $password );
2421 =head2 AddEnrolmentFeeIfNeeded
2423 AddEnrolmentFeeIfNeeded( $borrower->{categorycode}, $borrower->{borrowernumber} );
2425 Add enrolment fee for a patron if needed.
2429 sub AddEnrolmentFeeIfNeeded {
2430 my ( $categorycode, $borrowernumber ) = @_;
2431 # check for enrollment fee & add it if needed
2432 my $dbh = C4::Context->dbh;
2433 my $sth = $dbh->prepare(q{
2436 WHERE categorycode=?
2438 $sth->execute( $categorycode );
2440 warn sprintf('Database returned the following error: %s', $sth->errstr);
2443 my ($enrolmentfee) = $sth->fetchrow;
2444 if ($enrolmentfee && $enrolmentfee > 0) {
2445 # insert fee in patron debts
2446 C4::Accounts::manualinvoice( $borrowernumber, '', '', 'A', $enrolmentfee );
2451 my ( $borrowernumber ) = @_;
2453 my $sql = "SELECT COUNT(*) FROM issues WHERE date_due < NOW() AND borrowernumber = ?";
2454 my $sth = C4::Context->dbh->prepare( $sql );
2455 $sth->execute( $borrowernumber );
2456 my ( $count ) = $sth->fetchrow_array();
2461 END { } # module clean-up code here (global destructor)