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 Digest::MD5 qw(md5_base64);
28 use String::Random qw( random_string );
29 use Date::Calc qw/Today Add_Delta_YM check_date Date_to_Days/;
30 use C4::Log; # logaction
36 use C4::SQLHelper qw(InsertInTable UpdateInTable SearchInTable);
37 use C4::Members::Attributes qw(SearchIdMatchingAttribute);
38 use C4::NewsChannels; #get slip news
40 use DateTime::Format::DateParse;
42 use Text::Unaccent qw( unac_string );
44 our ($VERSION,@ISA,@EXPORT,@EXPORT_OK,$debug);
47 $VERSION = 3.07.00.049;
48 $debug = $ENV{DEBUG} || 0;
60 &GetMemberIssuesAndFines
68 &GetFirstValidEmailAddress
81 &GetHideLostItemsPreference
84 &GetMemberAccountRecords
85 &GetBorNotifyAcctRecord
89 GetBorrowerCategorycode
90 &GetBorrowercategoryList
92 &GetBorrowersToExpunge
93 &GetBorrowersWhoHaveNeverBorrowed
94 &GetBorrowersWithIssuesHistoryOlderThan
104 GetBorrowersWithEmail
125 &ExtendMemberSubscriptionTo
143 C4::Members - Perl Module containing convenience functions for member handling
151 This module contains routines for adding, modifying and deleting members/patrons/borrowers
157 $borrowers_result_array_ref = &Search($filter,$orderby, $limit,
158 $columns_out, $search_on_fields,$searchtype);
160 Looks up patrons (borrowers) on filter. A wrapper for SearchInTable('borrowers').
162 For C<$filter>, C<$orderby>, C<$limit>, C<&columns_out>, C<&search_on_fields> and C<&searchtype>
163 refer to C4::SQLHelper:SearchInTable().
165 Special C<$filter> key '' is effectively expanded to search on surname firstname othernamescw
166 and cardnumber unless C<&search_on_fields> is defined
170 $borrowers = Search('abcd', 'cardnumber');
172 $borrowers = Search({''=>'abcd', category_type=>'I'}, 'surname');
176 sub _express_member_find {
179 # this is used by circulation everytime a new borrowers cardnumber is scanned
180 # so we can check an exact match first, if that works return, otherwise do the rest
181 my $dbh = C4::Context->dbh;
182 my $query = "SELECT borrowernumber FROM borrowers WHERE cardnumber = ?";
183 if ( my $borrowernumber = $dbh->selectrow_array($query, undef, $filter) ) {
184 return( {"borrowernumber"=>$borrowernumber} );
187 my ($search_on_fields, $searchtype);
188 if ( length($filter) == 1 ) {
189 $search_on_fields = [ qw(surname) ];
190 $searchtype = 'start_with';
192 $search_on_fields = [ qw(surname firstname othernames cardnumber) ];
193 $searchtype = 'contain';
196 return (undef, $search_on_fields, $searchtype);
200 my ( $filter, $orderby, $limit, $columns_out, $search_on_fields, $searchtype ) = @_;
205 if ( my $fr = ref $filter ) {
206 if ( $fr eq "HASH" ) {
207 if ( my $search_string = $filter->{''} ) {
208 my ($member_filter, $member_search_on_fields, $member_searchtype) = _express_member_find($search_string);
209 if ($member_filter) {
210 $filter = $member_filter;
213 $search_on_fields ||= $member_search_on_fields;
214 $searchtype ||= $member_searchtype;
219 $search_string = $filter;
223 $search_string = $filter;
224 my ($member_filter, $member_search_on_fields, $member_searchtype) = _express_member_find($search_string);
225 if ($member_filter) {
226 $filter = $member_filter;
229 $search_on_fields ||= $member_search_on_fields;
230 $searchtype ||= $member_searchtype;
234 if ( !$found_borrower && C4::Context->preference('ExtendedPatronAttributes') && $search_string ) {
235 my $matching_records = C4::Members::Attributes::SearchIdMatchingAttribute($search_string);
236 if(scalar(@$matching_records)>0) {
237 if ( my $fr = ref $filter ) {
238 if ( $fr eq "HASH" ) {
240 $filter = [ $filter ];
242 push @$filter, { %f, "borrowernumber"=>$$matching_records };
245 push @$filter, {"borrowernumber"=>$matching_records};
249 $filter = [ $filter ];
250 push @$filter, {"borrowernumber"=>$matching_records};
255 # $showallbranches was not used at the time SearchMember() was mainstreamed into Search().
256 # Mentioning for the reference
258 if ( C4::Context->preference("IndependantBranches") ) { # && !$showallbranches){
259 if ( my $userenv = C4::Context->userenv ) {
260 my $branch = $userenv->{'branch'};
261 if ( ($userenv->{flags} % 2 !=1) &&
262 $branch && $branch ne "insecure" ){
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 ($amount) = GetMemberAccountRecords( $patroninformation->{'borrowernumber'});
438 my $noissuescharge = C4::Context->preference("noissuescharge") || 5;
439 $flaginfo{'message'} = sprintf "Patron owes \$%.02f", $amount;
440 $flaginfo{'amount'} = sprintf "%.02f", $amount;
441 if ( $amount > $noissuescharge && !C4::Context->preference("AllowFineOverride") ) {
442 $flaginfo{'noissues'} = 1;
444 $flags{'CHARGES'} = \%flaginfo;
446 elsif ( $amount < 0 ) {
448 $flaginfo{'message'} = sprintf "Patron has credit of \$%.02f", -$amount;
449 $flaginfo{'amount'} = sprintf "%.02f", $amount;
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 = CheckBorrowerDebarred($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);
700 return @{C4::Context->dbh->selectcol_arrayref("SHOW columns from borrowers")};
705 my $success = ModMember(borrowernumber => $borrowernumber,
706 [ field => value ]... );
708 Modify borrower's data. All date fields should ALREADY be in ISO format.
711 true on success, or false on failure
717 # test to know if you must update or not the borrower password
718 if (exists $data{password}) {
719 if ($data{password} eq '****' or $data{password} eq '') {
720 delete $data{password};
722 $data{password} = md5_base64($data{password});
725 my $execute_success=UpdateInTable("borrowers",\%data);
726 if ($execute_success) { # only proceed if the update was a success
727 # ok if its an adult (type) it may have borrowers that depend on it as a guarantor
728 # so when we update information for an adult we should check for guarantees and update the relevant part
729 # of their records, ie addresses and phone numbers
730 my $borrowercategory= GetBorrowercategory( $data{'category_type'} );
731 if ( exists $borrowercategory->{'category_type'} && $borrowercategory->{'category_type'} eq ('A' || 'S') ) {
732 # is adult check guarantees;
733 UpdateGuarantees(%data);
735 logaction("MEMBERS", "MODIFY", $data{'borrowernumber'}, "UPDATE (executed w/ arg: $data{'borrowernumber'})") if C4::Context->preference("BorrowersLog");
737 return $execute_success;
743 $borrowernumber = &AddMember(%borrower);
745 insert new borrower into table
746 Returns the borrowernumber upon success
748 Returns as undef upon any db error without further processing
755 my $dbh = C4::Context->dbh;
757 # generate a proper login if none provided
758 $data{'userid'} = Generate_Userid($data{'borrowernumber'}, $data{'firstname'}, $data{'surname'}) if $data{'userid'} eq '';
760 # add expiration date if it isn't already there
761 unless ( $data{'dateexpiry'} ) {
762 $data{'dateexpiry'} = GetExpiryDate( $data{'categorycode'}, C4::Dates->new()->output("iso") );
765 # add enrollment date if it isn't already there
766 unless ( $data{'dateenrolled'} ) {
767 $data{'dateenrolled'} = C4::Dates->new()->output("iso");
770 # create a disabled account if no password provided
771 $data{'password'} = ($data{'password'})? md5_base64($data{'password'}) : '!';
772 $data{'borrowernumber'}=InsertInTable("borrowers",\%data);
775 # mysql_insertid is probably bad. not necessarily accurate and mysql-specific at best.
776 logaction("MEMBERS", "CREATE", $data{'borrowernumber'}, "") if C4::Context->preference("BorrowersLog");
778 # check for enrollment fee & add it if needed
779 my $sth = $dbh->prepare("SELECT enrolmentfee FROM categories WHERE categorycode=?");
780 $sth->execute($data{'categorycode'});
781 my ($enrolmentfee) = $sth->fetchrow;
783 warn sprintf('Database returned the following error: %s', $sth->errstr);
786 if ($enrolmentfee && $enrolmentfee > 0) {
787 # insert fee in patron debts
788 manualinvoice($data{'borrowernumber'}, '', '', 'A', $enrolmentfee);
791 return $data{'borrowernumber'};
796 my ($uid,$member) = @_;
797 my $dbh = C4::Context->dbh;
798 # Make sure the userid chosen is unique and not theirs if non-empty. If it is not,
799 # Then we need to tell the user and have them create a new one.
802 "SELECT * FROM borrowers WHERE userid=? AND borrowernumber != ?");
803 $sth->execute( $uid, $member );
804 if ( ( $uid ne '' ) && ( my $row = $sth->fetchrow_hashref ) ) {
812 sub Generate_Userid {
813 my ($borrowernumber, $firstname, $surname) = @_;
817 $firstname =~ s/[[:digit:][:space:][:blank:][:punct:][:cntrl:]]//g;
818 $surname =~ s/[[:digit:][:space:][:blank:][:punct:][:cntrl:]]//g;
819 $newuid = lc(($firstname)? "$firstname.$surname" : $surname);
820 $newuid = unac_string('utf-8',$newuid);
821 $newuid .= $offset unless $offset == 0;
824 } while (!Check_Userid($newuid,$borrowernumber));
830 my ( $uid, $member, $digest ) = @_;
831 my $dbh = C4::Context->dbh;
833 #Make sure the userid chosen is unique and not theirs if non-empty. If it is not,
834 #Then we need to tell the user and have them create a new one.
838 "SELECT * FROM borrowers WHERE userid=? AND borrowernumber != ?");
839 $sth->execute( $uid, $member );
840 if ( ( $uid ne '' ) && ( my $row = $sth->fetchrow_hashref ) ) {
844 #Everything is good so we can update the information.
847 "update borrowers set userid=?, password=? where borrowernumber=?");
848 $sth->execute( $uid, $digest, $member );
852 logaction("MEMBERS", "CHANGE PASS", $member, "") if C4::Context->preference("BorrowersLog");
858 =head2 fixup_cardnumber
860 Warning: The caller is responsible for locking the members table in write
861 mode, to avoid database corruption.
865 use vars qw( @weightings );
866 my @weightings = ( 8, 4, 6, 3, 5, 2, 1 );
868 sub fixup_cardnumber {
869 my ($cardnumber) = @_;
870 my $autonumber_members = C4::Context->boolean_preference('autoMemberNum') || 0;
872 # Find out whether member numbers should be generated
873 # automatically. Should be either "1" or something else.
874 # Defaults to "0", which is interpreted as "no".
876 # if ($cardnumber !~ /\S/ && $autonumber_members) {
877 ($autonumber_members) or return $cardnumber;
878 my $checkdigit = C4::Context->preference('checkdigit');
879 my $dbh = C4::Context->dbh;
880 if ( $checkdigit and $checkdigit eq 'katipo' ) {
882 # if checkdigit is selected, calculate katipo-style cardnumber.
883 # otherwise, just use the max()
884 # purpose: generate checksum'd member numbers.
885 # We'll assume we just got the max value of digits 2-8 of member #'s
886 # from the database and our job is to increment that by one,
887 # determine the 1st and 9th digits and return the full string.
888 my $sth = $dbh->prepare(
889 "select max(substring(borrowers.cardnumber,2,7)) as new_num from borrowers"
892 my $data = $sth->fetchrow_hashref;
893 $cardnumber = $data->{new_num};
894 if ( !$cardnumber ) { # If DB has no values,
895 $cardnumber = 1000000; # start at 1000000
901 for ( my $i = 0 ; $i < 8 ; $i += 1 ) {
902 # read weightings, left to right, 1 char at a time
903 my $temp1 = $weightings[$i];
905 # sequence left to right, 1 char at a time
906 my $temp2 = substr( $cardnumber, $i, 1 );
908 # mult each char 1-7 by its corresponding weighting
909 $sum += $temp1 * $temp2;
912 my $rem = ( $sum % 11 );
913 $rem = 'X' if $rem == 10;
915 return "V$cardnumber$rem";
918 my $sth = $dbh->prepare(
919 'SELECT MAX( CAST( cardnumber AS SIGNED ) ) FROM borrowers WHERE cardnumber REGEXP "^-?[0-9]+$"'
922 my ($result) = $sth->fetchrow;
925 return $cardnumber; # just here as a fallback/reminder
930 ($num_children, $children_arrayref) = &GetGuarantees($parent_borrno);
931 $child0_cardno = $children_arrayref->[0]{"cardnumber"};
932 $child0_borrno = $children_arrayref->[0]{"borrowernumber"};
934 C<&GetGuarantees> takes a borrower number (e.g., that of a patron
935 with children) and looks up the borrowers who are guaranteed by that
936 borrower (i.e., the patron's children).
938 C<&GetGuarantees> returns two values: an integer giving the number of
939 borrowers guaranteed by C<$parent_borrno>, and a reference to an array
940 of references to hash, which gives the actual results.
946 my ($borrowernumber) = @_;
947 my $dbh = C4::Context->dbh;
950 "select cardnumber,borrowernumber, firstname, surname from borrowers where guarantorid=?"
952 $sth->execute($borrowernumber);
955 my $data = $sth->fetchall_arrayref({});
956 return ( scalar(@$data), $data );
959 =head2 UpdateGuarantees
961 &UpdateGuarantees($parent_borrno);
964 C<&UpdateGuarantees> borrower data for an adult and updates all the guarantees
965 with the modified information
970 sub UpdateGuarantees {
972 my $dbh = C4::Context->dbh;
973 my ( $count, $guarantees ) = GetGuarantees( $data{'borrowernumber'} );
974 foreach my $guarantee (@$guarantees){
975 my $guaquery = qq|UPDATE borrowers
976 SET address=?,fax=?,B_city=?,mobile=?,city=?,phone=?
977 WHERE borrowernumber=?
979 my $sth = $dbh->prepare($guaquery);
980 $sth->execute($data{'address'},$data{'fax'},$data{'B_city'},$data{'mobile'},$data{'city'},$data{'phone'},$guarantee->{'borrowernumber'});
983 =head2 GetPendingIssues
985 my $issues = &GetPendingIssues(@borrowernumber);
987 Looks up what the patron with the given borrowernumber has borrowed.
989 C<&GetPendingIssues> returns a
990 reference-to-array where each element is a reference-to-hash; the
991 keys are the fields from the C<issues>, C<biblio>, and C<items> tables.
992 The keys include C<biblioitems> fields except marc and marcxml.
997 sub GetPendingIssues {
998 my @borrowernumbers = @_;
1000 unless (@borrowernumbers ) { # return a ref_to_array
1001 return \@borrowernumbers; # to not cause surprise to caller
1004 # Borrowers part of the query
1006 for (my $i = 0; $i < @borrowernumbers; $i++) {
1007 $bquery .= ' issues.borrowernumber = ?';
1008 if ($i < $#borrowernumbers ) {
1013 # must avoid biblioitems.* to prevent large marc and marcxml fields from killing performance
1014 # FIXME: namespace collision: each table has "timestamp" fields. Which one is "timestamp" ?
1015 # FIXME: circ/ciculation.pl tries to sort by timestamp!
1016 # FIXME: namespace collision: other collisions possible.
1017 # FIXME: most of this data isn't really being used by callers.
1024 biblioitems.itemtype,
1027 biblioitems.publicationyear,
1028 biblioitems.publishercode,
1029 biblioitems.volumedate,
1030 biblioitems.volumedesc,
1033 borrowers.firstname,
1035 borrowers.cardnumber,
1036 issues.timestamp AS timestamp,
1037 issues.renewals AS renewals,
1038 issues.borrowernumber AS borrowernumber,
1039 items.renewals AS totalrenewals
1041 LEFT JOIN items ON items.itemnumber = issues.itemnumber
1042 LEFT JOIN biblio ON items.biblionumber = biblio.biblionumber
1043 LEFT JOIN biblioitems ON items.biblioitemnumber = biblioitems.biblioitemnumber
1044 LEFT JOIN borrowers ON issues.borrowernumber = borrowers.borrowernumber
1047 ORDER BY issues.issuedate"
1050 my $sth = C4::Context->dbh->prepare($query);
1051 $sth->execute(@borrowernumbers);
1052 my $data = $sth->fetchall_arrayref({});
1053 my $tz = C4::Context->tz();
1054 my $today = DateTime->now( time_zone => $tz);
1055 foreach (@{$data}) {
1056 if ($_->{issuedate}) {
1057 $_->{issuedate} = dt_from_string($_->{issuedate}, 'sql');
1059 $_->{date_due} or next;
1060 $_->{date_due} = DateTime::Format::DateParse->parse_datetime($_->{date_due}, $tz->name());
1061 if ( DateTime->compare($_->{date_due}, $today) == -1 ) {
1070 $issues = &GetAllIssues($borrowernumber, $sortkey, $limit);
1072 Looks up what the patron with the given borrowernumber has borrowed,
1073 and sorts the results.
1075 C<$sortkey> is the name of a field on which to sort the results. This
1076 should be the name of a field in the C<issues>, C<biblio>,
1077 C<biblioitems>, or C<items> table in the Koha database.
1079 C<$limit> is the maximum number of results to return.
1081 C<&GetAllIssues> an arrayref, C<$issues>, of hashrefs, the keys of which
1082 are the fields from the C<issues>, C<biblio>, C<biblioitems>, and
1083 C<items> tables of the Koha database.
1089 my ( $borrowernumber, $order, $limit ) = @_;
1091 my $dbh = C4::Context->dbh;
1093 'SELECT *, issues.timestamp as issuestimestamp, issues.renewals AS renewals,items.renewals AS totalrenewals,items.timestamp AS itemstimestamp
1095 LEFT JOIN items on items.itemnumber=issues.itemnumber
1096 LEFT JOIN biblio ON items.biblionumber=biblio.biblionumber
1097 LEFT JOIN biblioitems ON items.biblioitemnumber=biblioitems.biblioitemnumber
1098 WHERE borrowernumber=?
1100 SELECT *, old_issues.timestamp as issuestimestamp, old_issues.renewals AS renewals,items.renewals AS totalrenewals,items.timestamp AS itemstimestamp
1102 LEFT JOIN items on items.itemnumber=old_issues.itemnumber
1103 LEFT JOIN biblio ON items.biblionumber=biblio.biblionumber
1104 LEFT JOIN biblioitems ON items.biblioitemnumber=biblioitems.biblioitemnumber
1105 WHERE borrowernumber=? AND old_issues.itemnumber IS NOT NULL
1106 order by ' . $order;
1108 $query .= " limit $limit";
1111 my $sth = $dbh->prepare($query);
1112 $sth->execute( $borrowernumber, $borrowernumber );
1113 return $sth->fetchall_arrayref( {} );
1117 =head2 GetMemberAccountRecords
1119 ($total, $acctlines, $count) = &GetMemberAccountRecords($borrowernumber);
1121 Looks up accounting data for the patron with the given borrowernumber.
1123 C<&GetMemberAccountRecords> returns a three-element array. C<$acctlines> is a
1124 reference-to-array, where each element is a reference-to-hash; the
1125 keys are the fields of the C<accountlines> table in the Koha database.
1126 C<$count> is the number of elements in C<$acctlines>. C<$total> is the
1127 total amount outstanding for all of the account lines.
1132 sub GetMemberAccountRecords {
1133 my ($borrowernumber,$date) = @_;
1134 my $dbh = C4::Context->dbh;
1140 WHERE borrowernumber=?);
1141 my @bind = ($borrowernumber);
1142 if ($date && $date ne ''){
1143 $strsth.=" AND date < ? ";
1146 $strsth.=" ORDER BY date desc,timestamp DESC";
1147 my $sth= $dbh->prepare( $strsth );
1148 $sth->execute( @bind );
1150 while ( my $data = $sth->fetchrow_hashref ) {
1151 if ( $data->{itemnumber} ) {
1152 my $biblio = GetBiblioFromItemNumber( $data->{itemnumber} );
1153 $data->{biblionumber} = $biblio->{biblionumber};
1154 $data->{title} = $biblio->{title};
1156 $acctlines[$numlines] = $data;
1158 $total += int(1000 * $data->{'amountoutstanding'}); # convert float to integer to avoid round-off errors
1161 return ( $total, \@acctlines,$numlines);
1164 =head2 GetBorNotifyAcctRecord
1166 ($total, $acctlines, $count) = &GetBorNotifyAcctRecord($params,$notifyid);
1168 Looks up accounting data for the patron with the given borrowernumber per file number.
1170 C<&GetBorNotifyAcctRecord> returns a three-element array. C<$acctlines> is a
1171 reference-to-array, where each element is a reference-to-hash; the
1172 keys are the fields of the C<accountlines> table in the Koha database.
1173 C<$count> is the number of elements in C<$acctlines>. C<$total> is the
1174 total amount outstanding for all of the account lines.
1178 sub GetBorNotifyAcctRecord {
1179 my ( $borrowernumber, $notifyid ) = @_;
1180 my $dbh = C4::Context->dbh;
1183 my $sth = $dbh->prepare(
1186 WHERE borrowernumber=?
1188 AND amountoutstanding != '0'
1189 ORDER BY notify_id,accounttype
1192 $sth->execute( $borrowernumber, $notifyid );
1194 while ( my $data = $sth->fetchrow_hashref ) {
1195 if ( $data->{itemnumber} ) {
1196 my $biblio = GetBiblioFromItemNumber( $data->{itemnumber} );
1197 $data->{biblionumber} = $biblio->{biblionumber};
1198 $data->{title} = $biblio->{title};
1200 $acctlines[$numlines] = $data;
1202 $total += int(100 * $data->{'amountoutstanding'});
1205 return ( $total, \@acctlines, $numlines );
1208 =head2 checkuniquemember (OUEST-PROVENCE)
1210 ($result,$categorycode) = &checkuniquemember($collectivity,$surname,$firstname,$dateofbirth);
1212 Checks that a member exists or not in the database.
1214 C<&result> is nonzero (=exist) or 0 (=does not exist)
1215 C<&categorycode> is from categorycode table
1216 C<&collectivity> is 1 (= we add a collectivity) or 0 (= we add a physical member)
1217 C<&surname> is the surname
1218 C<&firstname> is the firstname (only if collectivity=0)
1219 C<&dateofbirth> is the date of birth in ISO format (only if collectivity=0)
1223 # FIXME: This function is not legitimate. Multiple patrons might have the same first/last name and birthdate.
1224 # This is especially true since first name is not even a required field.
1226 sub checkuniquemember {
1227 my ( $collectivity, $surname, $firstname, $dateofbirth ) = @_;
1228 my $dbh = C4::Context->dbh;
1229 my $request = ($collectivity) ?
1230 "SELECT borrowernumber,categorycode FROM borrowers WHERE surname=? " :
1232 "SELECT borrowernumber,categorycode FROM borrowers WHERE surname=? and firstname=? and dateofbirth=?" :
1233 "SELECT borrowernumber,categorycode FROM borrowers WHERE surname=? and firstname=?";
1234 my $sth = $dbh->prepare($request);
1235 if ($collectivity) {
1236 $sth->execute( uc($surname) );
1237 } elsif($dateofbirth){
1238 $sth->execute( uc($surname), ucfirst($firstname), $dateofbirth );
1240 $sth->execute( uc($surname), ucfirst($firstname));
1242 my @data = $sth->fetchrow;
1243 ( $data[0] ) and return $data[0], $data[1];
1247 sub checkcardnumber {
1248 my ($cardnumber,$borrowernumber) = @_;
1249 # If cardnumber is null, we assume they're allowed.
1250 return 0 if !defined($cardnumber);
1251 my $dbh = C4::Context->dbh;
1252 my $query = "SELECT * FROM borrowers WHERE cardnumber=?";
1253 $query .= " AND borrowernumber <> ?" if ($borrowernumber);
1254 my $sth = $dbh->prepare($query);
1255 if ($borrowernumber) {
1256 $sth->execute($cardnumber,$borrowernumber);
1258 $sth->execute($cardnumber);
1260 if (my $data= $sth->fetchrow_hashref()){
1269 =head2 getzipnamecity (OUEST-PROVENCE)
1271 take all info from table city for the fields city and zip
1272 check for the name and the zip code of the city selected
1276 sub getzipnamecity {
1278 my $dbh = C4::Context->dbh;
1281 "select city_name,city_state,city_zipcode,city_country from cities where cityid=? ");
1282 $sth->execute($cityid);
1283 my @data = $sth->fetchrow;
1284 return $data[0], $data[1], $data[2], $data[3];
1288 =head2 getdcity (OUEST-PROVENCE)
1290 recover cityid with city_name condition
1295 my ($city_name) = @_;
1296 my $dbh = C4::Context->dbh;
1297 my $sth = $dbh->prepare("select cityid from cities where city_name=? ");
1298 $sth->execute($city_name);
1299 my $data = $sth->fetchrow;
1303 =head2 GetFirstValidEmailAddress
1305 $email = GetFirstValidEmailAddress($borrowernumber);
1307 Return the first valid email address for a borrower, given the borrowernumber. For now, the order
1308 is defined as email, emailpro, B_email. Returns the empty string if the borrower has no email
1313 sub GetFirstValidEmailAddress {
1314 my $borrowernumber = shift;
1315 my $dbh = C4::Context->dbh;
1316 my $sth = $dbh->prepare( "SELECT email, emailpro, B_email FROM borrowers where borrowernumber = ? ");
1317 $sth->execute( $borrowernumber );
1318 my $data = $sth->fetchrow_hashref;
1320 if ($data->{'email'}) {
1321 return $data->{'email'};
1322 } elsif ($data->{'emailpro'}) {
1323 return $data->{'emailpro'};
1324 } elsif ($data->{'B_email'}) {
1325 return $data->{'B_email'};
1331 =head2 GetExpiryDate
1333 $expirydate = GetExpiryDate($categorycode, $dateenrolled);
1335 Calculate expiry date given a categorycode and starting date. Date argument must be in ISO format.
1336 Return date is also in ISO format.
1341 my ( $categorycode, $dateenrolled ) = @_;
1343 if ($categorycode) {
1344 my $dbh = C4::Context->dbh;
1345 my $sth = $dbh->prepare("SELECT enrolmentperiod,enrolmentperioddate FROM categories WHERE categorycode=?");
1346 $sth->execute($categorycode);
1347 $enrolments = $sth->fetchrow_hashref;
1349 # die "GetExpiryDate: for enrollmentperiod $enrolmentperiod (category '$categorycode') starting $dateenrolled.\n";
1350 my @date = split (/-/,$dateenrolled);
1351 if($enrolments->{enrolmentperiod}){
1352 return sprintf("%04d-%02d-%02d", Add_Delta_YM(@date,0,$enrolments->{enrolmentperiod}));
1354 return $enrolments->{enrolmentperioddate};
1358 =head2 checkuserpassword (OUEST-PROVENCE)
1360 check for the password and login are not used
1361 return the number of record
1362 0=> NOT USED 1=> USED
1366 sub checkuserpassword {
1367 my ( $borrowernumber, $userid, $password ) = @_;
1368 $password = md5_base64($password);
1369 my $dbh = C4::Context->dbh;
1372 "Select count(*) from borrowers where borrowernumber !=? and userid =? and password=? "
1374 $sth->execute( $borrowernumber, $userid, $password );
1375 my $number_rows = $sth->fetchrow;
1376 return $number_rows;
1380 =head2 GetborCatFromCatType
1382 ($codes_arrayref, $labels_hashref) = &GetborCatFromCatType();
1384 Looks up the different types of borrowers in the database. Returns two
1385 elements: a reference-to-array, which lists the borrower category
1386 codes, and a reference-to-hash, which maps the borrower category codes
1387 to category descriptions.
1392 sub GetborCatFromCatType {
1393 my ( $category_type, $action, $no_branch_limit ) = @_;
1395 my $branch_limit = $no_branch_limit
1397 : C4::Context->userenv ? C4::Context->userenv->{"branch"} : "";
1399 # FIXME - This API seems both limited and dangerous.
1400 my $dbh = C4::Context->dbh;
1403 SELECT categories.categorycode, categories.description
1407 LEFT JOIN categories_branches ON categories.categorycode = categories_branches.categorycode
1410 $request .= " $action ";
1411 $request .= " AND (branchcode = ? OR branchcode IS NULL) GROUP BY description" if $branch_limit;
1413 $request .= " WHERE branchcode = ? OR branchcode IS NULL GROUP BY description" if $branch_limit;
1415 $request .= " ORDER BY categorycode";
1417 my $sth = $dbh->prepare($request);
1419 $action ? $category_type : (),
1420 $branch_limit ? $branch_limit : ()
1426 while ( my $data = $sth->fetchrow_hashref ) {
1427 push @codes, $data->{'categorycode'};
1428 $labels{ $data->{'categorycode'} } = $data->{'description'};
1431 return ( \@codes, \%labels );
1434 =head2 GetBorrowercategory
1436 $hashref = &GetBorrowercategory($categorycode);
1438 Given the borrower's category code, the function returns the corresponding
1439 data hashref for a comprehensive information display.
1443 sub GetBorrowercategory {
1445 my $dbh = C4::Context->dbh;
1449 "SELECT description,dateofbirthrequired,upperagelimit,category_type
1451 WHERE categorycode = ?"
1453 $sth->execute($catcode);
1455 $sth->fetchrow_hashref;
1459 } # sub getborrowercategory
1462 =head2 GetBorrowerCategorycode
1464 $categorycode = &GetBorrowerCategoryCode( $borrowernumber );
1466 Given the borrowernumber, the function returns the corresponding categorycode
1469 sub GetBorrowerCategorycode {
1470 my ( $borrowernumber ) = @_;
1471 my $dbh = C4::Context->dbh;
1472 my $sth = $dbh->prepare( qq{
1475 WHERE borrowernumber = ?
1477 $sth->execute( $borrowernumber );
1478 return $sth->fetchrow;
1481 =head2 GetBorrowercategoryList
1483 $arrayref_hashref = &GetBorrowercategoryList;
1484 If no category code provided, the function returns all the categories.
1488 sub GetBorrowercategoryList {
1489 my $no_branch_limit = @_ ? shift : 0;
1490 my $branch_limit = $no_branch_limit
1492 : C4::Context->userenv ? C4::Context->userenv->{"branch"} : "";
1493 my $dbh = C4::Context->dbh;
1494 my $query = "SELECT categories.* FROM categories";
1496 LEFT JOIN categories_branches ON categories.categorycode = categories_branches.categorycode
1497 WHERE branchcode = ? OR branchcode IS NULL GROUP BY description
1499 $query .= " ORDER BY description";
1500 my $sth = $dbh->prepare( $query );
1501 $sth->execute( $branch_limit ? $branch_limit : () );
1502 my $data = $sth->fetchall_arrayref( {} );
1505 } # sub getborrowercategory
1507 =head2 ethnicitycategories
1509 ($codes_arrayref, $labels_hashref) = ðnicitycategories();
1511 Looks up the different ethnic types in the database. Returns two
1512 elements: a reference-to-array, which lists the ethnicity codes, and a
1513 reference-to-hash, which maps the ethnicity codes to ethnicity
1520 sub ethnicitycategories {
1521 my $dbh = C4::Context->dbh;
1522 my $sth = $dbh->prepare("Select code,name from ethnicity order by name");
1526 while ( my $data = $sth->fetchrow_hashref ) {
1527 push @codes, $data->{'code'};
1528 $labels{ $data->{'code'} } = $data->{'name'};
1530 return ( \@codes, \%labels );
1535 $ethn_name = &fixEthnicity($ethn_code);
1537 Takes an ethnicity code (e.g., "european" or "pi") and returns the
1538 corresponding descriptive name from the C<ethnicity> table in the
1539 Koha database ("European" or "Pacific Islander").
1546 my $ethnicity = shift;
1547 return unless $ethnicity;
1548 my $dbh = C4::Context->dbh;
1549 my $sth = $dbh->prepare("Select name from ethnicity where code = ?");
1550 $sth->execute($ethnicity);
1551 my $data = $sth->fetchrow_hashref;
1552 return $data->{'name'};
1553 } # sub fixEthnicity
1557 $dateofbirth,$date = &GetAge($date);
1559 this function return the borrowers age with the value of dateofbirth
1565 my ( $date, $date_ref ) = @_;
1567 if ( not defined $date_ref ) {
1568 $date_ref = sprintf( '%04d-%02d-%02d', Today() );
1571 my ( $year1, $month1, $day1 ) = split /-/, $date;
1572 my ( $year2, $month2, $day2 ) = split /-/, $date_ref;
1574 my $age = $year2 - $year1;
1575 if ( $month1 . $day1 > $month2 . $day2 ) {
1582 =head2 get_institutions
1584 $insitutions = get_institutions();
1586 Just returns a list of all the borrowers of type I, borrownumber and name
1591 sub get_institutions {
1592 my $dbh = C4::Context->dbh();
1595 "SELECT borrowernumber,surname FROM borrowers WHERE categorycode=? ORDER BY surname"
1599 while ( my $data = $sth->fetchrow_hashref() ) {
1600 $orgs{ $data->{'borrowernumber'} } = $data;
1604 } # sub get_institutions
1606 =head2 add_member_orgs
1608 add_member_orgs($borrowernumber,$borrowernumbers);
1610 Takes a borrowernumber and a list of other borrowernumbers and inserts them into the borrowers_to_borrowers table
1615 sub add_member_orgs {
1616 my ( $borrowernumber, $otherborrowers ) = @_;
1617 my $dbh = C4::Context->dbh();
1619 "INSERT INTO borrowers_to_borrowers (borrower1,borrower2) VALUES (?,?)";
1620 my $sth = $dbh->prepare($query);
1621 foreach my $otherborrowernumber (@$otherborrowers) {
1622 $sth->execute( $borrowernumber, $otherborrowernumber );
1625 } # sub add_member_orgs
1629 $cityarrayref = GetCities();
1631 Returns an array_ref of the entries in the cities table
1632 If there are entries in the table an empty row is returned
1633 This is currently only used to populate a popup in memberentry
1639 my $dbh = C4::Context->dbh;
1640 my $city_arr = $dbh->selectall_arrayref(
1641 q|SELECT cityid,city_zipcode,city_name,city_state,city_country FROM cities ORDER BY city_name|,
1643 if ( @{$city_arr} ) {
1644 unshift @{$city_arr}, {
1645 city_zipcode => q{},
1649 city_country => q{},
1656 =head2 GetSortDetails (OUEST-PROVENCE)
1658 ($lib) = &GetSortDetails($category,$sortvalue);
1660 Returns the authorized value details
1661 C<&$lib>return value of authorized value details
1662 C<&$sortvalue>this is the value of authorized value
1663 C<&$category>this is the value of authorized value category
1667 sub GetSortDetails {
1668 my ( $category, $sortvalue ) = @_;
1669 my $dbh = C4::Context->dbh;
1670 my $query = qq|SELECT lib
1671 FROM authorised_values
1673 AND authorised_value=? |;
1674 my $sth = $dbh->prepare($query);
1675 $sth->execute( $category, $sortvalue );
1676 my $lib = $sth->fetchrow;
1677 return ($lib) if ($lib);
1678 return ($sortvalue) unless ($lib);
1681 =head2 MoveMemberToDeleted
1683 $result = &MoveMemberToDeleted($borrowernumber);
1685 Copy the record from borrowers to deletedborrowers table.
1689 # FIXME: should do it in one SQL statement w/ subquery
1690 # Otherwise, we should return the @data on success
1692 sub MoveMemberToDeleted {
1693 my ($member) = shift or return;
1694 my $dbh = C4::Context->dbh;
1695 my $query = qq|SELECT *
1697 WHERE borrowernumber=?|;
1698 my $sth = $dbh->prepare($query);
1699 $sth->execute($member);
1700 my @data = $sth->fetchrow_array;
1701 (@data) or return; # if we got a bad borrowernumber, there's nothing to insert
1703 $dbh->prepare( "INSERT INTO deletedborrowers VALUES ("
1704 . ( "?," x ( scalar(@data) - 1 ) )
1706 $sth->execute(@data);
1711 DelMember($borrowernumber);
1713 This function remove directly a borrower whitout writing it on deleteborrower.
1714 + Deletes reserves for the borrower
1719 my $dbh = C4::Context->dbh;
1720 my $borrowernumber = shift;
1721 #warn "in delmember with $borrowernumber";
1722 return unless $borrowernumber; # borrowernumber is mandatory.
1724 my $query = qq|DELETE
1726 WHERE borrowernumber=?|;
1727 my $sth = $dbh->prepare($query);
1728 $sth->execute($borrowernumber);
1732 WHERE borrowernumber = ?
1734 $sth = $dbh->prepare($query);
1735 $sth->execute($borrowernumber);
1736 logaction("MEMBERS", "DELETE", $borrowernumber, "") if C4::Context->preference("BorrowersLog");
1740 =head2 ExtendMemberSubscriptionTo (OUEST-PROVENCE)
1742 $date = ExtendMemberSubscriptionTo($borrowerid, $date);
1744 Extending the subscription to a given date or to the expiry date calculated on ISO date.
1749 sub ExtendMemberSubscriptionTo {
1750 my ( $borrowerid,$date) = @_;
1751 my $dbh = C4::Context->dbh;
1752 my $borrower = GetMember('borrowernumber'=>$borrowerid);
1754 $date = (C4::Context->preference('BorrowerRenewalPeriodBase') eq 'dateexpiry') ?
1755 C4::Dates->new($borrower->{'dateexpiry'}, 'iso')->output("iso") :
1756 C4::Dates->new()->output("iso");
1757 $date = GetExpiryDate( $borrower->{'categorycode'}, $date );
1759 my $sth = $dbh->do(<<EOF);
1761 SET dateexpiry='$date'
1762 WHERE borrowernumber='$borrowerid'
1764 # add enrolmentfee if needed
1765 $sth = $dbh->prepare("SELECT enrolmentfee FROM categories WHERE categorycode=?");
1766 $sth->execute($borrower->{'categorycode'});
1767 my ($enrolmentfee) = $sth->fetchrow;
1768 if ($enrolmentfee && $enrolmentfee > 0) {
1769 # insert fee in patron debts
1770 manualinvoice($borrower->{'borrowernumber'}, '', '', 'A', $enrolmentfee);
1772 logaction("MEMBERS", "RENEW", $borrower->{'borrowernumber'}, "Membership renewed")if C4::Context->preference("BorrowersLog");
1773 return $date if ($sth);
1777 =head2 GetRoadTypes (OUEST-PROVENCE)
1779 ($idroadtypearrayref, $roadttype_hashref) = &GetRoadTypes();
1781 Looks up the different road type . Returns two
1782 elements: a reference-to-array, which lists the id_roadtype
1783 codes, and a reference-to-hash, which maps the road type of the road .
1788 my $dbh = C4::Context->dbh;
1790 SELECT roadtypeid,road_type
1792 ORDER BY road_type|;
1793 my $sth = $dbh->prepare($query);
1798 # insert empty value to create a empty choice in cgi popup
1800 while ( my $data = $sth->fetchrow_hashref ) {
1802 push @id, $data->{'roadtypeid'};
1803 $roadtype{ $data->{'roadtypeid'} } = $data->{'road_type'};
1806 #test to know if the table contain some records if no the function return nothing
1813 return ( \@id, \%roadtype );
1819 =head2 GetTitles (OUEST-PROVENCE)
1821 ($borrowertitle)= &GetTitles();
1823 Looks up the different title . Returns array with all borrowers title
1828 my @borrowerTitle = split (/,|\|/,C4::Context->preference('BorrowersTitles'));
1829 unshift( @borrowerTitle, "" );
1830 my $count=@borrowerTitle;
1835 return ( \@borrowerTitle);
1839 =head2 GetPatronImage
1841 my ($imagedata, $dberror) = GetPatronImage($cardnumber);
1843 Returns the mimetype and binary image data of the image for the patron with the supplied cardnumber.
1847 sub GetPatronImage {
1848 my ($cardnumber) = @_;
1849 warn "Cardnumber passed to GetPatronImage is $cardnumber" if $debug;
1850 my $dbh = C4::Context->dbh;
1851 my $query = 'SELECT mimetype, imagefile FROM patronimage WHERE cardnumber = ?';
1852 my $sth = $dbh->prepare($query);
1853 $sth->execute($cardnumber);
1854 my $imagedata = $sth->fetchrow_hashref;
1855 warn "Database error!" if $sth->errstr;
1856 return $imagedata, $sth->errstr;
1859 =head2 PutPatronImage
1861 PutPatronImage($cardnumber, $mimetype, $imgfile);
1863 Stores patron binary image data and mimetype in database.
1864 NOTE: This function is good for updating images as well as inserting new images in the database.
1868 sub PutPatronImage {
1869 my ($cardnumber, $mimetype, $imgfile) = @_;
1870 warn "Parameters passed in: Cardnumber=$cardnumber, Mimetype=$mimetype, " . ($imgfile ? "Imagefile" : "No Imagefile") if $debug;
1871 my $dbh = C4::Context->dbh;
1872 my $query = "INSERT INTO patronimage (cardnumber, mimetype, imagefile) VALUES (?,?,?) ON DUPLICATE KEY UPDATE imagefile = ?;";
1873 my $sth = $dbh->prepare($query);
1874 $sth->execute($cardnumber,$mimetype,$imgfile,$imgfile);
1875 warn "Error returned inserting $cardnumber.$mimetype." if $sth->errstr;
1876 return $sth->errstr;
1879 =head2 RmPatronImage
1881 my ($dberror) = RmPatronImage($cardnumber);
1883 Removes the image for the patron with the supplied cardnumber.
1888 my ($cardnumber) = @_;
1889 warn "Cardnumber passed to GetPatronImage is $cardnumber" if $debug;
1890 my $dbh = C4::Context->dbh;
1891 my $query = "DELETE FROM patronimage WHERE cardnumber = ?;";
1892 my $sth = $dbh->prepare($query);
1893 $sth->execute($cardnumber);
1894 my $dberror = $sth->errstr;
1895 warn "Database error!" if $sth->errstr;
1899 =head2 GetHideLostItemsPreference
1901 $hidelostitemspref = &GetHideLostItemsPreference($borrowernumber);
1903 Returns the HideLostItems preference for the patron category of the supplied borrowernumber
1904 C<&$hidelostitemspref>return value of function, 0 or 1
1908 sub GetHideLostItemsPreference {
1909 my ($borrowernumber) = @_;
1910 my $dbh = C4::Context->dbh;
1911 my $query = "SELECT hidelostitems FROM borrowers,categories WHERE borrowers.categorycode = categories.categorycode AND borrowernumber = ?";
1912 my $sth = $dbh->prepare($query);
1913 $sth->execute($borrowernumber);
1914 my $hidelostitems = $sth->fetchrow;
1915 return $hidelostitems;
1918 =head2 GetRoadTypeDetails (OUEST-PROVENCE)
1920 ($roadtype) = &GetRoadTypeDetails($roadtypeid);
1922 Returns the description of roadtype
1923 C<&$roadtype>return description of road type
1924 C<&$roadtypeid>this is the value of roadtype s
1928 sub GetRoadTypeDetails {
1929 my ($roadtypeid) = @_;
1930 my $dbh = C4::Context->dbh;
1934 WHERE roadtypeid=?|;
1935 my $sth = $dbh->prepare($query);
1936 $sth->execute($roadtypeid);
1937 my $roadtype = $sth->fetchrow;
1941 =head2 GetBorrowersToExpunge
1943 $borrowers = &GetBorrowersToExpunge(
1944 not_borrowered_since => $not_borrowered_since,
1945 expired_before => $expired_before,
1946 category_code => $category_code,
1947 branchcode => $branchcode
1950 This function get all borrowers based on the given criteria.
1954 sub GetBorrowersToExpunge {
1957 my $filterdate = $params->{'not_borrowered_since'};
1958 my $filterexpiry = $params->{'expired_before'};
1959 my $filtercategory = $params->{'category_code'};
1960 my $filterbranch = $params->{'branchcode'} ||
1961 ((C4::Context->preference('IndependantBranches')
1962 && C4::Context->userenv
1963 && C4::Context->userenv->{flags} % 2 !=1
1964 && C4::Context->userenv->{branch})
1965 ? C4::Context->userenv->{branch}
1968 my $dbh = C4::Context->dbh;
1970 SELECT borrowers.borrowernumber,
1971 MAX(old_issues.timestamp) AS latestissue,
1972 MAX(issues.timestamp) AS currentissue
1974 JOIN categories USING (categorycode)
1975 LEFT JOIN old_issues USING (borrowernumber)
1976 LEFT JOIN issues USING (borrowernumber)
1977 WHERE category_type <> 'S'
1978 AND borrowernumber NOT IN (SELECT guarantorid FROM borrowers WHERE guarantorid IS NOT NULL AND guarantorid <> 0)
1981 if ( $filterbranch && $filterbranch ne "" ) {
1982 $query.= " AND borrowers.branchcode = ? ";
1983 push( @query_params, $filterbranch );
1985 if ( $filterexpiry ) {
1986 $query .= " AND dateexpiry < ? ";
1987 push( @query_params, $filterexpiry );
1989 if ( $filtercategory ) {
1990 $query .= " AND categorycode = ? ";
1991 push( @query_params, $filtercategory );
1993 $query.=" GROUP BY borrowers.borrowernumber HAVING currentissue IS NULL ";
1994 if ( $filterdate ) {
1995 $query.=" AND ( latestissue < ? OR latestissue IS NULL ) ";
1996 push @query_params,$filterdate;
1998 warn $query if $debug;
2000 my $sth = $dbh->prepare($query);
2001 if (scalar(@query_params)>0){
2002 $sth->execute(@query_params);
2009 while ( my $data = $sth->fetchrow_hashref ) {
2010 push @results, $data;
2015 =head2 GetBorrowersWhoHaveNeverBorrowed
2017 $results = &GetBorrowersWhoHaveNeverBorrowed
2019 This function get all borrowers who have never borrowed.
2021 I<$result> is a ref to an array which all elements are a hasref.
2025 sub GetBorrowersWhoHaveNeverBorrowed {
2026 my $filterbranch = shift ||
2027 ((C4::Context->preference('IndependantBranches')
2028 && C4::Context->userenv
2029 && C4::Context->userenv->{flags} % 2 !=1
2030 && C4::Context->userenv->{branch})
2031 ? C4::Context->userenv->{branch}
2033 my $dbh = C4::Context->dbh;
2035 SELECT borrowers.borrowernumber,max(timestamp) as latestissue
2037 LEFT JOIN issues ON borrowers.borrowernumber = issues.borrowernumber
2038 WHERE issues.borrowernumber IS NULL
2041 if ($filterbranch && $filterbranch ne ""){
2042 $query.=" AND borrowers.branchcode= ?";
2043 push @query_params,$filterbranch;
2045 warn $query if $debug;
2047 my $sth = $dbh->prepare($query);
2048 if (scalar(@query_params)>0){
2049 $sth->execute(@query_params);
2056 while ( my $data = $sth->fetchrow_hashref ) {
2057 push @results, $data;
2062 =head2 GetBorrowersWithIssuesHistoryOlderThan
2064 $results = &GetBorrowersWithIssuesHistoryOlderThan($date)
2066 this function get all borrowers who has an issue history older than I<$date> given on input arg.
2068 I<$result> is a ref to an array which all elements are a hashref.
2069 This hashref is containt the number of time this borrowers has borrowed before I<$date> and the borrowernumber.
2073 sub GetBorrowersWithIssuesHistoryOlderThan {
2074 my $dbh = C4::Context->dbh;
2075 my $date = shift ||POSIX::strftime("%Y-%m-%d",localtime());
2076 my $filterbranch = shift ||
2077 ((C4::Context->preference('IndependantBranches')
2078 && C4::Context->userenv
2079 && C4::Context->userenv->{flags} % 2 !=1
2080 && C4::Context->userenv->{branch})
2081 ? C4::Context->userenv->{branch}
2084 SELECT count(borrowernumber) as n,borrowernumber
2086 WHERE returndate < ?
2087 AND borrowernumber IS NOT NULL
2090 push @query_params, $date;
2092 $query.=" AND branchcode = ?";
2093 push @query_params, $filterbranch;
2095 $query.=" GROUP BY borrowernumber ";
2096 warn $query if $debug;
2097 my $sth = $dbh->prepare($query);
2098 $sth->execute(@query_params);
2101 while ( my $data = $sth->fetchrow_hashref ) {
2102 push @results, $data;
2107 =head2 GetBorrowersNamesAndLatestIssue
2109 $results = &GetBorrowersNamesAndLatestIssueList(@borrowernumbers)
2111 this function get borrowers Names and surnames and Issue information.
2113 I<@borrowernumbers> is an array which all elements are borrowernumbers.
2114 This hashref is containt the number of time this borrowers has borrowed before I<$date> and the borrowernumber.
2118 sub GetBorrowersNamesAndLatestIssue {
2119 my $dbh = C4::Context->dbh;
2120 my @borrowernumbers=@_;
2122 SELECT surname,lastname, phone, email,max(timestamp)
2124 LEFT JOIN issues ON borrowers.borrowernumber=issues.borrowernumber
2125 GROUP BY borrowernumber
2127 my $sth = $dbh->prepare($query);
2129 my $results = $sth->fetchall_arrayref({});
2135 my $success = DebarMember( $borrowernumber, $todate );
2137 marks a Member as debarred, and therefore unable to checkout any more
2141 true on success, false on failure
2146 my $borrowernumber = shift;
2149 return unless defined $borrowernumber;
2150 return unless $borrowernumber =~ /^\d+$/;
2153 borrowernumber => $borrowernumber,
2163 my $success = ModPrivacy( $borrowernumber, $privacy );
2165 Update the privacy of a patron.
2168 true on success, false on failure
2175 my $borrowernumber = shift;
2176 my $privacy = shift;
2177 return unless defined $borrowernumber;
2178 return unless $borrowernumber =~ /^\d+$/;
2180 return ModMember( borrowernumber => $borrowernumber,
2181 privacy => $privacy );
2186 AddMessage( $borrowernumber, $message_type, $message, $branchcode );
2188 Adds a message to the messages table for the given borrower.
2197 my ( $borrowernumber, $message_type, $message, $branchcode ) = @_;
2199 my $dbh = C4::Context->dbh;
2201 if ( ! ( $borrowernumber && $message_type && $message && $branchcode ) ) {
2205 my $query = "INSERT INTO messages ( borrowernumber, branchcode, message_type, message ) VALUES ( ?, ?, ?, ? )";
2206 my $sth = $dbh->prepare($query);
2207 $sth->execute( $borrowernumber, $branchcode, $message_type, $message );
2208 logaction("MEMBERS", "ADDCIRCMESSAGE", $borrowernumber, $message) if C4::Context->preference("BorrowersLog");
2214 GetMessages( $borrowernumber, $type );
2216 $type is message type, B for borrower, or L for Librarian.
2217 Empty type returns all messages of any type.
2219 Returns all messages for the given borrowernumber
2224 my ( $borrowernumber, $type, $branchcode ) = @_;
2230 my $dbh = C4::Context->dbh;
2233 branches.branchname,
2236 messages.branchcode LIKE '$branchcode' AS can_delete
2237 FROM messages, branches
2238 WHERE borrowernumber = ?
2239 AND message_type LIKE ?
2240 AND messages.branchcode = branches.branchcode
2241 ORDER BY message_date DESC";
2242 my $sth = $dbh->prepare($query);
2243 $sth->execute( $borrowernumber, $type ) ;
2246 while ( my $data = $sth->fetchrow_hashref ) {
2247 my $d = C4::Dates->new( $data->{message_date}, 'iso' );
2248 $data->{message_date_formatted} = $d->output;
2249 push @results, $data;
2257 GetMessagesCount( $borrowernumber, $type );
2259 $type is message type, B for borrower, or L for Librarian.
2260 Empty type returns all messages of any type.
2262 Returns the number of messages for the given borrowernumber
2266 sub GetMessagesCount {
2267 my ( $borrowernumber, $type, $branchcode ) = @_;
2273 my $dbh = C4::Context->dbh;
2275 my $query = "SELECT COUNT(*) as MsgCount FROM messages WHERE borrowernumber = ? AND message_type LIKE ?";
2276 my $sth = $dbh->prepare($query);
2277 $sth->execute( $borrowernumber, $type ) ;
2280 my $data = $sth->fetchrow_hashref;
2281 my $count = $data->{'MsgCount'};
2288 =head2 DeleteMessage
2290 DeleteMessage( $message_id );
2295 my ( $message_id ) = @_;
2297 my $dbh = C4::Context->dbh;
2298 my $query = "SELECT * FROM messages WHERE message_id = ?";
2299 my $sth = $dbh->prepare($query);
2300 $sth->execute( $message_id );
2301 my $message = $sth->fetchrow_hashref();
2303 $query = "DELETE FROM messages WHERE message_id = ?";
2304 $sth = $dbh->prepare($query);
2305 $sth->execute( $message_id );
2306 logaction("MEMBERS", "DELCIRCMESSAGE", $message->{'borrowernumber'}, $message->{'message'}) if C4::Context->preference("BorrowersLog");
2311 IssueSlip($branchcode, $borrowernumber, $quickslip)
2313 Returns letter hash ( see C4::Letters::GetPreparedLetter )
2315 $quickslip is boolean, to indicate whether we want a quick slip
2320 my ($branch, $borrowernumber, $quickslip) = @_;
2322 # return unless ( C4::Context->boolean_preference('printcirculationslips') );
2324 my $now = POSIX::strftime("%Y-%m-%d", localtime);
2326 my $issueslist = GetPendingIssues($borrowernumber);
2327 foreach my $it (@$issueslist){
2328 if ((substr $it->{'issuedate'}, 0, 10) eq $now) {
2331 elsif ((substr $it->{'date_due'}, 0, 10) le $now) {
2332 $it->{'overdue'} = 1;
2335 $it->{'date_due'}=format_date($it->{'date_due'});
2337 my @issues = sort { $b->{'timestamp'} <=> $a->{'timestamp'} } @$issueslist;
2339 my ($letter_code, %repeat);
2341 $letter_code = 'ISSUEQSLIP';
2343 'checkedout' => [ map {
2347 }, grep { $_->{'now'} } @issues ],
2351 $letter_code = 'ISSUESLIP';
2353 'checkedout' => [ map {
2357 }, grep { !$_->{'overdue'} } @issues ],
2359 'overdue' => [ map {
2363 }, grep { $_->{'overdue'} } @issues ],
2366 $_->{'timestamp'} = $_->{'newdate'};
2368 } @{ GetNewsToDisplay("slip") } ],
2372 return C4::Letters::GetPreparedLetter (
2373 module => 'circulation',
2374 letter_code => $letter_code,
2375 branchcode => $branch,
2377 'branches' => $branch,
2378 'borrowers' => $borrowernumber,
2384 =head2 GetBorrowersWithEmail
2386 ([$borrnum,$userid], ...) = GetBorrowersWithEmail('me@example.com');
2388 This gets a list of users and their basic details from their email address.
2389 As it's possible for multiple user to have the same email address, it provides
2390 you with all of them. If there is no userid for the user, there will be an
2391 C<undef> there. An empty list will be returned if there are no matches.
2395 sub GetBorrowersWithEmail {
2398 my $dbh = C4::Context->dbh;
2400 my $query = "SELECT borrowernumber, userid FROM borrowers WHERE email=?";
2401 my $sth=$dbh->prepare($query);
2402 $sth->execute($email);
2404 while (my $ref = $sth->fetch) {
2407 die "Failure searching for borrowers by email address: $sth->errstr" if $sth->err;
2411 sub AddMember_Opac {
2412 my ( %borrower ) = @_;
2414 $borrower{'categorycode'} = C4::Context->preference('PatronSelfRegistrationDefaultCategory');
2416 my $sr = new String::Random;
2417 $sr->{'A'} = [ 'A'..'Z', 'a'..'z' ];
2418 my $password = $sr->randpattern("AAAAAAAAAA");
2419 $borrower{'password'} = $password;
2421 $borrower{'cardnumber'} = fixup_cardnumber();
2423 my $borrowernumber = AddMember(%borrower);
2425 return ( $borrowernumber, $password );
2428 END { } # module clean-up code here (global destructor)