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);
27 use Digest::MD5 qw(md5_base64);
28 use Date::Calc qw/Today Add_Delta_YM/;
29 use C4::Log; # logaction
34 use C4::SQLHelper qw(InsertInTable UpdateInTable SearchInTable);
35 use C4::Members::Attributes qw(SearchIdMatchingAttribute);
37 our ($VERSION,@ISA,@EXPORT,@EXPORT_OK,$debug);
41 $debug = $ENV{DEBUG} || 0;
53 &GetMemberIssuesAndFines
61 &GetFirstValidEmailAddress
74 &GetHideLostItemsPreference
77 &GetMemberAccountRecords
78 &GetBorNotifyAcctRecord
82 &GetBorrowercategoryList
84 &GetBorrowersWhoHaveNotBorrowedSince
85 &GetBorrowersWhoHaveNeverBorrowed
86 &GetBorrowersWithIssuesHistoryOlderThan
113 &ExtendMemberSubscriptionTo
131 C4::Members - Perl Module containing convenience functions for member handling
139 This module contains routines for adding, modifying and deleting members/patrons/borrowers
145 $borrowers_result_array_ref = &Search($filter,$orderby, $limit,
146 $columns_out, $search_on_fields,$searchtype);
148 Looks up patrons (borrowers) on filter. A wrapper for SearchInTable('borrowers').
150 For C<$filter>, C<$orderby>, C<$limit>, C<&columns_out>, C<&search_on_fields> and C<&searchtype>
151 refer to C4::SQLHelper:SearchInTable().
153 Special C<$filter> key '' is effectively expanded to search on surname firstname othernamescw
154 and cardnumber unless C<&search_on_fields> is defined
158 $borrowers = Search('abcd', 'cardnumber');
160 $borrowers = Search({''=>'abcd', category_type=>'I'}, 'surname');
164 sub _express_member_find {
167 # this is used by circulation everytime a new borrowers cardnumber is scanned
168 # so we can check an exact match first, if that works return, otherwise do the rest
169 my $dbh = C4::Context->dbh;
170 my $query = "SELECT borrowernumber FROM borrowers WHERE cardnumber = ?";
171 if ( my $borrowernumber = $dbh->selectrow_array($query, undef, $filter) ) {
172 return( {"borrowernumber"=>$borrowernumber} );
175 my ($search_on_fields, $searchtype);
176 if ( length($filter) == 1 ) {
177 $search_on_fields = [ qw(surname) ];
178 $searchtype = 'start_with';
180 $search_on_fields = [ qw(surname firstname othernames cardnumber) ];
181 $searchtype = 'contain';
184 return (undef, $search_on_fields, $searchtype);
188 my ( $filter, $orderby, $limit, $columns_out, $search_on_fields, $searchtype ) = @_;
193 if ( my $fr = ref $filter ) {
194 if ( $fr eq "HASH" ) {
195 if ( my $search_string = $filter->{''} ) {
196 my ($member_filter, $member_search_on_fields, $member_searchtype) = _express_member_find($search_string);
197 if ($member_filter) {
198 $filter = $member_filter;
201 $search_on_fields ||= $member_search_on_fields;
202 $searchtype ||= $member_searchtype;
207 $search_string = $filter;
211 $search_string = $filter;
212 my ($member_filter, $member_search_on_fields, $member_searchtype) = _express_member_find($search_string);
213 if ($member_filter) {
214 $filter = $member_filter;
217 $search_on_fields ||= $member_search_on_fields;
218 $searchtype ||= $member_searchtype;
222 if ( !$found_borrower && C4::Context->preference('ExtendedPatronAttributes') && $search_string ) {
223 my $matching_records = C4::Members::Attributes::SearchIdMatchingAttribute($search_string);
224 if(scalar(@$matching_records)>0) {
225 if ( my $fr = ref $filter ) {
226 if ( $fr eq "HASH" ) {
228 $filter = [ $filter ];
230 push @$filter, { %f, "borrowernumber"=>$$matching_records };
233 push @$filter, {"borrowernumber"=>$matching_records};
237 $filter = [ $filter ];
238 push @$filter, {"borrowernumber"=>$matching_records};
243 # $showallbranches was not used at the time SearchMember() was mainstreamed into Search().
244 # Mentioning for the reference
246 if ( C4::Context->preference("IndependantBranches") ) { # && !$showallbranches){
247 if ( my $userenv = C4::Context->userenv ) {
248 my $branch = $userenv->{'branch'};
249 if ( ($userenv->{flags} % 2 !=1) &&
250 $branch && $branch ne "insecure" ){
252 if (my $fr = ref $filter) {
253 if ( $fr eq "HASH" ) {
254 $filter->{branchcode} = $branch;
258 $_ = { '' => $_ } unless ref $_;
259 $_->{branchcode} = $branch;
264 $filter = { '' => $filter, branchcode => $branch };
270 if ($found_borrower) {
271 $searchtype = "exact";
273 $searchtype ||= "start_with";
275 return SearchInTable( "borrowers", $filter, $orderby, $limit, $columns_out, $search_on_fields, $searchtype );
278 =head2 GetMemberDetails
280 ($borrower) = &GetMemberDetails($borrowernumber, $cardnumber);
282 Looks up a patron and returns information about him or her. If
283 C<$borrowernumber> is true (nonzero), C<&GetMemberDetails> looks
284 up the borrower by number; otherwise, it looks up the borrower by card
287 C<$borrower> is a reference-to-hash whose keys are the fields of the
288 borrowers table in the Koha database. In addition,
289 C<$borrower-E<gt>{flags}> is a hash giving more detailed information
290 about the patron. Its keys act as flags :
292 if $borrower->{flags}->{LOST} {
293 # Patron's card was reported lost
296 If the state of a flag means that the patron should not be
297 allowed to borrow any more books, then it will have a C<noissues> key
300 See patronflags for more details.
302 C<$borrower-E<gt>{authflags}> is a hash giving more detailed information
303 about the top-level permissions flags set for the borrower. For example,
304 if a user has the "editcatalogue" permission,
305 C<$borrower-E<gt>{authflags}-E<gt>{editcatalogue}> will exist and have
310 sub GetMemberDetails {
311 my ( $borrowernumber, $cardnumber ) = @_;
312 my $dbh = C4::Context->dbh;
315 if ($borrowernumber) {
316 $sth = $dbh->prepare("SELECT borrowers.*,category_type,categories.description,reservefee,enrolmentperiod FROM borrowers LEFT JOIN categories ON borrowers.categorycode=categories.categorycode WHERE borrowernumber=?");
317 $sth->execute($borrowernumber);
319 elsif ($cardnumber) {
320 $sth = $dbh->prepare("SELECT borrowers.*,category_type,categories.description,reservefee,enrolmentperiod FROM borrowers LEFT JOIN categories ON borrowers.categorycode=categories.categorycode WHERE cardnumber=?");
321 $sth->execute($cardnumber);
326 my $borrower = $sth->fetchrow_hashref;
327 my ($amount) = GetMemberAccountRecords( $borrowernumber);
328 $borrower->{'amountoutstanding'} = $amount;
329 # FIXME - patronflags calls GetMemberAccountRecords... just have patronflags return $amount
330 my $flags = patronflags( $borrower);
333 $sth = $dbh->prepare("select bit,flag from userflags");
335 while ( my ( $bit, $flag ) = $sth->fetchrow ) {
336 if ( $borrower->{'flags'} && $borrower->{'flags'} & 2**$bit ) {
337 $accessflagshash->{$flag} = 1;
340 $borrower->{'flags'} = $flags;
341 $borrower->{'authflags'} = $accessflagshash;
343 # For the purposes of making templates easier, we'll define a
344 # 'showname' which is the alternate form the user's first name if
345 # 'other name' is defined.
346 if ($borrower->{category_type} eq 'I') {
347 $borrower->{'showname'} = $borrower->{'othernames'};
348 $borrower->{'showname'} .= " $borrower->{'firstname'}" if $borrower->{'firstname'};
350 $borrower->{'showname'} = $borrower->{'firstname'};
353 return ($borrower); #, $flags, $accessflagshash);
358 $flags = &patronflags($patron);
360 This function is not exported.
362 The following will be set where applicable:
363 $flags->{CHARGES}->{amount} Amount of debt
364 $flags->{CHARGES}->{noissues} Set if debt amount >$5.00 (or syspref noissuescharge)
365 $flags->{CHARGES}->{message} Message -- deprecated
367 $flags->{CREDITS}->{amount} Amount of credit
368 $flags->{CREDITS}->{message} Message -- deprecated
370 $flags->{ GNA } Patron has no valid address
371 $flags->{ GNA }->{noissues} Set for each GNA
372 $flags->{ GNA }->{message} "Borrower has no valid address" -- deprecated
374 $flags->{ LOST } Patron's card reported lost
375 $flags->{ LOST }->{noissues} Set for each LOST
376 $flags->{ LOST }->{message} Message -- deprecated
378 $flags->{DBARRED} Set if patron debarred, no access
379 $flags->{DBARRED}->{noissues} Set for each DBARRED
380 $flags->{DBARRED}->{message} Message -- deprecated
383 $flags->{ NOTES }->{message} The note itself. NOT deprecated
385 $flags->{ ODUES } Set if patron has overdue books.
386 $flags->{ ODUES }->{message} "Yes" -- deprecated
387 $flags->{ ODUES }->{itemlist} ref-to-array: list of overdue books
388 $flags->{ ODUES }->{itemlisttext} Text list of overdue items -- deprecated
390 $flags->{WAITING} Set if any of patron's reserves are available
391 $flags->{WAITING}->{message} Message -- deprecated
392 $flags->{WAITING}->{itemlist} ref-to-array: list of available items
396 =item C<$flags-E<gt>{ODUES}-E<gt>{itemlist}> is a reference-to-array listing the
397 overdue items. Its elements are references-to-hash, each describing an
398 overdue item. The keys are selected fields from the issues, biblio,
399 biblioitems, and items tables of the Koha database.
401 =item C<$flags-E<gt>{ODUES}-E<gt>{itemlisttext}> is a string giving a text listing of
402 the overdue items, one per line. Deprecated.
404 =item C<$flags-E<gt>{WAITING}-E<gt>{itemlist}> is a reference-to-array listing the
405 available items. Each element is a reference-to-hash whose keys are
406 fields from the reserves table of the Koha database.
410 All the "message" fields that include language generated in this function are deprecated,
411 because such strings belong properly in the display layer.
413 The "message" field that comes from the DB is OK.
417 # TODO: use {anonymous => hashes} instead of a dozen %flaginfo
418 # FIXME rename this function.
421 my ( $patroninformation) = @_;
422 my $dbh=C4::Context->dbh;
423 my ($amount) = GetMemberAccountRecords( $patroninformation->{'borrowernumber'});
426 my $noissuescharge = C4::Context->preference("noissuescharge") || 5;
427 $flaginfo{'message'} = sprintf "Patron owes \$%.02f", $amount;
428 $flaginfo{'amount'} = sprintf "%.02f", $amount;
429 if ( $amount > $noissuescharge && !C4::Context->preference("AllowFineOverride") ) {
430 $flaginfo{'noissues'} = 1;
432 $flags{'CHARGES'} = \%flaginfo;
434 elsif ( $amount < 0 ) {
436 $flaginfo{'message'} = sprintf "Patron has credit of \$%.02f", -$amount;
437 $flaginfo{'amount'} = sprintf "%.02f", $amount;
438 $flags{'CREDITS'} = \%flaginfo;
440 if ( $patroninformation->{'gonenoaddress'}
441 && $patroninformation->{'gonenoaddress'} == 1 )
444 $flaginfo{'message'} = 'Borrower has no valid address.';
445 $flaginfo{'noissues'} = 1;
446 $flags{'GNA'} = \%flaginfo;
448 if ( $patroninformation->{'lost'} && $patroninformation->{'lost'} == 1 ) {
450 $flaginfo{'message'} = 'Borrower\'s card reported lost.';
451 $flaginfo{'noissues'} = 1;
452 $flags{'LOST'} = \%flaginfo;
454 if ( $patroninformation->{'debarred'}
455 && $patroninformation->{'debarred'} == 1 )
458 $flaginfo{'message'} = 'Borrower is Debarred.';
459 $flaginfo{'noissues'} = 1;
460 $flags{'DBARRED'} = \%flaginfo;
462 if ( $patroninformation->{'borrowernotes'}
463 && $patroninformation->{'borrowernotes'} )
466 $flaginfo{'message'} = $patroninformation->{'borrowernotes'};
467 $flags{'NOTES'} = \%flaginfo;
469 my ( $odues, $itemsoverdue ) = checkoverdues($patroninformation->{'borrowernumber'});
470 if ( $odues && $odues > 0 ) {
472 $flaginfo{'message'} = "Yes";
473 $flaginfo{'itemlist'} = $itemsoverdue;
474 foreach ( sort { $a->{'date_due'} cmp $b->{'date_due'} }
477 $flaginfo{'itemlisttext'} .=
478 "$_->{'date_due'} $_->{'barcode'} $_->{'title'} \n"; # newline is display layer
480 $flags{'ODUES'} = \%flaginfo;
482 my @itemswaiting = C4::Reserves::GetReservesFromBorrowernumber( $patroninformation->{'borrowernumber'},'W' );
483 my $nowaiting = scalar @itemswaiting;
484 if ( $nowaiting > 0 ) {
486 $flaginfo{'message'} = "Reserved items available";
487 $flaginfo{'itemlist'} = \@itemswaiting;
488 $flags{'WAITING'} = \%flaginfo;
496 $borrower = &GetMember(%information);
498 Retrieve the first patron record meeting on criteria listed in the
499 C<%information> hash, which should contain one or more
500 pairs of borrowers column names and values, e.g.,
502 $borrower = GetMember(borrowernumber => id);
504 C<&GetBorrower> returns a reference-to-hash whose keys are the fields of
505 the C<borrowers> table in the Koha database.
507 FIXME: GetMember() is used throughout the code as a lookup
508 on a unique key such as the borrowernumber, but this meaning is not
509 enforced in the routine itself.
515 my ( %information ) = @_;
516 if (exists $information{borrowernumber} && !defined $information{borrowernumber}) {
517 #passing mysql's kohaadmin?? Makes no sense as a query
520 my $dbh = C4::Context->dbh;
522 q{SELECT borrowers.*, categories.category_type, categories.description
524 LEFT JOIN categories on borrowers.categorycode=categories.categorycode WHERE };
527 for (keys %information ) {
535 if (defined $information{$_}) {
537 push @values, $information{$_};
540 $select .= "$_ IS NULL";
543 $debug && warn $select, " ",values %information;
544 my $sth = $dbh->prepare("$select");
545 $sth->execute(map{$information{$_}} keys %information);
546 my $data = $sth->fetchall_arrayref({});
547 #FIXME interface to this routine now allows generation of a result set
548 #so whole array should be returned but bowhere in the current code expects this
556 =head2 GetMemberRelatives
558 @borrowernumbers = GetMemberRelatives($borrowernumber);
560 C<GetMemberRelatives> returns a borrowersnumber's list of guarantor/guarantees of the member given in parameter
563 sub GetMemberRelatives {
564 my $borrowernumber = shift;
565 my $dbh = C4::Context->dbh;
569 my $query = "SELECT guarantorid FROM borrowers WHERE borrowernumber=?";
570 my $sth = $dbh->prepare($query);
571 $sth->execute($borrowernumber);
572 my $data = $sth->fetchrow_arrayref();
573 push @glist, $data->[0] if $data->[0];
574 my $guarantor = $data->[0] if $data->[0];
577 $query = "SELECT borrowernumber FROM borrowers WHERE guarantorid=?";
578 $sth = $dbh->prepare($query);
579 $sth->execute($borrowernumber);
580 while ($data = $sth->fetchrow_arrayref()) {
581 push @glist, $data->[0];
584 # Getting sibling guarantees
586 $query = "SELECT borrowernumber FROM borrowers WHERE guarantorid=?";
587 $sth = $dbh->prepare($query);
588 $sth->execute($guarantor);
589 while ($data = $sth->fetchrow_arrayref()) {
590 push @glist, $data->[0] if ($data->[0] != $borrowernumber);
597 =head2 IsMemberBlocked
599 my ($block_status, $count) = IsMemberBlocked( $borrowernumber );
601 Returns whether a patron has overdue items that may result
602 in a block or whether the patron has active fine days
603 that would block circulation privileges.
605 C<$block_status> can have the following values:
607 1 if the patron has outstanding fine days, in which case C<$count> is the number of them
609 -1 if the patron has overdue items, in which case C<$count> is the number of them
611 0 if the patron has no overdue items or outstanding fine days, in which case C<$count> is 0
613 Outstanding fine days are checked before current overdue items
616 FIXME: this needs to be split into two functions; a potential block
617 based on the number of current overdue items could be orthogonal
618 to a block based on whether the patron has any fine days accrued.
622 sub IsMemberBlocked {
623 my $borrowernumber = shift;
624 my $dbh = C4::Context->dbh;
626 my $blockeddate = CheckBorrowerDebarred($borrowernumber);
628 return ( 1, $blockeddate ) if $blockeddate;
630 # if he have late issues
631 my $sth = $dbh->prepare(
632 "SELECT COUNT(*) as latedocs
634 WHERE borrowernumber = ?
635 AND date_due < curdate()"
637 $sth->execute($borrowernumber);
638 my $latedocs = $sth->fetchrow_hashref->{'latedocs'};
640 return ( -1, $latedocs ) if $latedocs > 0;
645 =head2 GetMemberIssuesAndFines
647 ($overdue_count, $issue_count, $total_fines) = &GetMemberIssuesAndFines($borrowernumber);
649 Returns aggregate data about items borrowed by the patron with the
650 given borrowernumber.
652 C<&GetMemberIssuesAndFines> returns a three-element array. C<$overdue_count> is the
653 number of overdue items the patron currently has borrowed. C<$issue_count> is the
654 number of books the patron currently has borrowed. C<$total_fines> is
655 the total fine currently due by the borrower.
660 sub GetMemberIssuesAndFines {
661 my ( $borrowernumber ) = @_;
662 my $dbh = C4::Context->dbh;
663 my $query = "SELECT COUNT(*) FROM issues WHERE borrowernumber = ?";
665 $debug and warn $query."\n";
666 my $sth = $dbh->prepare($query);
667 $sth->execute($borrowernumber);
668 my $issue_count = $sth->fetchrow_arrayref->[0];
670 $sth = $dbh->prepare(
671 "SELECT COUNT(*) FROM issues
672 WHERE borrowernumber = ?
673 AND date_due < curdate()"
675 $sth->execute($borrowernumber);
676 my $overdue_count = $sth->fetchrow_arrayref->[0];
678 $sth = $dbh->prepare("SELECT SUM(amountoutstanding) FROM accountlines WHERE borrowernumber = ?");
679 $sth->execute($borrowernumber);
680 my $total_fines = $sth->fetchrow_arrayref->[0];
682 return ($overdue_count, $issue_count, $total_fines);
686 return @{C4::Context->dbh->selectcol_arrayref("SHOW columns from borrowers")};
691 my $success = ModMember(borrowernumber => $borrowernumber,
692 [ field => value ]... );
694 Modify borrower's data. All date fields should ALREADY be in ISO format.
697 true on success, or false on failure
703 # test to know if you must update or not the borrower password
704 if (exists $data{password}) {
705 if ($data{password} eq '****' or $data{password} eq '') {
706 delete $data{password};
708 $data{password} = md5_base64($data{password});
711 my $execute_success=UpdateInTable("borrowers",\%data);
712 if ($execute_success) { # only proceed if the update was a success
713 # ok if its an adult (type) it may have borrowers that depend on it as a guarantor
714 # so when we update information for an adult we should check for guarantees and update the relevant part
715 # of their records, ie addresses and phone numbers
716 my $borrowercategory= GetBorrowercategory( $data{'category_type'} );
717 if ( exists $borrowercategory->{'category_type'} && $borrowercategory->{'category_type'} eq ('A' || 'S') ) {
718 # is adult check guarantees;
719 UpdateGuarantees(%data);
721 logaction("MEMBERS", "MODIFY", $data{'borrowernumber'}, "UPDATE (executed w/ arg: $data{'borrowernumber'})") if C4::Context->preference("BorrowersLog");
723 return $execute_success;
729 $borrowernumber = &AddMember(%borrower);
731 insert new borrower into table
732 Returns the borrowernumber upon success
734 Returns as undef upon any db error without further processing
741 my $dbh = C4::Context->dbh;
742 # generate a proper login if none provided
743 $data{'userid'} = Generate_Userid($data{'borrowernumber'}, $data{'firstname'}, $data{'surname'}) if $data{'userid'} eq '';
744 # create a disabled account if no password provided
745 $data{'password'} = ($data{'password'})? md5_base64($data{'password'}) : '!';
746 $data{'borrowernumber'}=InsertInTable("borrowers",\%data);
747 # mysql_insertid is probably bad. not necessarily accurate and mysql-specific at best.
748 logaction("MEMBERS", "CREATE", $data{'borrowernumber'}, "") if C4::Context->preference("BorrowersLog");
750 # check for enrollment fee & add it if needed
751 my $sth = $dbh->prepare("SELECT enrolmentfee FROM categories WHERE categorycode=?");
752 $sth->execute($data{'categorycode'});
753 my ($enrolmentfee) = $sth->fetchrow;
755 warn sprintf('Database returned the following error: %s', $sth->errstr);
758 if ($enrolmentfee && $enrolmentfee > 0) {
759 # insert fee in patron debts
760 manualinvoice($data{'borrowernumber'}, '', '', 'A', $enrolmentfee);
763 return $data{'borrowernumber'};
768 my ($uid,$member) = @_;
769 my $dbh = C4::Context->dbh;
770 # Make sure the userid chosen is unique and not theirs if non-empty. If it is not,
771 # Then we need to tell the user and have them create a new one.
774 "SELECT * FROM borrowers WHERE userid=? AND borrowernumber != ?");
775 $sth->execute( $uid, $member );
776 if ( ( $uid ne '' ) && ( my $row = $sth->fetchrow_hashref ) ) {
784 sub Generate_Userid {
785 my ($borrowernumber, $firstname, $surname) = @_;
789 $firstname =~ s/[[:digit:][:space:][:blank:][:punct:][:cntrl:]]//g;
790 $surname =~ s/[[:digit:][:space:][:blank:][:punct:][:cntrl:]]//g;
791 $newuid = lc(($firstname)? "$firstname.$surname" : $surname);
792 $newuid .= $offset unless $offset == 0;
795 } while (!Check_Userid($newuid,$borrowernumber));
801 my ( $uid, $member, $digest ) = @_;
802 my $dbh = C4::Context->dbh;
804 #Make sure the userid chosen is unique and not theirs if non-empty. If it is not,
805 #Then we need to tell the user and have them create a new one.
809 "SELECT * FROM borrowers WHERE userid=? AND borrowernumber != ?");
810 $sth->execute( $uid, $member );
811 if ( ( $uid ne '' ) && ( my $row = $sth->fetchrow_hashref ) ) {
815 #Everything is good so we can update the information.
818 "update borrowers set userid=?, password=? where borrowernumber=?");
819 $sth->execute( $uid, $digest, $member );
823 logaction("MEMBERS", "CHANGE PASS", $member, "") if C4::Context->preference("BorrowersLog");
829 =head2 fixup_cardnumber
831 Warning: The caller is responsible for locking the members table in write
832 mode, to avoid database corruption.
836 use vars qw( @weightings );
837 my @weightings = ( 8, 4, 6, 3, 5, 2, 1 );
839 sub fixup_cardnumber ($) {
840 my ($cardnumber) = @_;
841 my $autonumber_members = C4::Context->boolean_preference('autoMemberNum') || 0;
843 # Find out whether member numbers should be generated
844 # automatically. Should be either "1" or something else.
845 # Defaults to "0", which is interpreted as "no".
847 # if ($cardnumber !~ /\S/ && $autonumber_members) {
848 ($autonumber_members) or return $cardnumber;
849 my $checkdigit = C4::Context->preference('checkdigit');
850 my $dbh = C4::Context->dbh;
851 if ( $checkdigit and $checkdigit eq 'katipo' ) {
853 # if checkdigit is selected, calculate katipo-style cardnumber.
854 # otherwise, just use the max()
855 # purpose: generate checksum'd member numbers.
856 # We'll assume we just got the max value of digits 2-8 of member #'s
857 # from the database and our job is to increment that by one,
858 # determine the 1st and 9th digits and return the full string.
859 my $sth = $dbh->prepare(
860 "select max(substring(borrowers.cardnumber,2,7)) as new_num from borrowers"
863 my $data = $sth->fetchrow_hashref;
864 $cardnumber = $data->{new_num};
865 if ( !$cardnumber ) { # If DB has no values,
866 $cardnumber = 1000000; # start at 1000000
872 for ( my $i = 0 ; $i < 8 ; $i += 1 ) {
873 # read weightings, left to right, 1 char at a time
874 my $temp1 = $weightings[$i];
876 # sequence left to right, 1 char at a time
877 my $temp2 = substr( $cardnumber, $i, 1 );
879 # mult each char 1-7 by its corresponding weighting
880 $sum += $temp1 * $temp2;
883 my $rem = ( $sum % 11 );
884 $rem = 'X' if $rem == 10;
886 return "V$cardnumber$rem";
889 # MODIFIED BY JF: mysql4.1 allows casting as an integer, which is probably
890 # better. I'll leave the original in in case it needs to be changed for you
891 # my $sth=$dbh->prepare("select max(borrowers.cardnumber) from borrowers");
892 my $sth = $dbh->prepare(
893 "select max(cast(cardnumber as signed)) from borrowers"
896 my ($result) = $sth->fetchrow;
899 return $cardnumber; # just here as a fallback/reminder
904 ($num_children, $children_arrayref) = &GetGuarantees($parent_borrno);
905 $child0_cardno = $children_arrayref->[0]{"cardnumber"};
906 $child0_borrno = $children_arrayref->[0]{"borrowernumber"};
908 C<&GetGuarantees> takes a borrower number (e.g., that of a patron
909 with children) and looks up the borrowers who are guaranteed by that
910 borrower (i.e., the patron's children).
912 C<&GetGuarantees> returns two values: an integer giving the number of
913 borrowers guaranteed by C<$parent_borrno>, and a reference to an array
914 of references to hash, which gives the actual results.
920 my ($borrowernumber) = @_;
921 my $dbh = C4::Context->dbh;
924 "select cardnumber,borrowernumber, firstname, surname from borrowers where guarantorid=?"
926 $sth->execute($borrowernumber);
929 my $data = $sth->fetchall_arrayref({});
930 return ( scalar(@$data), $data );
933 =head2 UpdateGuarantees
935 &UpdateGuarantees($parent_borrno);
938 C<&UpdateGuarantees> borrower data for an adult and updates all the guarantees
939 with the modified information
944 sub UpdateGuarantees {
946 my $dbh = C4::Context->dbh;
947 my ( $count, $guarantees ) = GetGuarantees( $data{'borrowernumber'} );
948 foreach my $guarantee (@$guarantees){
949 my $guaquery = qq|UPDATE borrowers
950 SET address=?,fax=?,B_city=?,mobile=?,city=?,phone=?
951 WHERE borrowernumber=?
953 my $sth = $dbh->prepare($guaquery);
954 $sth->execute($data{'address'},$data{'fax'},$data{'B_city'},$data{'mobile'},$data{'city'},$data{'phone'},$guarantee->{'borrowernumber'});
957 =head2 GetPendingIssues
959 my $issues = &GetPendingIssues(@borrowernumber);
961 Looks up what the patron with the given borrowernumber has borrowed.
963 C<&GetPendingIssues> returns a
964 reference-to-array where each element is a reference-to-hash; the
965 keys are the fields from the C<issues>, C<biblio>, and C<items> tables.
966 The keys include C<biblioitems> fields except marc and marcxml.
971 sub GetPendingIssues {
972 my @borrowernumbers = @_;
974 unless (@borrowernumbers ) { # return a ref_to_array
975 return \@borrowernumbers; # to not cause surprise to caller
978 # Borrowers part of the query
980 for (my $i = 0; $i < @borrowernumbers; $i++) {
981 $bquery .= ' issues.borrowernumber = ?';
982 if ($i < $#borrowernumbers ) {
987 # must avoid biblioitems.* to prevent large marc and marcxml fields from killing performance
988 # FIXME: namespace collision: each table has "timestamp" fields. Which one is "timestamp" ?
989 # FIXME: circ/ciculation.pl tries to sort by timestamp!
990 # FIXME: C4::Print::printslip tries to sort by timestamp!
991 # FIXME: namespace collision: other collisions possible.
992 # FIXME: most of this data isn't really being used by callers.
999 biblioitems.itemtype,
1002 biblioitems.publicationyear,
1003 biblioitems.publishercode,
1004 biblioitems.volumedate,
1005 biblioitems.volumedesc,
1008 borrowers.firstname,
1010 borrowers.cardnumber,
1011 issues.timestamp AS timestamp,
1012 issues.renewals AS renewals,
1013 issues.borrowernumber AS borrowernumber,
1014 items.renewals AS totalrenewals
1016 LEFT JOIN items ON items.itemnumber = issues.itemnumber
1017 LEFT JOIN biblio ON items.biblionumber = biblio.biblionumber
1018 LEFT JOIN biblioitems ON items.biblioitemnumber = biblioitems.biblioitemnumber
1019 LEFT JOIN borrowers ON issues.borrowernumber = borrowers.borrowernumber
1022 ORDER BY issues.issuedate"
1025 my $sth = C4::Context->dbh->prepare($query);
1026 $sth->execute(@borrowernumbers);
1027 my $data = $sth->fetchall_arrayref({});
1028 my $today = C4::Dates->new->output('iso');
1029 foreach (@{$data}) {
1030 if ($_->{date_due} and $_->{date_due} lt $today) {
1039 $issues = &GetAllIssues($borrowernumber, $sortkey, $limit);
1041 Looks up what the patron with the given borrowernumber has borrowed,
1042 and sorts the results.
1044 C<$sortkey> is the name of a field on which to sort the results. This
1045 should be the name of a field in the C<issues>, C<biblio>,
1046 C<biblioitems>, or C<items> table in the Koha database.
1048 C<$limit> is the maximum number of results to return.
1050 C<&GetAllIssues> an arrayref, C<$issues>, of hashrefs, the keys of which
1051 are the fields from the C<issues>, C<biblio>, C<biblioitems>, and
1052 C<items> tables of the Koha database.
1058 my ( $borrowernumber, $order, $limit ) = @_;
1060 #FIXME: sanity-check order and limit
1061 my $dbh = C4::Context->dbh;
1063 "SELECT *, issues.timestamp as issuestimestamp, issues.renewals AS renewals,items.renewals AS totalrenewals,items.timestamp AS itemstimestamp
1065 LEFT JOIN items on items.itemnumber=issues.itemnumber
1066 LEFT JOIN biblio ON items.biblionumber=biblio.biblionumber
1067 LEFT JOIN biblioitems ON items.biblioitemnumber=biblioitems.biblioitemnumber
1068 WHERE borrowernumber=?
1070 SELECT *, old_issues.timestamp as issuestimestamp, old_issues.renewals AS renewals,items.renewals AS totalrenewals,items.timestamp AS itemstimestamp
1072 LEFT JOIN items on items.itemnumber=old_issues.itemnumber
1073 LEFT JOIN biblio ON items.biblionumber=biblio.biblionumber
1074 LEFT JOIN biblioitems ON items.biblioitemnumber=biblioitems.biblioitemnumber
1075 WHERE borrowernumber=? AND old_issues.itemnumber IS NOT NULL
1077 if ( $limit != 0 ) {
1078 $query .= " limit $limit";
1081 my $sth = $dbh->prepare($query);
1082 $sth->execute($borrowernumber, $borrowernumber);
1085 while ( my $data = $sth->fetchrow_hashref ) {
1086 push @result, $data;
1093 =head2 GetMemberAccountRecords
1095 ($total, $acctlines, $count) = &GetMemberAccountRecords($borrowernumber);
1097 Looks up accounting data for the patron with the given borrowernumber.
1099 C<&GetMemberAccountRecords> returns a three-element array. C<$acctlines> is a
1100 reference-to-array, where each element is a reference-to-hash; the
1101 keys are the fields of the C<accountlines> table in the Koha database.
1102 C<$count> is the number of elements in C<$acctlines>. C<$total> is the
1103 total amount outstanding for all of the account lines.
1108 sub GetMemberAccountRecords {
1109 my ($borrowernumber,$date) = @_;
1110 my $dbh = C4::Context->dbh;
1116 WHERE borrowernumber=?);
1117 my @bind = ($borrowernumber);
1118 if ($date && $date ne ''){
1119 $strsth.=" AND date < ? ";
1122 $strsth.=" ORDER BY date desc,timestamp DESC";
1123 my $sth= $dbh->prepare( $strsth );
1124 $sth->execute( @bind );
1126 while ( my $data = $sth->fetchrow_hashref ) {
1127 if ( $data->{itemnumber} ) {
1128 my $biblio = GetBiblioFromItemNumber( $data->{itemnumber} );
1129 $data->{biblionumber} = $biblio->{biblionumber};
1130 $data->{title} = $biblio->{title};
1132 $acctlines[$numlines] = $data;
1134 $total += int(1000 * $data->{'amountoutstanding'}); # convert float to integer to avoid round-off errors
1137 return ( $total, \@acctlines,$numlines);
1140 =head2 GetBorNotifyAcctRecord
1142 ($total, $acctlines, $count) = &GetBorNotifyAcctRecord($params,$notifyid);
1144 Looks up accounting data for the patron with the given borrowernumber per file number.
1146 C<&GetBorNotifyAcctRecord> returns a three-element array. C<$acctlines> is a
1147 reference-to-array, where each element is a reference-to-hash; the
1148 keys are the fields of the C<accountlines> table in the Koha database.
1149 C<$count> is the number of elements in C<$acctlines>. C<$total> is the
1150 total amount outstanding for all of the account lines.
1154 sub GetBorNotifyAcctRecord {
1155 my ( $borrowernumber, $notifyid ) = @_;
1156 my $dbh = C4::Context->dbh;
1159 my $sth = $dbh->prepare(
1162 WHERE borrowernumber=?
1164 AND amountoutstanding != '0'
1165 ORDER BY notify_id,accounttype
1168 $sth->execute( $borrowernumber, $notifyid );
1170 while ( my $data = $sth->fetchrow_hashref ) {
1171 $acctlines[$numlines] = $data;
1173 $total += int(100 * $data->{'amountoutstanding'});
1176 return ( $total, \@acctlines, $numlines );
1179 =head2 checkuniquemember (OUEST-PROVENCE)
1181 ($result,$categorycode) = &checkuniquemember($collectivity,$surname,$firstname,$dateofbirth);
1183 Checks that a member exists or not in the database.
1185 C<&result> is nonzero (=exist) or 0 (=does not exist)
1186 C<&categorycode> is from categorycode table
1187 C<&collectivity> is 1 (= we add a collectivity) or 0 (= we add a physical member)
1188 C<&surname> is the surname
1189 C<&firstname> is the firstname (only if collectivity=0)
1190 C<&dateofbirth> is the date of birth in ISO format (only if collectivity=0)
1194 # FIXME: This function is not legitimate. Multiple patrons might have the same first/last name and birthdate.
1195 # This is especially true since first name is not even a required field.
1197 sub checkuniquemember {
1198 my ( $collectivity, $surname, $firstname, $dateofbirth ) = @_;
1199 my $dbh = C4::Context->dbh;
1200 my $request = ($collectivity) ?
1201 "SELECT borrowernumber,categorycode FROM borrowers WHERE surname=? " :
1203 "SELECT borrowernumber,categorycode FROM borrowers WHERE surname=? and firstname=? and dateofbirth=?" :
1204 "SELECT borrowernumber,categorycode FROM borrowers WHERE surname=? and firstname=?";
1205 my $sth = $dbh->prepare($request);
1206 if ($collectivity) {
1207 $sth->execute( uc($surname) );
1208 } elsif($dateofbirth){
1209 $sth->execute( uc($surname), ucfirst($firstname), $dateofbirth );
1211 $sth->execute( uc($surname), ucfirst($firstname));
1213 my @data = $sth->fetchrow;
1214 ( $data[0] ) and return $data[0], $data[1];
1218 sub checkcardnumber {
1219 my ($cardnumber,$borrowernumber) = @_;
1220 # If cardnumber is null, we assume they're allowed.
1221 return 0 if !defined($cardnumber);
1222 my $dbh = C4::Context->dbh;
1223 my $query = "SELECT * FROM borrowers WHERE cardnumber=?";
1224 $query .= " AND borrowernumber <> ?" if ($borrowernumber);
1225 my $sth = $dbh->prepare($query);
1226 if ($borrowernumber) {
1227 $sth->execute($cardnumber,$borrowernumber);
1229 $sth->execute($cardnumber);
1231 if (my $data= $sth->fetchrow_hashref()){
1240 =head2 getzipnamecity (OUEST-PROVENCE)
1242 take all info from table city for the fields city and zip
1243 check for the name and the zip code of the city selected
1247 sub getzipnamecity {
1249 my $dbh = C4::Context->dbh;
1252 "select city_name,city_state,city_zipcode,city_country from cities where cityid=? ");
1253 $sth->execute($cityid);
1254 my @data = $sth->fetchrow;
1255 return $data[0], $data[1], $data[2], $data[3];
1259 =head2 getdcity (OUEST-PROVENCE)
1261 recover cityid with city_name condition
1266 my ($city_name) = @_;
1267 my $dbh = C4::Context->dbh;
1268 my $sth = $dbh->prepare("select cityid from cities where city_name=? ");
1269 $sth->execute($city_name);
1270 my $data = $sth->fetchrow;
1274 =head2 GetFirstValidEmailAddress
1276 $email = GetFirstValidEmailAddress($borrowernumber);
1278 Return the first valid email address for a borrower, given the borrowernumber. For now, the order
1279 is defined as email, emailpro, B_email. Returns the empty string if the borrower has no email
1284 sub GetFirstValidEmailAddress {
1285 my $borrowernumber = shift;
1286 my $dbh = C4::Context->dbh;
1287 my $sth = $dbh->prepare( "SELECT email, emailpro, B_email FROM borrowers where borrowernumber = ? ");
1288 $sth->execute( $borrowernumber );
1289 my $data = $sth->fetchrow_hashref;
1291 if ($data->{'email'}) {
1292 return $data->{'email'};
1293 } elsif ($data->{'emailpro'}) {
1294 return $data->{'emailpro'};
1295 } elsif ($data->{'B_email'}) {
1296 return $data->{'B_email'};
1302 =head2 GetExpiryDate
1304 $expirydate = GetExpiryDate($categorycode, $dateenrolled);
1306 Calculate expiry date given a categorycode and starting date. Date argument must be in ISO format.
1307 Return date is also in ISO format.
1312 my ( $categorycode, $dateenrolled ) = @_;
1314 if ($categorycode) {
1315 my $dbh = C4::Context->dbh;
1316 my $sth = $dbh->prepare("SELECT enrolmentperiod,enrolmentperioddate FROM categories WHERE categorycode=?");
1317 $sth->execute($categorycode);
1318 $enrolments = $sth->fetchrow_hashref;
1320 # die "GetExpiryDate: for enrollmentperiod $enrolmentperiod (category '$categorycode') starting $dateenrolled.\n";
1321 my @date = split (/-/,$dateenrolled);
1322 if($enrolments->{enrolmentperiod}){
1323 return sprintf("%04d-%02d-%02d", Add_Delta_YM(@date,0,$enrolments->{enrolmentperiod}));
1325 return $enrolments->{enrolmentperioddate};
1329 =head2 checkuserpassword (OUEST-PROVENCE)
1331 check for the password and login are not used
1332 return the number of record
1333 0=> NOT USED 1=> USED
1337 sub checkuserpassword {
1338 my ( $borrowernumber, $userid, $password ) = @_;
1339 $password = md5_base64($password);
1340 my $dbh = C4::Context->dbh;
1343 "Select count(*) from borrowers where borrowernumber !=? and userid =? and password=? "
1345 $sth->execute( $borrowernumber, $userid, $password );
1346 my $number_rows = $sth->fetchrow;
1347 return $number_rows;
1351 =head2 GetborCatFromCatType
1353 ($codes_arrayref, $labels_hashref) = &GetborCatFromCatType();
1355 Looks up the different types of borrowers in the database. Returns two
1356 elements: a reference-to-array, which lists the borrower category
1357 codes, and a reference-to-hash, which maps the borrower category codes
1358 to category descriptions.
1363 sub GetborCatFromCatType {
1364 my ( $category_type, $action ) = @_;
1365 # FIXME - This API seems both limited and dangerous.
1366 my $dbh = C4::Context->dbh;
1367 my $request = qq| SELECT categorycode,description
1370 ORDER BY categorycode|;
1371 my $sth = $dbh->prepare($request);
1373 $sth->execute($category_type);
1382 while ( my $data = $sth->fetchrow_hashref ) {
1383 push @codes, $data->{'categorycode'};
1384 $labels{ $data->{'categorycode'} } = $data->{'description'};
1386 return ( \@codes, \%labels );
1389 =head2 GetBorrowercategory
1391 $hashref = &GetBorrowercategory($categorycode);
1393 Given the borrower's category code, the function returns the corresponding
1394 data hashref for a comprehensive information display.
1396 $arrayref_hashref = &GetBorrowercategory;
1398 If no category code provided, the function returns all the categories.
1402 sub GetBorrowercategory {
1404 my $dbh = C4::Context->dbh;
1408 "SELECT description,dateofbirthrequired,upperagelimit,category_type
1410 WHERE categorycode = ?"
1412 $sth->execute($catcode);
1414 $sth->fetchrow_hashref;
1418 } # sub getborrowercategory
1420 =head2 GetBorrowercategoryList
1422 $arrayref_hashref = &GetBorrowercategoryList;
1423 If no category code provided, the function returns all the categories.
1427 sub GetBorrowercategoryList {
1428 my $dbh = C4::Context->dbh;
1433 ORDER BY description"
1437 $sth->fetchall_arrayref({});
1439 } # sub getborrowercategory
1441 =head2 ethnicitycategories
1443 ($codes_arrayref, $labels_hashref) = ðnicitycategories();
1445 Looks up the different ethnic types in the database. Returns two
1446 elements: a reference-to-array, which lists the ethnicity codes, and a
1447 reference-to-hash, which maps the ethnicity codes to ethnicity
1454 sub ethnicitycategories {
1455 my $dbh = C4::Context->dbh;
1456 my $sth = $dbh->prepare("Select code,name from ethnicity order by name");
1460 while ( my $data = $sth->fetchrow_hashref ) {
1461 push @codes, $data->{'code'};
1462 $labels{ $data->{'code'} } = $data->{'name'};
1464 return ( \@codes, \%labels );
1469 $ethn_name = &fixEthnicity($ethn_code);
1471 Takes an ethnicity code (e.g., "european" or "pi") and returns the
1472 corresponding descriptive name from the C<ethnicity> table in the
1473 Koha database ("European" or "Pacific Islander").
1480 my $ethnicity = shift;
1481 return unless $ethnicity;
1482 my $dbh = C4::Context->dbh;
1483 my $sth = $dbh->prepare("Select name from ethnicity where code = ?");
1484 $sth->execute($ethnicity);
1485 my $data = $sth->fetchrow_hashref;
1486 return $data->{'name'};
1487 } # sub fixEthnicity
1491 $dateofbirth,$date = &GetAge($date);
1493 this function return the borrowers age with the value of dateofbirth
1499 my ( $date, $date_ref ) = @_;
1501 if ( not defined $date_ref ) {
1502 $date_ref = sprintf( '%04d-%02d-%02d', Today() );
1505 my ( $year1, $month1, $day1 ) = split /-/, $date;
1506 my ( $year2, $month2, $day2 ) = split /-/, $date_ref;
1508 my $age = $year2 - $year1;
1509 if ( $month1 . $day1 > $month2 . $day2 ) {
1516 =head2 get_institutions
1518 $insitutions = get_institutions();
1520 Just returns a list of all the borrowers of type I, borrownumber and name
1525 sub get_institutions {
1526 my $dbh = C4::Context->dbh();
1529 "SELECT borrowernumber,surname FROM borrowers WHERE categorycode=? ORDER BY surname"
1533 while ( my $data = $sth->fetchrow_hashref() ) {
1534 $orgs{ $data->{'borrowernumber'} } = $data;
1538 } # sub get_institutions
1540 =head2 add_member_orgs
1542 add_member_orgs($borrowernumber,$borrowernumbers);
1544 Takes a borrowernumber and a list of other borrowernumbers and inserts them into the borrowers_to_borrowers table
1549 sub add_member_orgs {
1550 my ( $borrowernumber, $otherborrowers ) = @_;
1551 my $dbh = C4::Context->dbh();
1553 "INSERT INTO borrowers_to_borrowers (borrower1,borrower2) VALUES (?,?)";
1554 my $sth = $dbh->prepare($query);
1555 foreach my $otherborrowernumber (@$otherborrowers) {
1556 $sth->execute( $borrowernumber, $otherborrowernumber );
1559 } # sub add_member_orgs
1563 $cityarrayref = GetCities();
1565 Returns an array_ref of the entries in the cities table
1566 If there are entries in the table an empty row is returned
1567 This is currently only used to populate a popup in memberentry
1573 my $dbh = C4::Context->dbh;
1574 my $city_arr = $dbh->selectall_arrayref(
1575 q|SELECT cityid,city_zipcode,city_name,city_state,city_country FROM cities ORDER BY city_name|,
1577 if ( @{$city_arr} ) {
1578 unshift @{$city_arr}, {
1579 city_zipcode => q{},
1583 city_country => q{},
1590 =head2 GetSortDetails (OUEST-PROVENCE)
1592 ($lib) = &GetSortDetails($category,$sortvalue);
1594 Returns the authorized value details
1595 C<&$lib>return value of authorized value details
1596 C<&$sortvalue>this is the value of authorized value
1597 C<&$category>this is the value of authorized value category
1601 sub GetSortDetails {
1602 my ( $category, $sortvalue ) = @_;
1603 my $dbh = C4::Context->dbh;
1604 my $query = qq|SELECT lib
1605 FROM authorised_values
1607 AND authorised_value=? |;
1608 my $sth = $dbh->prepare($query);
1609 $sth->execute( $category, $sortvalue );
1610 my $lib = $sth->fetchrow;
1611 return ($lib) if ($lib);
1612 return ($sortvalue) unless ($lib);
1615 =head2 MoveMemberToDeleted
1617 $result = &MoveMemberToDeleted($borrowernumber);
1619 Copy the record from borrowers to deletedborrowers table.
1623 # FIXME: should do it in one SQL statement w/ subquery
1624 # Otherwise, we should return the @data on success
1626 sub MoveMemberToDeleted {
1627 my ($member) = shift or return;
1628 my $dbh = C4::Context->dbh;
1629 my $query = qq|SELECT *
1631 WHERE borrowernumber=?|;
1632 my $sth = $dbh->prepare($query);
1633 $sth->execute($member);
1634 my @data = $sth->fetchrow_array;
1635 (@data) or return; # if we got a bad borrowernumber, there's nothing to insert
1637 $dbh->prepare( "INSERT INTO deletedborrowers VALUES ("
1638 . ( "?," x ( scalar(@data) - 1 ) )
1640 $sth->execute(@data);
1645 DelMember($borrowernumber);
1647 This function remove directly a borrower whitout writing it on deleteborrower.
1648 + Deletes reserves for the borrower
1653 my $dbh = C4::Context->dbh;
1654 my $borrowernumber = shift;
1655 #warn "in delmember with $borrowernumber";
1656 return unless $borrowernumber; # borrowernumber is mandatory.
1658 my $query = qq|DELETE
1660 WHERE borrowernumber=?|;
1661 my $sth = $dbh->prepare($query);
1662 $sth->execute($borrowernumber);
1666 WHERE borrowernumber = ?
1668 $sth = $dbh->prepare($query);
1669 $sth->execute($borrowernumber);
1670 logaction("MEMBERS", "DELETE", $borrowernumber, "") if C4::Context->preference("BorrowersLog");
1674 =head2 ExtendMemberSubscriptionTo (OUEST-PROVENCE)
1676 $date = ExtendMemberSubscriptionTo($borrowerid, $date);
1678 Extending the subscription to a given date or to the expiry date calculated on ISO date.
1683 sub ExtendMemberSubscriptionTo {
1684 my ( $borrowerid,$date) = @_;
1685 my $dbh = C4::Context->dbh;
1686 my $borrower = GetMember('borrowernumber'=>$borrowerid);
1688 $date=POSIX::strftime("%Y-%m-%d",localtime());
1689 $date = GetExpiryDate( $borrower->{'categorycode'}, $date );
1691 my $sth = $dbh->do(<<EOF);
1693 SET dateexpiry='$date'
1694 WHERE borrowernumber='$borrowerid'
1696 # add enrolmentfee if needed
1697 $sth = $dbh->prepare("SELECT enrolmentfee FROM categories WHERE categorycode=?");
1698 $sth->execute($borrower->{'categorycode'});
1699 my ($enrolmentfee) = $sth->fetchrow;
1700 if ($enrolmentfee && $enrolmentfee > 0) {
1701 # insert fee in patron debts
1702 manualinvoice($borrower->{'borrowernumber'}, '', '', 'A', $enrolmentfee);
1704 logaction("MEMBERS", "RENEW", $borrower->{'borrowernumber'}, "Membership renewed")if C4::Context->preference("BorrowersLog");
1705 return $date if ($sth);
1709 =head2 GetRoadTypes (OUEST-PROVENCE)
1711 ($idroadtypearrayref, $roadttype_hashref) = &GetRoadTypes();
1713 Looks up the different road type . Returns two
1714 elements: a reference-to-array, which lists the id_roadtype
1715 codes, and a reference-to-hash, which maps the road type of the road .
1720 my $dbh = C4::Context->dbh;
1722 SELECT roadtypeid,road_type
1724 ORDER BY road_type|;
1725 my $sth = $dbh->prepare($query);
1730 # insert empty value to create a empty choice in cgi popup
1732 while ( my $data = $sth->fetchrow_hashref ) {
1734 push @id, $data->{'roadtypeid'};
1735 $roadtype{ $data->{'roadtypeid'} } = $data->{'road_type'};
1738 #test to know if the table contain some records if no the function return nothing
1745 return ( \@id, \%roadtype );
1751 =head2 GetTitles (OUEST-PROVENCE)
1753 ($borrowertitle)= &GetTitles();
1755 Looks up the different title . Returns array with all borrowers title
1760 my @borrowerTitle = split (/,|\|/,C4::Context->preference('BorrowersTitles'));
1761 unshift( @borrowerTitle, "" );
1762 my $count=@borrowerTitle;
1767 return ( \@borrowerTitle);
1771 =head2 GetPatronImage
1773 my ($imagedata, $dberror) = GetPatronImage($cardnumber);
1775 Returns the mimetype and binary image data of the image for the patron with the supplied cardnumber.
1779 sub GetPatronImage {
1780 my ($cardnumber) = @_;
1781 warn "Cardnumber passed to GetPatronImage is $cardnumber" if $debug;
1782 my $dbh = C4::Context->dbh;
1783 my $query = 'SELECT mimetype, imagefile FROM patronimage WHERE cardnumber = ?';
1784 my $sth = $dbh->prepare($query);
1785 $sth->execute($cardnumber);
1786 my $imagedata = $sth->fetchrow_hashref;
1787 warn "Database error!" if $sth->errstr;
1788 return $imagedata, $sth->errstr;
1791 =head2 PutPatronImage
1793 PutPatronImage($cardnumber, $mimetype, $imgfile);
1795 Stores patron binary image data and mimetype in database.
1796 NOTE: This function is good for updating images as well as inserting new images in the database.
1800 sub PutPatronImage {
1801 my ($cardnumber, $mimetype, $imgfile) = @_;
1802 warn "Parameters passed in: Cardnumber=$cardnumber, Mimetype=$mimetype, " . ($imgfile ? "Imagefile" : "No Imagefile") if $debug;
1803 my $dbh = C4::Context->dbh;
1804 my $query = "INSERT INTO patronimage (cardnumber, mimetype, imagefile) VALUES (?,?,?) ON DUPLICATE KEY UPDATE imagefile = ?;";
1805 my $sth = $dbh->prepare($query);
1806 $sth->execute($cardnumber,$mimetype,$imgfile,$imgfile);
1807 warn "Error returned inserting $cardnumber.$mimetype." if $sth->errstr;
1808 return $sth->errstr;
1811 =head2 RmPatronImage
1813 my ($dberror) = RmPatronImage($cardnumber);
1815 Removes the image for the patron with the supplied cardnumber.
1820 my ($cardnumber) = @_;
1821 warn "Cardnumber passed to GetPatronImage is $cardnumber" if $debug;
1822 my $dbh = C4::Context->dbh;
1823 my $query = "DELETE FROM patronimage WHERE cardnumber = ?;";
1824 my $sth = $dbh->prepare($query);
1825 $sth->execute($cardnumber);
1826 my $dberror = $sth->errstr;
1827 warn "Database error!" if $sth->errstr;
1831 =head2 GetHideLostItemsPreference
1833 $hidelostitemspref = &GetHideLostItemsPreference($borrowernumber);
1835 Returns the HideLostItems preference for the patron category of the supplied borrowernumber
1836 C<&$hidelostitemspref>return value of function, 0 or 1
1840 sub GetHideLostItemsPreference {
1841 my ($borrowernumber) = @_;
1842 my $dbh = C4::Context->dbh;
1843 my $query = "SELECT hidelostitems FROM borrowers,categories WHERE borrowers.categorycode = categories.categorycode AND borrowernumber = ?";
1844 my $sth = $dbh->prepare($query);
1845 $sth->execute($borrowernumber);
1846 my $hidelostitems = $sth->fetchrow;
1847 return $hidelostitems;
1850 =head2 GetRoadTypeDetails (OUEST-PROVENCE)
1852 ($roadtype) = &GetRoadTypeDetails($roadtypeid);
1854 Returns the description of roadtype
1855 C<&$roadtype>return description of road type
1856 C<&$roadtypeid>this is the value of roadtype s
1860 sub GetRoadTypeDetails {
1861 my ($roadtypeid) = @_;
1862 my $dbh = C4::Context->dbh;
1866 WHERE roadtypeid=?|;
1867 my $sth = $dbh->prepare($query);
1868 $sth->execute($roadtypeid);
1869 my $roadtype = $sth->fetchrow;
1873 =head2 GetBorrowersWhoHaveNotBorrowedSince
1875 &GetBorrowersWhoHaveNotBorrowedSince($date)
1877 this function get all borrowers who haven't borrowed since the date given on input arg.
1881 sub GetBorrowersWhoHaveNotBorrowedSince {
1882 my $filterdate = shift||POSIX::strftime("%Y-%m-%d",localtime());
1883 my $filterexpiry = shift;
1884 my $filterbranch = shift ||
1885 ((C4::Context->preference('IndependantBranches')
1886 && C4::Context->userenv
1887 && C4::Context->userenv->{flags} % 2 !=1
1888 && C4::Context->userenv->{branch})
1889 ? C4::Context->userenv->{branch}
1891 my $dbh = C4::Context->dbh;
1893 SELECT borrowers.borrowernumber,
1894 max(old_issues.timestamp) as latestissue,
1895 max(issues.timestamp) as currentissue
1897 JOIN categories USING (categorycode)
1898 LEFT JOIN old_issues USING (borrowernumber)
1899 LEFT JOIN issues USING (borrowernumber)
1900 WHERE category_type <> 'S'
1901 AND borrowernumber NOT IN (SELECT guarantorid FROM borrowers WHERE guarantorid IS NOT NULL AND guarantorid <> 0)
1904 if ($filterbranch && $filterbranch ne ""){
1905 $query.=" AND borrowers.branchcode= ?";
1906 push @query_params,$filterbranch;
1909 $query .= " AND dateexpiry < ? ";
1910 push @query_params,$filterdate;
1912 $query.=" GROUP BY borrowers.borrowernumber";
1914 $query.=" HAVING (latestissue < ? OR latestissue IS NULL)
1915 AND currentissue IS NULL";
1916 push @query_params,$filterdate;
1918 warn $query if $debug;
1919 my $sth = $dbh->prepare($query);
1920 if (scalar(@query_params)>0){
1921 $sth->execute(@query_params);
1928 while ( my $data = $sth->fetchrow_hashref ) {
1929 push @results, $data;
1934 =head2 GetBorrowersWhoHaveNeverBorrowed
1936 $results = &GetBorrowersWhoHaveNeverBorrowed
1938 This function get all borrowers who have never borrowed.
1940 I<$result> is a ref to an array which all elements are a hasref.
1944 sub GetBorrowersWhoHaveNeverBorrowed {
1945 my $filterbranch = shift ||
1946 ((C4::Context->preference('IndependantBranches')
1947 && C4::Context->userenv
1948 && C4::Context->userenv->{flags} % 2 !=1
1949 && C4::Context->userenv->{branch})
1950 ? C4::Context->userenv->{branch}
1952 my $dbh = C4::Context->dbh;
1954 SELECT borrowers.borrowernumber,max(timestamp) as latestissue
1956 LEFT JOIN issues ON borrowers.borrowernumber = issues.borrowernumber
1957 WHERE issues.borrowernumber IS NULL
1960 if ($filterbranch && $filterbranch ne ""){
1961 $query.=" AND borrowers.branchcode= ?";
1962 push @query_params,$filterbranch;
1964 warn $query if $debug;
1966 my $sth = $dbh->prepare($query);
1967 if (scalar(@query_params)>0){
1968 $sth->execute(@query_params);
1975 while ( my $data = $sth->fetchrow_hashref ) {
1976 push @results, $data;
1981 =head2 GetBorrowersWithIssuesHistoryOlderThan
1983 $results = &GetBorrowersWithIssuesHistoryOlderThan($date)
1985 this function get all borrowers who has an issue history older than I<$date> given on input arg.
1987 I<$result> is a ref to an array which all elements are a hashref.
1988 This hashref is containt the number of time this borrowers has borrowed before I<$date> and the borrowernumber.
1992 sub GetBorrowersWithIssuesHistoryOlderThan {
1993 my $dbh = C4::Context->dbh;
1994 my $date = shift ||POSIX::strftime("%Y-%m-%d",localtime());
1995 my $filterbranch = shift ||
1996 ((C4::Context->preference('IndependantBranches')
1997 && C4::Context->userenv
1998 && C4::Context->userenv->{flags} % 2 !=1
1999 && C4::Context->userenv->{branch})
2000 ? C4::Context->userenv->{branch}
2003 SELECT count(borrowernumber) as n,borrowernumber
2005 WHERE returndate < ?
2006 AND borrowernumber IS NOT NULL
2009 push @query_params, $date;
2011 $query.=" AND branchcode = ?";
2012 push @query_params, $filterbranch;
2014 $query.=" GROUP BY borrowernumber ";
2015 warn $query if $debug;
2016 my $sth = $dbh->prepare($query);
2017 $sth->execute(@query_params);
2020 while ( my $data = $sth->fetchrow_hashref ) {
2021 push @results, $data;
2026 =head2 GetBorrowersNamesAndLatestIssue
2028 $results = &GetBorrowersNamesAndLatestIssueList(@borrowernumbers)
2030 this function get borrowers Names and surnames and Issue information.
2032 I<@borrowernumbers> is an array which all elements are borrowernumbers.
2033 This hashref is containt the number of time this borrowers has borrowed before I<$date> and the borrowernumber.
2037 sub GetBorrowersNamesAndLatestIssue {
2038 my $dbh = C4::Context->dbh;
2039 my @borrowernumbers=@_;
2041 SELECT surname,lastname, phone, email,max(timestamp)
2043 LEFT JOIN issues ON borrowers.borrowernumber=issues.borrowernumber
2044 GROUP BY borrowernumber
2046 my $sth = $dbh->prepare($query);
2048 my $results = $sth->fetchall_arrayref({});
2054 my $success = DebarMember( $borrowernumber, $todate );
2056 marks a Member as debarred, and therefore unable to checkout any more
2060 true on success, false on failure
2065 my $borrowernumber = shift;
2068 return unless defined $borrowernumber;
2069 return unless $borrowernumber =~ /^\d+$/;
2072 borrowernumber => $borrowernumber,
2082 my $success = ModPrivacy( $borrowernumber, $privacy );
2084 Update the privacy of a patron.
2087 true on success, false on failure
2094 my $borrowernumber = shift;
2095 my $privacy = shift;
2096 return unless defined $borrowernumber;
2097 return unless $borrowernumber =~ /^\d+$/;
2099 return ModMember( borrowernumber => $borrowernumber,
2100 privacy => $privacy );
2105 AddMessage( $borrowernumber, $message_type, $message, $branchcode );
2107 Adds a message to the messages table for the given borrower.
2116 my ( $borrowernumber, $message_type, $message, $branchcode ) = @_;
2118 my $dbh = C4::Context->dbh;
2120 if ( ! ( $borrowernumber && $message_type && $message && $branchcode ) ) {
2124 my $query = "INSERT INTO messages ( borrowernumber, branchcode, message_type, message ) VALUES ( ?, ?, ?, ? )";
2125 my $sth = $dbh->prepare($query);
2126 $sth->execute( $borrowernumber, $branchcode, $message_type, $message );
2133 GetMessages( $borrowernumber, $type );
2135 $type is message type, B for borrower, or L for Librarian.
2136 Empty type returns all messages of any type.
2138 Returns all messages for the given borrowernumber
2143 my ( $borrowernumber, $type, $branchcode ) = @_;
2149 my $dbh = C4::Context->dbh;
2152 branches.branchname,
2155 messages.branchcode LIKE '$branchcode' AS can_delete
2156 FROM messages, branches
2157 WHERE borrowernumber = ?
2158 AND message_type LIKE ?
2159 AND messages.branchcode = branches.branchcode
2160 ORDER BY message_date DESC";
2161 my $sth = $dbh->prepare($query);
2162 $sth->execute( $borrowernumber, $type ) ;
2165 while ( my $data = $sth->fetchrow_hashref ) {
2166 my $d = C4::Dates->new( $data->{message_date}, 'iso' );
2167 $data->{message_date_formatted} = $d->output;
2168 push @results, $data;
2176 GetMessagesCount( $borrowernumber, $type );
2178 $type is message type, B for borrower, or L for Librarian.
2179 Empty type returns all messages of any type.
2181 Returns the number of messages for the given borrowernumber
2185 sub GetMessagesCount {
2186 my ( $borrowernumber, $type, $branchcode ) = @_;
2192 my $dbh = C4::Context->dbh;
2194 my $query = "SELECT COUNT(*) as MsgCount FROM messages WHERE borrowernumber = ? AND message_type LIKE ?";
2195 my $sth = $dbh->prepare($query);
2196 $sth->execute( $borrowernumber, $type ) ;
2199 my $data = $sth->fetchrow_hashref;
2200 my $count = $data->{'MsgCount'};
2207 =head2 DeleteMessage
2209 DeleteMessage( $message_id );
2214 my ( $message_id ) = @_;
2216 my $dbh = C4::Context->dbh;
2218 my $query = "DELETE FROM messages WHERE message_id = ?";
2219 my $sth = $dbh->prepare($query);
2220 $sth->execute( $message_id );
2224 END { } # module clean-up code here (global destructor)