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
118 &ExtendMemberSubscriptionTo
136 C4::Members - Perl Module containing convenience functions for member handling
144 This module contains routines for adding, modifying and deleting members/patrons/borrowers
150 $borrowers_result_array_ref = &Search($filter,$orderby, $limit,
151 $columns_out, $search_on_fields,$searchtype);
153 Looks up patrons (borrowers) on filter. A wrapper for SearchInTable('borrowers').
155 For C<$filter>, C<$orderby>, C<$limit>, C<&columns_out>, C<&search_on_fields> and C<&searchtype>
156 refer to C4::SQLHelper:SearchInTable().
158 Special C<$filter> key '' is effectively expanded to search on surname firstname othernamescw
159 and cardnumber unless C<&search_on_fields> is defined
163 $borrowers = Search('abcd', 'cardnumber');
165 $borrowers = Search({''=>'abcd', category_type=>'I'}, 'surname');
169 sub _express_member_find {
172 # this is used by circulation everytime a new borrowers cardnumber is scanned
173 # so we can check an exact match first, if that works return, otherwise do the rest
174 my $dbh = C4::Context->dbh;
175 my $query = "SELECT borrowernumber FROM borrowers WHERE cardnumber = ?";
176 if ( my $borrowernumber = $dbh->selectrow_array($query, undef, $filter) ) {
177 return( {"borrowernumber"=>$borrowernumber} );
180 my ($search_on_fields, $searchtype);
181 if ( length($filter) == 1 ) {
182 $search_on_fields = [ qw(surname) ];
183 $searchtype = 'start_with';
185 $search_on_fields = [ qw(surname firstname othernames cardnumber) ];
186 $searchtype = 'contain';
189 return (undef, $search_on_fields, $searchtype);
193 my ( $filter, $orderby, $limit, $columns_out, $search_on_fields, $searchtype ) = @_;
198 if ( my $fr = ref $filter ) {
199 if ( $fr eq "HASH" ) {
200 if ( my $search_string = $filter->{''} ) {
201 my ($member_filter, $member_search_on_fields, $member_searchtype) = _express_member_find($search_string);
202 if ($member_filter) {
203 $filter = $member_filter;
206 $search_on_fields ||= $member_search_on_fields;
207 $searchtype ||= $member_searchtype;
212 $search_string = $filter;
216 $search_string = $filter;
217 my ($member_filter, $member_search_on_fields, $member_searchtype) = _express_member_find($search_string);
218 if ($member_filter) {
219 $filter = $member_filter;
222 $search_on_fields ||= $member_search_on_fields;
223 $searchtype ||= $member_searchtype;
227 if ( !$found_borrower && C4::Context->preference('ExtendedPatronAttributes') && $search_string ) {
228 my $matching_records = C4::Members::Attributes::SearchIdMatchingAttribute($search_string);
229 if(scalar(@$matching_records)>0) {
230 if ( my $fr = ref $filter ) {
231 if ( $fr eq "HASH" ) {
233 $filter = [ $filter ];
235 push @$filter, { %f, "borrowernumber"=>$$matching_records };
238 push @$filter, {"borrowernumber"=>$matching_records};
242 $filter = [ $filter ];
243 push @$filter, {"borrowernumber"=>$matching_records};
248 # $showallbranches was not used at the time SearchMember() was mainstreamed into Search().
249 # Mentioning for the reference
251 if ( C4::Context->preference("IndependantBranches") ) { # && !$showallbranches){
252 if ( my $userenv = C4::Context->userenv ) {
253 my $branch = $userenv->{'branch'};
254 if ( ($userenv->{flags} % 2 !=1) &&
255 $branch && $branch ne "insecure" ){
257 if (my $fr = ref $filter) {
258 if ( $fr eq "HASH" ) {
259 $filter->{branchcode} = $branch;
263 $_ = { '' => $_ } unless ref $_;
264 $_->{branchcode} = $branch;
269 $filter = { '' => $filter, branchcode => $branch };
275 if ($found_borrower) {
276 $searchtype = "exact";
278 $searchtype ||= "start_with";
280 return SearchInTable( "borrowers", $filter, $orderby, $limit, $columns_out, $search_on_fields, $searchtype );
283 =head2 GetMemberDetails
285 ($borrower) = &GetMemberDetails($borrowernumber, $cardnumber);
287 Looks up a patron and returns information about him or her. If
288 C<$borrowernumber> is true (nonzero), C<&GetMemberDetails> looks
289 up the borrower by number; otherwise, it looks up the borrower by card
292 C<$borrower> is a reference-to-hash whose keys are the fields of the
293 borrowers table in the Koha database. In addition,
294 C<$borrower-E<gt>{flags}> is a hash giving more detailed information
295 about the patron. Its keys act as flags :
297 if $borrower->{flags}->{LOST} {
298 # Patron's card was reported lost
301 If the state of a flag means that the patron should not be
302 allowed to borrow any more books, then it will have a C<noissues> key
305 See patronflags for more details.
307 C<$borrower-E<gt>{authflags}> is a hash giving more detailed information
308 about the top-level permissions flags set for the borrower. For example,
309 if a user has the "editcatalogue" permission,
310 C<$borrower-E<gt>{authflags}-E<gt>{editcatalogue}> will exist and have
315 sub GetMemberDetails {
316 my ( $borrowernumber, $cardnumber ) = @_;
317 my $dbh = C4::Context->dbh;
320 if ($borrowernumber) {
321 $sth = $dbh->prepare("SELECT borrowers.*,category_type,categories.description,reservefee,enrolmentperiod FROM borrowers LEFT JOIN categories ON borrowers.categorycode=categories.categorycode WHERE borrowernumber=?");
322 $sth->execute($borrowernumber);
324 elsif ($cardnumber) {
325 $sth = $dbh->prepare("SELECT borrowers.*,category_type,categories.description,reservefee,enrolmentperiod FROM borrowers LEFT JOIN categories ON borrowers.categorycode=categories.categorycode WHERE cardnumber=?");
326 $sth->execute($cardnumber);
331 my $borrower = $sth->fetchrow_hashref;
332 my ($amount) = GetMemberAccountRecords( $borrowernumber);
333 $borrower->{'amountoutstanding'} = $amount;
334 # FIXME - patronflags calls GetMemberAccountRecords... just have patronflags return $amount
335 my $flags = patronflags( $borrower);
338 $sth = $dbh->prepare("select bit,flag from userflags");
340 while ( my ( $bit, $flag ) = $sth->fetchrow ) {
341 if ( $borrower->{'flags'} && $borrower->{'flags'} & 2**$bit ) {
342 $accessflagshash->{$flag} = 1;
345 $borrower->{'flags'} = $flags;
346 $borrower->{'authflags'} = $accessflagshash;
348 # For the purposes of making templates easier, we'll define a
349 # 'showname' which is the alternate form the user's first name if
350 # 'other name' is defined.
351 if ($borrower->{category_type} eq 'I') {
352 $borrower->{'showname'} = $borrower->{'othernames'};
353 $borrower->{'showname'} .= " $borrower->{'firstname'}" if $borrower->{'firstname'};
355 $borrower->{'showname'} = $borrower->{'firstname'};
358 return ($borrower); #, $flags, $accessflagshash);
363 $flags = &patronflags($patron);
365 This function is not exported.
367 The following will be set where applicable:
368 $flags->{CHARGES}->{amount} Amount of debt
369 $flags->{CHARGES}->{noissues} Set if debt amount >$5.00 (or syspref noissuescharge)
370 $flags->{CHARGES}->{message} Message -- deprecated
372 $flags->{CREDITS}->{amount} Amount of credit
373 $flags->{CREDITS}->{message} Message -- deprecated
375 $flags->{ GNA } Patron has no valid address
376 $flags->{ GNA }->{noissues} Set for each GNA
377 $flags->{ GNA }->{message} "Borrower has no valid address" -- deprecated
379 $flags->{ LOST } Patron's card reported lost
380 $flags->{ LOST }->{noissues} Set for each LOST
381 $flags->{ LOST }->{message} Message -- deprecated
383 $flags->{DBARRED} Set if patron debarred, no access
384 $flags->{DBARRED}->{noissues} Set for each DBARRED
385 $flags->{DBARRED}->{message} Message -- deprecated
388 $flags->{ NOTES }->{message} The note itself. NOT deprecated
390 $flags->{ ODUES } Set if patron has overdue books.
391 $flags->{ ODUES }->{message} "Yes" -- deprecated
392 $flags->{ ODUES }->{itemlist} ref-to-array: list of overdue books
393 $flags->{ ODUES }->{itemlisttext} Text list of overdue items -- deprecated
395 $flags->{WAITING} Set if any of patron's reserves are available
396 $flags->{WAITING}->{message} Message -- deprecated
397 $flags->{WAITING}->{itemlist} ref-to-array: list of available items
401 =item C<$flags-E<gt>{ODUES}-E<gt>{itemlist}> is a reference-to-array listing the
402 overdue items. Its elements are references-to-hash, each describing an
403 overdue item. The keys are selected fields from the issues, biblio,
404 biblioitems, and items tables of the Koha database.
406 =item C<$flags-E<gt>{ODUES}-E<gt>{itemlisttext}> is a string giving a text listing of
407 the overdue items, one per line. Deprecated.
409 =item C<$flags-E<gt>{WAITING}-E<gt>{itemlist}> is a reference-to-array listing the
410 available items. Each element is a reference-to-hash whose keys are
411 fields from the reserves table of the Koha database.
415 All the "message" fields that include language generated in this function are deprecated,
416 because such strings belong properly in the display layer.
418 The "message" field that comes from the DB is OK.
422 # TODO: use {anonymous => hashes} instead of a dozen %flaginfo
423 # FIXME rename this function.
426 my ( $patroninformation) = @_;
427 my $dbh=C4::Context->dbh;
428 my ($amount) = GetMemberAccountRecords( $patroninformation->{'borrowernumber'});
431 my $noissuescharge = C4::Context->preference("noissuescharge") || 5;
432 $flaginfo{'message'} = sprintf "Patron owes \$%.02f", $amount;
433 $flaginfo{'amount'} = sprintf "%.02f", $amount;
434 if ( $amount > $noissuescharge && !C4::Context->preference("AllowFineOverride") ) {
435 $flaginfo{'noissues'} = 1;
437 $flags{'CHARGES'} = \%flaginfo;
439 elsif ( $amount < 0 ) {
441 $flaginfo{'message'} = sprintf "Patron has credit of \$%.02f", -$amount;
442 $flaginfo{'amount'} = sprintf "%.02f", $amount;
443 $flags{'CREDITS'} = \%flaginfo;
445 if ( $patroninformation->{'gonenoaddress'}
446 && $patroninformation->{'gonenoaddress'} == 1 )
449 $flaginfo{'message'} = 'Borrower has no valid address.';
450 $flaginfo{'noissues'} = 1;
451 $flags{'GNA'} = \%flaginfo;
453 if ( $patroninformation->{'lost'} && $patroninformation->{'lost'} == 1 ) {
455 $flaginfo{'message'} = 'Borrower\'s card reported lost.';
456 $flaginfo{'noissues'} = 1;
457 $flags{'LOST'} = \%flaginfo;
459 if ( $patroninformation->{'debarred'} && check_date( split( /-/, $patroninformation->{'debarred'} ) ) ) {
460 if ( Date_to_Days(Date::Calc::Today) < Date_to_Days( split( /-/, $patroninformation->{'debarred'} ) ) ) {
462 $flaginfo{'debarredcomment'} = $patroninformation->{'debarredcomment'};
463 $flaginfo{'message'} = $patroninformation->{'debarredcomment'};
464 $flaginfo{'noissues'} = 1;
465 $flaginfo{'dateend'} = $patroninformation->{'debarred'};
466 $flags{'DBARRED'} = \%flaginfo;
469 if ( $patroninformation->{'borrowernotes'}
470 && $patroninformation->{'borrowernotes'} )
473 $flaginfo{'message'} = $patroninformation->{'borrowernotes'};
474 $flags{'NOTES'} = \%flaginfo;
476 my ( $odues, $itemsoverdue ) = C4::Overdues::checkoverdues($patroninformation->{'borrowernumber'});
477 if ( $odues && $odues > 0 ) {
479 $flaginfo{'message'} = "Yes";
480 $flaginfo{'itemlist'} = $itemsoverdue;
481 foreach ( sort { $a->{'date_due'} cmp $b->{'date_due'} }
484 $flaginfo{'itemlisttext'} .=
485 "$_->{'date_due'} $_->{'barcode'} $_->{'title'} \n"; # newline is display layer
487 $flags{'ODUES'} = \%flaginfo;
489 my @itemswaiting = C4::Reserves::GetReservesFromBorrowernumber( $patroninformation->{'borrowernumber'},'W' );
490 my $nowaiting = scalar @itemswaiting;
491 if ( $nowaiting > 0 ) {
493 $flaginfo{'message'} = "Reserved items available";
494 $flaginfo{'itemlist'} = \@itemswaiting;
495 $flags{'WAITING'} = \%flaginfo;
503 $borrower = &GetMember(%information);
505 Retrieve the first patron record meeting on criteria listed in the
506 C<%information> hash, which should contain one or more
507 pairs of borrowers column names and values, e.g.,
509 $borrower = GetMember(borrowernumber => id);
511 C<&GetBorrower> returns a reference-to-hash whose keys are the fields of
512 the C<borrowers> table in the Koha database.
514 FIXME: GetMember() is used throughout the code as a lookup
515 on a unique key such as the borrowernumber, but this meaning is not
516 enforced in the routine itself.
522 my ( %information ) = @_;
523 if (exists $information{borrowernumber} && !defined $information{borrowernumber}) {
524 #passing mysql's kohaadmin?? Makes no sense as a query
527 my $dbh = C4::Context->dbh;
529 q{SELECT borrowers.*, categories.category_type, categories.description
531 LEFT JOIN categories on borrowers.categorycode=categories.categorycode WHERE };
534 for (keys %information ) {
542 if (defined $information{$_}) {
544 push @values, $information{$_};
547 $select .= "$_ IS NULL";
550 $debug && warn $select, " ",values %information;
551 my $sth = $dbh->prepare("$select");
552 $sth->execute(map{$information{$_}} keys %information);
553 my $data = $sth->fetchall_arrayref({});
554 #FIXME interface to this routine now allows generation of a result set
555 #so whole array should be returned but bowhere in the current code expects this
563 =head2 GetMemberRelatives
565 @borrowernumbers = GetMemberRelatives($borrowernumber);
567 C<GetMemberRelatives> returns a borrowersnumber's list of guarantor/guarantees of the member given in parameter
570 sub GetMemberRelatives {
571 my $borrowernumber = shift;
572 my $dbh = C4::Context->dbh;
576 my $query = "SELECT guarantorid FROM borrowers WHERE borrowernumber=?";
577 my $sth = $dbh->prepare($query);
578 $sth->execute($borrowernumber);
579 my $data = $sth->fetchrow_arrayref();
580 push @glist, $data->[0] if $data->[0];
581 my $guarantor = $data->[0] if $data->[0];
584 $query = "SELECT borrowernumber FROM borrowers WHERE guarantorid=?";
585 $sth = $dbh->prepare($query);
586 $sth->execute($borrowernumber);
587 while ($data = $sth->fetchrow_arrayref()) {
588 push @glist, $data->[0];
591 # Getting sibling guarantees
593 $query = "SELECT borrowernumber FROM borrowers WHERE guarantorid=?";
594 $sth = $dbh->prepare($query);
595 $sth->execute($guarantor);
596 while ($data = $sth->fetchrow_arrayref()) {
597 push @glist, $data->[0] if ($data->[0] != $borrowernumber);
604 =head2 IsMemberBlocked
606 my ($block_status, $count) = IsMemberBlocked( $borrowernumber );
608 Returns whether a patron has overdue items that may result
609 in a block or whether the patron has active fine days
610 that would block circulation privileges.
612 C<$block_status> can have the following values:
614 1 if the patron has outstanding fine days, in which case C<$count> is the number of them
616 -1 if the patron has overdue items, in which case C<$count> is the number of them
618 0 if the patron has no overdue items or outstanding fine days, in which case C<$count> is 0
620 Outstanding fine days are checked before current overdue items
623 FIXME: this needs to be split into two functions; a potential block
624 based on the number of current overdue items could be orthogonal
625 to a block based on whether the patron has any fine days accrued.
629 sub IsMemberBlocked {
630 my $borrowernumber = shift;
631 my $dbh = C4::Context->dbh;
633 my $blockeddate = CheckBorrowerDebarred($borrowernumber);
635 return ( 1, $blockeddate ) if $blockeddate;
637 # if he have late issues
638 my $sth = $dbh->prepare(
639 "SELECT COUNT(*) as latedocs
641 WHERE borrowernumber = ?
642 AND date_due < curdate()"
644 $sth->execute($borrowernumber);
645 my $latedocs = $sth->fetchrow_hashref->{'latedocs'};
647 return ( -1, $latedocs ) if $latedocs > 0;
652 =head2 GetMemberIssuesAndFines
654 ($overdue_count, $issue_count, $total_fines) = &GetMemberIssuesAndFines($borrowernumber);
656 Returns aggregate data about items borrowed by the patron with the
657 given borrowernumber.
659 C<&GetMemberIssuesAndFines> returns a three-element array. C<$overdue_count> is the
660 number of overdue items the patron currently has borrowed. C<$issue_count> is the
661 number of books the patron currently has borrowed. C<$total_fines> is
662 the total fine currently due by the borrower.
667 sub GetMemberIssuesAndFines {
668 my ( $borrowernumber ) = @_;
669 my $dbh = C4::Context->dbh;
670 my $query = "SELECT COUNT(*) FROM issues WHERE borrowernumber = ?";
672 $debug and warn $query."\n";
673 my $sth = $dbh->prepare($query);
674 $sth->execute($borrowernumber);
675 my $issue_count = $sth->fetchrow_arrayref->[0];
677 $sth = $dbh->prepare(
678 "SELECT COUNT(*) FROM issues
679 WHERE borrowernumber = ?
680 AND date_due < curdate()"
682 $sth->execute($borrowernumber);
683 my $overdue_count = $sth->fetchrow_arrayref->[0];
685 $sth = $dbh->prepare("SELECT SUM(amountoutstanding) FROM accountlines WHERE borrowernumber = ?");
686 $sth->execute($borrowernumber);
687 my $total_fines = $sth->fetchrow_arrayref->[0];
689 return ($overdue_count, $issue_count, $total_fines);
693 return @{C4::Context->dbh->selectcol_arrayref("SHOW columns from borrowers")};
698 my $success = ModMember(borrowernumber => $borrowernumber,
699 [ field => value ]... );
701 Modify borrower's data. All date fields should ALREADY be in ISO format.
704 true on success, or false on failure
710 # test to know if you must update or not the borrower password
711 if (exists $data{password}) {
712 if ($data{password} eq '****' or $data{password} eq '') {
713 delete $data{password};
715 $data{password} = md5_base64($data{password});
718 my $execute_success=UpdateInTable("borrowers",\%data);
719 if ($execute_success) { # only proceed if the update was a success
720 # ok if its an adult (type) it may have borrowers that depend on it as a guarantor
721 # so when we update information for an adult we should check for guarantees and update the relevant part
722 # of their records, ie addresses and phone numbers
723 my $borrowercategory= GetBorrowercategory( $data{'category_type'} );
724 if ( exists $borrowercategory->{'category_type'} && $borrowercategory->{'category_type'} eq ('A' || 'S') ) {
725 # is adult check guarantees;
726 UpdateGuarantees(%data);
728 logaction("MEMBERS", "MODIFY", $data{'borrowernumber'}, "UPDATE (executed w/ arg: $data{'borrowernumber'})") if C4::Context->preference("BorrowersLog");
730 return $execute_success;
736 $borrowernumber = &AddMember(%borrower);
738 insert new borrower into table
739 Returns the borrowernumber upon success
741 Returns as undef upon any db error without further processing
748 my $dbh = C4::Context->dbh;
749 # generate a proper login if none provided
750 $data{'userid'} = Generate_Userid($data{'borrowernumber'}, $data{'firstname'}, $data{'surname'}) if $data{'userid'} eq '';
751 # create a disabled account if no password provided
752 $data{'password'} = ($data{'password'})? md5_base64($data{'password'}) : '!';
753 $data{'borrowernumber'}=InsertInTable("borrowers",\%data);
754 # mysql_insertid is probably bad. not necessarily accurate and mysql-specific at best.
755 logaction("MEMBERS", "CREATE", $data{'borrowernumber'}, "") if C4::Context->preference("BorrowersLog");
757 # check for enrollment fee & add it if needed
758 my $sth = $dbh->prepare("SELECT enrolmentfee FROM categories WHERE categorycode=?");
759 $sth->execute($data{'categorycode'});
760 my ($enrolmentfee) = $sth->fetchrow;
762 warn sprintf('Database returned the following error: %s', $sth->errstr);
765 if ($enrolmentfee && $enrolmentfee > 0) {
766 # insert fee in patron debts
767 manualinvoice($data{'borrowernumber'}, '', '', 'A', $enrolmentfee);
770 return $data{'borrowernumber'};
775 my ($uid,$member) = @_;
776 my $dbh = C4::Context->dbh;
777 # Make sure the userid chosen is unique and not theirs if non-empty. If it is not,
778 # Then we need to tell the user and have them create a new one.
781 "SELECT * FROM borrowers WHERE userid=? AND borrowernumber != ?");
782 $sth->execute( $uid, $member );
783 if ( ( $uid ne '' ) && ( my $row = $sth->fetchrow_hashref ) ) {
791 sub Generate_Userid {
792 my ($borrowernumber, $firstname, $surname) = @_;
796 $firstname =~ s/[[:digit:][:space:][:blank:][:punct:][:cntrl:]]//g;
797 $surname =~ s/[[:digit:][:space:][:blank:][:punct:][:cntrl:]]//g;
798 $newuid = lc(($firstname)? "$firstname.$surname" : $surname);
799 $newuid .= $offset unless $offset == 0;
802 } while (!Check_Userid($newuid,$borrowernumber));
808 my ( $uid, $member, $digest ) = @_;
809 my $dbh = C4::Context->dbh;
811 #Make sure the userid chosen is unique and not theirs if non-empty. If it is not,
812 #Then we need to tell the user and have them create a new one.
816 "SELECT * FROM borrowers WHERE userid=? AND borrowernumber != ?");
817 $sth->execute( $uid, $member );
818 if ( ( $uid ne '' ) && ( my $row = $sth->fetchrow_hashref ) ) {
822 #Everything is good so we can update the information.
825 "update borrowers set userid=?, password=? where borrowernumber=?");
826 $sth->execute( $uid, $digest, $member );
830 logaction("MEMBERS", "CHANGE PASS", $member, "") if C4::Context->preference("BorrowersLog");
836 =head2 fixup_cardnumber
838 Warning: The caller is responsible for locking the members table in write
839 mode, to avoid database corruption.
843 use vars qw( @weightings );
844 my @weightings = ( 8, 4, 6, 3, 5, 2, 1 );
846 sub fixup_cardnumber ($) {
847 my ($cardnumber) = @_;
848 my $autonumber_members = C4::Context->boolean_preference('autoMemberNum') || 0;
850 # Find out whether member numbers should be generated
851 # automatically. Should be either "1" or something else.
852 # Defaults to "0", which is interpreted as "no".
854 # if ($cardnumber !~ /\S/ && $autonumber_members) {
855 ($autonumber_members) or return $cardnumber;
856 my $checkdigit = C4::Context->preference('checkdigit');
857 my $dbh = C4::Context->dbh;
858 if ( $checkdigit and $checkdigit eq 'katipo' ) {
860 # if checkdigit is selected, calculate katipo-style cardnumber.
861 # otherwise, just use the max()
862 # purpose: generate checksum'd member numbers.
863 # We'll assume we just got the max value of digits 2-8 of member #'s
864 # from the database and our job is to increment that by one,
865 # determine the 1st and 9th digits and return the full string.
866 my $sth = $dbh->prepare(
867 "select max(substring(borrowers.cardnumber,2,7)) as new_num from borrowers"
870 my $data = $sth->fetchrow_hashref;
871 $cardnumber = $data->{new_num};
872 if ( !$cardnumber ) { # If DB has no values,
873 $cardnumber = 1000000; # start at 1000000
879 for ( my $i = 0 ; $i < 8 ; $i += 1 ) {
880 # read weightings, left to right, 1 char at a time
881 my $temp1 = $weightings[$i];
883 # sequence left to right, 1 char at a time
884 my $temp2 = substr( $cardnumber, $i, 1 );
886 # mult each char 1-7 by its corresponding weighting
887 $sum += $temp1 * $temp2;
890 my $rem = ( $sum % 11 );
891 $rem = 'X' if $rem == 10;
893 return "V$cardnumber$rem";
896 # MODIFIED BY JF: mysql4.1 allows casting as an integer, which is probably
897 # better. I'll leave the original in in case it needs to be changed for you
898 # my $sth=$dbh->prepare("select max(borrowers.cardnumber) from borrowers");
899 my $sth = $dbh->prepare(
900 "select max(cast(cardnumber as signed)) from borrowers"
903 my ($result) = $sth->fetchrow;
906 return $cardnumber; # just here as a fallback/reminder
911 ($num_children, $children_arrayref) = &GetGuarantees($parent_borrno);
912 $child0_cardno = $children_arrayref->[0]{"cardnumber"};
913 $child0_borrno = $children_arrayref->[0]{"borrowernumber"};
915 C<&GetGuarantees> takes a borrower number (e.g., that of a patron
916 with children) and looks up the borrowers who are guaranteed by that
917 borrower (i.e., the patron's children).
919 C<&GetGuarantees> returns two values: an integer giving the number of
920 borrowers guaranteed by C<$parent_borrno>, and a reference to an array
921 of references to hash, which gives the actual results.
927 my ($borrowernumber) = @_;
928 my $dbh = C4::Context->dbh;
931 "select cardnumber,borrowernumber, firstname, surname from borrowers where guarantorid=?"
933 $sth->execute($borrowernumber);
936 my $data = $sth->fetchall_arrayref({});
937 return ( scalar(@$data), $data );
940 =head2 UpdateGuarantees
942 &UpdateGuarantees($parent_borrno);
945 C<&UpdateGuarantees> borrower data for an adult and updates all the guarantees
946 with the modified information
951 sub UpdateGuarantees {
953 my $dbh = C4::Context->dbh;
954 my ( $count, $guarantees ) = GetGuarantees( $data{'borrowernumber'} );
955 foreach my $guarantee (@$guarantees){
956 my $guaquery = qq|UPDATE borrowers
957 SET address=?,fax=?,B_city=?,mobile=?,city=?,phone=?
958 WHERE borrowernumber=?
960 my $sth = $dbh->prepare($guaquery);
961 $sth->execute($data{'address'},$data{'fax'},$data{'B_city'},$data{'mobile'},$data{'city'},$data{'phone'},$guarantee->{'borrowernumber'});
964 =head2 GetPendingIssues
966 my $issues = &GetPendingIssues(@borrowernumber);
968 Looks up what the patron with the given borrowernumber has borrowed.
970 C<&GetPendingIssues> returns a
971 reference-to-array where each element is a reference-to-hash; the
972 keys are the fields from the C<issues>, C<biblio>, and C<items> tables.
973 The keys include C<biblioitems> fields except marc and marcxml.
978 sub GetPendingIssues {
979 my @borrowernumbers = @_;
981 unless (@borrowernumbers ) { # return a ref_to_array
982 return \@borrowernumbers; # to not cause surprise to caller
985 # Borrowers part of the query
987 for (my $i = 0; $i < @borrowernumbers; $i++) {
988 $bquery .= ' issues.borrowernumber = ?';
989 if ($i < $#borrowernumbers ) {
994 # must avoid biblioitems.* to prevent large marc and marcxml fields from killing performance
995 # FIXME: namespace collision: each table has "timestamp" fields. Which one is "timestamp" ?
996 # FIXME: circ/ciculation.pl tries to sort by timestamp!
997 # FIXME: C4::Print::printslip tries to sort by timestamp!
998 # FIXME: namespace collision: other collisions possible.
999 # FIXME: most of this data isn't really being used by callers.
1006 biblioitems.itemtype,
1009 biblioitems.publicationyear,
1010 biblioitems.publishercode,
1011 biblioitems.volumedate,
1012 biblioitems.volumedesc,
1015 borrowers.firstname,
1017 borrowers.cardnumber,
1018 issues.timestamp AS timestamp,
1019 issues.renewals AS renewals,
1020 issues.borrowernumber AS borrowernumber,
1021 items.renewals AS totalrenewals
1023 LEFT JOIN items ON items.itemnumber = issues.itemnumber
1024 LEFT JOIN biblio ON items.biblionumber = biblio.biblionumber
1025 LEFT JOIN biblioitems ON items.biblioitemnumber = biblioitems.biblioitemnumber
1026 LEFT JOIN borrowers ON issues.borrowernumber = borrowers.borrowernumber
1029 ORDER BY issues.issuedate"
1032 my $sth = C4::Context->dbh->prepare($query);
1033 $sth->execute(@borrowernumbers);
1034 my $data = $sth->fetchall_arrayref({});
1035 my $today = C4::Dates->new->output('iso');
1036 foreach (@{$data}) {
1037 if ($_->{date_due} and $_->{date_due} lt $today) {
1046 $issues = &GetAllIssues($borrowernumber, $sortkey, $limit);
1048 Looks up what the patron with the given borrowernumber has borrowed,
1049 and sorts the results.
1051 C<$sortkey> is the name of a field on which to sort the results. This
1052 should be the name of a field in the C<issues>, C<biblio>,
1053 C<biblioitems>, or C<items> table in the Koha database.
1055 C<$limit> is the maximum number of results to return.
1057 C<&GetAllIssues> an arrayref, C<$issues>, of hashrefs, the keys of which
1058 are the fields from the C<issues>, C<biblio>, C<biblioitems>, and
1059 C<items> tables of the Koha database.
1065 my ( $borrowernumber, $order, $limit ) = @_;
1067 #FIXME: sanity-check order and limit
1068 my $dbh = C4::Context->dbh;
1070 "SELECT *, issues.timestamp as issuestimestamp, issues.renewals AS renewals,items.renewals AS totalrenewals,items.timestamp AS itemstimestamp
1072 LEFT JOIN items on items.itemnumber=issues.itemnumber
1073 LEFT JOIN biblio ON items.biblionumber=biblio.biblionumber
1074 LEFT JOIN biblioitems ON items.biblioitemnumber=biblioitems.biblioitemnumber
1075 WHERE borrowernumber=?
1077 SELECT *, old_issues.timestamp as issuestimestamp, old_issues.renewals AS renewals,items.renewals AS totalrenewals,items.timestamp AS itemstimestamp
1079 LEFT JOIN items on items.itemnumber=old_issues.itemnumber
1080 LEFT JOIN biblio ON items.biblionumber=biblio.biblionumber
1081 LEFT JOIN biblioitems ON items.biblioitemnumber=biblioitems.biblioitemnumber
1082 WHERE borrowernumber=? AND old_issues.itemnumber IS NOT NULL
1084 if ( $limit != 0 ) {
1085 $query .= " limit $limit";
1088 my $sth = $dbh->prepare($query);
1089 $sth->execute($borrowernumber, $borrowernumber);
1092 while ( my $data = $sth->fetchrow_hashref ) {
1093 push @result, $data;
1100 =head2 GetMemberAccountRecords
1102 ($total, $acctlines, $count) = &GetMemberAccountRecords($borrowernumber);
1104 Looks up accounting data for the patron with the given borrowernumber.
1106 C<&GetMemberAccountRecords> returns a three-element array. C<$acctlines> is a
1107 reference-to-array, where each element is a reference-to-hash; the
1108 keys are the fields of the C<accountlines> table in the Koha database.
1109 C<$count> is the number of elements in C<$acctlines>. C<$total> is the
1110 total amount outstanding for all of the account lines.
1115 sub GetMemberAccountRecords {
1116 my ($borrowernumber,$date) = @_;
1117 my $dbh = C4::Context->dbh;
1123 WHERE borrowernumber=?);
1124 my @bind = ($borrowernumber);
1125 if ($date && $date ne ''){
1126 $strsth.=" AND date < ? ";
1129 $strsth.=" ORDER BY date desc,timestamp DESC";
1130 my $sth= $dbh->prepare( $strsth );
1131 $sth->execute( @bind );
1133 while ( my $data = $sth->fetchrow_hashref ) {
1134 if ( $data->{itemnumber} ) {
1135 my $biblio = GetBiblioFromItemNumber( $data->{itemnumber} );
1136 $data->{biblionumber} = $biblio->{biblionumber};
1137 $data->{title} = $biblio->{title};
1139 $acctlines[$numlines] = $data;
1141 $total += int(1000 * $data->{'amountoutstanding'}); # convert float to integer to avoid round-off errors
1144 return ( $total, \@acctlines,$numlines);
1147 =head2 GetBorNotifyAcctRecord
1149 ($total, $acctlines, $count) = &GetBorNotifyAcctRecord($params,$notifyid);
1151 Looks up accounting data for the patron with the given borrowernumber per file number.
1153 C<&GetBorNotifyAcctRecord> returns a three-element array. C<$acctlines> is a
1154 reference-to-array, where each element is a reference-to-hash; the
1155 keys are the fields of the C<accountlines> table in the Koha database.
1156 C<$count> is the number of elements in C<$acctlines>. C<$total> is the
1157 total amount outstanding for all of the account lines.
1161 sub GetBorNotifyAcctRecord {
1162 my ( $borrowernumber, $notifyid ) = @_;
1163 my $dbh = C4::Context->dbh;
1166 my $sth = $dbh->prepare(
1169 WHERE borrowernumber=?
1171 AND amountoutstanding != '0'
1172 ORDER BY notify_id,accounttype
1175 $sth->execute( $borrowernumber, $notifyid );
1177 while ( my $data = $sth->fetchrow_hashref ) {
1178 $acctlines[$numlines] = $data;
1180 $total += int(100 * $data->{'amountoutstanding'});
1183 return ( $total, \@acctlines, $numlines );
1186 =head2 checkuniquemember (OUEST-PROVENCE)
1188 ($result,$categorycode) = &checkuniquemember($collectivity,$surname,$firstname,$dateofbirth);
1190 Checks that a member exists or not in the database.
1192 C<&result> is nonzero (=exist) or 0 (=does not exist)
1193 C<&categorycode> is from categorycode table
1194 C<&collectivity> is 1 (= we add a collectivity) or 0 (= we add a physical member)
1195 C<&surname> is the surname
1196 C<&firstname> is the firstname (only if collectivity=0)
1197 C<&dateofbirth> is the date of birth in ISO format (only if collectivity=0)
1201 # FIXME: This function is not legitimate. Multiple patrons might have the same first/last name and birthdate.
1202 # This is especially true since first name is not even a required field.
1204 sub checkuniquemember {
1205 my ( $collectivity, $surname, $firstname, $dateofbirth ) = @_;
1206 my $dbh = C4::Context->dbh;
1207 my $request = ($collectivity) ?
1208 "SELECT borrowernumber,categorycode FROM borrowers WHERE surname=? " :
1210 "SELECT borrowernumber,categorycode FROM borrowers WHERE surname=? and firstname=? and dateofbirth=?" :
1211 "SELECT borrowernumber,categorycode FROM borrowers WHERE surname=? and firstname=?";
1212 my $sth = $dbh->prepare($request);
1213 if ($collectivity) {
1214 $sth->execute( uc($surname) );
1215 } elsif($dateofbirth){
1216 $sth->execute( uc($surname), ucfirst($firstname), $dateofbirth );
1218 $sth->execute( uc($surname), ucfirst($firstname));
1220 my @data = $sth->fetchrow;
1221 ( $data[0] ) and return $data[0], $data[1];
1225 sub checkcardnumber {
1226 my ($cardnumber,$borrowernumber) = @_;
1227 # If cardnumber is null, we assume they're allowed.
1228 return 0 if !defined($cardnumber);
1229 my $dbh = C4::Context->dbh;
1230 my $query = "SELECT * FROM borrowers WHERE cardnumber=?";
1231 $query .= " AND borrowernumber <> ?" if ($borrowernumber);
1232 my $sth = $dbh->prepare($query);
1233 if ($borrowernumber) {
1234 $sth->execute($cardnumber,$borrowernumber);
1236 $sth->execute($cardnumber);
1238 if (my $data= $sth->fetchrow_hashref()){
1247 =head2 getzipnamecity (OUEST-PROVENCE)
1249 take all info from table city for the fields city and zip
1250 check for the name and the zip code of the city selected
1254 sub getzipnamecity {
1256 my $dbh = C4::Context->dbh;
1259 "select city_name,city_state,city_zipcode,city_country from cities where cityid=? ");
1260 $sth->execute($cityid);
1261 my @data = $sth->fetchrow;
1262 return $data[0], $data[1], $data[2], $data[3];
1266 =head2 getdcity (OUEST-PROVENCE)
1268 recover cityid with city_name condition
1273 my ($city_name) = @_;
1274 my $dbh = C4::Context->dbh;
1275 my $sth = $dbh->prepare("select cityid from cities where city_name=? ");
1276 $sth->execute($city_name);
1277 my $data = $sth->fetchrow;
1281 =head2 GetFirstValidEmailAddress
1283 $email = GetFirstValidEmailAddress($borrowernumber);
1285 Return the first valid email address for a borrower, given the borrowernumber. For now, the order
1286 is defined as email, emailpro, B_email. Returns the empty string if the borrower has no email
1291 sub GetFirstValidEmailAddress {
1292 my $borrowernumber = shift;
1293 my $dbh = C4::Context->dbh;
1294 my $sth = $dbh->prepare( "SELECT email, emailpro, B_email FROM borrowers where borrowernumber = ? ");
1295 $sth->execute( $borrowernumber );
1296 my $data = $sth->fetchrow_hashref;
1298 if ($data->{'email'}) {
1299 return $data->{'email'};
1300 } elsif ($data->{'emailpro'}) {
1301 return $data->{'emailpro'};
1302 } elsif ($data->{'B_email'}) {
1303 return $data->{'B_email'};
1309 =head2 GetExpiryDate
1311 $expirydate = GetExpiryDate($categorycode, $dateenrolled);
1313 Calculate expiry date given a categorycode and starting date. Date argument must be in ISO format.
1314 Return date is also in ISO format.
1319 my ( $categorycode, $dateenrolled ) = @_;
1321 if ($categorycode) {
1322 my $dbh = C4::Context->dbh;
1323 my $sth = $dbh->prepare("SELECT enrolmentperiod,enrolmentperioddate FROM categories WHERE categorycode=?");
1324 $sth->execute($categorycode);
1325 $enrolments = $sth->fetchrow_hashref;
1327 # die "GetExpiryDate: for enrollmentperiod $enrolmentperiod (category '$categorycode') starting $dateenrolled.\n";
1328 my @date = split (/-/,$dateenrolled);
1329 if($enrolments->{enrolmentperiod}){
1330 return sprintf("%04d-%02d-%02d", Add_Delta_YM(@date,0,$enrolments->{enrolmentperiod}));
1332 return $enrolments->{enrolmentperioddate};
1336 =head2 checkuserpassword (OUEST-PROVENCE)
1338 check for the password and login are not used
1339 return the number of record
1340 0=> NOT USED 1=> USED
1344 sub checkuserpassword {
1345 my ( $borrowernumber, $userid, $password ) = @_;
1346 $password = md5_base64($password);
1347 my $dbh = C4::Context->dbh;
1350 "Select count(*) from borrowers where borrowernumber !=? and userid =? and password=? "
1352 $sth->execute( $borrowernumber, $userid, $password );
1353 my $number_rows = $sth->fetchrow;
1354 return $number_rows;
1358 =head2 GetborCatFromCatType
1360 ($codes_arrayref, $labels_hashref) = &GetborCatFromCatType();
1362 Looks up the different types of borrowers in the database. Returns two
1363 elements: a reference-to-array, which lists the borrower category
1364 codes, and a reference-to-hash, which maps the borrower category codes
1365 to category descriptions.
1370 sub GetborCatFromCatType {
1371 my ( $category_type, $action ) = @_;
1372 # FIXME - This API seems both limited and dangerous.
1373 my $dbh = C4::Context->dbh;
1374 my $request = qq| SELECT categorycode,description
1377 ORDER BY categorycode|;
1378 my $sth = $dbh->prepare($request);
1380 $sth->execute($category_type);
1389 while ( my $data = $sth->fetchrow_hashref ) {
1390 push @codes, $data->{'categorycode'};
1391 $labels{ $data->{'categorycode'} } = $data->{'description'};
1393 return ( \@codes, \%labels );
1396 =head2 GetBorrowercategory
1398 $hashref = &GetBorrowercategory($categorycode);
1400 Given the borrower's category code, the function returns the corresponding
1401 data hashref for a comprehensive information display.
1403 $arrayref_hashref = &GetBorrowercategory;
1405 If no category code provided, the function returns all the categories.
1409 sub GetBorrowercategory {
1411 my $dbh = C4::Context->dbh;
1415 "SELECT description,dateofbirthrequired,upperagelimit,category_type
1417 WHERE categorycode = ?"
1419 $sth->execute($catcode);
1421 $sth->fetchrow_hashref;
1425 } # sub getborrowercategory
1427 =head2 GetBorrowercategoryList
1429 $arrayref_hashref = &GetBorrowercategoryList;
1430 If no category code provided, the function returns all the categories.
1434 sub GetBorrowercategoryList {
1435 my $dbh = C4::Context->dbh;
1440 ORDER BY description"
1444 $sth->fetchall_arrayref({});
1446 } # sub getborrowercategory
1448 =head2 ethnicitycategories
1450 ($codes_arrayref, $labels_hashref) = ðnicitycategories();
1452 Looks up the different ethnic types in the database. Returns two
1453 elements: a reference-to-array, which lists the ethnicity codes, and a
1454 reference-to-hash, which maps the ethnicity codes to ethnicity
1461 sub ethnicitycategories {
1462 my $dbh = C4::Context->dbh;
1463 my $sth = $dbh->prepare("Select code,name from ethnicity order by name");
1467 while ( my $data = $sth->fetchrow_hashref ) {
1468 push @codes, $data->{'code'};
1469 $labels{ $data->{'code'} } = $data->{'name'};
1471 return ( \@codes, \%labels );
1476 $ethn_name = &fixEthnicity($ethn_code);
1478 Takes an ethnicity code (e.g., "european" or "pi") and returns the
1479 corresponding descriptive name from the C<ethnicity> table in the
1480 Koha database ("European" or "Pacific Islander").
1487 my $ethnicity = shift;
1488 return unless $ethnicity;
1489 my $dbh = C4::Context->dbh;
1490 my $sth = $dbh->prepare("Select name from ethnicity where code = ?");
1491 $sth->execute($ethnicity);
1492 my $data = $sth->fetchrow_hashref;
1493 return $data->{'name'};
1494 } # sub fixEthnicity
1498 $dateofbirth,$date = &GetAge($date);
1500 this function return the borrowers age with the value of dateofbirth
1506 my ( $date, $date_ref ) = @_;
1508 if ( not defined $date_ref ) {
1509 $date_ref = sprintf( '%04d-%02d-%02d', Today() );
1512 my ( $year1, $month1, $day1 ) = split /-/, $date;
1513 my ( $year2, $month2, $day2 ) = split /-/, $date_ref;
1515 my $age = $year2 - $year1;
1516 if ( $month1 . $day1 > $month2 . $day2 ) {
1523 =head2 get_institutions
1525 $insitutions = get_institutions();
1527 Just returns a list of all the borrowers of type I, borrownumber and name
1532 sub get_institutions {
1533 my $dbh = C4::Context->dbh();
1536 "SELECT borrowernumber,surname FROM borrowers WHERE categorycode=? ORDER BY surname"
1540 while ( my $data = $sth->fetchrow_hashref() ) {
1541 $orgs{ $data->{'borrowernumber'} } = $data;
1545 } # sub get_institutions
1547 =head2 add_member_orgs
1549 add_member_orgs($borrowernumber,$borrowernumbers);
1551 Takes a borrowernumber and a list of other borrowernumbers and inserts them into the borrowers_to_borrowers table
1556 sub add_member_orgs {
1557 my ( $borrowernumber, $otherborrowers ) = @_;
1558 my $dbh = C4::Context->dbh();
1560 "INSERT INTO borrowers_to_borrowers (borrower1,borrower2) VALUES (?,?)";
1561 my $sth = $dbh->prepare($query);
1562 foreach my $otherborrowernumber (@$otherborrowers) {
1563 $sth->execute( $borrowernumber, $otherborrowernumber );
1566 } # sub add_member_orgs
1570 $cityarrayref = GetCities();
1572 Returns an array_ref of the entries in the cities table
1573 If there are entries in the table an empty row is returned
1574 This is currently only used to populate a popup in memberentry
1580 my $dbh = C4::Context->dbh;
1581 my $city_arr = $dbh->selectall_arrayref(
1582 q|SELECT cityid,city_zipcode,city_name,city_state,city_country FROM cities ORDER BY city_name|,
1584 if ( @{$city_arr} ) {
1585 unshift @{$city_arr}, {
1586 city_zipcode => q{},
1590 city_country => q{},
1597 =head2 GetSortDetails (OUEST-PROVENCE)
1599 ($lib) = &GetSortDetails($category,$sortvalue);
1601 Returns the authorized value details
1602 C<&$lib>return value of authorized value details
1603 C<&$sortvalue>this is the value of authorized value
1604 C<&$category>this is the value of authorized value category
1608 sub GetSortDetails {
1609 my ( $category, $sortvalue ) = @_;
1610 my $dbh = C4::Context->dbh;
1611 my $query = qq|SELECT lib
1612 FROM authorised_values
1614 AND authorised_value=? |;
1615 my $sth = $dbh->prepare($query);
1616 $sth->execute( $category, $sortvalue );
1617 my $lib = $sth->fetchrow;
1618 return ($lib) if ($lib);
1619 return ($sortvalue) unless ($lib);
1622 =head2 MoveMemberToDeleted
1624 $result = &MoveMemberToDeleted($borrowernumber);
1626 Copy the record from borrowers to deletedborrowers table.
1630 # FIXME: should do it in one SQL statement w/ subquery
1631 # Otherwise, we should return the @data on success
1633 sub MoveMemberToDeleted {
1634 my ($member) = shift or return;
1635 my $dbh = C4::Context->dbh;
1636 my $query = qq|SELECT *
1638 WHERE borrowernumber=?|;
1639 my $sth = $dbh->prepare($query);
1640 $sth->execute($member);
1641 my @data = $sth->fetchrow_array;
1642 (@data) or return; # if we got a bad borrowernumber, there's nothing to insert
1644 $dbh->prepare( "INSERT INTO deletedborrowers VALUES ("
1645 . ( "?," x ( scalar(@data) - 1 ) )
1647 $sth->execute(@data);
1652 DelMember($borrowernumber);
1654 This function remove directly a borrower whitout writing it on deleteborrower.
1655 + Deletes reserves for the borrower
1660 my $dbh = C4::Context->dbh;
1661 my $borrowernumber = shift;
1662 #warn "in delmember with $borrowernumber";
1663 return unless $borrowernumber; # borrowernumber is mandatory.
1665 my $query = qq|DELETE
1667 WHERE borrowernumber=?|;
1668 my $sth = $dbh->prepare($query);
1669 $sth->execute($borrowernumber);
1673 WHERE borrowernumber = ?
1675 $sth = $dbh->prepare($query);
1676 $sth->execute($borrowernumber);
1677 logaction("MEMBERS", "DELETE", $borrowernumber, "") if C4::Context->preference("BorrowersLog");
1681 =head2 ExtendMemberSubscriptionTo (OUEST-PROVENCE)
1683 $date = ExtendMemberSubscriptionTo($borrowerid, $date);
1685 Extending the subscription to a given date or to the expiry date calculated on ISO date.
1690 sub ExtendMemberSubscriptionTo {
1691 my ( $borrowerid,$date) = @_;
1692 my $dbh = C4::Context->dbh;
1693 my $borrower = GetMember('borrowernumber'=>$borrowerid);
1695 $date = (C4::Context->preference('BorrowerRenewalPeriodBase') eq 'dateexpiry') ?
1696 C4::Dates->new($borrower->{'dateexpiry'}, 'iso')->output("iso") :
1697 C4::Dates->new()->output("iso");
1698 $date = GetExpiryDate( $borrower->{'categorycode'}, $date );
1700 my $sth = $dbh->do(<<EOF);
1702 SET dateexpiry='$date'
1703 WHERE borrowernumber='$borrowerid'
1705 # add enrolmentfee if needed
1706 $sth = $dbh->prepare("SELECT enrolmentfee FROM categories WHERE categorycode=?");
1707 $sth->execute($borrower->{'categorycode'});
1708 my ($enrolmentfee) = $sth->fetchrow;
1709 if ($enrolmentfee && $enrolmentfee > 0) {
1710 # insert fee in patron debts
1711 manualinvoice($borrower->{'borrowernumber'}, '', '', 'A', $enrolmentfee);
1713 logaction("MEMBERS", "RENEW", $borrower->{'borrowernumber'}, "Membership renewed")if C4::Context->preference("BorrowersLog");
1714 return $date if ($sth);
1718 =head2 GetRoadTypes (OUEST-PROVENCE)
1720 ($idroadtypearrayref, $roadttype_hashref) = &GetRoadTypes();
1722 Looks up the different road type . Returns two
1723 elements: a reference-to-array, which lists the id_roadtype
1724 codes, and a reference-to-hash, which maps the road type of the road .
1729 my $dbh = C4::Context->dbh;
1731 SELECT roadtypeid,road_type
1733 ORDER BY road_type|;
1734 my $sth = $dbh->prepare($query);
1739 # insert empty value to create a empty choice in cgi popup
1741 while ( my $data = $sth->fetchrow_hashref ) {
1743 push @id, $data->{'roadtypeid'};
1744 $roadtype{ $data->{'roadtypeid'} } = $data->{'road_type'};
1747 #test to know if the table contain some records if no the function return nothing
1754 return ( \@id, \%roadtype );
1760 =head2 GetTitles (OUEST-PROVENCE)
1762 ($borrowertitle)= &GetTitles();
1764 Looks up the different title . Returns array with all borrowers title
1769 my @borrowerTitle = split (/,|\|/,C4::Context->preference('BorrowersTitles'));
1770 unshift( @borrowerTitle, "" );
1771 my $count=@borrowerTitle;
1776 return ( \@borrowerTitle);
1780 =head2 GetPatronImage
1782 my ($imagedata, $dberror) = GetPatronImage($cardnumber);
1784 Returns the mimetype and binary image data of the image for the patron with the supplied cardnumber.
1788 sub GetPatronImage {
1789 my ($cardnumber) = @_;
1790 warn "Cardnumber passed to GetPatronImage is $cardnumber" if $debug;
1791 my $dbh = C4::Context->dbh;
1792 my $query = 'SELECT mimetype, imagefile FROM patronimage WHERE cardnumber = ?';
1793 my $sth = $dbh->prepare($query);
1794 $sth->execute($cardnumber);
1795 my $imagedata = $sth->fetchrow_hashref;
1796 warn "Database error!" if $sth->errstr;
1797 return $imagedata, $sth->errstr;
1800 =head2 PutPatronImage
1802 PutPatronImage($cardnumber, $mimetype, $imgfile);
1804 Stores patron binary image data and mimetype in database.
1805 NOTE: This function is good for updating images as well as inserting new images in the database.
1809 sub PutPatronImage {
1810 my ($cardnumber, $mimetype, $imgfile) = @_;
1811 warn "Parameters passed in: Cardnumber=$cardnumber, Mimetype=$mimetype, " . ($imgfile ? "Imagefile" : "No Imagefile") if $debug;
1812 my $dbh = C4::Context->dbh;
1813 my $query = "INSERT INTO patronimage (cardnumber, mimetype, imagefile) VALUES (?,?,?) ON DUPLICATE KEY UPDATE imagefile = ?;";
1814 my $sth = $dbh->prepare($query);
1815 $sth->execute($cardnumber,$mimetype,$imgfile,$imgfile);
1816 warn "Error returned inserting $cardnumber.$mimetype." if $sth->errstr;
1817 return $sth->errstr;
1820 =head2 RmPatronImage
1822 my ($dberror) = RmPatronImage($cardnumber);
1824 Removes the image for the patron with the supplied cardnumber.
1829 my ($cardnumber) = @_;
1830 warn "Cardnumber passed to GetPatronImage is $cardnumber" if $debug;
1831 my $dbh = C4::Context->dbh;
1832 my $query = "DELETE FROM patronimage WHERE cardnumber = ?;";
1833 my $sth = $dbh->prepare($query);
1834 $sth->execute($cardnumber);
1835 my $dberror = $sth->errstr;
1836 warn "Database error!" if $sth->errstr;
1840 =head2 GetHideLostItemsPreference
1842 $hidelostitemspref = &GetHideLostItemsPreference($borrowernumber);
1844 Returns the HideLostItems preference for the patron category of the supplied borrowernumber
1845 C<&$hidelostitemspref>return value of function, 0 or 1
1849 sub GetHideLostItemsPreference {
1850 my ($borrowernumber) = @_;
1851 my $dbh = C4::Context->dbh;
1852 my $query = "SELECT hidelostitems FROM borrowers,categories WHERE borrowers.categorycode = categories.categorycode AND borrowernumber = ?";
1853 my $sth = $dbh->prepare($query);
1854 $sth->execute($borrowernumber);
1855 my $hidelostitems = $sth->fetchrow;
1856 return $hidelostitems;
1859 =head2 GetRoadTypeDetails (OUEST-PROVENCE)
1861 ($roadtype) = &GetRoadTypeDetails($roadtypeid);
1863 Returns the description of roadtype
1864 C<&$roadtype>return description of road type
1865 C<&$roadtypeid>this is the value of roadtype s
1869 sub GetRoadTypeDetails {
1870 my ($roadtypeid) = @_;
1871 my $dbh = C4::Context->dbh;
1875 WHERE roadtypeid=?|;
1876 my $sth = $dbh->prepare($query);
1877 $sth->execute($roadtypeid);
1878 my $roadtype = $sth->fetchrow;
1882 =head2 GetBorrowersWhoHaveNotBorrowedSince
1884 &GetBorrowersWhoHaveNotBorrowedSince($date)
1886 this function get all borrowers who haven't borrowed since the date given on input arg.
1890 sub GetBorrowersWhoHaveNotBorrowedSince {
1891 my $filterdate = shift||POSIX::strftime("%Y-%m-%d",localtime());
1892 my $filterexpiry = shift;
1893 my $filterbranch = shift ||
1894 ((C4::Context->preference('IndependantBranches')
1895 && C4::Context->userenv
1896 && C4::Context->userenv->{flags} % 2 !=1
1897 && C4::Context->userenv->{branch})
1898 ? C4::Context->userenv->{branch}
1900 my $dbh = C4::Context->dbh;
1902 SELECT borrowers.borrowernumber,
1903 max(old_issues.timestamp) as latestissue,
1904 max(issues.timestamp) as currentissue
1906 JOIN categories USING (categorycode)
1907 LEFT JOIN old_issues USING (borrowernumber)
1908 LEFT JOIN issues USING (borrowernumber)
1909 WHERE category_type <> 'S'
1910 AND borrowernumber NOT IN (SELECT guarantorid FROM borrowers WHERE guarantorid IS NOT NULL AND guarantorid <> 0)
1913 if ($filterbranch && $filterbranch ne ""){
1914 $query.=" AND borrowers.branchcode= ?";
1915 push @query_params,$filterbranch;
1918 $query .= " AND dateexpiry < ? ";
1919 push @query_params,$filterdate;
1921 $query.=" GROUP BY borrowers.borrowernumber";
1923 $query.=" HAVING (latestissue < ? OR latestissue IS NULL)
1924 AND currentissue IS NULL";
1925 push @query_params,$filterdate;
1927 warn $query if $debug;
1928 my $sth = $dbh->prepare($query);
1929 if (scalar(@query_params)>0){
1930 $sth->execute(@query_params);
1937 while ( my $data = $sth->fetchrow_hashref ) {
1938 push @results, $data;
1943 =head2 GetBorrowersWhoHaveNeverBorrowed
1945 $results = &GetBorrowersWhoHaveNeverBorrowed
1947 This function get all borrowers who have never borrowed.
1949 I<$result> is a ref to an array which all elements are a hasref.
1953 sub GetBorrowersWhoHaveNeverBorrowed {
1954 my $filterbranch = shift ||
1955 ((C4::Context->preference('IndependantBranches')
1956 && C4::Context->userenv
1957 && C4::Context->userenv->{flags} % 2 !=1
1958 && C4::Context->userenv->{branch})
1959 ? C4::Context->userenv->{branch}
1961 my $dbh = C4::Context->dbh;
1963 SELECT borrowers.borrowernumber,max(timestamp) as latestissue
1965 LEFT JOIN issues ON borrowers.borrowernumber = issues.borrowernumber
1966 WHERE issues.borrowernumber IS NULL
1969 if ($filterbranch && $filterbranch ne ""){
1970 $query.=" AND borrowers.branchcode= ?";
1971 push @query_params,$filterbranch;
1973 warn $query if $debug;
1975 my $sth = $dbh->prepare($query);
1976 if (scalar(@query_params)>0){
1977 $sth->execute(@query_params);
1984 while ( my $data = $sth->fetchrow_hashref ) {
1985 push @results, $data;
1990 =head2 GetBorrowersWithIssuesHistoryOlderThan
1992 $results = &GetBorrowersWithIssuesHistoryOlderThan($date)
1994 this function get all borrowers who has an issue history older than I<$date> given on input arg.
1996 I<$result> is a ref to an array which all elements are a hashref.
1997 This hashref is containt the number of time this borrowers has borrowed before I<$date> and the borrowernumber.
2001 sub GetBorrowersWithIssuesHistoryOlderThan {
2002 my $dbh = C4::Context->dbh;
2003 my $date = shift ||POSIX::strftime("%Y-%m-%d",localtime());
2004 my $filterbranch = shift ||
2005 ((C4::Context->preference('IndependantBranches')
2006 && C4::Context->userenv
2007 && C4::Context->userenv->{flags} % 2 !=1
2008 && C4::Context->userenv->{branch})
2009 ? C4::Context->userenv->{branch}
2012 SELECT count(borrowernumber) as n,borrowernumber
2014 WHERE returndate < ?
2015 AND borrowernumber IS NOT NULL
2018 push @query_params, $date;
2020 $query.=" AND branchcode = ?";
2021 push @query_params, $filterbranch;
2023 $query.=" GROUP BY borrowernumber ";
2024 warn $query if $debug;
2025 my $sth = $dbh->prepare($query);
2026 $sth->execute(@query_params);
2029 while ( my $data = $sth->fetchrow_hashref ) {
2030 push @results, $data;
2035 =head2 GetBorrowersNamesAndLatestIssue
2037 $results = &GetBorrowersNamesAndLatestIssueList(@borrowernumbers)
2039 this function get borrowers Names and surnames and Issue information.
2041 I<@borrowernumbers> is an array which all elements are borrowernumbers.
2042 This hashref is containt the number of time this borrowers has borrowed before I<$date> and the borrowernumber.
2046 sub GetBorrowersNamesAndLatestIssue {
2047 my $dbh = C4::Context->dbh;
2048 my @borrowernumbers=@_;
2050 SELECT surname,lastname, phone, email,max(timestamp)
2052 LEFT JOIN issues ON borrowers.borrowernumber=issues.borrowernumber
2053 GROUP BY borrowernumber
2055 my $sth = $dbh->prepare($query);
2057 my $results = $sth->fetchall_arrayref({});
2063 my $success = DebarMember( $borrowernumber, $todate );
2065 marks a Member as debarred, and therefore unable to checkout any more
2069 true on success, false on failure
2074 my $borrowernumber = shift;
2077 return unless defined $borrowernumber;
2078 return unless $borrowernumber =~ /^\d+$/;
2081 borrowernumber => $borrowernumber,
2091 my $success = ModPrivacy( $borrowernumber, $privacy );
2093 Update the privacy of a patron.
2096 true on success, false on failure
2103 my $borrowernumber = shift;
2104 my $privacy = shift;
2105 return unless defined $borrowernumber;
2106 return unless $borrowernumber =~ /^\d+$/;
2108 return ModMember( borrowernumber => $borrowernumber,
2109 privacy => $privacy );
2114 AddMessage( $borrowernumber, $message_type, $message, $branchcode );
2116 Adds a message to the messages table for the given borrower.
2125 my ( $borrowernumber, $message_type, $message, $branchcode ) = @_;
2127 my $dbh = C4::Context->dbh;
2129 if ( ! ( $borrowernumber && $message_type && $message && $branchcode ) ) {
2133 my $query = "INSERT INTO messages ( borrowernumber, branchcode, message_type, message ) VALUES ( ?, ?, ?, ? )";
2134 my $sth = $dbh->prepare($query);
2135 $sth->execute( $borrowernumber, $branchcode, $message_type, $message );
2136 logaction("MEMBERS", "ADDCIRCMESSAGE", $borrowernumber, $message) if C4::Context->preference("BorrowersLog");
2142 GetMessages( $borrowernumber, $type );
2144 $type is message type, B for borrower, or L for Librarian.
2145 Empty type returns all messages of any type.
2147 Returns all messages for the given borrowernumber
2152 my ( $borrowernumber, $type, $branchcode ) = @_;
2158 my $dbh = C4::Context->dbh;
2161 branches.branchname,
2164 messages.branchcode LIKE '$branchcode' AS can_delete
2165 FROM messages, branches
2166 WHERE borrowernumber = ?
2167 AND message_type LIKE ?
2168 AND messages.branchcode = branches.branchcode
2169 ORDER BY message_date DESC";
2170 my $sth = $dbh->prepare($query);
2171 $sth->execute( $borrowernumber, $type ) ;
2174 while ( my $data = $sth->fetchrow_hashref ) {
2175 my $d = C4::Dates->new( $data->{message_date}, 'iso' );
2176 $data->{message_date_formatted} = $d->output;
2177 push @results, $data;
2185 GetMessagesCount( $borrowernumber, $type );
2187 $type is message type, B for borrower, or L for Librarian.
2188 Empty type returns all messages of any type.
2190 Returns the number of messages for the given borrowernumber
2194 sub GetMessagesCount {
2195 my ( $borrowernumber, $type, $branchcode ) = @_;
2201 my $dbh = C4::Context->dbh;
2203 my $query = "SELECT COUNT(*) as MsgCount FROM messages WHERE borrowernumber = ? AND message_type LIKE ?";
2204 my $sth = $dbh->prepare($query);
2205 $sth->execute( $borrowernumber, $type ) ;
2208 my $data = $sth->fetchrow_hashref;
2209 my $count = $data->{'MsgCount'};
2216 =head2 DeleteMessage
2218 DeleteMessage( $message_id );
2223 my ( $message_id ) = @_;
2225 my $dbh = C4::Context->dbh;
2226 my $query = "SELECT * FROM messages WHERE message_id = ?";
2227 my $sth = $dbh->prepare($query);
2228 $sth->execute( $message_id );
2229 my $message = $sth->fetchrow_hashref();
2231 $query = "DELETE FROM messages WHERE message_id = ?";
2232 $sth = $dbh->prepare($query);
2233 $sth->execute( $message_id );
2234 logaction("MEMBERS", "DELCIRCMESSAGE", $message->{'borrowernumber'}, $message->{'message'}) if C4::Context->preference("BorrowersLog");
2239 IssueSlip($branchcode, $borrowernumber, $quickslip)
2241 Returns letter hash ( see C4::Letters::GetPreparedLetter )
2243 $quickslip is boolean, to indicate whether we want a quick slip
2248 my ($branch, $borrowernumber, $quickslip) = @_;
2250 # return unless ( C4::Context->boolean_preference('printcirculationslips') );
2252 my $today = POSIX::strftime("%Y-%m-%d", localtime);
2254 my $issueslist = GetPendingIssues($borrowernumber);
2255 foreach my $it (@$issueslist){
2256 if ($it->{'issuedate'} eq $today) {
2259 elsif ($it->{'date_due'} le $today) {
2260 $it->{'overdue'} = 1;
2263 $it->{'date_due'}=format_date($it->{'date_due'});
2265 my @issues = sort { $b->{'timestamp'} <=> $a->{'timestamp'} } @$issueslist;
2267 my ($letter_code, %repeat);
2269 $letter_code = 'ISSUEQSLIP';
2271 'checkedout' => [ map {
2275 }, grep { $_->{'today'} } @issues ],
2279 $letter_code = 'ISSUESLIP';
2281 'checkedout' => [ map {
2285 }, grep { !$_->{'overdue'} } @issues ],
2287 'overdue' => [ map {
2291 }, grep { $_->{'overdue'} } @issues ],
2294 $_->{'timestamp'} = $_->{'newdate'};
2296 } @{ GetNewsToDisplay("slip") } ],
2300 return C4::Letters::GetPreparedLetter (
2301 module => 'circulation',
2302 letter_code => $letter_code,
2303 branchcode => $branch,
2305 'branches' => $branch,
2306 'borrowers' => $borrowernumber,
2312 =head2 GetBorrowersWithEmail
2314 ([$borrnum,$userid], ...) = GetBorrowersWithEmail('me@example.com');
2316 This gets a list of users and their basic details from their email address.
2317 As it's possible for multiple user to have the same email address, it provides
2318 you with all of them. If there is no userid for the user, there will be an
2319 C<undef> there. An empty list will be returned if there are no matches.
2323 sub GetBorrowersWithEmail {
2326 my $dbh = C4::Context->dbh;
2328 my $query = "SELECT borrowernumber, userid FROM borrowers WHERE email=?";
2329 my $sth=$dbh->prepare($query);
2330 $sth->execute($email);
2332 while (my $ref = $sth->fetch) {
2335 die "Failure searching for borrowers by email address: $sth->errstr" if $sth->err;
2340 END { } # module clean-up code here (global destructor)