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 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 our ($VERSION,@ISA,@EXPORT,@EXPORT_OK,$debug);
43 $debug = $ENV{DEBUG} || 0;
55 &GetMemberIssuesAndFines
63 &GetFirstValidEmailAddress
76 &GetHideLostItemsPreference
79 &GetMemberAccountRecords
80 &GetBorNotifyAcctRecord
84 &GetBorrowercategoryList
86 &GetBorrowersWhoHaveNotBorrowedSince
87 &GetBorrowersWhoHaveNeverBorrowed
88 &GetBorrowersWithIssuesHistoryOlderThan
117 &ExtendMemberSubscriptionTo
135 C4::Members - Perl Module containing convenience functions for member handling
143 This module contains routines for adding, modifying and deleting members/patrons/borrowers
149 $borrowers_result_array_ref = &Search($filter,$orderby, $limit,
150 $columns_out, $search_on_fields,$searchtype);
152 Looks up patrons (borrowers) on filter. A wrapper for SearchInTable('borrowers').
154 For C<$filter>, C<$orderby>, C<$limit>, C<&columns_out>, C<&search_on_fields> and C<&searchtype>
155 refer to C4::SQLHelper:SearchInTable().
157 Special C<$filter> key '' is effectively expanded to search on surname firstname othernamescw
158 and cardnumber unless C<&search_on_fields> is defined
162 $borrowers = Search('abcd', 'cardnumber');
164 $borrowers = Search({''=>'abcd', category_type=>'I'}, 'surname');
168 sub _express_member_find {
171 # this is used by circulation everytime a new borrowers cardnumber is scanned
172 # so we can check an exact match first, if that works return, otherwise do the rest
173 my $dbh = C4::Context->dbh;
174 my $query = "SELECT borrowernumber FROM borrowers WHERE cardnumber = ?";
175 if ( my $borrowernumber = $dbh->selectrow_array($query, undef, $filter) ) {
176 return( {"borrowernumber"=>$borrowernumber} );
179 my ($search_on_fields, $searchtype);
180 if ( length($filter) == 1 ) {
181 $search_on_fields = [ qw(surname) ];
182 $searchtype = 'start_with';
184 $search_on_fields = [ qw(surname firstname othernames cardnumber) ];
185 $searchtype = 'contain';
188 return (undef, $search_on_fields, $searchtype);
192 my ( $filter, $orderby, $limit, $columns_out, $search_on_fields, $searchtype ) = @_;
197 if ( my $fr = ref $filter ) {
198 if ( $fr eq "HASH" ) {
199 if ( my $search_string = $filter->{''} ) {
200 my ($member_filter, $member_search_on_fields, $member_searchtype) = _express_member_find($search_string);
201 if ($member_filter) {
202 $filter = $member_filter;
205 $search_on_fields ||= $member_search_on_fields;
206 $searchtype ||= $member_searchtype;
211 $search_string = $filter;
215 $search_string = $filter;
216 my ($member_filter, $member_search_on_fields, $member_searchtype) = _express_member_find($search_string);
217 if ($member_filter) {
218 $filter = $member_filter;
221 $search_on_fields ||= $member_search_on_fields;
222 $searchtype ||= $member_searchtype;
226 if ( !$found_borrower && C4::Context->preference('ExtendedPatronAttributes') && $search_string ) {
227 my $matching_records = C4::Members::Attributes::SearchIdMatchingAttribute($search_string);
228 if(scalar(@$matching_records)>0) {
229 if ( my $fr = ref $filter ) {
230 if ( $fr eq "HASH" ) {
232 $filter = [ $filter ];
234 push @$filter, { %f, "borrowernumber"=>$$matching_records };
237 push @$filter, {"borrowernumber"=>$matching_records};
241 $filter = [ $filter ];
242 push @$filter, {"borrowernumber"=>$matching_records};
247 # $showallbranches was not used at the time SearchMember() was mainstreamed into Search().
248 # Mentioning for the reference
250 if ( C4::Context->preference("IndependantBranches") ) { # && !$showallbranches){
251 if ( my $userenv = C4::Context->userenv ) {
252 my $branch = $userenv->{'branch'};
253 if ( ($userenv->{flags} % 2 !=1) &&
254 $branch && $branch ne "insecure" ){
256 if (my $fr = ref $filter) {
257 if ( $fr eq "HASH" ) {
258 $filter->{branchcode} = $branch;
262 $_ = { '' => $_ } unless ref $_;
263 $_->{branchcode} = $branch;
268 $filter = { '' => $filter, branchcode => $branch };
274 if ($found_borrower) {
275 $searchtype = "exact";
277 $searchtype ||= "start_with";
279 return SearchInTable( "borrowers", $filter, $orderby, $limit, $columns_out, $search_on_fields, $searchtype );
282 =head2 GetMemberDetails
284 ($borrower) = &GetMemberDetails($borrowernumber, $cardnumber);
286 Looks up a patron and returns information about him or her. If
287 C<$borrowernumber> is true (nonzero), C<&GetMemberDetails> looks
288 up the borrower by number; otherwise, it looks up the borrower by card
291 C<$borrower> is a reference-to-hash whose keys are the fields of the
292 borrowers table in the Koha database. In addition,
293 C<$borrower-E<gt>{flags}> is a hash giving more detailed information
294 about the patron. Its keys act as flags :
296 if $borrower->{flags}->{LOST} {
297 # Patron's card was reported lost
300 If the state of a flag means that the patron should not be
301 allowed to borrow any more books, then it will have a C<noissues> key
304 See patronflags for more details.
306 C<$borrower-E<gt>{authflags}> is a hash giving more detailed information
307 about the top-level permissions flags set for the borrower. For example,
308 if a user has the "editcatalogue" permission,
309 C<$borrower-E<gt>{authflags}-E<gt>{editcatalogue}> will exist and have
314 sub GetMemberDetails {
315 my ( $borrowernumber, $cardnumber ) = @_;
316 my $dbh = C4::Context->dbh;
319 if ($borrowernumber) {
320 $sth = $dbh->prepare("SELECT borrowers.*,category_type,categories.description,reservefee,enrolmentperiod FROM borrowers LEFT JOIN categories ON borrowers.categorycode=categories.categorycode WHERE borrowernumber=?");
321 $sth->execute($borrowernumber);
323 elsif ($cardnumber) {
324 $sth = $dbh->prepare("SELECT borrowers.*,category_type,categories.description,reservefee,enrolmentperiod FROM borrowers LEFT JOIN categories ON borrowers.categorycode=categories.categorycode WHERE cardnumber=?");
325 $sth->execute($cardnumber);
330 my $borrower = $sth->fetchrow_hashref;
331 my ($amount) = GetMemberAccountRecords( $borrowernumber);
332 $borrower->{'amountoutstanding'} = $amount;
333 # FIXME - patronflags calls GetMemberAccountRecords... just have patronflags return $amount
334 my $flags = patronflags( $borrower);
337 $sth = $dbh->prepare("select bit,flag from userflags");
339 while ( my ( $bit, $flag ) = $sth->fetchrow ) {
340 if ( $borrower->{'flags'} && $borrower->{'flags'} & 2**$bit ) {
341 $accessflagshash->{$flag} = 1;
344 $borrower->{'flags'} = $flags;
345 $borrower->{'authflags'} = $accessflagshash;
347 # For the purposes of making templates easier, we'll define a
348 # 'showname' which is the alternate form the user's first name if
349 # 'other name' is defined.
350 if ($borrower->{category_type} eq 'I') {
351 $borrower->{'showname'} = $borrower->{'othernames'};
352 $borrower->{'showname'} .= " $borrower->{'firstname'}" if $borrower->{'firstname'};
354 $borrower->{'showname'} = $borrower->{'firstname'};
357 return ($borrower); #, $flags, $accessflagshash);
362 $flags = &patronflags($patron);
364 This function is not exported.
366 The following will be set where applicable:
367 $flags->{CHARGES}->{amount} Amount of debt
368 $flags->{CHARGES}->{noissues} Set if debt amount >$5.00 (or syspref noissuescharge)
369 $flags->{CHARGES}->{message} Message -- deprecated
371 $flags->{CREDITS}->{amount} Amount of credit
372 $flags->{CREDITS}->{message} Message -- deprecated
374 $flags->{ GNA } Patron has no valid address
375 $flags->{ GNA }->{noissues} Set for each GNA
376 $flags->{ GNA }->{message} "Borrower has no valid address" -- deprecated
378 $flags->{ LOST } Patron's card reported lost
379 $flags->{ LOST }->{noissues} Set for each LOST
380 $flags->{ LOST }->{message} Message -- deprecated
382 $flags->{DBARRED} Set if patron debarred, no access
383 $flags->{DBARRED}->{noissues} Set for each DBARRED
384 $flags->{DBARRED}->{message} Message -- deprecated
387 $flags->{ NOTES }->{message} The note itself. NOT deprecated
389 $flags->{ ODUES } Set if patron has overdue books.
390 $flags->{ ODUES }->{message} "Yes" -- deprecated
391 $flags->{ ODUES }->{itemlist} ref-to-array: list of overdue books
392 $flags->{ ODUES }->{itemlisttext} Text list of overdue items -- deprecated
394 $flags->{WAITING} Set if any of patron's reserves are available
395 $flags->{WAITING}->{message} Message -- deprecated
396 $flags->{WAITING}->{itemlist} ref-to-array: list of available items
400 =item C<$flags-E<gt>{ODUES}-E<gt>{itemlist}> is a reference-to-array listing the
401 overdue items. Its elements are references-to-hash, each describing an
402 overdue item. The keys are selected fields from the issues, biblio,
403 biblioitems, and items tables of the Koha database.
405 =item C<$flags-E<gt>{ODUES}-E<gt>{itemlisttext}> is a string giving a text listing of
406 the overdue items, one per line. Deprecated.
408 =item C<$flags-E<gt>{WAITING}-E<gt>{itemlist}> is a reference-to-array listing the
409 available items. Each element is a reference-to-hash whose keys are
410 fields from the reserves table of the Koha database.
414 All the "message" fields that include language generated in this function are deprecated,
415 because such strings belong properly in the display layer.
417 The "message" field that comes from the DB is OK.
421 # TODO: use {anonymous => hashes} instead of a dozen %flaginfo
422 # FIXME rename this function.
425 my ( $patroninformation) = @_;
426 my $dbh=C4::Context->dbh;
427 my ($amount) = GetMemberAccountRecords( $patroninformation->{'borrowernumber'});
430 my $noissuescharge = C4::Context->preference("noissuescharge") || 5;
431 $flaginfo{'message'} = sprintf "Patron owes \$%.02f", $amount;
432 $flaginfo{'amount'} = sprintf "%.02f", $amount;
433 if ( $amount > $noissuescharge && !C4::Context->preference("AllowFineOverride") ) {
434 $flaginfo{'noissues'} = 1;
436 $flags{'CHARGES'} = \%flaginfo;
438 elsif ( $amount < 0 ) {
440 $flaginfo{'message'} = sprintf "Patron has credit of \$%.02f", -$amount;
441 $flaginfo{'amount'} = sprintf "%.02f", $amount;
442 $flags{'CREDITS'} = \%flaginfo;
444 if ( $patroninformation->{'gonenoaddress'}
445 && $patroninformation->{'gonenoaddress'} == 1 )
448 $flaginfo{'message'} = 'Borrower has no valid address.';
449 $flaginfo{'noissues'} = 1;
450 $flags{'GNA'} = \%flaginfo;
452 if ( $patroninformation->{'lost'} && $patroninformation->{'lost'} == 1 ) {
454 $flaginfo{'message'} = 'Borrower\'s card reported lost.';
455 $flaginfo{'noissues'} = 1;
456 $flags{'LOST'} = \%flaginfo;
458 if ( $patroninformation->{'debarred'} && check_date( split( /-/, $patroninformation->{'debarred'} ) ) ) {
459 if ( Date_to_Days(Date::Calc::Today) < Date_to_Days( split( /-/, $patroninformation->{'debarred'} ) ) ) {
461 $flaginfo{'debarredcomment'} = $patroninformation->{'debarredcomment'};
462 $flaginfo{'message'} = $patroninformation->{'debarredcomment'};
463 $flaginfo{'noissues'} = 1;
464 $flaginfo{'dateend'} = $patroninformation->{'debarred'};
465 $flags{'DBARRED'} = \%flaginfo;
468 if ( $patroninformation->{'borrowernotes'}
469 && $patroninformation->{'borrowernotes'} )
472 $flaginfo{'message'} = $patroninformation->{'borrowernotes'};
473 $flags{'NOTES'} = \%flaginfo;
475 my ( $odues, $itemsoverdue ) = checkoverdues($patroninformation->{'borrowernumber'});
476 if ( $odues && $odues > 0 ) {
478 $flaginfo{'message'} = "Yes";
479 $flaginfo{'itemlist'} = $itemsoverdue;
480 foreach ( sort { $a->{'date_due'} cmp $b->{'date_due'} }
483 $flaginfo{'itemlisttext'} .=
484 "$_->{'date_due'} $_->{'barcode'} $_->{'title'} \n"; # newline is display layer
486 $flags{'ODUES'} = \%flaginfo;
488 my @itemswaiting = C4::Reserves::GetReservesFromBorrowernumber( $patroninformation->{'borrowernumber'},'W' );
489 my $nowaiting = scalar @itemswaiting;
490 if ( $nowaiting > 0 ) {
492 $flaginfo{'message'} = "Reserved items available";
493 $flaginfo{'itemlist'} = \@itemswaiting;
494 $flags{'WAITING'} = \%flaginfo;
502 $borrower = &GetMember(%information);
504 Retrieve the first patron record meeting on criteria listed in the
505 C<%information> hash, which should contain one or more
506 pairs of borrowers column names and values, e.g.,
508 $borrower = GetMember(borrowernumber => id);
510 C<&GetBorrower> returns a reference-to-hash whose keys are the fields of
511 the C<borrowers> table in the Koha database.
513 FIXME: GetMember() is used throughout the code as a lookup
514 on a unique key such as the borrowernumber, but this meaning is not
515 enforced in the routine itself.
521 my ( %information ) = @_;
522 if (exists $information{borrowernumber} && !defined $information{borrowernumber}) {
523 #passing mysql's kohaadmin?? Makes no sense as a query
526 my $dbh = C4::Context->dbh;
528 q{SELECT borrowers.*, categories.category_type, categories.description
530 LEFT JOIN categories on borrowers.categorycode=categories.categorycode WHERE };
533 for (keys %information ) {
541 if (defined $information{$_}) {
543 push @values, $information{$_};
546 $select .= "$_ IS NULL";
549 $debug && warn $select, " ",values %information;
550 my $sth = $dbh->prepare("$select");
551 $sth->execute(map{$information{$_}} keys %information);
552 my $data = $sth->fetchall_arrayref({});
553 #FIXME interface to this routine now allows generation of a result set
554 #so whole array should be returned but bowhere in the current code expects this
562 =head2 GetMemberRelatives
564 @borrowernumbers = GetMemberRelatives($borrowernumber);
566 C<GetMemberRelatives> returns a borrowersnumber's list of guarantor/guarantees of the member given in parameter
569 sub GetMemberRelatives {
570 my $borrowernumber = shift;
571 my $dbh = C4::Context->dbh;
575 my $query = "SELECT guarantorid FROM borrowers WHERE borrowernumber=?";
576 my $sth = $dbh->prepare($query);
577 $sth->execute($borrowernumber);
578 my $data = $sth->fetchrow_arrayref();
579 push @glist, $data->[0] if $data->[0];
580 my $guarantor = $data->[0] if $data->[0];
583 $query = "SELECT borrowernumber FROM borrowers WHERE guarantorid=?";
584 $sth = $dbh->prepare($query);
585 $sth->execute($borrowernumber);
586 while ($data = $sth->fetchrow_arrayref()) {
587 push @glist, $data->[0];
590 # Getting sibling guarantees
592 $query = "SELECT borrowernumber FROM borrowers WHERE guarantorid=?";
593 $sth = $dbh->prepare($query);
594 $sth->execute($guarantor);
595 while ($data = $sth->fetchrow_arrayref()) {
596 push @glist, $data->[0] if ($data->[0] != $borrowernumber);
603 =head2 IsMemberBlocked
605 my ($block_status, $count) = IsMemberBlocked( $borrowernumber );
607 Returns whether a patron has overdue items that may result
608 in a block or whether the patron has active fine days
609 that would block circulation privileges.
611 C<$block_status> can have the following values:
613 1 if the patron has outstanding fine days, in which case C<$count> is the number of them
615 -1 if the patron has overdue items, in which case C<$count> is the number of them
617 0 if the patron has no overdue items or outstanding fine days, in which case C<$count> is 0
619 Outstanding fine days are checked before current overdue items
622 FIXME: this needs to be split into two functions; a potential block
623 based on the number of current overdue items could be orthogonal
624 to a block based on whether the patron has any fine days accrued.
628 sub IsMemberBlocked {
629 my $borrowernumber = shift;
630 my $dbh = C4::Context->dbh;
632 my $blockeddate = CheckBorrowerDebarred($borrowernumber);
634 return ( 1, $blockeddate ) if $blockeddate;
636 # if he have late issues
637 my $sth = $dbh->prepare(
638 "SELECT COUNT(*) as latedocs
640 WHERE borrowernumber = ?
641 AND date_due < curdate()"
643 $sth->execute($borrowernumber);
644 my $latedocs = $sth->fetchrow_hashref->{'latedocs'};
646 return ( -1, $latedocs ) if $latedocs > 0;
651 =head2 GetMemberIssuesAndFines
653 ($overdue_count, $issue_count, $total_fines) = &GetMemberIssuesAndFines($borrowernumber);
655 Returns aggregate data about items borrowed by the patron with the
656 given borrowernumber.
658 C<&GetMemberIssuesAndFines> returns a three-element array. C<$overdue_count> is the
659 number of overdue items the patron currently has borrowed. C<$issue_count> is the
660 number of books the patron currently has borrowed. C<$total_fines> is
661 the total fine currently due by the borrower.
666 sub GetMemberIssuesAndFines {
667 my ( $borrowernumber ) = @_;
668 my $dbh = C4::Context->dbh;
669 my $query = "SELECT COUNT(*) FROM issues WHERE borrowernumber = ?";
671 $debug and warn $query."\n";
672 my $sth = $dbh->prepare($query);
673 $sth->execute($borrowernumber);
674 my $issue_count = $sth->fetchrow_arrayref->[0];
676 $sth = $dbh->prepare(
677 "SELECT COUNT(*) FROM issues
678 WHERE borrowernumber = ?
679 AND date_due < curdate()"
681 $sth->execute($borrowernumber);
682 my $overdue_count = $sth->fetchrow_arrayref->[0];
684 $sth = $dbh->prepare("SELECT SUM(amountoutstanding) FROM accountlines WHERE borrowernumber = ?");
685 $sth->execute($borrowernumber);
686 my $total_fines = $sth->fetchrow_arrayref->[0];
688 return ($overdue_count, $issue_count, $total_fines);
692 return @{C4::Context->dbh->selectcol_arrayref("SHOW columns from borrowers")};
697 my $success = ModMember(borrowernumber => $borrowernumber,
698 [ field => value ]... );
700 Modify borrower's data. All date fields should ALREADY be in ISO format.
703 true on success, or false on failure
709 # test to know if you must update or not the borrower password
710 if (exists $data{password}) {
711 if ($data{password} eq '****' or $data{password} eq '') {
712 delete $data{password};
714 $data{password} = md5_base64($data{password});
717 my $execute_success=UpdateInTable("borrowers",\%data);
718 if ($execute_success) { # only proceed if the update was a success
719 # ok if its an adult (type) it may have borrowers that depend on it as a guarantor
720 # so when we update information for an adult we should check for guarantees and update the relevant part
721 # of their records, ie addresses and phone numbers
722 my $borrowercategory= GetBorrowercategory( $data{'category_type'} );
723 if ( exists $borrowercategory->{'category_type'} && $borrowercategory->{'category_type'} eq ('A' || 'S') ) {
724 # is adult check guarantees;
725 UpdateGuarantees(%data);
727 logaction("MEMBERS", "MODIFY", $data{'borrowernumber'}, "UPDATE (executed w/ arg: $data{'borrowernumber'})") if C4::Context->preference("BorrowersLog");
729 return $execute_success;
735 $borrowernumber = &AddMember(%borrower);
737 insert new borrower into table
738 Returns the borrowernumber upon success
740 Returns as undef upon any db error without further processing
747 my $dbh = C4::Context->dbh;
748 # generate a proper login if none provided
749 $data{'userid'} = Generate_Userid($data{'borrowernumber'}, $data{'firstname'}, $data{'surname'}) if $data{'userid'} eq '';
750 # create a disabled account if no password provided
751 $data{'password'} = ($data{'password'})? md5_base64($data{'password'}) : '!';
752 $data{'borrowernumber'}=InsertInTable("borrowers",\%data);
753 # mysql_insertid is probably bad. not necessarily accurate and mysql-specific at best.
754 logaction("MEMBERS", "CREATE", $data{'borrowernumber'}, "") if C4::Context->preference("BorrowersLog");
756 # check for enrollment fee & add it if needed
757 my $sth = $dbh->prepare("SELECT enrolmentfee FROM categories WHERE categorycode=?");
758 $sth->execute($data{'categorycode'});
759 my ($enrolmentfee) = $sth->fetchrow;
761 warn sprintf('Database returned the following error: %s', $sth->errstr);
764 if ($enrolmentfee && $enrolmentfee > 0) {
765 # insert fee in patron debts
766 manualinvoice($data{'borrowernumber'}, '', '', 'A', $enrolmentfee);
769 return $data{'borrowernumber'};
774 my ($uid,$member) = @_;
775 my $dbh = C4::Context->dbh;
776 # Make sure the userid chosen is unique and not theirs if non-empty. If it is not,
777 # Then we need to tell the user and have them create a new one.
780 "SELECT * FROM borrowers WHERE userid=? AND borrowernumber != ?");
781 $sth->execute( $uid, $member );
782 if ( ( $uid ne '' ) && ( my $row = $sth->fetchrow_hashref ) ) {
790 sub Generate_Userid {
791 my ($borrowernumber, $firstname, $surname) = @_;
795 $firstname =~ s/[[:digit:][:space:][:blank:][:punct:][:cntrl:]]//g;
796 $surname =~ s/[[:digit:][:space:][:blank:][:punct:][:cntrl:]]//g;
797 $newuid = lc(($firstname)? "$firstname.$surname" : $surname);
798 $newuid .= $offset unless $offset == 0;
801 } while (!Check_Userid($newuid,$borrowernumber));
807 my ( $uid, $member, $digest ) = @_;
808 my $dbh = C4::Context->dbh;
810 #Make sure the userid chosen is unique and not theirs if non-empty. If it is not,
811 #Then we need to tell the user and have them create a new one.
815 "SELECT * FROM borrowers WHERE userid=? AND borrowernumber != ?");
816 $sth->execute( $uid, $member );
817 if ( ( $uid ne '' ) && ( my $row = $sth->fetchrow_hashref ) ) {
821 #Everything is good so we can update the information.
824 "update borrowers set userid=?, password=? where borrowernumber=?");
825 $sth->execute( $uid, $digest, $member );
829 logaction("MEMBERS", "CHANGE PASS", $member, "") if C4::Context->preference("BorrowersLog");
835 =head2 fixup_cardnumber
837 Warning: The caller is responsible for locking the members table in write
838 mode, to avoid database corruption.
842 use vars qw( @weightings );
843 my @weightings = ( 8, 4, 6, 3, 5, 2, 1 );
845 sub fixup_cardnumber ($) {
846 my ($cardnumber) = @_;
847 my $autonumber_members = C4::Context->boolean_preference('autoMemberNum') || 0;
849 # Find out whether member numbers should be generated
850 # automatically. Should be either "1" or something else.
851 # Defaults to "0", which is interpreted as "no".
853 # if ($cardnumber !~ /\S/ && $autonumber_members) {
854 ($autonumber_members) or return $cardnumber;
855 my $checkdigit = C4::Context->preference('checkdigit');
856 my $dbh = C4::Context->dbh;
857 if ( $checkdigit and $checkdigit eq 'katipo' ) {
859 # if checkdigit is selected, calculate katipo-style cardnumber.
860 # otherwise, just use the max()
861 # purpose: generate checksum'd member numbers.
862 # We'll assume we just got the max value of digits 2-8 of member #'s
863 # from the database and our job is to increment that by one,
864 # determine the 1st and 9th digits and return the full string.
865 my $sth = $dbh->prepare(
866 "select max(substring(borrowers.cardnumber,2,7)) as new_num from borrowers"
869 my $data = $sth->fetchrow_hashref;
870 $cardnumber = $data->{new_num};
871 if ( !$cardnumber ) { # If DB has no values,
872 $cardnumber = 1000000; # start at 1000000
878 for ( my $i = 0 ; $i < 8 ; $i += 1 ) {
879 # read weightings, left to right, 1 char at a time
880 my $temp1 = $weightings[$i];
882 # sequence left to right, 1 char at a time
883 my $temp2 = substr( $cardnumber, $i, 1 );
885 # mult each char 1-7 by its corresponding weighting
886 $sum += $temp1 * $temp2;
889 my $rem = ( $sum % 11 );
890 $rem = 'X' if $rem == 10;
892 return "V$cardnumber$rem";
895 # MODIFIED BY JF: mysql4.1 allows casting as an integer, which is probably
896 # better. I'll leave the original in in case it needs to be changed for you
897 # my $sth=$dbh->prepare("select max(borrowers.cardnumber) from borrowers");
898 my $sth = $dbh->prepare(
899 "select max(cast(cardnumber as signed)) from borrowers"
902 my ($result) = $sth->fetchrow;
905 return $cardnumber; # just here as a fallback/reminder
910 ($num_children, $children_arrayref) = &GetGuarantees($parent_borrno);
911 $child0_cardno = $children_arrayref->[0]{"cardnumber"};
912 $child0_borrno = $children_arrayref->[0]{"borrowernumber"};
914 C<&GetGuarantees> takes a borrower number (e.g., that of a patron
915 with children) and looks up the borrowers who are guaranteed by that
916 borrower (i.e., the patron's children).
918 C<&GetGuarantees> returns two values: an integer giving the number of
919 borrowers guaranteed by C<$parent_borrno>, and a reference to an array
920 of references to hash, which gives the actual results.
926 my ($borrowernumber) = @_;
927 my $dbh = C4::Context->dbh;
930 "select cardnumber,borrowernumber, firstname, surname from borrowers where guarantorid=?"
932 $sth->execute($borrowernumber);
935 my $data = $sth->fetchall_arrayref({});
936 return ( scalar(@$data), $data );
939 =head2 UpdateGuarantees
941 &UpdateGuarantees($parent_borrno);
944 C<&UpdateGuarantees> borrower data for an adult and updates all the guarantees
945 with the modified information
950 sub UpdateGuarantees {
952 my $dbh = C4::Context->dbh;
953 my ( $count, $guarantees ) = GetGuarantees( $data{'borrowernumber'} );
954 foreach my $guarantee (@$guarantees){
955 my $guaquery = qq|UPDATE borrowers
956 SET address=?,fax=?,B_city=?,mobile=?,city=?,phone=?
957 WHERE borrowernumber=?
959 my $sth = $dbh->prepare($guaquery);
960 $sth->execute($data{'address'},$data{'fax'},$data{'B_city'},$data{'mobile'},$data{'city'},$data{'phone'},$guarantee->{'borrowernumber'});
963 =head2 GetPendingIssues
965 my $issues = &GetPendingIssues(@borrowernumber);
967 Looks up what the patron with the given borrowernumber has borrowed.
969 C<&GetPendingIssues> returns a
970 reference-to-array where each element is a reference-to-hash; the
971 keys are the fields from the C<issues>, C<biblio>, and C<items> tables.
972 The keys include C<biblioitems> fields except marc and marcxml.
977 sub GetPendingIssues {
978 my @borrowernumbers = @_;
980 unless (@borrowernumbers ) { # return a ref_to_array
981 return \@borrowernumbers; # to not cause surprise to caller
984 # Borrowers part of the query
986 for (my $i = 0; $i < @borrowernumbers; $i++) {
987 $bquery .= ' issues.borrowernumber = ?';
988 if ($i < $#borrowernumbers ) {
993 # must avoid biblioitems.* to prevent large marc and marcxml fields from killing performance
994 # FIXME: namespace collision: each table has "timestamp" fields. Which one is "timestamp" ?
995 # FIXME: circ/ciculation.pl tries to sort by timestamp!
996 # FIXME: C4::Print::printslip tries to sort by timestamp!
997 # FIXME: namespace collision: other collisions possible.
998 # FIXME: most of this data isn't really being used by callers.
1005 biblioitems.itemtype,
1008 biblioitems.publicationyear,
1009 biblioitems.publishercode,
1010 biblioitems.volumedate,
1011 biblioitems.volumedesc,
1014 borrowers.firstname,
1016 borrowers.cardnumber,
1017 issues.timestamp AS timestamp,
1018 issues.renewals AS renewals,
1019 issues.borrowernumber AS borrowernumber,
1020 items.renewals AS totalrenewals
1022 LEFT JOIN items ON items.itemnumber = issues.itemnumber
1023 LEFT JOIN biblio ON items.biblionumber = biblio.biblionumber
1024 LEFT JOIN biblioitems ON items.biblioitemnumber = biblioitems.biblioitemnumber
1025 LEFT JOIN borrowers ON issues.borrowernumber = borrowers.borrowernumber
1028 ORDER BY issues.issuedate"
1031 my $sth = C4::Context->dbh->prepare($query);
1032 $sth->execute(@borrowernumbers);
1033 my $data = $sth->fetchall_arrayref({});
1034 my $today = C4::Dates->new->output('iso');
1035 foreach (@{$data}) {
1036 if ($_->{date_due} and $_->{date_due} lt $today) {
1045 $issues = &GetAllIssues($borrowernumber, $sortkey, $limit);
1047 Looks up what the patron with the given borrowernumber has borrowed,
1048 and sorts the results.
1050 C<$sortkey> is the name of a field on which to sort the results. This
1051 should be the name of a field in the C<issues>, C<biblio>,
1052 C<biblioitems>, or C<items> table in the Koha database.
1054 C<$limit> is the maximum number of results to return.
1056 C<&GetAllIssues> an arrayref, C<$issues>, of hashrefs, the keys of which
1057 are the fields from the C<issues>, C<biblio>, C<biblioitems>, and
1058 C<items> tables of the Koha database.
1064 my ( $borrowernumber, $order, $limit ) = @_;
1066 #FIXME: sanity-check order and limit
1067 my $dbh = C4::Context->dbh;
1069 "SELECT *, issues.timestamp as issuestimestamp, issues.renewals AS renewals,items.renewals AS totalrenewals,items.timestamp AS itemstimestamp
1071 LEFT JOIN items on items.itemnumber=issues.itemnumber
1072 LEFT JOIN biblio ON items.biblionumber=biblio.biblionumber
1073 LEFT JOIN biblioitems ON items.biblioitemnumber=biblioitems.biblioitemnumber
1074 WHERE borrowernumber=?
1076 SELECT *, old_issues.timestamp as issuestimestamp, old_issues.renewals AS renewals,items.renewals AS totalrenewals,items.timestamp AS itemstimestamp
1078 LEFT JOIN items on items.itemnumber=old_issues.itemnumber
1079 LEFT JOIN biblio ON items.biblionumber=biblio.biblionumber
1080 LEFT JOIN biblioitems ON items.biblioitemnumber=biblioitems.biblioitemnumber
1081 WHERE borrowernumber=? AND old_issues.itemnumber IS NOT NULL
1083 if ( $limit != 0 ) {
1084 $query .= " limit $limit";
1087 my $sth = $dbh->prepare($query);
1088 $sth->execute($borrowernumber, $borrowernumber);
1091 while ( my $data = $sth->fetchrow_hashref ) {
1092 push @result, $data;
1099 =head2 GetMemberAccountRecords
1101 ($total, $acctlines, $count) = &GetMemberAccountRecords($borrowernumber);
1103 Looks up accounting data for the patron with the given borrowernumber.
1105 C<&GetMemberAccountRecords> returns a three-element array. C<$acctlines> is a
1106 reference-to-array, where each element is a reference-to-hash; the
1107 keys are the fields of the C<accountlines> table in the Koha database.
1108 C<$count> is the number of elements in C<$acctlines>. C<$total> is the
1109 total amount outstanding for all of the account lines.
1114 sub GetMemberAccountRecords {
1115 my ($borrowernumber,$date) = @_;
1116 my $dbh = C4::Context->dbh;
1122 WHERE borrowernumber=?);
1123 my @bind = ($borrowernumber);
1124 if ($date && $date ne ''){
1125 $strsth.=" AND date < ? ";
1128 $strsth.=" ORDER BY date desc,timestamp DESC";
1129 my $sth= $dbh->prepare( $strsth );
1130 $sth->execute( @bind );
1132 while ( my $data = $sth->fetchrow_hashref ) {
1133 if ( $data->{itemnumber} ) {
1134 my $biblio = GetBiblioFromItemNumber( $data->{itemnumber} );
1135 $data->{biblionumber} = $biblio->{biblionumber};
1136 $data->{title} = $biblio->{title};
1138 $acctlines[$numlines] = $data;
1140 $total += int(1000 * $data->{'amountoutstanding'}); # convert float to integer to avoid round-off errors
1143 return ( $total, \@acctlines,$numlines);
1146 =head2 GetBorNotifyAcctRecord
1148 ($total, $acctlines, $count) = &GetBorNotifyAcctRecord($params,$notifyid);
1150 Looks up accounting data for the patron with the given borrowernumber per file number.
1152 C<&GetBorNotifyAcctRecord> returns a three-element array. C<$acctlines> is a
1153 reference-to-array, where each element is a reference-to-hash; the
1154 keys are the fields of the C<accountlines> table in the Koha database.
1155 C<$count> is the number of elements in C<$acctlines>. C<$total> is the
1156 total amount outstanding for all of the account lines.
1160 sub GetBorNotifyAcctRecord {
1161 my ( $borrowernumber, $notifyid ) = @_;
1162 my $dbh = C4::Context->dbh;
1165 my $sth = $dbh->prepare(
1168 WHERE borrowernumber=?
1170 AND amountoutstanding != '0'
1171 ORDER BY notify_id,accounttype
1174 $sth->execute( $borrowernumber, $notifyid );
1176 while ( my $data = $sth->fetchrow_hashref ) {
1177 $acctlines[$numlines] = $data;
1179 $total += int(100 * $data->{'amountoutstanding'});
1182 return ( $total, \@acctlines, $numlines );
1185 =head2 checkuniquemember (OUEST-PROVENCE)
1187 ($result,$categorycode) = &checkuniquemember($collectivity,$surname,$firstname,$dateofbirth);
1189 Checks that a member exists or not in the database.
1191 C<&result> is nonzero (=exist) or 0 (=does not exist)
1192 C<&categorycode> is from categorycode table
1193 C<&collectivity> is 1 (= we add a collectivity) or 0 (= we add a physical member)
1194 C<&surname> is the surname
1195 C<&firstname> is the firstname (only if collectivity=0)
1196 C<&dateofbirth> is the date of birth in ISO format (only if collectivity=0)
1200 # FIXME: This function is not legitimate. Multiple patrons might have the same first/last name and birthdate.
1201 # This is especially true since first name is not even a required field.
1203 sub checkuniquemember {
1204 my ( $collectivity, $surname, $firstname, $dateofbirth ) = @_;
1205 my $dbh = C4::Context->dbh;
1206 my $request = ($collectivity) ?
1207 "SELECT borrowernumber,categorycode FROM borrowers WHERE surname=? " :
1209 "SELECT borrowernumber,categorycode FROM borrowers WHERE surname=? and firstname=? and dateofbirth=?" :
1210 "SELECT borrowernumber,categorycode FROM borrowers WHERE surname=? and firstname=?";
1211 my $sth = $dbh->prepare($request);
1212 if ($collectivity) {
1213 $sth->execute( uc($surname) );
1214 } elsif($dateofbirth){
1215 $sth->execute( uc($surname), ucfirst($firstname), $dateofbirth );
1217 $sth->execute( uc($surname), ucfirst($firstname));
1219 my @data = $sth->fetchrow;
1220 ( $data[0] ) and return $data[0], $data[1];
1224 sub checkcardnumber {
1225 my ($cardnumber,$borrowernumber) = @_;
1226 # If cardnumber is null, we assume they're allowed.
1227 return 0 if !defined($cardnumber);
1228 my $dbh = C4::Context->dbh;
1229 my $query = "SELECT * FROM borrowers WHERE cardnumber=?";
1230 $query .= " AND borrowernumber <> ?" if ($borrowernumber);
1231 my $sth = $dbh->prepare($query);
1232 if ($borrowernumber) {
1233 $sth->execute($cardnumber,$borrowernumber);
1235 $sth->execute($cardnumber);
1237 if (my $data= $sth->fetchrow_hashref()){
1246 =head2 getzipnamecity (OUEST-PROVENCE)
1248 take all info from table city for the fields city and zip
1249 check for the name and the zip code of the city selected
1253 sub getzipnamecity {
1255 my $dbh = C4::Context->dbh;
1258 "select city_name,city_state,city_zipcode,city_country from cities where cityid=? ");
1259 $sth->execute($cityid);
1260 my @data = $sth->fetchrow;
1261 return $data[0], $data[1], $data[2], $data[3];
1265 =head2 getdcity (OUEST-PROVENCE)
1267 recover cityid with city_name condition
1272 my ($city_name) = @_;
1273 my $dbh = C4::Context->dbh;
1274 my $sth = $dbh->prepare("select cityid from cities where city_name=? ");
1275 $sth->execute($city_name);
1276 my $data = $sth->fetchrow;
1280 =head2 GetFirstValidEmailAddress
1282 $email = GetFirstValidEmailAddress($borrowernumber);
1284 Return the first valid email address for a borrower, given the borrowernumber. For now, the order
1285 is defined as email, emailpro, B_email. Returns the empty string if the borrower has no email
1290 sub GetFirstValidEmailAddress {
1291 my $borrowernumber = shift;
1292 my $dbh = C4::Context->dbh;
1293 my $sth = $dbh->prepare( "SELECT email, emailpro, B_email FROM borrowers where borrowernumber = ? ");
1294 $sth->execute( $borrowernumber );
1295 my $data = $sth->fetchrow_hashref;
1297 if ($data->{'email'}) {
1298 return $data->{'email'};
1299 } elsif ($data->{'emailpro'}) {
1300 return $data->{'emailpro'};
1301 } elsif ($data->{'B_email'}) {
1302 return $data->{'B_email'};
1308 =head2 GetExpiryDate
1310 $expirydate = GetExpiryDate($categorycode, $dateenrolled);
1312 Calculate expiry date given a categorycode and starting date. Date argument must be in ISO format.
1313 Return date is also in ISO format.
1318 my ( $categorycode, $dateenrolled ) = @_;
1320 if ($categorycode) {
1321 my $dbh = C4::Context->dbh;
1322 my $sth = $dbh->prepare("SELECT enrolmentperiod,enrolmentperioddate FROM categories WHERE categorycode=?");
1323 $sth->execute($categorycode);
1324 $enrolments = $sth->fetchrow_hashref;
1326 # die "GetExpiryDate: for enrollmentperiod $enrolmentperiod (category '$categorycode') starting $dateenrolled.\n";
1327 my @date = split (/-/,$dateenrolled);
1328 if($enrolments->{enrolmentperiod}){
1329 return sprintf("%04d-%02d-%02d", Add_Delta_YM(@date,0,$enrolments->{enrolmentperiod}));
1331 return $enrolments->{enrolmentperioddate};
1335 =head2 checkuserpassword (OUEST-PROVENCE)
1337 check for the password and login are not used
1338 return the number of record
1339 0=> NOT USED 1=> USED
1343 sub checkuserpassword {
1344 my ( $borrowernumber, $userid, $password ) = @_;
1345 $password = md5_base64($password);
1346 my $dbh = C4::Context->dbh;
1349 "Select count(*) from borrowers where borrowernumber !=? and userid =? and password=? "
1351 $sth->execute( $borrowernumber, $userid, $password );
1352 my $number_rows = $sth->fetchrow;
1353 return $number_rows;
1357 =head2 GetborCatFromCatType
1359 ($codes_arrayref, $labels_hashref) = &GetborCatFromCatType();
1361 Looks up the different types of borrowers in the database. Returns two
1362 elements: a reference-to-array, which lists the borrower category
1363 codes, and a reference-to-hash, which maps the borrower category codes
1364 to category descriptions.
1369 sub GetborCatFromCatType {
1370 my ( $category_type, $action ) = @_;
1371 # FIXME - This API seems both limited and dangerous.
1372 my $dbh = C4::Context->dbh;
1373 my $request = qq| SELECT categorycode,description
1376 ORDER BY categorycode|;
1377 my $sth = $dbh->prepare($request);
1379 $sth->execute($category_type);
1388 while ( my $data = $sth->fetchrow_hashref ) {
1389 push @codes, $data->{'categorycode'};
1390 $labels{ $data->{'categorycode'} } = $data->{'description'};
1392 return ( \@codes, \%labels );
1395 =head2 GetBorrowercategory
1397 $hashref = &GetBorrowercategory($categorycode);
1399 Given the borrower's category code, the function returns the corresponding
1400 data hashref for a comprehensive information display.
1402 $arrayref_hashref = &GetBorrowercategory;
1404 If no category code provided, the function returns all the categories.
1408 sub GetBorrowercategory {
1410 my $dbh = C4::Context->dbh;
1414 "SELECT description,dateofbirthrequired,upperagelimit,category_type
1416 WHERE categorycode = ?"
1418 $sth->execute($catcode);
1420 $sth->fetchrow_hashref;
1424 } # sub getborrowercategory
1426 =head2 GetBorrowercategoryList
1428 $arrayref_hashref = &GetBorrowercategoryList;
1429 If no category code provided, the function returns all the categories.
1433 sub GetBorrowercategoryList {
1434 my $dbh = C4::Context->dbh;
1439 ORDER BY description"
1443 $sth->fetchall_arrayref({});
1445 } # sub getborrowercategory
1447 =head2 ethnicitycategories
1449 ($codes_arrayref, $labels_hashref) = ðnicitycategories();
1451 Looks up the different ethnic types in the database. Returns two
1452 elements: a reference-to-array, which lists the ethnicity codes, and a
1453 reference-to-hash, which maps the ethnicity codes to ethnicity
1460 sub ethnicitycategories {
1461 my $dbh = C4::Context->dbh;
1462 my $sth = $dbh->prepare("Select code,name from ethnicity order by name");
1466 while ( my $data = $sth->fetchrow_hashref ) {
1467 push @codes, $data->{'code'};
1468 $labels{ $data->{'code'} } = $data->{'name'};
1470 return ( \@codes, \%labels );
1475 $ethn_name = &fixEthnicity($ethn_code);
1477 Takes an ethnicity code (e.g., "european" or "pi") and returns the
1478 corresponding descriptive name from the C<ethnicity> table in the
1479 Koha database ("European" or "Pacific Islander").
1486 my $ethnicity = shift;
1487 return unless $ethnicity;
1488 my $dbh = C4::Context->dbh;
1489 my $sth = $dbh->prepare("Select name from ethnicity where code = ?");
1490 $sth->execute($ethnicity);
1491 my $data = $sth->fetchrow_hashref;
1492 return $data->{'name'};
1493 } # sub fixEthnicity
1497 $dateofbirth,$date = &GetAge($date);
1499 this function return the borrowers age with the value of dateofbirth
1505 my ( $date, $date_ref ) = @_;
1507 if ( not defined $date_ref ) {
1508 $date_ref = sprintf( '%04d-%02d-%02d', Today() );
1511 my ( $year1, $month1, $day1 ) = split /-/, $date;
1512 my ( $year2, $month2, $day2 ) = split /-/, $date_ref;
1514 my $age = $year2 - $year1;
1515 if ( $month1 . $day1 > $month2 . $day2 ) {
1522 =head2 get_institutions
1524 $insitutions = get_institutions();
1526 Just returns a list of all the borrowers of type I, borrownumber and name
1531 sub get_institutions {
1532 my $dbh = C4::Context->dbh();
1535 "SELECT borrowernumber,surname FROM borrowers WHERE categorycode=? ORDER BY surname"
1539 while ( my $data = $sth->fetchrow_hashref() ) {
1540 $orgs{ $data->{'borrowernumber'} } = $data;
1544 } # sub get_institutions
1546 =head2 add_member_orgs
1548 add_member_orgs($borrowernumber,$borrowernumbers);
1550 Takes a borrowernumber and a list of other borrowernumbers and inserts them into the borrowers_to_borrowers table
1555 sub add_member_orgs {
1556 my ( $borrowernumber, $otherborrowers ) = @_;
1557 my $dbh = C4::Context->dbh();
1559 "INSERT INTO borrowers_to_borrowers (borrower1,borrower2) VALUES (?,?)";
1560 my $sth = $dbh->prepare($query);
1561 foreach my $otherborrowernumber (@$otherborrowers) {
1562 $sth->execute( $borrowernumber, $otherborrowernumber );
1565 } # sub add_member_orgs
1569 $cityarrayref = GetCities();
1571 Returns an array_ref of the entries in the cities table
1572 If there are entries in the table an empty row is returned
1573 This is currently only used to populate a popup in memberentry
1579 my $dbh = C4::Context->dbh;
1580 my $city_arr = $dbh->selectall_arrayref(
1581 q|SELECT cityid,city_zipcode,city_name,city_state,city_country FROM cities ORDER BY city_name|,
1583 if ( @{$city_arr} ) {
1584 unshift @{$city_arr}, {
1585 city_zipcode => q{},
1589 city_country => q{},
1596 =head2 GetSortDetails (OUEST-PROVENCE)
1598 ($lib) = &GetSortDetails($category,$sortvalue);
1600 Returns the authorized value details
1601 C<&$lib>return value of authorized value details
1602 C<&$sortvalue>this is the value of authorized value
1603 C<&$category>this is the value of authorized value category
1607 sub GetSortDetails {
1608 my ( $category, $sortvalue ) = @_;
1609 my $dbh = C4::Context->dbh;
1610 my $query = qq|SELECT lib
1611 FROM authorised_values
1613 AND authorised_value=? |;
1614 my $sth = $dbh->prepare($query);
1615 $sth->execute( $category, $sortvalue );
1616 my $lib = $sth->fetchrow;
1617 return ($lib) if ($lib);
1618 return ($sortvalue) unless ($lib);
1621 =head2 MoveMemberToDeleted
1623 $result = &MoveMemberToDeleted($borrowernumber);
1625 Copy the record from borrowers to deletedborrowers table.
1629 # FIXME: should do it in one SQL statement w/ subquery
1630 # Otherwise, we should return the @data on success
1632 sub MoveMemberToDeleted {
1633 my ($member) = shift or return;
1634 my $dbh = C4::Context->dbh;
1635 my $query = qq|SELECT *
1637 WHERE borrowernumber=?|;
1638 my $sth = $dbh->prepare($query);
1639 $sth->execute($member);
1640 my @data = $sth->fetchrow_array;
1641 (@data) or return; # if we got a bad borrowernumber, there's nothing to insert
1643 $dbh->prepare( "INSERT INTO deletedborrowers VALUES ("
1644 . ( "?," x ( scalar(@data) - 1 ) )
1646 $sth->execute(@data);
1651 DelMember($borrowernumber);
1653 This function remove directly a borrower whitout writing it on deleteborrower.
1654 + Deletes reserves for the borrower
1659 my $dbh = C4::Context->dbh;
1660 my $borrowernumber = shift;
1661 #warn "in delmember with $borrowernumber";
1662 return unless $borrowernumber; # borrowernumber is mandatory.
1664 my $query = qq|DELETE
1666 WHERE borrowernumber=?|;
1667 my $sth = $dbh->prepare($query);
1668 $sth->execute($borrowernumber);
1672 WHERE borrowernumber = ?
1674 $sth = $dbh->prepare($query);
1675 $sth->execute($borrowernumber);
1676 logaction("MEMBERS", "DELETE", $borrowernumber, "") if C4::Context->preference("BorrowersLog");
1680 =head2 ExtendMemberSubscriptionTo (OUEST-PROVENCE)
1682 $date = ExtendMemberSubscriptionTo($borrowerid, $date);
1684 Extending the subscription to a given date or to the expiry date calculated on ISO date.
1689 sub ExtendMemberSubscriptionTo {
1690 my ( $borrowerid,$date) = @_;
1691 my $dbh = C4::Context->dbh;
1692 my $borrower = GetMember('borrowernumber'=>$borrowerid);
1694 $date = (C4::Context->preference('BorrowerRenewalPeriodBase') eq 'dateexpiry') ?
1695 C4::Dates->new($borrower->{'dateexpiry'}, 'iso')->output("iso") :
1696 C4::Dates->new()->output("iso");
1697 $date = GetExpiryDate( $borrower->{'categorycode'}, $date );
1699 my $sth = $dbh->do(<<EOF);
1701 SET dateexpiry='$date'
1702 WHERE borrowernumber='$borrowerid'
1704 # add enrolmentfee if needed
1705 $sth = $dbh->prepare("SELECT enrolmentfee FROM categories WHERE categorycode=?");
1706 $sth->execute($borrower->{'categorycode'});
1707 my ($enrolmentfee) = $sth->fetchrow;
1708 if ($enrolmentfee && $enrolmentfee > 0) {
1709 # insert fee in patron debts
1710 manualinvoice($borrower->{'borrowernumber'}, '', '', 'A', $enrolmentfee);
1712 logaction("MEMBERS", "RENEW", $borrower->{'borrowernumber'}, "Membership renewed")if C4::Context->preference("BorrowersLog");
1713 return $date if ($sth);
1717 =head2 GetRoadTypes (OUEST-PROVENCE)
1719 ($idroadtypearrayref, $roadttype_hashref) = &GetRoadTypes();
1721 Looks up the different road type . Returns two
1722 elements: a reference-to-array, which lists the id_roadtype
1723 codes, and a reference-to-hash, which maps the road type of the road .
1728 my $dbh = C4::Context->dbh;
1730 SELECT roadtypeid,road_type
1732 ORDER BY road_type|;
1733 my $sth = $dbh->prepare($query);
1738 # insert empty value to create a empty choice in cgi popup
1740 while ( my $data = $sth->fetchrow_hashref ) {
1742 push @id, $data->{'roadtypeid'};
1743 $roadtype{ $data->{'roadtypeid'} } = $data->{'road_type'};
1746 #test to know if the table contain some records if no the function return nothing
1753 return ( \@id, \%roadtype );
1759 =head2 GetTitles (OUEST-PROVENCE)
1761 ($borrowertitle)= &GetTitles();
1763 Looks up the different title . Returns array with all borrowers title
1768 my @borrowerTitle = split (/,|\|/,C4::Context->preference('BorrowersTitles'));
1769 unshift( @borrowerTitle, "" );
1770 my $count=@borrowerTitle;
1775 return ( \@borrowerTitle);
1779 =head2 GetPatronImage
1781 my ($imagedata, $dberror) = GetPatronImage($cardnumber);
1783 Returns the mimetype and binary image data of the image for the patron with the supplied cardnumber.
1787 sub GetPatronImage {
1788 my ($cardnumber) = @_;
1789 warn "Cardnumber passed to GetPatronImage is $cardnumber" if $debug;
1790 my $dbh = C4::Context->dbh;
1791 my $query = 'SELECT mimetype, imagefile FROM patronimage WHERE cardnumber = ?';
1792 my $sth = $dbh->prepare($query);
1793 $sth->execute($cardnumber);
1794 my $imagedata = $sth->fetchrow_hashref;
1795 warn "Database error!" if $sth->errstr;
1796 return $imagedata, $sth->errstr;
1799 =head2 PutPatronImage
1801 PutPatronImage($cardnumber, $mimetype, $imgfile);
1803 Stores patron binary image data and mimetype in database.
1804 NOTE: This function is good for updating images as well as inserting new images in the database.
1808 sub PutPatronImage {
1809 my ($cardnumber, $mimetype, $imgfile) = @_;
1810 warn "Parameters passed in: Cardnumber=$cardnumber, Mimetype=$mimetype, " . ($imgfile ? "Imagefile" : "No Imagefile") if $debug;
1811 my $dbh = C4::Context->dbh;
1812 my $query = "INSERT INTO patronimage (cardnumber, mimetype, imagefile) VALUES (?,?,?) ON DUPLICATE KEY UPDATE imagefile = ?;";
1813 my $sth = $dbh->prepare($query);
1814 $sth->execute($cardnumber,$mimetype,$imgfile,$imgfile);
1815 warn "Error returned inserting $cardnumber.$mimetype." if $sth->errstr;
1816 return $sth->errstr;
1819 =head2 RmPatronImage
1821 my ($dberror) = RmPatronImage($cardnumber);
1823 Removes the image for the patron with the supplied cardnumber.
1828 my ($cardnumber) = @_;
1829 warn "Cardnumber passed to GetPatronImage is $cardnumber" if $debug;
1830 my $dbh = C4::Context->dbh;
1831 my $query = "DELETE FROM patronimage WHERE cardnumber = ?;";
1832 my $sth = $dbh->prepare($query);
1833 $sth->execute($cardnumber);
1834 my $dberror = $sth->errstr;
1835 warn "Database error!" if $sth->errstr;
1839 =head2 GetHideLostItemsPreference
1841 $hidelostitemspref = &GetHideLostItemsPreference($borrowernumber);
1843 Returns the HideLostItems preference for the patron category of the supplied borrowernumber
1844 C<&$hidelostitemspref>return value of function, 0 or 1
1848 sub GetHideLostItemsPreference {
1849 my ($borrowernumber) = @_;
1850 my $dbh = C4::Context->dbh;
1851 my $query = "SELECT hidelostitems FROM borrowers,categories WHERE borrowers.categorycode = categories.categorycode AND borrowernumber = ?";
1852 my $sth = $dbh->prepare($query);
1853 $sth->execute($borrowernumber);
1854 my $hidelostitems = $sth->fetchrow;
1855 return $hidelostitems;
1858 =head2 GetRoadTypeDetails (OUEST-PROVENCE)
1860 ($roadtype) = &GetRoadTypeDetails($roadtypeid);
1862 Returns the description of roadtype
1863 C<&$roadtype>return description of road type
1864 C<&$roadtypeid>this is the value of roadtype s
1868 sub GetRoadTypeDetails {
1869 my ($roadtypeid) = @_;
1870 my $dbh = C4::Context->dbh;
1874 WHERE roadtypeid=?|;
1875 my $sth = $dbh->prepare($query);
1876 $sth->execute($roadtypeid);
1877 my $roadtype = $sth->fetchrow;
1881 =head2 GetBorrowersWhoHaveNotBorrowedSince
1883 &GetBorrowersWhoHaveNotBorrowedSince($date)
1885 this function get all borrowers who haven't borrowed since the date given on input arg.
1889 sub GetBorrowersWhoHaveNotBorrowedSince {
1890 my $filterdate = shift||POSIX::strftime("%Y-%m-%d",localtime());
1891 my $filterexpiry = shift;
1892 my $filterbranch = shift ||
1893 ((C4::Context->preference('IndependantBranches')
1894 && C4::Context->userenv
1895 && C4::Context->userenv->{flags} % 2 !=1
1896 && C4::Context->userenv->{branch})
1897 ? C4::Context->userenv->{branch}
1899 my $dbh = C4::Context->dbh;
1901 SELECT borrowers.borrowernumber,
1902 max(old_issues.timestamp) as latestissue,
1903 max(issues.timestamp) as currentissue
1905 JOIN categories USING (categorycode)
1906 LEFT JOIN old_issues USING (borrowernumber)
1907 LEFT JOIN issues USING (borrowernumber)
1908 WHERE category_type <> 'S'
1909 AND borrowernumber NOT IN (SELECT guarantorid FROM borrowers WHERE guarantorid IS NOT NULL AND guarantorid <> 0)
1912 if ($filterbranch && $filterbranch ne ""){
1913 $query.=" AND borrowers.branchcode= ?";
1914 push @query_params,$filterbranch;
1917 $query .= " AND dateexpiry < ? ";
1918 push @query_params,$filterdate;
1920 $query.=" GROUP BY borrowers.borrowernumber";
1922 $query.=" HAVING (latestissue < ? OR latestissue IS NULL)
1923 AND currentissue IS NULL";
1924 push @query_params,$filterdate;
1926 warn $query if $debug;
1927 my $sth = $dbh->prepare($query);
1928 if (scalar(@query_params)>0){
1929 $sth->execute(@query_params);
1936 while ( my $data = $sth->fetchrow_hashref ) {
1937 push @results, $data;
1942 =head2 GetBorrowersWhoHaveNeverBorrowed
1944 $results = &GetBorrowersWhoHaveNeverBorrowed
1946 This function get all borrowers who have never borrowed.
1948 I<$result> is a ref to an array which all elements are a hasref.
1952 sub GetBorrowersWhoHaveNeverBorrowed {
1953 my $filterbranch = shift ||
1954 ((C4::Context->preference('IndependantBranches')
1955 && C4::Context->userenv
1956 && C4::Context->userenv->{flags} % 2 !=1
1957 && C4::Context->userenv->{branch})
1958 ? C4::Context->userenv->{branch}
1960 my $dbh = C4::Context->dbh;
1962 SELECT borrowers.borrowernumber,max(timestamp) as latestissue
1964 LEFT JOIN issues ON borrowers.borrowernumber = issues.borrowernumber
1965 WHERE issues.borrowernumber IS NULL
1968 if ($filterbranch && $filterbranch ne ""){
1969 $query.=" AND borrowers.branchcode= ?";
1970 push @query_params,$filterbranch;
1972 warn $query if $debug;
1974 my $sth = $dbh->prepare($query);
1975 if (scalar(@query_params)>0){
1976 $sth->execute(@query_params);
1983 while ( my $data = $sth->fetchrow_hashref ) {
1984 push @results, $data;
1989 =head2 GetBorrowersWithIssuesHistoryOlderThan
1991 $results = &GetBorrowersWithIssuesHistoryOlderThan($date)
1993 this function get all borrowers who has an issue history older than I<$date> given on input arg.
1995 I<$result> is a ref to an array which all elements are a hashref.
1996 This hashref is containt the number of time this borrowers has borrowed before I<$date> and the borrowernumber.
2000 sub GetBorrowersWithIssuesHistoryOlderThan {
2001 my $dbh = C4::Context->dbh;
2002 my $date = shift ||POSIX::strftime("%Y-%m-%d",localtime());
2003 my $filterbranch = shift ||
2004 ((C4::Context->preference('IndependantBranches')
2005 && C4::Context->userenv
2006 && C4::Context->userenv->{flags} % 2 !=1
2007 && C4::Context->userenv->{branch})
2008 ? C4::Context->userenv->{branch}
2011 SELECT count(borrowernumber) as n,borrowernumber
2013 WHERE returndate < ?
2014 AND borrowernumber IS NOT NULL
2017 push @query_params, $date;
2019 $query.=" AND branchcode = ?";
2020 push @query_params, $filterbranch;
2022 $query.=" GROUP BY borrowernumber ";
2023 warn $query if $debug;
2024 my $sth = $dbh->prepare($query);
2025 $sth->execute(@query_params);
2028 while ( my $data = $sth->fetchrow_hashref ) {
2029 push @results, $data;
2034 =head2 GetBorrowersNamesAndLatestIssue
2036 $results = &GetBorrowersNamesAndLatestIssueList(@borrowernumbers)
2038 this function get borrowers Names and surnames and Issue information.
2040 I<@borrowernumbers> is an array which all elements are borrowernumbers.
2041 This hashref is containt the number of time this borrowers has borrowed before I<$date> and the borrowernumber.
2045 sub GetBorrowersNamesAndLatestIssue {
2046 my $dbh = C4::Context->dbh;
2047 my @borrowernumbers=@_;
2049 SELECT surname,lastname, phone, email,max(timestamp)
2051 LEFT JOIN issues ON borrowers.borrowernumber=issues.borrowernumber
2052 GROUP BY borrowernumber
2054 my $sth = $dbh->prepare($query);
2056 my $results = $sth->fetchall_arrayref({});
2062 my $success = DebarMember( $borrowernumber, $todate );
2064 marks a Member as debarred, and therefore unable to checkout any more
2068 true on success, false on failure
2073 my $borrowernumber = shift;
2076 return unless defined $borrowernumber;
2077 return unless $borrowernumber =~ /^\d+$/;
2080 borrowernumber => $borrowernumber,
2090 my $success = ModPrivacy( $borrowernumber, $privacy );
2092 Update the privacy of a patron.
2095 true on success, false on failure
2102 my $borrowernumber = shift;
2103 my $privacy = shift;
2104 return unless defined $borrowernumber;
2105 return unless $borrowernumber =~ /^\d+$/;
2107 return ModMember( borrowernumber => $borrowernumber,
2108 privacy => $privacy );
2113 AddMessage( $borrowernumber, $message_type, $message, $branchcode );
2115 Adds a message to the messages table for the given borrower.
2124 my ( $borrowernumber, $message_type, $message, $branchcode ) = @_;
2126 my $dbh = C4::Context->dbh;
2128 if ( ! ( $borrowernumber && $message_type && $message && $branchcode ) ) {
2132 my $query = "INSERT INTO messages ( borrowernumber, branchcode, message_type, message ) VALUES ( ?, ?, ?, ? )";
2133 my $sth = $dbh->prepare($query);
2134 $sth->execute( $borrowernumber, $branchcode, $message_type, $message );
2135 logaction("MEMBERS", "ADDCIRCMESSAGE", $borrowernumber, $message) if C4::Context->preference("BorrowersLog");
2141 GetMessages( $borrowernumber, $type );
2143 $type is message type, B for borrower, or L for Librarian.
2144 Empty type returns all messages of any type.
2146 Returns all messages for the given borrowernumber
2151 my ( $borrowernumber, $type, $branchcode ) = @_;
2157 my $dbh = C4::Context->dbh;
2160 branches.branchname,
2163 messages.branchcode LIKE '$branchcode' AS can_delete
2164 FROM messages, branches
2165 WHERE borrowernumber = ?
2166 AND message_type LIKE ?
2167 AND messages.branchcode = branches.branchcode
2168 ORDER BY message_date DESC";
2169 my $sth = $dbh->prepare($query);
2170 $sth->execute( $borrowernumber, $type ) ;
2173 while ( my $data = $sth->fetchrow_hashref ) {
2174 my $d = C4::Dates->new( $data->{message_date}, 'iso' );
2175 $data->{message_date_formatted} = $d->output;
2176 push @results, $data;
2184 GetMessagesCount( $borrowernumber, $type );
2186 $type is message type, B for borrower, or L for Librarian.
2187 Empty type returns all messages of any type.
2189 Returns the number of messages for the given borrowernumber
2193 sub GetMessagesCount {
2194 my ( $borrowernumber, $type, $branchcode ) = @_;
2200 my $dbh = C4::Context->dbh;
2202 my $query = "SELECT COUNT(*) as MsgCount FROM messages WHERE borrowernumber = ? AND message_type LIKE ?";
2203 my $sth = $dbh->prepare($query);
2204 $sth->execute( $borrowernumber, $type ) ;
2207 my $data = $sth->fetchrow_hashref;
2208 my $count = $data->{'MsgCount'};
2215 =head2 DeleteMessage
2217 DeleteMessage( $message_id );
2222 my ( $message_id ) = @_;
2224 my $dbh = C4::Context->dbh;
2225 my $query = "SELECT * FROM messages WHERE message_id = ?";
2226 my $sth = $dbh->prepare($query);
2227 $sth->execute( $message_id );
2228 my $message = $sth->fetchrow_hashref();
2230 $query = "DELETE FROM messages WHERE message_id = ?";
2231 $sth = $dbh->prepare($query);
2232 $sth->execute( $message_id );
2233 logaction("MEMBERS", "DELCIRCMESSAGE", $message->{'borrowernumber'}, $message->{'message'}) if C4::Context->preference("BorrowersLog");
2238 IssueSlip($branchcode, $borrowernumber, $quickslip)
2240 Returns letter hash ( see C4::Letters::GetPreparedLetter )
2242 $quickslip is boolean, to indicate whether we want a quick slip
2247 my ($branch, $borrowernumber, $quickslip) = @_;
2249 # return unless ( C4::Context->boolean_preference('printcirculationslips') );
2251 my $today = POSIX::strftime("%Y-%m-%d", localtime);
2253 my $issueslist = GetPendingIssues($borrowernumber);
2254 foreach my $it (@$issueslist){
2255 if ($it->{'issuedate'} eq $today) {
2258 elsif ($it->{'date_due'} le $today) {
2259 $it->{'overdue'} = 1;
2262 $it->{'date_due'}=format_date($it->{'date_due'});
2264 my @issues = sort { $b->{'timestamp'} <=> $a->{'timestamp'} } @$issueslist;
2266 my ($letter_code, %repeat);
2268 $letter_code = 'ISSUEQSLIP';
2270 'checkedout' => [ map {
2274 }, grep { $_->{'today'} } @issues ],
2278 $letter_code = 'ISSUESLIP';
2280 'checkedout' => [ map {
2284 }, grep { !$_->{'overdue'} } @issues ],
2286 'overdue' => [ map {
2290 }, grep { $_->{'overdue'} } @issues ],
2293 $_->{'timestamp'} = $_->{'newdate'};
2295 } @{ GetNewsToDisplay("slip") } ],
2299 return C4::Letters::GetPreparedLetter (
2300 module => 'circulation',
2301 letter_code => $letter_code,
2302 branchcode => $branch,
2304 'branches' => $branch,
2305 'borrowers' => $borrowernumber,