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 use DateTime::Format::DateParse;
42 our ($VERSION,@ISA,@EXPORT,@EXPORT_OK,$debug);
46 $debug = $ENV{DEBUG} || 0;
58 &GetMemberIssuesAndFines
66 &GetFirstValidEmailAddress
79 &GetHideLostItemsPreference
82 &GetMemberAccountRecords
83 &GetBorNotifyAcctRecord
87 GetBorrowerCategorycode
88 &GetBorrowercategoryList
90 &GetBorrowersWhoHaveNotBorrowedSince
91 &GetBorrowersWhoHaveNeverBorrowed
92 &GetBorrowersWithIssuesHistoryOlderThan
102 GetBorrowersWithEmail
122 &ExtendMemberSubscriptionTo
140 C4::Members - Perl Module containing convenience functions for member handling
148 This module contains routines for adding, modifying and deleting members/patrons/borrowers
154 $borrowers_result_array_ref = &Search($filter,$orderby, $limit,
155 $columns_out, $search_on_fields,$searchtype);
157 Looks up patrons (borrowers) on filter. A wrapper for SearchInTable('borrowers').
159 For C<$filter>, C<$orderby>, C<$limit>, C<&columns_out>, C<&search_on_fields> and C<&searchtype>
160 refer to C4::SQLHelper:SearchInTable().
162 Special C<$filter> key '' is effectively expanded to search on surname firstname othernamescw
163 and cardnumber unless C<&search_on_fields> is defined
167 $borrowers = Search('abcd', 'cardnumber');
169 $borrowers = Search({''=>'abcd', category_type=>'I'}, 'surname');
173 sub _express_member_find {
176 # this is used by circulation everytime a new borrowers cardnumber is scanned
177 # so we can check an exact match first, if that works return, otherwise do the rest
178 my $dbh = C4::Context->dbh;
179 my $query = "SELECT borrowernumber FROM borrowers WHERE cardnumber = ?";
180 if ( my $borrowernumber = $dbh->selectrow_array($query, undef, $filter) ) {
181 return( {"borrowernumber"=>$borrowernumber} );
184 my ($search_on_fields, $searchtype);
185 if ( length($filter) == 1 ) {
186 $search_on_fields = [ qw(surname) ];
187 $searchtype = 'start_with';
189 $search_on_fields = [ qw(surname firstname othernames cardnumber) ];
190 $searchtype = 'contain';
193 return (undef, $search_on_fields, $searchtype);
197 my ( $filter, $orderby, $limit, $columns_out, $search_on_fields, $searchtype ) = @_;
202 if ( my $fr = ref $filter ) {
203 if ( $fr eq "HASH" ) {
204 if ( my $search_string = $filter->{''} ) {
205 my ($member_filter, $member_search_on_fields, $member_searchtype) = _express_member_find($search_string);
206 if ($member_filter) {
207 $filter = $member_filter;
210 $search_on_fields ||= $member_search_on_fields;
211 $searchtype ||= $member_searchtype;
216 $search_string = $filter;
220 $search_string = $filter;
221 my ($member_filter, $member_search_on_fields, $member_searchtype) = _express_member_find($search_string);
222 if ($member_filter) {
223 $filter = $member_filter;
226 $search_on_fields ||= $member_search_on_fields;
227 $searchtype ||= $member_searchtype;
231 if ( !$found_borrower && C4::Context->preference('ExtendedPatronAttributes') && $search_string ) {
232 my $matching_records = C4::Members::Attributes::SearchIdMatchingAttribute($search_string);
233 if(scalar(@$matching_records)>0) {
234 if ( my $fr = ref $filter ) {
235 if ( $fr eq "HASH" ) {
237 $filter = [ $filter ];
239 push @$filter, { %f, "borrowernumber"=>$$matching_records };
242 push @$filter, {"borrowernumber"=>$matching_records};
246 $filter = [ $filter ];
247 push @$filter, {"borrowernumber"=>$matching_records};
252 # $showallbranches was not used at the time SearchMember() was mainstreamed into Search().
253 # Mentioning for the reference
255 if ( C4::Context->preference("IndependantBranches") ) { # && !$showallbranches){
256 if ( my $userenv = C4::Context->userenv ) {
257 my $branch = $userenv->{'branch'};
258 if ( ($userenv->{flags} % 2 !=1) &&
259 $branch && $branch ne "insecure" ){
261 if (my $fr = ref $filter) {
262 if ( $fr eq "HASH" ) {
263 $filter->{branchcode} = $branch;
267 $_ = { '' => $_ } unless ref $_;
268 $_->{branchcode} = $branch;
273 $filter = { '' => $filter, branchcode => $branch };
279 if ($found_borrower) {
280 $searchtype = "exact";
282 $searchtype ||= "start_with";
284 return SearchInTable( "borrowers", $filter, $orderby, $limit, $columns_out, $search_on_fields, $searchtype );
287 =head2 GetMemberDetails
289 ($borrower) = &GetMemberDetails($borrowernumber, $cardnumber);
291 Looks up a patron and returns information about him or her. If
292 C<$borrowernumber> is true (nonzero), C<&GetMemberDetails> looks
293 up the borrower by number; otherwise, it looks up the borrower by card
296 C<$borrower> is a reference-to-hash whose keys are the fields of the
297 borrowers table in the Koha database. In addition,
298 C<$borrower-E<gt>{flags}> is a hash giving more detailed information
299 about the patron. Its keys act as flags :
301 if $borrower->{flags}->{LOST} {
302 # Patron's card was reported lost
305 If the state of a flag means that the patron should not be
306 allowed to borrow any more books, then it will have a C<noissues> key
309 See patronflags for more details.
311 C<$borrower-E<gt>{authflags}> is a hash giving more detailed information
312 about the top-level permissions flags set for the borrower. For example,
313 if a user has the "editcatalogue" permission,
314 C<$borrower-E<gt>{authflags}-E<gt>{editcatalogue}> will exist and have
319 sub GetMemberDetails {
320 my ( $borrowernumber, $cardnumber ) = @_;
321 my $dbh = C4::Context->dbh;
324 if ($borrowernumber) {
325 $sth = $dbh->prepare("SELECT borrowers.*,category_type,categories.description,reservefee,enrolmentperiod FROM borrowers LEFT JOIN categories ON borrowers.categorycode=categories.categorycode WHERE borrowernumber=?");
326 $sth->execute($borrowernumber);
328 elsif ($cardnumber) {
329 $sth = $dbh->prepare("SELECT borrowers.*,category_type,categories.description,reservefee,enrolmentperiod FROM borrowers LEFT JOIN categories ON borrowers.categorycode=categories.categorycode WHERE cardnumber=?");
330 $sth->execute($cardnumber);
335 my $borrower = $sth->fetchrow_hashref;
336 my ($amount) = GetMemberAccountRecords( $borrowernumber);
337 $borrower->{'amountoutstanding'} = $amount;
338 # FIXME - patronflags calls GetMemberAccountRecords... just have patronflags return $amount
339 my $flags = patronflags( $borrower);
342 $sth = $dbh->prepare("select bit,flag from userflags");
344 while ( my ( $bit, $flag ) = $sth->fetchrow ) {
345 if ( $borrower->{'flags'} && $borrower->{'flags'} & 2**$bit ) {
346 $accessflagshash->{$flag} = 1;
349 $borrower->{'flags'} = $flags;
350 $borrower->{'authflags'} = $accessflagshash;
352 # For the purposes of making templates easier, we'll define a
353 # 'showname' which is the alternate form the user's first name if
354 # 'other name' is defined.
355 if ($borrower->{category_type} eq 'I') {
356 $borrower->{'showname'} = $borrower->{'othernames'};
357 $borrower->{'showname'} .= " $borrower->{'firstname'}" if $borrower->{'firstname'};
359 $borrower->{'showname'} = $borrower->{'firstname'};
362 return ($borrower); #, $flags, $accessflagshash);
367 $flags = &patronflags($patron);
369 This function is not exported.
371 The following will be set where applicable:
372 $flags->{CHARGES}->{amount} Amount of debt
373 $flags->{CHARGES}->{noissues} Set if debt amount >$5.00 (or syspref noissuescharge)
374 $flags->{CHARGES}->{message} Message -- deprecated
376 $flags->{CREDITS}->{amount} Amount of credit
377 $flags->{CREDITS}->{message} Message -- deprecated
379 $flags->{ GNA } Patron has no valid address
380 $flags->{ GNA }->{noissues} Set for each GNA
381 $flags->{ GNA }->{message} "Borrower has no valid address" -- deprecated
383 $flags->{ LOST } Patron's card reported lost
384 $flags->{ LOST }->{noissues} Set for each LOST
385 $flags->{ LOST }->{message} Message -- deprecated
387 $flags->{DBARRED} Set if patron debarred, no access
388 $flags->{DBARRED}->{noissues} Set for each DBARRED
389 $flags->{DBARRED}->{message} Message -- deprecated
392 $flags->{ NOTES }->{message} The note itself. NOT deprecated
394 $flags->{ ODUES } Set if patron has overdue books.
395 $flags->{ ODUES }->{message} "Yes" -- deprecated
396 $flags->{ ODUES }->{itemlist} ref-to-array: list of overdue books
397 $flags->{ ODUES }->{itemlisttext} Text list of overdue items -- deprecated
399 $flags->{WAITING} Set if any of patron's reserves are available
400 $flags->{WAITING}->{message} Message -- deprecated
401 $flags->{WAITING}->{itemlist} ref-to-array: list of available items
405 =item C<$flags-E<gt>{ODUES}-E<gt>{itemlist}> is a reference-to-array listing the
406 overdue items. Its elements are references-to-hash, each describing an
407 overdue item. The keys are selected fields from the issues, biblio,
408 biblioitems, and items tables of the Koha database.
410 =item C<$flags-E<gt>{ODUES}-E<gt>{itemlisttext}> is a string giving a text listing of
411 the overdue items, one per line. Deprecated.
413 =item C<$flags-E<gt>{WAITING}-E<gt>{itemlist}> is a reference-to-array listing the
414 available items. Each element is a reference-to-hash whose keys are
415 fields from the reserves table of the Koha database.
419 All the "message" fields that include language generated in this function are deprecated,
420 because such strings belong properly in the display layer.
422 The "message" field that comes from the DB is OK.
426 # TODO: use {anonymous => hashes} instead of a dozen %flaginfo
427 # FIXME rename this function.
430 my ( $patroninformation) = @_;
431 my $dbh=C4::Context->dbh;
432 my ($amount) = GetMemberAccountRecords( $patroninformation->{'borrowernumber'});
435 my $noissuescharge = C4::Context->preference("noissuescharge") || 5;
436 $flaginfo{'message'} = sprintf "Patron owes \$%.02f", $amount;
437 $flaginfo{'amount'} = sprintf "%.02f", $amount;
438 if ( $amount > $noissuescharge && !C4::Context->preference("AllowFineOverride") ) {
439 $flaginfo{'noissues'} = 1;
441 $flags{'CHARGES'} = \%flaginfo;
443 elsif ( $amount < 0 ) {
445 $flaginfo{'message'} = sprintf "Patron has credit of \$%.02f", -$amount;
446 $flaginfo{'amount'} = sprintf "%.02f", $amount;
447 $flags{'CREDITS'} = \%flaginfo;
449 if ( $patroninformation->{'gonenoaddress'}
450 && $patroninformation->{'gonenoaddress'} == 1 )
453 $flaginfo{'message'} = 'Borrower has no valid address.';
454 $flaginfo{'noissues'} = 1;
455 $flags{'GNA'} = \%flaginfo;
457 if ( $patroninformation->{'lost'} && $patroninformation->{'lost'} == 1 ) {
459 $flaginfo{'message'} = 'Borrower\'s card reported lost.';
460 $flaginfo{'noissues'} = 1;
461 $flags{'LOST'} = \%flaginfo;
463 if ( $patroninformation->{'debarred'} && check_date( split( /-/, $patroninformation->{'debarred'} ) ) ) {
464 if ( Date_to_Days(Date::Calc::Today) < Date_to_Days( split( /-/, $patroninformation->{'debarred'} ) ) ) {
466 $flaginfo{'debarredcomment'} = $patroninformation->{'debarredcomment'};
467 $flaginfo{'message'} = $patroninformation->{'debarredcomment'};
468 $flaginfo{'noissues'} = 1;
469 $flaginfo{'dateend'} = $patroninformation->{'debarred'};
470 $flags{'DBARRED'} = \%flaginfo;
473 if ( $patroninformation->{'borrowernotes'}
474 && $patroninformation->{'borrowernotes'} )
477 $flaginfo{'message'} = $patroninformation->{'borrowernotes'};
478 $flags{'NOTES'} = \%flaginfo;
480 my ( $odues, $itemsoverdue ) = C4::Overdues::checkoverdues($patroninformation->{'borrowernumber'});
481 if ( $odues && $odues > 0 ) {
483 $flaginfo{'message'} = "Yes";
484 $flaginfo{'itemlist'} = $itemsoverdue;
485 foreach ( sort { $a->{'date_due'} cmp $b->{'date_due'} }
488 $flaginfo{'itemlisttext'} .=
489 "$_->{'date_due'} $_->{'barcode'} $_->{'title'} \n"; # newline is display layer
491 $flags{'ODUES'} = \%flaginfo;
493 my @itemswaiting = C4::Reserves::GetReservesFromBorrowernumber( $patroninformation->{'borrowernumber'},'W' );
494 my $nowaiting = scalar @itemswaiting;
495 if ( $nowaiting > 0 ) {
497 $flaginfo{'message'} = "Reserved items available";
498 $flaginfo{'itemlist'} = \@itemswaiting;
499 $flags{'WAITING'} = \%flaginfo;
507 $borrower = &GetMember(%information);
509 Retrieve the first patron record meeting on criteria listed in the
510 C<%information> hash, which should contain one or more
511 pairs of borrowers column names and values, e.g.,
513 $borrower = GetMember(borrowernumber => id);
515 C<&GetBorrower> returns a reference-to-hash whose keys are the fields of
516 the C<borrowers> table in the Koha database.
518 FIXME: GetMember() is used throughout the code as a lookup
519 on a unique key such as the borrowernumber, but this meaning is not
520 enforced in the routine itself.
526 my ( %information ) = @_;
527 if (exists $information{borrowernumber} && !defined $information{borrowernumber}) {
528 #passing mysql's kohaadmin?? Makes no sense as a query
531 my $dbh = C4::Context->dbh;
533 q{SELECT borrowers.*, categories.category_type, categories.description
535 LEFT JOIN categories on borrowers.categorycode=categories.categorycode WHERE };
538 for (keys %information ) {
546 if (defined $information{$_}) {
548 push @values, $information{$_};
551 $select .= "$_ IS NULL";
554 $debug && warn $select, " ",values %information;
555 my $sth = $dbh->prepare("$select");
556 $sth->execute(map{$information{$_}} keys %information);
557 my $data = $sth->fetchall_arrayref({});
558 #FIXME interface to this routine now allows generation of a result set
559 #so whole array should be returned but bowhere in the current code expects this
567 =head2 GetMemberRelatives
569 @borrowernumbers = GetMemberRelatives($borrowernumber);
571 C<GetMemberRelatives> returns a borrowersnumber's list of guarantor/guarantees of the member given in parameter
574 sub GetMemberRelatives {
575 my $borrowernumber = shift;
576 my $dbh = C4::Context->dbh;
580 my $query = "SELECT guarantorid FROM borrowers WHERE borrowernumber=?";
581 my $sth = $dbh->prepare($query);
582 $sth->execute($borrowernumber);
583 my $data = $sth->fetchrow_arrayref();
584 push @glist, $data->[0] if $data->[0];
585 my $guarantor = $data->[0] ? $data->[0] : undef;
588 $query = "SELECT borrowernumber FROM borrowers WHERE guarantorid=?";
589 $sth = $dbh->prepare($query);
590 $sth->execute($borrowernumber);
591 while ($data = $sth->fetchrow_arrayref()) {
592 push @glist, $data->[0];
595 # Getting sibling guarantees
597 $query = "SELECT borrowernumber FROM borrowers WHERE guarantorid=?";
598 $sth = $dbh->prepare($query);
599 $sth->execute($guarantor);
600 while ($data = $sth->fetchrow_arrayref()) {
601 push @glist, $data->[0] if ($data->[0] != $borrowernumber);
608 =head2 IsMemberBlocked
610 my ($block_status, $count) = IsMemberBlocked( $borrowernumber );
612 Returns whether a patron has overdue items that may result
613 in a block or whether the patron has active fine days
614 that would block circulation privileges.
616 C<$block_status> can have the following values:
618 1 if the patron has outstanding fine days, in which case C<$count> is the number of them
620 -1 if the patron has overdue items, in which case C<$count> is the number of them
622 0 if the patron has no overdue items or outstanding fine days, in which case C<$count> is 0
624 Outstanding fine days are checked before current overdue items
627 FIXME: this needs to be split into two functions; a potential block
628 based on the number of current overdue items could be orthogonal
629 to a block based on whether the patron has any fine days accrued.
633 sub IsMemberBlocked {
634 my $borrowernumber = shift;
635 my $dbh = C4::Context->dbh;
637 my $blockeddate = CheckBorrowerDebarred($borrowernumber);
639 return ( 1, $blockeddate ) if $blockeddate;
641 # if he have late issues
642 my $sth = $dbh->prepare(
643 "SELECT COUNT(*) as latedocs
645 WHERE borrowernumber = ?
646 AND date_due < now()"
648 $sth->execute($borrowernumber);
649 my $latedocs = $sth->fetchrow_hashref->{'latedocs'};
651 return ( -1, $latedocs ) if $latedocs > 0;
656 =head2 GetMemberIssuesAndFines
658 ($overdue_count, $issue_count, $total_fines) = &GetMemberIssuesAndFines($borrowernumber);
660 Returns aggregate data about items borrowed by the patron with the
661 given borrowernumber.
663 C<&GetMemberIssuesAndFines> returns a three-element array. C<$overdue_count> is the
664 number of overdue items the patron currently has borrowed. C<$issue_count> is the
665 number of books the patron currently has borrowed. C<$total_fines> is
666 the total fine currently due by the borrower.
671 sub GetMemberIssuesAndFines {
672 my ( $borrowernumber ) = @_;
673 my $dbh = C4::Context->dbh;
674 my $query = "SELECT COUNT(*) FROM issues WHERE borrowernumber = ?";
676 $debug and warn $query."\n";
677 my $sth = $dbh->prepare($query);
678 $sth->execute($borrowernumber);
679 my $issue_count = $sth->fetchrow_arrayref->[0];
681 $sth = $dbh->prepare(
682 "SELECT COUNT(*) FROM issues
683 WHERE borrowernumber = ?
684 AND date_due < now()"
686 $sth->execute($borrowernumber);
687 my $overdue_count = $sth->fetchrow_arrayref->[0];
689 $sth = $dbh->prepare("SELECT SUM(amountoutstanding) FROM accountlines WHERE borrowernumber = ?");
690 $sth->execute($borrowernumber);
691 my $total_fines = $sth->fetchrow_arrayref->[0];
693 return ($overdue_count, $issue_count, $total_fines);
697 return @{C4::Context->dbh->selectcol_arrayref("SHOW columns from borrowers")};
702 my $success = ModMember(borrowernumber => $borrowernumber,
703 [ field => value ]... );
705 Modify borrower's data. All date fields should ALREADY be in ISO format.
708 true on success, or false on failure
714 # test to know if you must update or not the borrower password
715 if (exists $data{password}) {
716 if ($data{password} eq '****' or $data{password} eq '') {
717 delete $data{password};
719 $data{password} = md5_base64($data{password});
722 my $execute_success=UpdateInTable("borrowers",\%data);
723 if ($execute_success) { # only proceed if the update was a success
724 # ok if its an adult (type) it may have borrowers that depend on it as a guarantor
725 # so when we update information for an adult we should check for guarantees and update the relevant part
726 # of their records, ie addresses and phone numbers
727 my $borrowercategory= GetBorrowercategory( $data{'category_type'} );
728 if ( exists $borrowercategory->{'category_type'} && $borrowercategory->{'category_type'} eq ('A' || 'S') ) {
729 # is adult check guarantees;
730 UpdateGuarantees(%data);
732 logaction("MEMBERS", "MODIFY", $data{'borrowernumber'}, "UPDATE (executed w/ arg: $data{'borrowernumber'})") if C4::Context->preference("BorrowersLog");
734 return $execute_success;
740 $borrowernumber = &AddMember(%borrower);
742 insert new borrower into table
743 Returns the borrowernumber upon success
745 Returns as undef upon any db error without further processing
752 my $dbh = C4::Context->dbh;
753 # generate a proper login if none provided
754 $data{'userid'} = Generate_Userid($data{'borrowernumber'}, $data{'firstname'}, $data{'surname'}) if $data{'userid'} eq '';
755 # create a disabled account if no password provided
756 $data{'password'} = ($data{'password'})? md5_base64($data{'password'}) : '!';
757 $data{'borrowernumber'}=InsertInTable("borrowers",\%data);
758 # mysql_insertid is probably bad. not necessarily accurate and mysql-specific at best.
759 logaction("MEMBERS", "CREATE", $data{'borrowernumber'}, "") if C4::Context->preference("BorrowersLog");
761 # check for enrollment fee & add it if needed
762 my $sth = $dbh->prepare("SELECT enrolmentfee FROM categories WHERE categorycode=?");
763 $sth->execute($data{'categorycode'});
764 my ($enrolmentfee) = $sth->fetchrow;
766 warn sprintf('Database returned the following error: %s', $sth->errstr);
769 if ($enrolmentfee && $enrolmentfee > 0) {
770 # insert fee in patron debts
771 manualinvoice($data{'borrowernumber'}, '', '', 'A', $enrolmentfee);
774 return $data{'borrowernumber'};
779 my ($uid,$member) = @_;
780 my $dbh = C4::Context->dbh;
781 # Make sure the userid chosen is unique and not theirs if non-empty. If it is not,
782 # Then we need to tell the user and have them create a new one.
785 "SELECT * FROM borrowers WHERE userid=? AND borrowernumber != ?");
786 $sth->execute( $uid, $member );
787 if ( ( $uid ne '' ) && ( my $row = $sth->fetchrow_hashref ) ) {
795 sub Generate_Userid {
796 my ($borrowernumber, $firstname, $surname) = @_;
800 $firstname =~ s/[[:digit:][:space:][:blank:][:punct:][:cntrl:]]//g;
801 $surname =~ s/[[:digit:][:space:][:blank:][:punct:][:cntrl:]]//g;
802 $newuid = lc(($firstname)? "$firstname.$surname" : $surname);
803 $newuid .= $offset unless $offset == 0;
806 } while (!Check_Userid($newuid,$borrowernumber));
812 my ( $uid, $member, $digest ) = @_;
813 my $dbh = C4::Context->dbh;
815 #Make sure the userid chosen is unique and not theirs if non-empty. If it is not,
816 #Then we need to tell the user and have them create a new one.
820 "SELECT * FROM borrowers WHERE userid=? AND borrowernumber != ?");
821 $sth->execute( $uid, $member );
822 if ( ( $uid ne '' ) && ( my $row = $sth->fetchrow_hashref ) ) {
826 #Everything is good so we can update the information.
829 "update borrowers set userid=?, password=? where borrowernumber=?");
830 $sth->execute( $uid, $digest, $member );
834 logaction("MEMBERS", "CHANGE PASS", $member, "") if C4::Context->preference("BorrowersLog");
840 =head2 fixup_cardnumber
842 Warning: The caller is responsible for locking the members table in write
843 mode, to avoid database corruption.
847 use vars qw( @weightings );
848 my @weightings = ( 8, 4, 6, 3, 5, 2, 1 );
850 sub fixup_cardnumber {
851 my ($cardnumber) = @_;
852 my $autonumber_members = C4::Context->boolean_preference('autoMemberNum') || 0;
854 # Find out whether member numbers should be generated
855 # automatically. Should be either "1" or something else.
856 # Defaults to "0", which is interpreted as "no".
858 # if ($cardnumber !~ /\S/ && $autonumber_members) {
859 ($autonumber_members) or return $cardnumber;
860 my $checkdigit = C4::Context->preference('checkdigit');
861 my $dbh = C4::Context->dbh;
862 if ( $checkdigit and $checkdigit eq 'katipo' ) {
864 # if checkdigit is selected, calculate katipo-style cardnumber.
865 # otherwise, just use the max()
866 # purpose: generate checksum'd member numbers.
867 # We'll assume we just got the max value of digits 2-8 of member #'s
868 # from the database and our job is to increment that by one,
869 # determine the 1st and 9th digits and return the full string.
870 my $sth = $dbh->prepare(
871 "select max(substring(borrowers.cardnumber,2,7)) as new_num from borrowers"
874 my $data = $sth->fetchrow_hashref;
875 $cardnumber = $data->{new_num};
876 if ( !$cardnumber ) { # If DB has no values,
877 $cardnumber = 1000000; # start at 1000000
883 for ( my $i = 0 ; $i < 8 ; $i += 1 ) {
884 # read weightings, left to right, 1 char at a time
885 my $temp1 = $weightings[$i];
887 # sequence left to right, 1 char at a time
888 my $temp2 = substr( $cardnumber, $i, 1 );
890 # mult each char 1-7 by its corresponding weighting
891 $sum += $temp1 * $temp2;
894 my $rem = ( $sum % 11 );
895 $rem = 'X' if $rem == 10;
897 return "V$cardnumber$rem";
900 # MODIFIED BY JF: mysql4.1 allows casting as an integer, which is probably
901 # better. I'll leave the original in in case it needs to be changed for you
902 # my $sth=$dbh->prepare("select max(borrowers.cardnumber) from borrowers");
903 my $sth = $dbh->prepare(
904 "select max(cast(cardnumber as signed)) from borrowers"
907 my ($result) = $sth->fetchrow;
910 return $cardnumber; # just here as a fallback/reminder
915 ($num_children, $children_arrayref) = &GetGuarantees($parent_borrno);
916 $child0_cardno = $children_arrayref->[0]{"cardnumber"};
917 $child0_borrno = $children_arrayref->[0]{"borrowernumber"};
919 C<&GetGuarantees> takes a borrower number (e.g., that of a patron
920 with children) and looks up the borrowers who are guaranteed by that
921 borrower (i.e., the patron's children).
923 C<&GetGuarantees> returns two values: an integer giving the number of
924 borrowers guaranteed by C<$parent_borrno>, and a reference to an array
925 of references to hash, which gives the actual results.
931 my ($borrowernumber) = @_;
932 my $dbh = C4::Context->dbh;
935 "select cardnumber,borrowernumber, firstname, surname from borrowers where guarantorid=?"
937 $sth->execute($borrowernumber);
940 my $data = $sth->fetchall_arrayref({});
941 return ( scalar(@$data), $data );
944 =head2 UpdateGuarantees
946 &UpdateGuarantees($parent_borrno);
949 C<&UpdateGuarantees> borrower data for an adult and updates all the guarantees
950 with the modified information
955 sub UpdateGuarantees {
957 my $dbh = C4::Context->dbh;
958 my ( $count, $guarantees ) = GetGuarantees( $data{'borrowernumber'} );
959 foreach my $guarantee (@$guarantees){
960 my $guaquery = qq|UPDATE borrowers
961 SET address=?,fax=?,B_city=?,mobile=?,city=?,phone=?
962 WHERE borrowernumber=?
964 my $sth = $dbh->prepare($guaquery);
965 $sth->execute($data{'address'},$data{'fax'},$data{'B_city'},$data{'mobile'},$data{'city'},$data{'phone'},$guarantee->{'borrowernumber'});
968 =head2 GetPendingIssues
970 my $issues = &GetPendingIssues(@borrowernumber);
972 Looks up what the patron with the given borrowernumber has borrowed.
974 C<&GetPendingIssues> returns a
975 reference-to-array where each element is a reference-to-hash; the
976 keys are the fields from the C<issues>, C<biblio>, and C<items> tables.
977 The keys include C<biblioitems> fields except marc and marcxml.
982 sub GetPendingIssues {
983 my @borrowernumbers = @_;
985 unless (@borrowernumbers ) { # return a ref_to_array
986 return \@borrowernumbers; # to not cause surprise to caller
989 # Borrowers part of the query
991 for (my $i = 0; $i < @borrowernumbers; $i++) {
992 $bquery .= ' issues.borrowernumber = ?';
993 if ($i < $#borrowernumbers ) {
998 # must avoid biblioitems.* to prevent large marc and marcxml fields from killing performance
999 # FIXME: namespace collision: each table has "timestamp" fields. Which one is "timestamp" ?
1000 # FIXME: circ/ciculation.pl tries to sort by timestamp!
1001 # FIXME: C4::Print::printslip tries to sort by timestamp!
1002 # FIXME: namespace collision: other collisions possible.
1003 # FIXME: most of this data isn't really being used by callers.
1010 biblioitems.itemtype,
1013 biblioitems.publicationyear,
1014 biblioitems.publishercode,
1015 biblioitems.volumedate,
1016 biblioitems.volumedesc,
1019 borrowers.firstname,
1021 borrowers.cardnumber,
1022 issues.timestamp AS timestamp,
1023 issues.renewals AS renewals,
1024 issues.borrowernumber AS borrowernumber,
1025 items.renewals AS totalrenewals
1027 LEFT JOIN items ON items.itemnumber = issues.itemnumber
1028 LEFT JOIN biblio ON items.biblionumber = biblio.biblionumber
1029 LEFT JOIN biblioitems ON items.biblioitemnumber = biblioitems.biblioitemnumber
1030 LEFT JOIN borrowers ON issues.borrowernumber = borrowers.borrowernumber
1033 ORDER BY issues.issuedate"
1036 my $sth = C4::Context->dbh->prepare($query);
1037 $sth->execute(@borrowernumbers);
1038 my $data = $sth->fetchall_arrayref({});
1039 my $tz = C4::Context->tz();
1040 my $today = DateTime->now( time_zone => $tz);
1041 foreach (@{$data}) {
1042 if ($_->{issuedate}) {
1043 $_->{issuedate} = dt_from_string($_->{issuedate}, 'sql');
1045 $_->{date_due} or next;
1046 $_->{date_due} = DateTime::Format::DateParse->parse_datetime($_->{date_due}, $tz->name());
1047 if ( DateTime->compare($_->{date_due}, $today) == -1 ) {
1056 $issues = &GetAllIssues($borrowernumber, $sortkey, $limit);
1058 Looks up what the patron with the given borrowernumber has borrowed,
1059 and sorts the results.
1061 C<$sortkey> is the name of a field on which to sort the results. This
1062 should be the name of a field in the C<issues>, C<biblio>,
1063 C<biblioitems>, or C<items> table in the Koha database.
1065 C<$limit> is the maximum number of results to return.
1067 C<&GetAllIssues> an arrayref, C<$issues>, of hashrefs, the keys of which
1068 are the fields from the C<issues>, C<biblio>, C<biblioitems>, and
1069 C<items> tables of the Koha database.
1075 my ( $borrowernumber, $order, $limit ) = @_;
1077 #FIXME: sanity-check order and limit
1078 my $dbh = C4::Context->dbh;
1080 "SELECT *, issues.timestamp as issuestimestamp, issues.renewals AS renewals,items.renewals AS totalrenewals,items.timestamp AS itemstimestamp
1082 LEFT JOIN items on items.itemnumber=issues.itemnumber
1083 LEFT JOIN biblio ON items.biblionumber=biblio.biblionumber
1084 LEFT JOIN biblioitems ON items.biblioitemnumber=biblioitems.biblioitemnumber
1085 WHERE borrowernumber=?
1087 SELECT *, old_issues.timestamp as issuestimestamp, old_issues.renewals AS renewals,items.renewals AS totalrenewals,items.timestamp AS itemstimestamp
1089 LEFT JOIN items on items.itemnumber=old_issues.itemnumber
1090 LEFT JOIN biblio ON items.biblionumber=biblio.biblionumber
1091 LEFT JOIN biblioitems ON items.biblioitemnumber=biblioitems.biblioitemnumber
1092 WHERE borrowernumber=? AND old_issues.itemnumber IS NOT NULL
1094 if ( $limit != 0 ) {
1095 $query .= " limit $limit";
1098 my $sth = $dbh->prepare($query);
1099 $sth->execute($borrowernumber, $borrowernumber);
1102 while ( my $data = $sth->fetchrow_hashref ) {
1103 push @result, $data;
1110 =head2 GetMemberAccountRecords
1112 ($total, $acctlines, $count) = &GetMemberAccountRecords($borrowernumber);
1114 Looks up accounting data for the patron with the given borrowernumber.
1116 C<&GetMemberAccountRecords> returns a three-element array. C<$acctlines> is a
1117 reference-to-array, where each element is a reference-to-hash; the
1118 keys are the fields of the C<accountlines> table in the Koha database.
1119 C<$count> is the number of elements in C<$acctlines>. C<$total> is the
1120 total amount outstanding for all of the account lines.
1125 sub GetMemberAccountRecords {
1126 my ($borrowernumber,$date) = @_;
1127 my $dbh = C4::Context->dbh;
1133 WHERE borrowernumber=?);
1134 my @bind = ($borrowernumber);
1135 if ($date && $date ne ''){
1136 $strsth.=" AND date < ? ";
1139 $strsth.=" ORDER BY date desc,timestamp DESC";
1140 my $sth= $dbh->prepare( $strsth );
1141 $sth->execute( @bind );
1143 while ( my $data = $sth->fetchrow_hashref ) {
1144 if ( $data->{itemnumber} ) {
1145 my $biblio = GetBiblioFromItemNumber( $data->{itemnumber} );
1146 $data->{biblionumber} = $biblio->{biblionumber};
1147 $data->{title} = $biblio->{title};
1149 $acctlines[$numlines] = $data;
1151 $total += int(1000 * $data->{'amountoutstanding'}); # convert float to integer to avoid round-off errors
1154 return ( $total, \@acctlines,$numlines);
1157 =head2 GetBorNotifyAcctRecord
1159 ($total, $acctlines, $count) = &GetBorNotifyAcctRecord($params,$notifyid);
1161 Looks up accounting data for the patron with the given borrowernumber per file number.
1163 C<&GetBorNotifyAcctRecord> returns a three-element array. C<$acctlines> is a
1164 reference-to-array, where each element is a reference-to-hash; the
1165 keys are the fields of the C<accountlines> table in the Koha database.
1166 C<$count> is the number of elements in C<$acctlines>. C<$total> is the
1167 total amount outstanding for all of the account lines.
1171 sub GetBorNotifyAcctRecord {
1172 my ( $borrowernumber, $notifyid ) = @_;
1173 my $dbh = C4::Context->dbh;
1176 my $sth = $dbh->prepare(
1179 WHERE borrowernumber=?
1181 AND amountoutstanding != '0'
1182 ORDER BY notify_id,accounttype
1185 $sth->execute( $borrowernumber, $notifyid );
1187 while ( my $data = $sth->fetchrow_hashref ) {
1188 $acctlines[$numlines] = $data;
1190 $total += int(100 * $data->{'amountoutstanding'});
1193 return ( $total, \@acctlines, $numlines );
1196 =head2 checkuniquemember (OUEST-PROVENCE)
1198 ($result,$categorycode) = &checkuniquemember($collectivity,$surname,$firstname,$dateofbirth);
1200 Checks that a member exists or not in the database.
1202 C<&result> is nonzero (=exist) or 0 (=does not exist)
1203 C<&categorycode> is from categorycode table
1204 C<&collectivity> is 1 (= we add a collectivity) or 0 (= we add a physical member)
1205 C<&surname> is the surname
1206 C<&firstname> is the firstname (only if collectivity=0)
1207 C<&dateofbirth> is the date of birth in ISO format (only if collectivity=0)
1211 # FIXME: This function is not legitimate. Multiple patrons might have the same first/last name and birthdate.
1212 # This is especially true since first name is not even a required field.
1214 sub checkuniquemember {
1215 my ( $collectivity, $surname, $firstname, $dateofbirth ) = @_;
1216 my $dbh = C4::Context->dbh;
1217 my $request = ($collectivity) ?
1218 "SELECT borrowernumber,categorycode FROM borrowers WHERE surname=? " :
1220 "SELECT borrowernumber,categorycode FROM borrowers WHERE surname=? and firstname=? and dateofbirth=?" :
1221 "SELECT borrowernumber,categorycode FROM borrowers WHERE surname=? and firstname=?";
1222 my $sth = $dbh->prepare($request);
1223 if ($collectivity) {
1224 $sth->execute( uc($surname) );
1225 } elsif($dateofbirth){
1226 $sth->execute( uc($surname), ucfirst($firstname), $dateofbirth );
1228 $sth->execute( uc($surname), ucfirst($firstname));
1230 my @data = $sth->fetchrow;
1231 ( $data[0] ) and return $data[0], $data[1];
1235 sub checkcardnumber {
1236 my ($cardnumber,$borrowernumber) = @_;
1237 # If cardnumber is null, we assume they're allowed.
1238 return 0 if !defined($cardnumber);
1239 my $dbh = C4::Context->dbh;
1240 my $query = "SELECT * FROM borrowers WHERE cardnumber=?";
1241 $query .= " AND borrowernumber <> ?" if ($borrowernumber);
1242 my $sth = $dbh->prepare($query);
1243 if ($borrowernumber) {
1244 $sth->execute($cardnumber,$borrowernumber);
1246 $sth->execute($cardnumber);
1248 if (my $data= $sth->fetchrow_hashref()){
1257 =head2 getzipnamecity (OUEST-PROVENCE)
1259 take all info from table city for the fields city and zip
1260 check for the name and the zip code of the city selected
1264 sub getzipnamecity {
1266 my $dbh = C4::Context->dbh;
1269 "select city_name,city_state,city_zipcode,city_country from cities where cityid=? ");
1270 $sth->execute($cityid);
1271 my @data = $sth->fetchrow;
1272 return $data[0], $data[1], $data[2], $data[3];
1276 =head2 getdcity (OUEST-PROVENCE)
1278 recover cityid with city_name condition
1283 my ($city_name) = @_;
1284 my $dbh = C4::Context->dbh;
1285 my $sth = $dbh->prepare("select cityid from cities where city_name=? ");
1286 $sth->execute($city_name);
1287 my $data = $sth->fetchrow;
1291 =head2 GetFirstValidEmailAddress
1293 $email = GetFirstValidEmailAddress($borrowernumber);
1295 Return the first valid email address for a borrower, given the borrowernumber. For now, the order
1296 is defined as email, emailpro, B_email. Returns the empty string if the borrower has no email
1301 sub GetFirstValidEmailAddress {
1302 my $borrowernumber = shift;
1303 my $dbh = C4::Context->dbh;
1304 my $sth = $dbh->prepare( "SELECT email, emailpro, B_email FROM borrowers where borrowernumber = ? ");
1305 $sth->execute( $borrowernumber );
1306 my $data = $sth->fetchrow_hashref;
1308 if ($data->{'email'}) {
1309 return $data->{'email'};
1310 } elsif ($data->{'emailpro'}) {
1311 return $data->{'emailpro'};
1312 } elsif ($data->{'B_email'}) {
1313 return $data->{'B_email'};
1319 =head2 GetExpiryDate
1321 $expirydate = GetExpiryDate($categorycode, $dateenrolled);
1323 Calculate expiry date given a categorycode and starting date. Date argument must be in ISO format.
1324 Return date is also in ISO format.
1329 my ( $categorycode, $dateenrolled ) = @_;
1331 if ($categorycode) {
1332 my $dbh = C4::Context->dbh;
1333 my $sth = $dbh->prepare("SELECT enrolmentperiod,enrolmentperioddate FROM categories WHERE categorycode=?");
1334 $sth->execute($categorycode);
1335 $enrolments = $sth->fetchrow_hashref;
1337 # die "GetExpiryDate: for enrollmentperiod $enrolmentperiod (category '$categorycode') starting $dateenrolled.\n";
1338 my @date = split (/-/,$dateenrolled);
1339 if($enrolments->{enrolmentperiod}){
1340 return sprintf("%04d-%02d-%02d", Add_Delta_YM(@date,0,$enrolments->{enrolmentperiod}));
1342 return $enrolments->{enrolmentperioddate};
1346 =head2 checkuserpassword (OUEST-PROVENCE)
1348 check for the password and login are not used
1349 return the number of record
1350 0=> NOT USED 1=> USED
1354 sub checkuserpassword {
1355 my ( $borrowernumber, $userid, $password ) = @_;
1356 $password = md5_base64($password);
1357 my $dbh = C4::Context->dbh;
1360 "Select count(*) from borrowers where borrowernumber !=? and userid =? and password=? "
1362 $sth->execute( $borrowernumber, $userid, $password );
1363 my $number_rows = $sth->fetchrow;
1364 return $number_rows;
1368 =head2 GetborCatFromCatType
1370 ($codes_arrayref, $labels_hashref) = &GetborCatFromCatType();
1372 Looks up the different types of borrowers in the database. Returns two
1373 elements: a reference-to-array, which lists the borrower category
1374 codes, and a reference-to-hash, which maps the borrower category codes
1375 to category descriptions.
1380 sub GetborCatFromCatType {
1381 my ( $category_type, $action ) = @_;
1382 # FIXME - This API seems both limited and dangerous.
1383 my $dbh = C4::Context->dbh;
1384 my $request = qq| SELECT categorycode,description
1387 ORDER BY categorycode|;
1388 my $sth = $dbh->prepare($request);
1390 $sth->execute($category_type);
1399 while ( my $data = $sth->fetchrow_hashref ) {
1400 push @codes, $data->{'categorycode'};
1401 $labels{ $data->{'categorycode'} } = $data->{'description'};
1403 return ( \@codes, \%labels );
1406 =head2 GetBorrowercategory
1408 $hashref = &GetBorrowercategory($categorycode);
1410 Given the borrower's category code, the function returns the corresponding
1411 data hashref for a comprehensive information display.
1415 sub GetBorrowercategory {
1417 my $dbh = C4::Context->dbh;
1421 "SELECT description,dateofbirthrequired,upperagelimit,category_type
1423 WHERE categorycode = ?"
1425 $sth->execute($catcode);
1427 $sth->fetchrow_hashref;
1431 } # sub getborrowercategory
1434 =head2 GetBorrowerCategorycode
1436 $categorycode = &GetBorrowerCategoryCode( $borrowernumber );
1438 Given the borrowernumber, the function returns the corresponding categorycode
1441 sub GetBorrowerCategorycode {
1442 my ( $borrowernumber ) = @_;
1443 my $dbh = C4::Context->dbh;
1444 my $sth = $dbh->prepare( qq{
1447 WHERE borrowernumber = ?
1449 $sth->execute( $borrowernumber );
1450 return $sth->fetchrow;
1453 =head2 GetBorrowercategoryList
1455 $arrayref_hashref = &GetBorrowercategoryList;
1456 If no category code provided, the function returns all the categories.
1460 sub GetBorrowercategoryList {
1461 my $dbh = C4::Context->dbh;
1466 ORDER BY description"
1470 $sth->fetchall_arrayref({});
1472 } # sub getborrowercategory
1474 =head2 ethnicitycategories
1476 ($codes_arrayref, $labels_hashref) = ðnicitycategories();
1478 Looks up the different ethnic types in the database. Returns two
1479 elements: a reference-to-array, which lists the ethnicity codes, and a
1480 reference-to-hash, which maps the ethnicity codes to ethnicity
1487 sub ethnicitycategories {
1488 my $dbh = C4::Context->dbh;
1489 my $sth = $dbh->prepare("Select code,name from ethnicity order by name");
1493 while ( my $data = $sth->fetchrow_hashref ) {
1494 push @codes, $data->{'code'};
1495 $labels{ $data->{'code'} } = $data->{'name'};
1497 return ( \@codes, \%labels );
1502 $ethn_name = &fixEthnicity($ethn_code);
1504 Takes an ethnicity code (e.g., "european" or "pi") and returns the
1505 corresponding descriptive name from the C<ethnicity> table in the
1506 Koha database ("European" or "Pacific Islander").
1513 my $ethnicity = shift;
1514 return unless $ethnicity;
1515 my $dbh = C4::Context->dbh;
1516 my $sth = $dbh->prepare("Select name from ethnicity where code = ?");
1517 $sth->execute($ethnicity);
1518 my $data = $sth->fetchrow_hashref;
1519 return $data->{'name'};
1520 } # sub fixEthnicity
1524 $dateofbirth,$date = &GetAge($date);
1526 this function return the borrowers age with the value of dateofbirth
1532 my ( $date, $date_ref ) = @_;
1534 if ( not defined $date_ref ) {
1535 $date_ref = sprintf( '%04d-%02d-%02d', Today() );
1538 my ( $year1, $month1, $day1 ) = split /-/, $date;
1539 my ( $year2, $month2, $day2 ) = split /-/, $date_ref;
1541 my $age = $year2 - $year1;
1542 if ( $month1 . $day1 > $month2 . $day2 ) {
1549 =head2 get_institutions
1551 $insitutions = get_institutions();
1553 Just returns a list of all the borrowers of type I, borrownumber and name
1558 sub get_institutions {
1559 my $dbh = C4::Context->dbh();
1562 "SELECT borrowernumber,surname FROM borrowers WHERE categorycode=? ORDER BY surname"
1566 while ( my $data = $sth->fetchrow_hashref() ) {
1567 $orgs{ $data->{'borrowernumber'} } = $data;
1571 } # sub get_institutions
1573 =head2 add_member_orgs
1575 add_member_orgs($borrowernumber,$borrowernumbers);
1577 Takes a borrowernumber and a list of other borrowernumbers and inserts them into the borrowers_to_borrowers table
1582 sub add_member_orgs {
1583 my ( $borrowernumber, $otherborrowers ) = @_;
1584 my $dbh = C4::Context->dbh();
1586 "INSERT INTO borrowers_to_borrowers (borrower1,borrower2) VALUES (?,?)";
1587 my $sth = $dbh->prepare($query);
1588 foreach my $otherborrowernumber (@$otherborrowers) {
1589 $sth->execute( $borrowernumber, $otherborrowernumber );
1592 } # sub add_member_orgs
1596 $cityarrayref = GetCities();
1598 Returns an array_ref of the entries in the cities table
1599 If there are entries in the table an empty row is returned
1600 This is currently only used to populate a popup in memberentry
1606 my $dbh = C4::Context->dbh;
1607 my $city_arr = $dbh->selectall_arrayref(
1608 q|SELECT cityid,city_zipcode,city_name,city_state,city_country FROM cities ORDER BY city_name|,
1610 if ( @{$city_arr} ) {
1611 unshift @{$city_arr}, {
1612 city_zipcode => q{},
1616 city_country => q{},
1623 =head2 GetSortDetails (OUEST-PROVENCE)
1625 ($lib) = &GetSortDetails($category,$sortvalue);
1627 Returns the authorized value details
1628 C<&$lib>return value of authorized value details
1629 C<&$sortvalue>this is the value of authorized value
1630 C<&$category>this is the value of authorized value category
1634 sub GetSortDetails {
1635 my ( $category, $sortvalue ) = @_;
1636 my $dbh = C4::Context->dbh;
1637 my $query = qq|SELECT lib
1638 FROM authorised_values
1640 AND authorised_value=? |;
1641 my $sth = $dbh->prepare($query);
1642 $sth->execute( $category, $sortvalue );
1643 my $lib = $sth->fetchrow;
1644 return ($lib) if ($lib);
1645 return ($sortvalue) unless ($lib);
1648 =head2 MoveMemberToDeleted
1650 $result = &MoveMemberToDeleted($borrowernumber);
1652 Copy the record from borrowers to deletedborrowers table.
1656 # FIXME: should do it in one SQL statement w/ subquery
1657 # Otherwise, we should return the @data on success
1659 sub MoveMemberToDeleted {
1660 my ($member) = shift or return;
1661 my $dbh = C4::Context->dbh;
1662 my $query = qq|SELECT *
1664 WHERE borrowernumber=?|;
1665 my $sth = $dbh->prepare($query);
1666 $sth->execute($member);
1667 my @data = $sth->fetchrow_array;
1668 (@data) or return; # if we got a bad borrowernumber, there's nothing to insert
1670 $dbh->prepare( "INSERT INTO deletedborrowers VALUES ("
1671 . ( "?," x ( scalar(@data) - 1 ) )
1673 $sth->execute(@data);
1678 DelMember($borrowernumber);
1680 This function remove directly a borrower whitout writing it on deleteborrower.
1681 + Deletes reserves for the borrower
1686 my $dbh = C4::Context->dbh;
1687 my $borrowernumber = shift;
1688 #warn "in delmember with $borrowernumber";
1689 return unless $borrowernumber; # borrowernumber is mandatory.
1691 my $query = qq|DELETE
1693 WHERE borrowernumber=?|;
1694 my $sth = $dbh->prepare($query);
1695 $sth->execute($borrowernumber);
1699 WHERE borrowernumber = ?
1701 $sth = $dbh->prepare($query);
1702 $sth->execute($borrowernumber);
1703 logaction("MEMBERS", "DELETE", $borrowernumber, "") if C4::Context->preference("BorrowersLog");
1707 =head2 ExtendMemberSubscriptionTo (OUEST-PROVENCE)
1709 $date = ExtendMemberSubscriptionTo($borrowerid, $date);
1711 Extending the subscription to a given date or to the expiry date calculated on ISO date.
1716 sub ExtendMemberSubscriptionTo {
1717 my ( $borrowerid,$date) = @_;
1718 my $dbh = C4::Context->dbh;
1719 my $borrower = GetMember('borrowernumber'=>$borrowerid);
1721 $date = (C4::Context->preference('BorrowerRenewalPeriodBase') eq 'dateexpiry') ?
1722 C4::Dates->new($borrower->{'dateexpiry'}, 'iso')->output("iso") :
1723 C4::Dates->new()->output("iso");
1724 $date = GetExpiryDate( $borrower->{'categorycode'}, $date );
1726 my $sth = $dbh->do(<<EOF);
1728 SET dateexpiry='$date'
1729 WHERE borrowernumber='$borrowerid'
1731 # add enrolmentfee if needed
1732 $sth = $dbh->prepare("SELECT enrolmentfee FROM categories WHERE categorycode=?");
1733 $sth->execute($borrower->{'categorycode'});
1734 my ($enrolmentfee) = $sth->fetchrow;
1735 if ($enrolmentfee && $enrolmentfee > 0) {
1736 # insert fee in patron debts
1737 manualinvoice($borrower->{'borrowernumber'}, '', '', 'A', $enrolmentfee);
1739 logaction("MEMBERS", "RENEW", $borrower->{'borrowernumber'}, "Membership renewed")if C4::Context->preference("BorrowersLog");
1740 return $date if ($sth);
1744 =head2 GetRoadTypes (OUEST-PROVENCE)
1746 ($idroadtypearrayref, $roadttype_hashref) = &GetRoadTypes();
1748 Looks up the different road type . Returns two
1749 elements: a reference-to-array, which lists the id_roadtype
1750 codes, and a reference-to-hash, which maps the road type of the road .
1755 my $dbh = C4::Context->dbh;
1757 SELECT roadtypeid,road_type
1759 ORDER BY road_type|;
1760 my $sth = $dbh->prepare($query);
1765 # insert empty value to create a empty choice in cgi popup
1767 while ( my $data = $sth->fetchrow_hashref ) {
1769 push @id, $data->{'roadtypeid'};
1770 $roadtype{ $data->{'roadtypeid'} } = $data->{'road_type'};
1773 #test to know if the table contain some records if no the function return nothing
1780 return ( \@id, \%roadtype );
1786 =head2 GetTitles (OUEST-PROVENCE)
1788 ($borrowertitle)= &GetTitles();
1790 Looks up the different title . Returns array with all borrowers title
1795 my @borrowerTitle = split (/,|\|/,C4::Context->preference('BorrowersTitles'));
1796 unshift( @borrowerTitle, "" );
1797 my $count=@borrowerTitle;
1802 return ( \@borrowerTitle);
1806 =head2 GetPatronImage
1808 my ($imagedata, $dberror) = GetPatronImage($cardnumber);
1810 Returns the mimetype and binary image data of the image for the patron with the supplied cardnumber.
1814 sub GetPatronImage {
1815 my ($cardnumber) = @_;
1816 warn "Cardnumber passed to GetPatronImage is $cardnumber" if $debug;
1817 my $dbh = C4::Context->dbh;
1818 my $query = 'SELECT mimetype, imagefile FROM patronimage WHERE cardnumber = ?';
1819 my $sth = $dbh->prepare($query);
1820 $sth->execute($cardnumber);
1821 my $imagedata = $sth->fetchrow_hashref;
1822 warn "Database error!" if $sth->errstr;
1823 return $imagedata, $sth->errstr;
1826 =head2 PutPatronImage
1828 PutPatronImage($cardnumber, $mimetype, $imgfile);
1830 Stores patron binary image data and mimetype in database.
1831 NOTE: This function is good for updating images as well as inserting new images in the database.
1835 sub PutPatronImage {
1836 my ($cardnumber, $mimetype, $imgfile) = @_;
1837 warn "Parameters passed in: Cardnumber=$cardnumber, Mimetype=$mimetype, " . ($imgfile ? "Imagefile" : "No Imagefile") if $debug;
1838 my $dbh = C4::Context->dbh;
1839 my $query = "INSERT INTO patronimage (cardnumber, mimetype, imagefile) VALUES (?,?,?) ON DUPLICATE KEY UPDATE imagefile = ?;";
1840 my $sth = $dbh->prepare($query);
1841 $sth->execute($cardnumber,$mimetype,$imgfile,$imgfile);
1842 warn "Error returned inserting $cardnumber.$mimetype." if $sth->errstr;
1843 return $sth->errstr;
1846 =head2 RmPatronImage
1848 my ($dberror) = RmPatronImage($cardnumber);
1850 Removes the image for the patron with the supplied cardnumber.
1855 my ($cardnumber) = @_;
1856 warn "Cardnumber passed to GetPatronImage is $cardnumber" if $debug;
1857 my $dbh = C4::Context->dbh;
1858 my $query = "DELETE FROM patronimage WHERE cardnumber = ?;";
1859 my $sth = $dbh->prepare($query);
1860 $sth->execute($cardnumber);
1861 my $dberror = $sth->errstr;
1862 warn "Database error!" if $sth->errstr;
1866 =head2 GetHideLostItemsPreference
1868 $hidelostitemspref = &GetHideLostItemsPreference($borrowernumber);
1870 Returns the HideLostItems preference for the patron category of the supplied borrowernumber
1871 C<&$hidelostitemspref>return value of function, 0 or 1
1875 sub GetHideLostItemsPreference {
1876 my ($borrowernumber) = @_;
1877 my $dbh = C4::Context->dbh;
1878 my $query = "SELECT hidelostitems FROM borrowers,categories WHERE borrowers.categorycode = categories.categorycode AND borrowernumber = ?";
1879 my $sth = $dbh->prepare($query);
1880 $sth->execute($borrowernumber);
1881 my $hidelostitems = $sth->fetchrow;
1882 return $hidelostitems;
1885 =head2 GetRoadTypeDetails (OUEST-PROVENCE)
1887 ($roadtype) = &GetRoadTypeDetails($roadtypeid);
1889 Returns the description of roadtype
1890 C<&$roadtype>return description of road type
1891 C<&$roadtypeid>this is the value of roadtype s
1895 sub GetRoadTypeDetails {
1896 my ($roadtypeid) = @_;
1897 my $dbh = C4::Context->dbh;
1901 WHERE roadtypeid=?|;
1902 my $sth = $dbh->prepare($query);
1903 $sth->execute($roadtypeid);
1904 my $roadtype = $sth->fetchrow;
1908 =head2 GetBorrowersWhoHaveNotBorrowedSince
1910 &GetBorrowersWhoHaveNotBorrowedSince($date)
1912 this function get all borrowers who haven't borrowed since the date given on input arg.
1916 sub GetBorrowersWhoHaveNotBorrowedSince {
1917 my $filterdate = shift||POSIX::strftime("%Y-%m-%d",localtime());
1918 my $filterexpiry = shift;
1919 my $filterbranch = shift ||
1920 ((C4::Context->preference('IndependantBranches')
1921 && C4::Context->userenv
1922 && C4::Context->userenv->{flags} % 2 !=1
1923 && C4::Context->userenv->{branch})
1924 ? C4::Context->userenv->{branch}
1926 my $dbh = C4::Context->dbh;
1928 SELECT borrowers.borrowernumber,
1929 max(old_issues.timestamp) as latestissue,
1930 max(issues.timestamp) as currentissue
1932 JOIN categories USING (categorycode)
1933 LEFT JOIN old_issues USING (borrowernumber)
1934 LEFT JOIN issues USING (borrowernumber)
1935 WHERE category_type <> 'S'
1936 AND borrowernumber NOT IN (SELECT guarantorid FROM borrowers WHERE guarantorid IS NOT NULL AND guarantorid <> 0)
1939 if ($filterbranch && $filterbranch ne ""){
1940 $query.=" AND borrowers.branchcode= ?";
1941 push @query_params,$filterbranch;
1944 $query .= " AND dateexpiry < ? ";
1945 push @query_params,$filterdate;
1947 $query.=" GROUP BY borrowers.borrowernumber";
1949 $query.=" HAVING (latestissue < ? OR latestissue IS NULL)
1950 AND currentissue IS NULL";
1951 push @query_params,$filterdate;
1953 warn $query if $debug;
1954 my $sth = $dbh->prepare($query);
1955 if (scalar(@query_params)>0){
1956 $sth->execute(@query_params);
1963 while ( my $data = $sth->fetchrow_hashref ) {
1964 push @results, $data;
1969 =head2 GetBorrowersWhoHaveNeverBorrowed
1971 $results = &GetBorrowersWhoHaveNeverBorrowed
1973 This function get all borrowers who have never borrowed.
1975 I<$result> is a ref to an array which all elements are a hasref.
1979 sub GetBorrowersWhoHaveNeverBorrowed {
1980 my $filterbranch = shift ||
1981 ((C4::Context->preference('IndependantBranches')
1982 && C4::Context->userenv
1983 && C4::Context->userenv->{flags} % 2 !=1
1984 && C4::Context->userenv->{branch})
1985 ? C4::Context->userenv->{branch}
1987 my $dbh = C4::Context->dbh;
1989 SELECT borrowers.borrowernumber,max(timestamp) as latestissue
1991 LEFT JOIN issues ON borrowers.borrowernumber = issues.borrowernumber
1992 WHERE issues.borrowernumber IS NULL
1995 if ($filterbranch && $filterbranch ne ""){
1996 $query.=" AND borrowers.branchcode= ?";
1997 push @query_params,$filterbranch;
1999 warn $query if $debug;
2001 my $sth = $dbh->prepare($query);
2002 if (scalar(@query_params)>0){
2003 $sth->execute(@query_params);
2010 while ( my $data = $sth->fetchrow_hashref ) {
2011 push @results, $data;
2016 =head2 GetBorrowersWithIssuesHistoryOlderThan
2018 $results = &GetBorrowersWithIssuesHistoryOlderThan($date)
2020 this function get all borrowers who has an issue history older than I<$date> given on input arg.
2022 I<$result> is a ref to an array which all elements are a hashref.
2023 This hashref is containt the number of time this borrowers has borrowed before I<$date> and the borrowernumber.
2027 sub GetBorrowersWithIssuesHistoryOlderThan {
2028 my $dbh = C4::Context->dbh;
2029 my $date = shift ||POSIX::strftime("%Y-%m-%d",localtime());
2030 my $filterbranch = shift ||
2031 ((C4::Context->preference('IndependantBranches')
2032 && C4::Context->userenv
2033 && C4::Context->userenv->{flags} % 2 !=1
2034 && C4::Context->userenv->{branch})
2035 ? C4::Context->userenv->{branch}
2038 SELECT count(borrowernumber) as n,borrowernumber
2040 WHERE returndate < ?
2041 AND borrowernumber IS NOT NULL
2044 push @query_params, $date;
2046 $query.=" AND branchcode = ?";
2047 push @query_params, $filterbranch;
2049 $query.=" GROUP BY borrowernumber ";
2050 warn $query if $debug;
2051 my $sth = $dbh->prepare($query);
2052 $sth->execute(@query_params);
2055 while ( my $data = $sth->fetchrow_hashref ) {
2056 push @results, $data;
2061 =head2 GetBorrowersNamesAndLatestIssue
2063 $results = &GetBorrowersNamesAndLatestIssueList(@borrowernumbers)
2065 this function get borrowers Names and surnames and Issue information.
2067 I<@borrowernumbers> is an array which all elements are borrowernumbers.
2068 This hashref is containt the number of time this borrowers has borrowed before I<$date> and the borrowernumber.
2072 sub GetBorrowersNamesAndLatestIssue {
2073 my $dbh = C4::Context->dbh;
2074 my @borrowernumbers=@_;
2076 SELECT surname,lastname, phone, email,max(timestamp)
2078 LEFT JOIN issues ON borrowers.borrowernumber=issues.borrowernumber
2079 GROUP BY borrowernumber
2081 my $sth = $dbh->prepare($query);
2083 my $results = $sth->fetchall_arrayref({});
2089 my $success = DebarMember( $borrowernumber, $todate );
2091 marks a Member as debarred, and therefore unable to checkout any more
2095 true on success, false on failure
2100 my $borrowernumber = shift;
2103 return unless defined $borrowernumber;
2104 return unless $borrowernumber =~ /^\d+$/;
2107 borrowernumber => $borrowernumber,
2117 my $success = ModPrivacy( $borrowernumber, $privacy );
2119 Update the privacy of a patron.
2122 true on success, false on failure
2129 my $borrowernumber = shift;
2130 my $privacy = shift;
2131 return unless defined $borrowernumber;
2132 return unless $borrowernumber =~ /^\d+$/;
2134 return ModMember( borrowernumber => $borrowernumber,
2135 privacy => $privacy );
2140 AddMessage( $borrowernumber, $message_type, $message, $branchcode );
2142 Adds a message to the messages table for the given borrower.
2151 my ( $borrowernumber, $message_type, $message, $branchcode ) = @_;
2153 my $dbh = C4::Context->dbh;
2155 if ( ! ( $borrowernumber && $message_type && $message && $branchcode ) ) {
2159 my $query = "INSERT INTO messages ( borrowernumber, branchcode, message_type, message ) VALUES ( ?, ?, ?, ? )";
2160 my $sth = $dbh->prepare($query);
2161 $sth->execute( $borrowernumber, $branchcode, $message_type, $message );
2162 logaction("MEMBERS", "ADDCIRCMESSAGE", $borrowernumber, $message) if C4::Context->preference("BorrowersLog");
2168 GetMessages( $borrowernumber, $type );
2170 $type is message type, B for borrower, or L for Librarian.
2171 Empty type returns all messages of any type.
2173 Returns all messages for the given borrowernumber
2178 my ( $borrowernumber, $type, $branchcode ) = @_;
2184 my $dbh = C4::Context->dbh;
2187 branches.branchname,
2190 messages.branchcode LIKE '$branchcode' AS can_delete
2191 FROM messages, branches
2192 WHERE borrowernumber = ?
2193 AND message_type LIKE ?
2194 AND messages.branchcode = branches.branchcode
2195 ORDER BY message_date DESC";
2196 my $sth = $dbh->prepare($query);
2197 $sth->execute( $borrowernumber, $type ) ;
2200 while ( my $data = $sth->fetchrow_hashref ) {
2201 my $d = C4::Dates->new( $data->{message_date}, 'iso' );
2202 $data->{message_date_formatted} = $d->output;
2203 push @results, $data;
2211 GetMessagesCount( $borrowernumber, $type );
2213 $type is message type, B for borrower, or L for Librarian.
2214 Empty type returns all messages of any type.
2216 Returns the number of messages for the given borrowernumber
2220 sub GetMessagesCount {
2221 my ( $borrowernumber, $type, $branchcode ) = @_;
2227 my $dbh = C4::Context->dbh;
2229 my $query = "SELECT COUNT(*) as MsgCount FROM messages WHERE borrowernumber = ? AND message_type LIKE ?";
2230 my $sth = $dbh->prepare($query);
2231 $sth->execute( $borrowernumber, $type ) ;
2234 my $data = $sth->fetchrow_hashref;
2235 my $count = $data->{'MsgCount'};
2242 =head2 DeleteMessage
2244 DeleteMessage( $message_id );
2249 my ( $message_id ) = @_;
2251 my $dbh = C4::Context->dbh;
2252 my $query = "SELECT * FROM messages WHERE message_id = ?";
2253 my $sth = $dbh->prepare($query);
2254 $sth->execute( $message_id );
2255 my $message = $sth->fetchrow_hashref();
2257 $query = "DELETE FROM messages WHERE message_id = ?";
2258 $sth = $dbh->prepare($query);
2259 $sth->execute( $message_id );
2260 logaction("MEMBERS", "DELCIRCMESSAGE", $message->{'borrowernumber'}, $message->{'message'}) if C4::Context->preference("BorrowersLog");
2265 IssueSlip($branchcode, $borrowernumber, $quickslip)
2267 Returns letter hash ( see C4::Letters::GetPreparedLetter )
2269 $quickslip is boolean, to indicate whether we want a quick slip
2274 my ($branch, $borrowernumber, $quickslip) = @_;
2276 # return unless ( C4::Context->boolean_preference('printcirculationslips') );
2278 my $today = POSIX::strftime("%Y-%m-%d", localtime);
2280 my $issueslist = GetPendingIssues($borrowernumber);
2281 foreach my $it (@$issueslist){
2282 if ($it->{'issuedate'} eq $today) {
2285 elsif ($it->{'date_due'} le $today) {
2286 $it->{'overdue'} = 1;
2289 $it->{'date_due'}=format_date($it->{'date_due'});
2291 my @issues = sort { $b->{'timestamp'} <=> $a->{'timestamp'} } @$issueslist;
2293 my ($letter_code, %repeat);
2295 $letter_code = 'ISSUEQSLIP';
2297 'checkedout' => [ map {
2301 }, grep { $_->{'today'} } @issues ],
2305 $letter_code = 'ISSUESLIP';
2307 'checkedout' => [ map {
2311 }, grep { !$_->{'overdue'} } @issues ],
2313 'overdue' => [ map {
2317 }, grep { $_->{'overdue'} } @issues ],
2320 $_->{'timestamp'} = $_->{'newdate'};
2322 } @{ GetNewsToDisplay("slip") } ],
2326 return C4::Letters::GetPreparedLetter (
2327 module => 'circulation',
2328 letter_code => $letter_code,
2329 branchcode => $branch,
2331 'branches' => $branch,
2332 'borrowers' => $borrowernumber,
2338 =head2 GetBorrowersWithEmail
2340 ([$borrnum,$userid], ...) = GetBorrowersWithEmail('me@example.com');
2342 This gets a list of users and their basic details from their email address.
2343 As it's possible for multiple user to have the same email address, it provides
2344 you with all of them. If there is no userid for the user, there will be an
2345 C<undef> there. An empty list will be returned if there are no matches.
2349 sub GetBorrowersWithEmail {
2352 my $dbh = C4::Context->dbh;
2354 my $query = "SELECT borrowernumber, userid FROM borrowers WHERE email=?";
2355 my $sth=$dbh->prepare($query);
2356 $sth->execute($email);
2358 while (my $ref = $sth->fetch) {
2361 die "Failure searching for borrowers by email address: $sth->errstr" if $sth->err;
2366 END { } # module clean-up code here (global destructor)