3 # Copyright 2000-2003 Katipo Communications
4 # Copyright 2010 BibLibre
6 # This file is part of Koha.
8 # Koha is free software; you can redistribute it and/or modify it under the
9 # terms of the GNU General Public License as published by the Free Software
10 # Foundation; either version 2 of the License, or (at your option) any later
13 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
14 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
15 # A PARTICULAR PURPOSE. See the GNU General Public License for more details.
17 # You should have received a copy of the GNU General Public License along
18 # with Koha; if not, write to the Free Software Foundation, Inc.,
19 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
23 #use warnings; FIXME - Bug 2505
25 use C4::Dates qw(format_date_in_iso);
26 use Digest::MD5 qw(md5_base64);
27 use Date::Calc qw/Today Add_Delta_YM/;
28 use C4::Log; # logaction
33 use C4::SQLHelper qw(InsertInTable UpdateInTable SearchInTable);
34 use C4::Members::Attributes qw(SearchIdMatchingAttribute);
36 our ($VERSION,@ISA,@EXPORT,@EXPORT_OK,$debug);
40 $debug = $ENV{DEBUG} || 0;
52 &GetMemberIssuesAndFines
60 &GetFirstValidEmailAddress
73 &GetHideLostItemsPreference
76 &GetMemberAccountRecords
77 &GetBorNotifyAcctRecord
81 &GetBorrowercategoryList
83 &GetBorrowersWhoHaveNotBorrowedSince
84 &GetBorrowersWhoHaveNeverBorrowed
85 &GetBorrowersWithIssuesHistoryOlderThan
112 &ExtendMemberSubscriptionTo
130 C4::Members - Perl Module containing convenience functions for member handling
138 This module contains routines for adding, modifying and deleting members/patrons/borrowers
144 ($count, $borrowers) = &SearchMember($searchstring, $type,
145 $category_type, $filter, $showallbranches);
147 Looks up patrons (borrowers) by name.
149 BUGFIX 499: C<$type> is now used to determine type of search.
150 if $type is "simple", search is performed on the first letter of the
153 $category_type is used to get a specified type of user.
154 (mainly adults when creating a child.)
156 C<$searchstring> is a space-separated list of search terms. Each term
157 must match the beginning a borrower's surname, first name, or other
160 C<$filter> is assumed to be a list of elements to filter results on
162 C<$showallbranches> is used in IndependantBranches Context to display all branches results.
164 C<&SearchMember> returns a two-element list. C<$borrowers> is a
165 reference-to-array; each element is a reference-to-hash, whose keys
166 are the fields of the C<borrowers> table in the Koha database.
167 C<$count> is the number of elements in C<$borrowers>.
172 #used by member enquiries from the intranet
174 my ($searchstring, $orderby, $type,$category_type,$filter,$showallbranches ) = @_;
175 my $dbh = C4::Context->dbh;
181 # this is used by circulation everytime a new borrowers cardnumber is scanned
182 # so we can check an exact match first, if that works return, otherwise do the rest
183 $query = "SELECT * FROM borrowers
184 LEFT JOIN categories ON borrowers.categorycode=categories.categorycode
186 my $sth = $dbh->prepare("$query WHERE cardnumber = ?");
187 $sth->execute($searchstring);
188 my $data = $sth->fetchall_arrayref({});
190 return ( scalar(@$data), $data );
193 if ( $type eq "simple" ) # simple search for one letter only
195 $query .= ($category_type ? " AND category_type = ".$dbh->quote($category_type) : "");
196 $query .= " WHERE (surname LIKE ? OR cardnumber like ?) ";
197 if (C4::Context->preference("IndependantBranches") && !$showallbranches){
198 if (C4::Context->userenv && C4::Context->userenv->{flags} % 2 !=1 && C4::Context->userenv->{'branch'}){
199 $query.=" AND borrowers.branchcode =".$dbh->quote(C4::Context->userenv->{'branch'}) unless (C4::Context->userenv->{'branch'} eq "insecure");
202 $query.=" ORDER BY $orderby";
203 @bind = ("$searchstring%","$searchstring");
205 else # advanced search looking in surname, firstname and othernames
207 @data = split( ' ', $searchstring );
210 if (C4::Context->preference("IndependantBranches") && !$showallbranches){
211 if (C4::Context->userenv && C4::Context->userenv->{flags} % 2 !=1 && C4::Context->userenv->{'branch'}){
212 $query.=" borrowers.branchcode =".$dbh->quote(C4::Context->userenv->{'branch'})." AND " unless (C4::Context->userenv->{'branch'} eq "insecure");
215 $query.="((surname LIKE ? OR surname LIKE ?
216 OR firstname LIKE ? OR firstname LIKE ?
217 OR othernames LIKE ? OR othernames LIKE ?)
219 ($category_type?" AND category_type = ".$dbh->quote($category_type):"");
221 "$data[0]%", "% $data[0]%", "$data[0]%", "% $data[0]%",
222 "$data[0]%", "% $data[0]%"
224 for ( my $i = 1 ; $i < $count ; $i++ ) {
225 $query = $query . " AND (" . " surname LIKE ? OR surname LIKE ?
226 OR firstname LIKE ? OR firstname LIKE ?
227 OR othernames LIKE ? OR othernames LIKE ?)";
229 "$data[$i]%", "% $data[$i]%", "$data[$i]%",
230 "% $data[$i]%", "$data[$i]%", "% $data[$i]%" );
234 $query = $query . ") OR cardnumber LIKE ? ";
235 push( @bind, $searchstring );
236 $query .= "order by $orderby";
241 $sth = $dbh->prepare($query);
243 $debug and print STDERR "Q $orderby : $query\n";
244 $sth->execute(@bind);
246 $data = $sth->fetchall_arrayref({});
248 return ( scalar(@$data), $data );
253 $borrowers_result_array_ref = &Search($filter,$orderby, $limit,
254 $columns_out, $search_on_fields,$searchtype);
256 Looks up patrons (borrowers) on filter.
258 BUGFIX 499: C<$type> is now used to determine type of search.
259 if $type is "simple", search is performed on the first letter of the
262 $category_type is used to get a specified type of user.
263 (mainly adults when creating a child.)
266 - a space-separated list of search terms. Implicit AND is done on them
267 - a hash ref containing fieldnames associated with queried value
268 - an array ref combining the two previous elements Implicit OR is done between each array element
271 C<$orderby> is an arrayref of hashref. Contains the name of the field and 0 or 1 depending if order is ascending or descending
273 C<$limit> is there to allow limiting number of results returned
275 C<&columns_out> is an array ref to the fieldnames you want to see in the result list
277 C<&search_on_fields> is an array ref to the fieldnames you want to limit search on when you are using string search
279 C<&searchtype> is a string telling the type of search you want todo : start_with, exact or contains are allowed
284 my ( $filter, $orderby, $limit, $columns_out, $search_on_fields, $searchtype ) = @_;
286 my %filtersmatching_record;
288 if ( ref($filter) eq "ARRAY" ) {
289 push @filters, @$filter;
291 push @filters, $filter;
293 if ( C4::Context->preference('ExtendedPatronAttributes') ) {
294 my $matching_records = C4::Members::Attributes::SearchIdMatchingAttribute($filter);
295 if(scalar(@$matching_records)>0) {
296 foreach my $matching_record (@$matching_records) {
297 $filtersmatching_record{$$matching_record[0]}=1;
299 foreach my $k (keys(%filtersmatching_record)) {
300 push @filters, {"borrowernumber"=>$k};
304 $searchtype ||= "start_with";
305 push @finalfilter, \@filters;
306 my $data = SearchInTable( "borrowers", \@finalfilter, $orderby, $limit, $columns_out, $search_on_fields, $searchtype );
310 =head2 GetMemberDetails
312 ($borrower) = &GetMemberDetails($borrowernumber, $cardnumber);
314 Looks up a patron and returns information about him or her. If
315 C<$borrowernumber> is true (nonzero), C<&GetMemberDetails> looks
316 up the borrower by number; otherwise, it looks up the borrower by card
319 C<$borrower> is a reference-to-hash whose keys are the fields of the
320 borrowers table in the Koha database. In addition,
321 C<$borrower-E<gt>{flags}> is a hash giving more detailed information
322 about the patron. Its keys act as flags :
324 if $borrower->{flags}->{LOST} {
325 # Patron's card was reported lost
328 If the state of a flag means that the patron should not be
329 allowed to borrow any more books, then it will have a C<noissues> key
332 See patronflags for more details.
334 C<$borrower-E<gt>{authflags}> is a hash giving more detailed information
335 about the top-level permissions flags set for the borrower. For example,
336 if a user has the "editcatalogue" permission,
337 C<$borrower-E<gt>{authflags}-E<gt>{editcatalogue}> will exist and have
342 sub GetMemberDetails {
343 my ( $borrowernumber, $cardnumber ) = @_;
344 my $dbh = C4::Context->dbh;
347 if ($borrowernumber) {
348 $sth = $dbh->prepare("select borrowers.*,category_type,categories.description from borrowers left join categories on borrowers.categorycode=categories.categorycode where borrowernumber=?");
349 $sth->execute($borrowernumber);
351 elsif ($cardnumber) {
352 $sth = $dbh->prepare("select borrowers.*,category_type,categories.description from borrowers left join categories on borrowers.categorycode=categories.categorycode where cardnumber=?");
353 $sth->execute($cardnumber);
358 my $borrower = $sth->fetchrow_hashref;
359 my ($amount) = GetMemberAccountRecords( $borrowernumber);
360 $borrower->{'amountoutstanding'} = $amount;
361 # FIXME - patronflags calls GetMemberAccountRecords... just have patronflags return $amount
362 my $flags = patronflags( $borrower);
365 $sth = $dbh->prepare("select bit,flag from userflags");
367 while ( my ( $bit, $flag ) = $sth->fetchrow ) {
368 if ( $borrower->{'flags'} && $borrower->{'flags'} & 2**$bit ) {
369 $accessflagshash->{$flag} = 1;
372 $borrower->{'flags'} = $flags;
373 $borrower->{'authflags'} = $accessflagshash;
375 # find out how long the membership lasts
378 "select enrolmentperiod from categories where categorycode = ?");
379 $sth->execute( $borrower->{'categorycode'} );
380 my $enrolment = $sth->fetchrow;
381 $borrower->{'enrolmentperiod'} = $enrolment;
382 return ($borrower); #, $flags, $accessflagshash);
387 $flags = &patronflags($patron);
389 This function is not exported.
391 The following will be set where applicable:
392 $flags->{CHARGES}->{amount} Amount of debt
393 $flags->{CHARGES}->{noissues} Set if debt amount >$5.00 (or syspref noissuescharge)
394 $flags->{CHARGES}->{message} Message -- deprecated
396 $flags->{CREDITS}->{amount} Amount of credit
397 $flags->{CREDITS}->{message} Message -- deprecated
399 $flags->{ GNA } Patron has no valid address
400 $flags->{ GNA }->{noissues} Set for each GNA
401 $flags->{ GNA }->{message} "Borrower has no valid address" -- deprecated
403 $flags->{ LOST } Patron's card reported lost
404 $flags->{ LOST }->{noissues} Set for each LOST
405 $flags->{ LOST }->{message} Message -- deprecated
407 $flags->{DBARRED} Set if patron debarred, no access
408 $flags->{DBARRED}->{noissues} Set for each DBARRED
409 $flags->{DBARRED}->{message} Message -- deprecated
412 $flags->{ NOTES }->{message} The note itself. NOT deprecated
414 $flags->{ ODUES } Set if patron has overdue books.
415 $flags->{ ODUES }->{message} "Yes" -- deprecated
416 $flags->{ ODUES }->{itemlist} ref-to-array: list of overdue books
417 $flags->{ ODUES }->{itemlisttext} Text list of overdue items -- deprecated
419 $flags->{WAITING} Set if any of patron's reserves are available
420 $flags->{WAITING}->{message} Message -- deprecated
421 $flags->{WAITING}->{itemlist} ref-to-array: list of available items
425 =item C<$flags-E<gt>{ODUES}-E<gt>{itemlist}> is a reference-to-array listing the
426 overdue items. Its elements are references-to-hash, each describing an
427 overdue item. The keys are selected fields from the issues, biblio,
428 biblioitems, and items tables of the Koha database.
430 =item C<$flags-E<gt>{ODUES}-E<gt>{itemlisttext}> is a string giving a text listing of
431 the overdue items, one per line. Deprecated.
433 =item C<$flags-E<gt>{WAITING}-E<gt>{itemlist}> is a reference-to-array listing the
434 available items. Each element is a reference-to-hash whose keys are
435 fields from the reserves table of the Koha database.
439 All the "message" fields that include language generated in this function are deprecated,
440 because such strings belong properly in the display layer.
442 The "message" field that comes from the DB is OK.
446 # TODO: use {anonymous => hashes} instead of a dozen %flaginfo
447 # FIXME rename this function.
450 my ( $patroninformation) = @_;
451 my $dbh=C4::Context->dbh;
452 my ($amount) = GetMemberAccountRecords( $patroninformation->{'borrowernumber'});
455 my $noissuescharge = C4::Context->preference("noissuescharge") || 5;
456 $flaginfo{'message'} = sprintf "Patron owes \$%.02f", $amount;
457 $flaginfo{'amount'} = sprintf "%.02f", $amount;
458 if ( $amount > $noissuescharge && !C4::Context->preference("AllowFineOverride") ) {
459 $flaginfo{'noissues'} = 1;
461 $flags{'CHARGES'} = \%flaginfo;
463 elsif ( $amount < 0 ) {
465 $flaginfo{'message'} = sprintf "Patron has credit of \$%.02f", -$amount;
466 $flaginfo{'amount'} = sprintf "%.02f", $amount;
467 $flags{'CREDITS'} = \%flaginfo;
469 if ( $patroninformation->{'gonenoaddress'}
470 && $patroninformation->{'gonenoaddress'} == 1 )
473 $flaginfo{'message'} = 'Borrower has no valid address.';
474 $flaginfo{'noissues'} = 1;
475 $flags{'GNA'} = \%flaginfo;
477 if ( $patroninformation->{'lost'} && $patroninformation->{'lost'} == 1 ) {
479 $flaginfo{'message'} = 'Borrower\'s card reported lost.';
480 $flaginfo{'noissues'} = 1;
481 $flags{'LOST'} = \%flaginfo;
483 if ( $patroninformation->{'debarred'}
484 && $patroninformation->{'debarred'} == 1 )
487 $flaginfo{'message'} = 'Borrower is Debarred.';
488 $flaginfo{'noissues'} = 1;
489 $flags{'DBARRED'} = \%flaginfo;
491 if ( $patroninformation->{'borrowernotes'}
492 && $patroninformation->{'borrowernotes'} )
495 $flaginfo{'message'} = $patroninformation->{'borrowernotes'};
496 $flags{'NOTES'} = \%flaginfo;
498 my ( $odues, $itemsoverdue ) = checkoverdues($patroninformation->{'borrowernumber'});
499 if ( $odues && $odues > 0 ) {
501 $flaginfo{'message'} = "Yes";
502 $flaginfo{'itemlist'} = $itemsoverdue;
503 foreach ( sort { $a->{'date_due'} cmp $b->{'date_due'} }
506 $flaginfo{'itemlisttext'} .=
507 "$_->{'date_due'} $_->{'barcode'} $_->{'title'} \n"; # newline is display layer
509 $flags{'ODUES'} = \%flaginfo;
511 my @itemswaiting = C4::Reserves::GetReservesFromBorrowernumber( $patroninformation->{'borrowernumber'},'W' );
512 my $nowaiting = scalar @itemswaiting;
513 if ( $nowaiting > 0 ) {
515 $flaginfo{'message'} = "Reserved items available";
516 $flaginfo{'itemlist'} = \@itemswaiting;
517 $flags{'WAITING'} = \%flaginfo;
525 $borrower = &GetMember(%information);
527 Retrieve the first patron record meeting on criteria listed in the
528 C<%information> hash, which should contain one or more
529 pairs of borrowers column names and values, e.g.,
531 $borrower = GetMember(borrowernumber => id);
533 C<&GetBorrower> returns a reference-to-hash whose keys are the fields of
534 the C<borrowers> table in the Koha database.
536 FIXME: GetMember() is used throughout the code as a lookup
537 on a unique key such as the borrowernumber, but this meaning is not
538 enforced in the routine itself.
544 my ( %information ) = @_;
545 if (exists $information{borrowernumber} && !defined $information{borrowernumber}) {
546 #passing mysql's kohaadmin?? Makes no sense as a query
549 my $dbh = C4::Context->dbh;
551 q{SELECT borrowers.*, categories.category_type, categories.description
553 LEFT JOIN categories on borrowers.categorycode=categories.categorycode WHERE };
556 for (keys %information ) {
564 if (defined $information{$_}) {
566 push @values, $information{$_};
569 $select .= "$_ IS NULL";
572 $debug && warn $select, " ",values %information;
573 my $sth = $dbh->prepare("$select");
574 $sth->execute(map{$information{$_}} keys %information);
575 my $data = $sth->fetchall_arrayref({});
576 #FIXME interface to this routine now allows generation of a result set
577 #so whole array should be returned but bowhere in the current code expects this
586 =head2 IsMemberBlocked
588 my ($block_status, $count) = IsMemberBlocked( $borrowernumber );
590 Returns whether a patron has overdue items that may result
591 in a block or whether the patron has active fine days
592 that would block circulation privileges.
594 C<$block_status> can have the following values:
596 1 if the patron has outstanding fine days, in which case C<$count> is the number of them
598 -1 if the patron has overdue items, in which case C<$count> is the number of them
600 0 if the patron has no overdue items or outstanding fine days, in which case C<$count> is 0
602 Outstanding fine days are checked before current overdue items
605 FIXME: this needs to be split into two functions; a potential block
606 based on the number of current overdue items could be orthogonal
607 to a block based on whether the patron has any fine days accrued.
611 sub IsMemberBlocked {
612 my $borrowernumber = shift;
613 my $dbh = C4::Context->dbh;
615 # does patron have current fine days?
618 ADDDATE(returndate, finedays * DATEDIFF(returndate,date_due) ) AS blockingdate,
619 DATEDIFF(ADDDATE(returndate, finedays * DATEDIFF(returndate,date_due)),NOW()) AS blockedcount
622 if(C4::Context->preference("item-level_itypes")){
624 qq{ LEFT JOIN items ON (items.itemnumber=old_issues.itemnumber)
625 LEFT JOIN issuingrules ON (issuingrules.itemtype=items.itype)}
628 qq{ LEFT JOIN items ON (items.itemnumber=old_issues.itemnumber)
629 LEFT JOIN biblioitems ON (biblioitems.biblioitemnumber=items.biblioitemnumber)
630 LEFT JOIN issuingrules ON (issuingrules.itemtype=biblioitems.itemtype) };
633 qq{ WHERE finedays IS NOT NULL
634 AND date_due < returndate
635 AND borrowernumber = ?
636 ORDER BY blockingdate DESC, blockedcount DESC
638 my $sth=$dbh->prepare($strsth);
639 $sth->execute($borrowernumber);
640 my $row = $sth->fetchrow_hashref;
641 my $blockeddate = $row->{'blockeddate'};
642 my $blockedcount = $row->{'blockedcount'};
644 return (1, $blockedcount) if $blockedcount > 0;
646 # if he have late issues
647 $sth = $dbh->prepare(
648 "SELECT COUNT(*) as latedocs
650 WHERE borrowernumber = ?
651 AND date_due < curdate()"
653 $sth->execute($borrowernumber);
654 my $latedocs = $sth->fetchrow_hashref->{'latedocs'};
656 return (-1, $latedocs) if $latedocs > 0;
661 =head2 GetMemberIssuesAndFines
663 ($overdue_count, $issue_count, $total_fines) = &GetMemberIssuesAndFines($borrowernumber);
665 Returns aggregate data about items borrowed by the patron with the
666 given borrowernumber.
668 C<&GetMemberIssuesAndFines> returns a three-element array. C<$overdue_count> is the
669 number of overdue items the patron currently has borrowed. C<$issue_count> is the
670 number of books the patron currently has borrowed. C<$total_fines> is
671 the total fine currently due by the borrower.
676 sub GetMemberIssuesAndFines {
677 my ( $borrowernumber ) = @_;
678 my $dbh = C4::Context->dbh;
679 my $query = "SELECT COUNT(*) FROM issues WHERE borrowernumber = ?";
681 $debug and warn $query."\n";
682 my $sth = $dbh->prepare($query);
683 $sth->execute($borrowernumber);
684 my $issue_count = $sth->fetchrow_arrayref->[0];
686 $sth = $dbh->prepare(
687 "SELECT COUNT(*) FROM issues
688 WHERE borrowernumber = ?
689 AND date_due < curdate()"
691 $sth->execute($borrowernumber);
692 my $overdue_count = $sth->fetchrow_arrayref->[0];
694 $sth = $dbh->prepare("SELECT SUM(amountoutstanding) FROM accountlines WHERE borrowernumber = ?");
695 $sth->execute($borrowernumber);
696 my $total_fines = $sth->fetchrow_arrayref->[0];
698 return ($overdue_count, $issue_count, $total_fines);
702 return @{C4::Context->dbh->selectcol_arrayref("SHOW columns from borrowers")};
707 my $success = ModMember(borrowernumber => $borrowernumber,
708 [ field => value ]... );
710 Modify borrower's data. All date fields should ALREADY be in ISO format.
713 true on success, or false on failure
719 # test to know if you must update or not the borrower password
720 if (exists $data{password}) {
721 if ($data{password} eq '****' or $data{password} eq '') {
722 delete $data{password};
724 $data{password} = md5_base64($data{password});
727 my $execute_success=UpdateInTable("borrowers",\%data);
728 # ok if its an adult (type) it may have borrowers that depend on it as a guarantor
729 # so when we update information for an adult we should check for guarantees and update the relevant part
730 # of their records, ie addresses and phone numbers
731 my $borrowercategory= GetBorrowercategory( $data{'category_type'} );
732 if ( exists $borrowercategory->{'category_type'} && $borrowercategory->{'category_type'} eq ('A' || 'S') ) {
733 # is adult check guarantees;
734 UpdateGuarantees(%data);
736 logaction("MEMBERS", "MODIFY", $data{'borrowernumber'}, "UPDATE (executed w/ arg: $data{'borrowernumber'})")
737 if C4::Context->preference("BorrowersLog");
739 return $execute_success;
745 $borrowernumber = &AddMember(%borrower);
747 insert new borrower into table
748 Returns the borrowernumber
755 my $dbh = C4::Context->dbh;
756 $data{'password'} = '!' if (not $data{'password'} and $data{'userid'});
757 $data{'password'} = md5_base64( $data{'password'} ) if $data{'password'};
758 $data{'borrowernumber'}=InsertInTable("borrowers",\%data);
759 # mysql_insertid is probably bad. not necessarily accurate and mysql-specific at best.
760 logaction("MEMBERS", "CREATE", $data{'borrowernumber'}, "") if C4::Context->preference("BorrowersLog");
762 # check for enrollment fee & add it if needed
763 my $sth = $dbh->prepare("SELECT enrolmentfee FROM categories WHERE categorycode=?");
764 $sth->execute($data{'categorycode'});
765 my ($enrolmentfee) = $sth->fetchrow;
766 if ($enrolmentfee && $enrolmentfee > 0) {
767 # insert fee in patron debts
768 manualinvoice($data{'borrowernumber'}, '', '', 'A', $enrolmentfee);
770 return $data{'borrowernumber'};
775 my ($uid,$member) = @_;
776 my $dbh = C4::Context->dbh;
777 # Make sure the userid chosen is unique and not theirs if non-empty. If it is not,
778 # Then we need to tell the user and have them create a new one.
781 "SELECT * FROM borrowers WHERE userid=? AND borrowernumber != ?");
782 $sth->execute( $uid, $member );
783 if ( ( $uid ne '' ) && ( my $row = $sth->fetchrow_hashref ) ) {
791 sub Generate_Userid {
792 my ($borrowernumber, $firstname, $surname) = @_;
796 $firstname =~ s/[[:digit:][:space:][:blank:][:punct:][:cntrl:]]//g;
797 $surname =~ s/[[:digit:][:space:][:blank:][:punct:][:cntrl:]]//g;
798 $newuid = lc("$firstname.$surname");
799 $newuid .= $offset unless $offset == 0;
802 } while (!Check_Userid($newuid,$borrowernumber));
808 my ( $uid, $member, $digest ) = @_;
809 my $dbh = C4::Context->dbh;
811 #Make sure the userid chosen is unique and not theirs if non-empty. If it is not,
812 #Then we need to tell the user and have them create a new one.
816 "SELECT * FROM borrowers WHERE userid=? AND borrowernumber != ?");
817 $sth->execute( $uid, $member );
818 if ( ( $uid ne '' ) && ( my $row = $sth->fetchrow_hashref ) ) {
822 #Everything is good so we can update the information.
825 "update borrowers set userid=?, password=? where borrowernumber=?");
826 $sth->execute( $uid, $digest, $member );
830 logaction("MEMBERS", "CHANGE PASS", $member, "") if C4::Context->preference("BorrowersLog");
836 =head2 fixup_cardnumber
838 Warning: The caller is responsible for locking the members table in write
839 mode, to avoid database corruption.
843 use vars qw( @weightings );
844 my @weightings = ( 8, 4, 6, 3, 5, 2, 1 );
846 sub fixup_cardnumber ($) {
847 my ($cardnumber) = @_;
848 my $autonumber_members = C4::Context->boolean_preference('autoMemberNum') || 0;
850 # Find out whether member numbers should be generated
851 # automatically. Should be either "1" or something else.
852 # Defaults to "0", which is interpreted as "no".
854 # if ($cardnumber !~ /\S/ && $autonumber_members) {
855 ($autonumber_members) or return $cardnumber;
856 my $checkdigit = C4::Context->preference('checkdigit');
857 my $dbh = C4::Context->dbh;
858 if ( $checkdigit and $checkdigit eq 'katipo' ) {
860 # if checkdigit is selected, calculate katipo-style cardnumber.
861 # otherwise, just use the max()
862 # purpose: generate checksum'd member numbers.
863 # We'll assume we just got the max value of digits 2-8 of member #'s
864 # from the database and our job is to increment that by one,
865 # determine the 1st and 9th digits and return the full string.
866 my $sth = $dbh->prepare(
867 "select max(substring(borrowers.cardnumber,2,7)) as new_num from borrowers"
870 my $data = $sth->fetchrow_hashref;
871 $cardnumber = $data->{new_num};
872 if ( !$cardnumber ) { # If DB has no values,
873 $cardnumber = 1000000; # start at 1000000
879 for ( my $i = 0 ; $i < 8 ; $i += 1 ) {
880 # read weightings, left to right, 1 char at a time
881 my $temp1 = $weightings[$i];
883 # sequence left to right, 1 char at a time
884 my $temp2 = substr( $cardnumber, $i, 1 );
886 # mult each char 1-7 by its corresponding weighting
887 $sum += $temp1 * $temp2;
890 my $rem = ( $sum % 11 );
891 $rem = 'X' if $rem == 10;
893 return "V$cardnumber$rem";
896 # MODIFIED BY JF: mysql4.1 allows casting as an integer, which is probably
897 # better. I'll leave the original in in case it needs to be changed for you
898 # my $sth=$dbh->prepare("select max(borrowers.cardnumber) from borrowers");
899 my $sth = $dbh->prepare(
900 "select max(cast(cardnumber as signed)) from borrowers"
903 my ($result) = $sth->fetchrow;
906 return $cardnumber; # just here as a fallback/reminder
911 ($num_children, $children_arrayref) = &GetGuarantees($parent_borrno);
912 $child0_cardno = $children_arrayref->[0]{"cardnumber"};
913 $child0_borrno = $children_arrayref->[0]{"borrowernumber"};
915 C<&GetGuarantees> takes a borrower number (e.g., that of a patron
916 with children) and looks up the borrowers who are guaranteed by that
917 borrower (i.e., the patron's children).
919 C<&GetGuarantees> returns two values: an integer giving the number of
920 borrowers guaranteed by C<$parent_borrno>, and a reference to an array
921 of references to hash, which gives the actual results.
927 my ($borrowernumber) = @_;
928 my $dbh = C4::Context->dbh;
931 "select cardnumber,borrowernumber, firstname, surname from borrowers where guarantorid=?"
933 $sth->execute($borrowernumber);
936 my $data = $sth->fetchall_arrayref({});
937 return ( scalar(@$data), $data );
940 =head2 UpdateGuarantees
942 &UpdateGuarantees($parent_borrno);
945 C<&UpdateGuarantees> borrower data for an adult and updates all the guarantees
946 with the modified information
951 sub UpdateGuarantees {
953 my $dbh = C4::Context->dbh;
954 my ( $count, $guarantees ) = GetGuarantees( $data{'borrowernumber'} );
955 foreach my $guarantee (@$guarantees){
956 my $guaquery = qq|UPDATE borrowers
957 SET address=?,fax=?,B_city=?,mobile=?,city=?,phone=?
958 WHERE borrowernumber=?
960 my $sth = $dbh->prepare($guaquery);
961 $sth->execute($data{'address'},$data{'fax'},$data{'B_city'},$data{'mobile'},$data{'city'},$data{'phone'},$guarantee->{'borrowernumber'});
964 =head2 GetPendingIssues
966 my $issues = &GetPendingIssues($borrowernumber);
968 Looks up what the patron with the given borrowernumber has borrowed.
970 C<&GetPendingIssues> returns a
971 reference-to-array where each element is a reference-to-hash; the
972 keys are the fields from the C<issues>, C<biblio>, and C<items> tables.
973 The keys include C<biblioitems> fields except marc and marcxml.
978 sub GetPendingIssues {
979 my ($borrowernumber) = @_;
980 # must avoid biblioitems.* to prevent large marc and marcxml fields from killing performance
981 # FIXME: namespace collision: each table has "timestamp" fields. Which one is "timestamp" ?
982 # FIXME: circ/ciculation.pl tries to sort by timestamp!
983 # FIXME: C4::Print::printslip tries to sort by timestamp!
984 # FIXME: namespace collision: other collisions possible.
985 # FIXME: most of this data isn't really being used by callers.
986 my $sth = C4::Context->dbh->prepare(
992 biblioitems.itemtype,
995 biblioitems.publicationyear,
996 biblioitems.publishercode,
997 biblioitems.volumedate,
998 biblioitems.volumedesc,
1001 issues.timestamp AS timestamp,
1002 issues.renewals AS renewals,
1003 items.renewals AS totalrenewals
1005 LEFT JOIN items ON items.itemnumber = issues.itemnumber
1006 LEFT JOIN biblio ON items.biblionumber = biblio.biblionumber
1007 LEFT JOIN biblioitems ON items.biblioitemnumber = biblioitems.biblioitemnumber
1010 ORDER BY issues.issuedate"
1012 $sth->execute($borrowernumber);
1013 my $data = $sth->fetchall_arrayref({});
1014 my $today = C4::Dates->new->output('iso');
1016 $_->{date_due} or next;
1017 ($_->{date_due} lt $today) and $_->{overdue} = 1;
1024 $issues = &GetAllIssues($borrowernumber, $sortkey, $limit);
1026 Looks up what the patron with the given borrowernumber has borrowed,
1027 and sorts the results.
1029 C<$sortkey> is the name of a field on which to sort the results. This
1030 should be the name of a field in the C<issues>, C<biblio>,
1031 C<biblioitems>, or C<items> table in the Koha database.
1033 C<$limit> is the maximum number of results to return.
1035 C<&GetAllIssues> an arrayref, C<$issues>, of hashrefs, the keys of which
1036 are the fields from the C<issues>, C<biblio>, C<biblioitems>, and
1037 C<items> tables of the Koha database.
1043 my ( $borrowernumber, $order, $limit ) = @_;
1045 #FIXME: sanity-check order and limit
1046 my $dbh = C4::Context->dbh;
1048 "SELECT *, issues.timestamp as issuestimestamp, issues.renewals AS renewals,items.renewals AS totalrenewals,items.timestamp AS itemstimestamp
1050 LEFT JOIN items on items.itemnumber=issues.itemnumber
1051 LEFT JOIN biblio ON items.biblionumber=biblio.biblionumber
1052 LEFT JOIN biblioitems ON items.biblioitemnumber=biblioitems.biblioitemnumber
1053 WHERE borrowernumber=?
1055 SELECT *, old_issues.timestamp as issuestimestamp, old_issues.renewals AS renewals,items.renewals AS totalrenewals,items.timestamp AS itemstimestamp
1057 LEFT JOIN items on items.itemnumber=old_issues.itemnumber
1058 LEFT JOIN biblio ON items.biblionumber=biblio.biblionumber
1059 LEFT JOIN biblioitems ON items.biblioitemnumber=biblioitems.biblioitemnumber
1060 WHERE borrowernumber=?
1062 if ( $limit != 0 ) {
1063 $query .= " limit $limit";
1066 my $sth = $dbh->prepare($query);
1067 $sth->execute($borrowernumber, $borrowernumber);
1070 while ( my $data = $sth->fetchrow_hashref ) {
1071 push @result, $data;
1078 =head2 GetMemberAccountRecords
1080 ($total, $acctlines, $count) = &GetMemberAccountRecords($borrowernumber);
1082 Looks up accounting data for the patron with the given borrowernumber.
1084 C<&GetMemberAccountRecords> returns a three-element array. C<$acctlines> is a
1085 reference-to-array, where each element is a reference-to-hash; the
1086 keys are the fields of the C<accountlines> table in the Koha database.
1087 C<$count> is the number of elements in C<$acctlines>. C<$total> is the
1088 total amount outstanding for all of the account lines.
1093 sub GetMemberAccountRecords {
1094 my ($borrowernumber,$date) = @_;
1095 my $dbh = C4::Context->dbh;
1101 WHERE borrowernumber=?);
1102 my @bind = ($borrowernumber);
1103 if ($date && $date ne ''){
1104 $strsth.=" AND date < ? ";
1107 $strsth.=" ORDER BY date desc,timestamp DESC";
1108 my $sth= $dbh->prepare( $strsth );
1109 $sth->execute( @bind );
1111 while ( my $data = $sth->fetchrow_hashref ) {
1112 my $biblio = GetBiblioFromItemNumber($data->{itemnumber}) if $data->{itemnumber};
1113 $data->{biblionumber} = $biblio->{biblionumber};
1114 $data->{title} = $biblio->{title};
1115 $acctlines[$numlines] = $data;
1117 $total += int(1000 * $data->{'amountoutstanding'}); # convert float to integer to avoid round-off errors
1120 return ( $total, \@acctlines,$numlines);
1123 =head2 GetBorNotifyAcctRecord
1125 ($count, $acctlines, $total) = &GetBorNotifyAcctRecord($params,$notifyid);
1127 Looks up accounting data for the patron with the given borrowernumber per file number.
1129 (FIXME - I'm not at all sure what this is about.)
1131 C<&GetBorNotifyAcctRecord> returns a three-element array. C<$acctlines> is a
1132 reference-to-array, where each element is a reference-to-hash; the
1133 keys are the fields of the C<accountlines> table in the Koha database.
1134 C<$count> is the number of elements in C<$acctlines>. C<$total> is the
1135 total amount outstanding for all of the account lines.
1139 sub GetBorNotifyAcctRecord {
1140 my ( $borrowernumber, $notifyid ) = @_;
1141 my $dbh = C4::Context->dbh;
1144 my $sth = $dbh->prepare(
1147 WHERE borrowernumber=?
1149 AND amountoutstanding != '0'
1150 ORDER BY notify_id,accounttype
1152 # AND (accounttype='FU' OR accounttype='N' OR accounttype='M'OR accounttype='A'OR accounttype='F'OR accounttype='L' OR accounttype='IP' OR accounttype='CH' OR accounttype='RE' OR accounttype='RL')
1154 $sth->execute( $borrowernumber, $notifyid );
1156 while ( my $data = $sth->fetchrow_hashref ) {
1157 $acctlines[$numlines] = $data;
1159 $total += int(100 * $data->{'amountoutstanding'});
1162 return ( $total, \@acctlines, $numlines );
1165 =head2 checkuniquemember (OUEST-PROVENCE)
1167 ($result,$categorycode) = &checkuniquemember($collectivity,$surname,$firstname,$dateofbirth);
1169 Checks that a member exists or not in the database.
1171 C<&result> is nonzero (=exist) or 0 (=does not exist)
1172 C<&categorycode> is from categorycode table
1173 C<&collectivity> is 1 (= we add a collectivity) or 0 (= we add a physical member)
1174 C<&surname> is the surname
1175 C<&firstname> is the firstname (only if collectivity=0)
1176 C<&dateofbirth> is the date of birth in ISO format (only if collectivity=0)
1180 # FIXME: This function is not legitimate. Multiple patrons might have the same first/last name and birthdate.
1181 # This is especially true since first name is not even a required field.
1183 sub checkuniquemember {
1184 my ( $collectivity, $surname, $firstname, $dateofbirth ) = @_;
1185 my $dbh = C4::Context->dbh;
1186 my $request = ($collectivity) ?
1187 "SELECT borrowernumber,categorycode FROM borrowers WHERE surname=? " :
1189 "SELECT borrowernumber,categorycode FROM borrowers WHERE surname=? and firstname=? and dateofbirth=?" :
1190 "SELECT borrowernumber,categorycode FROM borrowers WHERE surname=? and firstname=?";
1191 my $sth = $dbh->prepare($request);
1192 if ($collectivity) {
1193 $sth->execute( uc($surname) );
1194 } elsif($dateofbirth){
1195 $sth->execute( uc($surname), ucfirst($firstname), $dateofbirth );
1197 $sth->execute( uc($surname), ucfirst($firstname));
1199 my @data = $sth->fetchrow;
1200 ( $data[0] ) and return $data[0], $data[1];
1204 sub checkcardnumber {
1205 my ($cardnumber,$borrowernumber) = @_;
1206 my $dbh = C4::Context->dbh;
1207 my $query = "SELECT * FROM borrowers WHERE cardnumber=?";
1208 $query .= " AND borrowernumber <> ?" if ($borrowernumber);
1209 my $sth = $dbh->prepare($query);
1210 if ($borrowernumber) {
1211 $sth->execute($cardnumber,$borrowernumber);
1213 $sth->execute($cardnumber);
1215 if (my $data= $sth->fetchrow_hashref()){
1224 =head2 getzipnamecity (OUEST-PROVENCE)
1226 take all info from table city for the fields city and zip
1227 check for the name and the zip code of the city selected
1231 sub getzipnamecity {
1233 my $dbh = C4::Context->dbh;
1236 "select city_name,city_zipcode from cities where cityid=? ");
1237 $sth->execute($cityid);
1238 my @data = $sth->fetchrow;
1239 return $data[0], $data[1];
1243 =head2 getdcity (OUEST-PROVENCE)
1245 recover cityid with city_name condition
1250 my ($city_name) = @_;
1251 my $dbh = C4::Context->dbh;
1252 my $sth = $dbh->prepare("select cityid from cities where city_name=? ");
1253 $sth->execute($city_name);
1254 my $data = $sth->fetchrow;
1258 =head2 GetFirstValidEmailAddress
1260 $email = GetFirstValidEmailAddress($borrowernumber);
1262 Return the first valid email address for a borrower, given the borrowernumber. For now, the order
1263 is defined as email, emailpro, B_email. Returns the empty string if the borrower has no email
1268 sub GetFirstValidEmailAddress {
1269 my $borrowernumber = shift;
1270 my $dbh = C4::Context->dbh;
1271 my $sth = $dbh->prepare( "SELECT email, emailpro, B_email FROM borrowers where borrowernumber = ? ");
1272 $sth->execute( $borrowernumber );
1273 my $data = $sth->fetchrow_hashref;
1275 if ($data->{'email'}) {
1276 return $data->{'email'};
1277 } elsif ($data->{'emailpro'}) {
1278 return $data->{'emailpro'};
1279 } elsif ($data->{'B_email'}) {
1280 return $data->{'B_email'};
1286 =head2 GetExpiryDate
1288 $expirydate = GetExpiryDate($categorycode, $dateenrolled);
1290 Calculate expiry date given a categorycode and starting date. Date argument must be in ISO format.
1291 Return date is also in ISO format.
1296 my ( $categorycode, $dateenrolled ) = @_;
1298 if ($categorycode) {
1299 my $dbh = C4::Context->dbh;
1300 my $sth = $dbh->prepare("SELECT enrolmentperiod,enrolmentperioddate FROM categories WHERE categorycode=?");
1301 $sth->execute($categorycode);
1302 $enrolments = $sth->fetchrow_hashref;
1304 # die "GetExpiryDate: for enrollmentperiod $enrolmentperiod (category '$categorycode') starting $dateenrolled.\n";
1305 my @date = split (/-/,$dateenrolled);
1306 if($enrolments->{enrolmentperiod}){
1307 return sprintf("%04d-%02d-%02d", Add_Delta_YM(@date,0,$enrolments->{enrolmentperiod}));
1309 return $enrolments->{enrolmentperioddate};
1313 =head2 checkuserpassword (OUEST-PROVENCE)
1315 check for the password and login are not used
1316 return the number of record
1317 0=> NOT USED 1=> USED
1321 sub checkuserpassword {
1322 my ( $borrowernumber, $userid, $password ) = @_;
1323 $password = md5_base64($password);
1324 my $dbh = C4::Context->dbh;
1327 "Select count(*) from borrowers where borrowernumber !=? and userid =? and password=? "
1329 $sth->execute( $borrowernumber, $userid, $password );
1330 my $number_rows = $sth->fetchrow;
1331 return $number_rows;
1335 =head2 GetborCatFromCatType
1337 ($codes_arrayref, $labels_hashref) = &GetborCatFromCatType();
1339 Looks up the different types of borrowers in the database. Returns two
1340 elements: a reference-to-array, which lists the borrower category
1341 codes, and a reference-to-hash, which maps the borrower category codes
1342 to category descriptions.
1347 sub GetborCatFromCatType {
1348 my ( $category_type, $action ) = @_;
1349 # FIXME - This API seems both limited and dangerous.
1350 my $dbh = C4::Context->dbh;
1351 my $request = qq| SELECT categorycode,description
1354 ORDER BY categorycode|;
1355 my $sth = $dbh->prepare($request);
1357 $sth->execute($category_type);
1366 while ( my $data = $sth->fetchrow_hashref ) {
1367 push @codes, $data->{'categorycode'};
1368 $labels{ $data->{'categorycode'} } = $data->{'description'};
1370 return ( \@codes, \%labels );
1373 =head2 GetBorrowercategory
1375 $hashref = &GetBorrowercategory($categorycode);
1377 Given the borrower's category code, the function returns the corresponding
1378 data hashref for a comprehensive information display.
1380 $arrayref_hashref = &GetBorrowercategory;
1382 If no category code provided, the function returns all the categories.
1386 sub GetBorrowercategory {
1388 my $dbh = C4::Context->dbh;
1392 "SELECT description,dateofbirthrequired,upperagelimit,category_type
1394 WHERE categorycode = ?"
1396 $sth->execute($catcode);
1398 $sth->fetchrow_hashref;
1402 } # sub getborrowercategory
1404 =head2 GetBorrowercategoryList
1406 $arrayref_hashref = &GetBorrowercategoryList;
1407 If no category code provided, the function returns all the categories.
1411 sub GetBorrowercategoryList {
1412 my $dbh = C4::Context->dbh;
1417 ORDER BY description"
1421 $sth->fetchall_arrayref({});
1423 } # sub getborrowercategory
1425 =head2 ethnicitycategories
1427 ($codes_arrayref, $labels_hashref) = ðnicitycategories();
1429 Looks up the different ethnic types in the database. Returns two
1430 elements: a reference-to-array, which lists the ethnicity codes, and a
1431 reference-to-hash, which maps the ethnicity codes to ethnicity
1438 sub ethnicitycategories {
1439 my $dbh = C4::Context->dbh;
1440 my $sth = $dbh->prepare("Select code,name from ethnicity order by name");
1444 while ( my $data = $sth->fetchrow_hashref ) {
1445 push @codes, $data->{'code'};
1446 $labels{ $data->{'code'} } = $data->{'name'};
1448 return ( \@codes, \%labels );
1453 $ethn_name = &fixEthnicity($ethn_code);
1455 Takes an ethnicity code (e.g., "european" or "pi") and returns the
1456 corresponding descriptive name from the C<ethnicity> table in the
1457 Koha database ("European" or "Pacific Islander").
1464 my $ethnicity = shift;
1465 return unless $ethnicity;
1466 my $dbh = C4::Context->dbh;
1467 my $sth = $dbh->prepare("Select name from ethnicity where code = ?");
1468 $sth->execute($ethnicity);
1469 my $data = $sth->fetchrow_hashref;
1470 return $data->{'name'};
1471 } # sub fixEthnicity
1475 $dateofbirth,$date = &GetAge($date);
1477 this function return the borrowers age with the value of dateofbirth
1483 my ( $date, $date_ref ) = @_;
1485 if ( not defined $date_ref ) {
1486 $date_ref = sprintf( '%04d-%02d-%02d', Today() );
1489 my ( $year1, $month1, $day1 ) = split /-/, $date;
1490 my ( $year2, $month2, $day2 ) = split /-/, $date_ref;
1492 my $age = $year2 - $year1;
1493 if ( $month1 . $day1 > $month2 . $day2 ) {
1500 =head2 get_institutions
1502 $insitutions = get_institutions();
1504 Just returns a list of all the borrowers of type I, borrownumber and name
1509 sub get_institutions {
1510 my $dbh = C4::Context->dbh();
1513 "SELECT borrowernumber,surname FROM borrowers WHERE categorycode=? ORDER BY surname"
1517 while ( my $data = $sth->fetchrow_hashref() ) {
1518 $orgs{ $data->{'borrowernumber'} } = $data;
1522 } # sub get_institutions
1524 =head2 add_member_orgs
1526 add_member_orgs($borrowernumber,$borrowernumbers);
1528 Takes a borrowernumber and a list of other borrowernumbers and inserts them into the borrowers_to_borrowers table
1533 sub add_member_orgs {
1534 my ( $borrowernumber, $otherborrowers ) = @_;
1535 my $dbh = C4::Context->dbh();
1537 "INSERT INTO borrowers_to_borrowers (borrower1,borrower2) VALUES (?,?)";
1538 my $sth = $dbh->prepare($query);
1539 foreach my $otherborrowernumber (@$otherborrowers) {
1540 $sth->execute( $borrowernumber, $otherborrowernumber );
1543 } # sub add_member_orgs
1547 $cityarrayref = GetCities();
1549 Returns an array_ref of the entries in the cities table
1550 If there are entries in the table an empty row is returned
1551 This is currently only used to populate a popup in memberentry
1557 my $dbh = C4::Context->dbh;
1558 my $city_arr = $dbh->selectall_arrayref(
1559 q|SELECT cityid,city_zipcode,city_name FROM cities ORDER BY city_name|,
1561 if ( @{$city_arr} ) {
1562 unshift @{$city_arr}, {
1563 city_zipcode => q{},
1572 =head2 GetSortDetails (OUEST-PROVENCE)
1574 ($lib) = &GetSortDetails($category,$sortvalue);
1576 Returns the authorized value details
1577 C<&$lib>return value of authorized value details
1578 C<&$sortvalue>this is the value of authorized value
1579 C<&$category>this is the value of authorized value category
1583 sub GetSortDetails {
1584 my ( $category, $sortvalue ) = @_;
1585 my $dbh = C4::Context->dbh;
1586 my $query = qq|SELECT lib
1587 FROM authorised_values
1589 AND authorised_value=? |;
1590 my $sth = $dbh->prepare($query);
1591 $sth->execute( $category, $sortvalue );
1592 my $lib = $sth->fetchrow;
1593 return ($lib) if ($lib);
1594 return ($sortvalue) unless ($lib);
1597 =head2 MoveMemberToDeleted
1599 $result = &MoveMemberToDeleted($borrowernumber);
1601 Copy the record from borrowers to deletedborrowers table.
1605 # FIXME: should do it in one SQL statement w/ subquery
1606 # Otherwise, we should return the @data on success
1608 sub MoveMemberToDeleted {
1609 my ($member) = shift or return;
1610 my $dbh = C4::Context->dbh;
1611 my $query = qq|SELECT *
1613 WHERE borrowernumber=?|;
1614 my $sth = $dbh->prepare($query);
1615 $sth->execute($member);
1616 my @data = $sth->fetchrow_array;
1617 (@data) or return; # if we got a bad borrowernumber, there's nothing to insert
1619 $dbh->prepare( "INSERT INTO deletedborrowers VALUES ("
1620 . ( "?," x ( scalar(@data) - 1 ) )
1622 $sth->execute(@data);
1627 DelMember($borrowernumber);
1629 This function remove directly a borrower whitout writing it on deleteborrower.
1630 + Deletes reserves for the borrower
1635 my $dbh = C4::Context->dbh;
1636 my $borrowernumber = shift;
1637 #warn "in delmember with $borrowernumber";
1638 return unless $borrowernumber; # borrowernumber is mandatory.
1640 my $query = qq|DELETE
1642 WHERE borrowernumber=?|;
1643 my $sth = $dbh->prepare($query);
1644 $sth->execute($borrowernumber);
1648 WHERE borrowernumber = ?
1650 $sth = $dbh->prepare($query);
1651 $sth->execute($borrowernumber);
1652 logaction("MEMBERS", "DELETE", $borrowernumber, "") if C4::Context->preference("BorrowersLog");
1656 =head2 ExtendMemberSubscriptionTo (OUEST-PROVENCE)
1658 $date = ExtendMemberSubscriptionTo($borrowerid, $date);
1660 Extending the subscription to a given date or to the expiry date calculated on ISO date.
1665 sub ExtendMemberSubscriptionTo {
1666 my ( $borrowerid,$date) = @_;
1667 my $dbh = C4::Context->dbh;
1668 my $borrower = GetMember('borrowernumber'=>$borrowerid);
1670 $date=POSIX::strftime("%Y-%m-%d",localtime());
1671 $date = GetExpiryDate( $borrower->{'categorycode'}, $date );
1673 my $sth = $dbh->do(<<EOF);
1675 SET dateexpiry='$date'
1676 WHERE borrowernumber='$borrowerid'
1678 # add enrolmentfee if needed
1679 $sth = $dbh->prepare("SELECT enrolmentfee FROM categories WHERE categorycode=?");
1680 $sth->execute($borrower->{'categorycode'});
1681 my ($enrolmentfee) = $sth->fetchrow;
1682 if ($enrolmentfee && $enrolmentfee > 0) {
1683 # insert fee in patron debts
1684 manualinvoice($borrower->{'borrowernumber'}, '', '', 'A', $enrolmentfee);
1686 return $date if ($sth);
1690 =head2 GetRoadTypes (OUEST-PROVENCE)
1692 ($idroadtypearrayref, $roadttype_hashref) = &GetRoadTypes();
1694 Looks up the different road type . Returns two
1695 elements: a reference-to-array, which lists the id_roadtype
1696 codes, and a reference-to-hash, which maps the road type of the road .
1701 my $dbh = C4::Context->dbh;
1703 SELECT roadtypeid,road_type
1705 ORDER BY road_type|;
1706 my $sth = $dbh->prepare($query);
1711 # insert empty value to create a empty choice in cgi popup
1713 while ( my $data = $sth->fetchrow_hashref ) {
1715 push @id, $data->{'roadtypeid'};
1716 $roadtype{ $data->{'roadtypeid'} } = $data->{'road_type'};
1719 #test to know if the table contain some records if no the function return nothing
1726 return ( \@id, \%roadtype );
1732 =head2 GetTitles (OUEST-PROVENCE)
1734 ($borrowertitle)= &GetTitles();
1736 Looks up the different title . Returns array with all borrowers title
1741 my @borrowerTitle = split (/,|\|/,C4::Context->preference('BorrowersTitles'));
1742 unshift( @borrowerTitle, "" );
1743 my $count=@borrowerTitle;
1748 return ( \@borrowerTitle);
1752 =head2 GetPatronImage
1754 my ($imagedata, $dberror) = GetPatronImage($cardnumber);
1756 Returns the mimetype and binary image data of the image for the patron with the supplied cardnumber.
1760 sub GetPatronImage {
1761 my ($cardnumber) = @_;
1762 warn "Cardnumber passed to GetPatronImage is $cardnumber" if $debug;
1763 my $dbh = C4::Context->dbh;
1764 my $query = 'SELECT mimetype, imagefile FROM patronimage WHERE cardnumber = ?';
1765 my $sth = $dbh->prepare($query);
1766 $sth->execute($cardnumber);
1767 my $imagedata = $sth->fetchrow_hashref;
1768 warn "Database error!" if $sth->errstr;
1769 return $imagedata, $sth->errstr;
1772 =head2 PutPatronImage
1774 PutPatronImage($cardnumber, $mimetype, $imgfile);
1776 Stores patron binary image data and mimetype in database.
1777 NOTE: This function is good for updating images as well as inserting new images in the database.
1781 sub PutPatronImage {
1782 my ($cardnumber, $mimetype, $imgfile) = @_;
1783 warn "Parameters passed in: Cardnumber=$cardnumber, Mimetype=$mimetype, " . ($imgfile ? "Imagefile" : "No Imagefile") if $debug;
1784 my $dbh = C4::Context->dbh;
1785 my $query = "INSERT INTO patronimage (cardnumber, mimetype, imagefile) VALUES (?,?,?) ON DUPLICATE KEY UPDATE imagefile = ?;";
1786 my $sth = $dbh->prepare($query);
1787 $sth->execute($cardnumber,$mimetype,$imgfile,$imgfile);
1788 warn "Error returned inserting $cardnumber.$mimetype." if $sth->errstr;
1789 return $sth->errstr;
1792 =head2 RmPatronImage
1794 my ($dberror) = RmPatronImage($cardnumber);
1796 Removes the image for the patron with the supplied cardnumber.
1801 my ($cardnumber) = @_;
1802 warn "Cardnumber passed to GetPatronImage is $cardnumber" if $debug;
1803 my $dbh = C4::Context->dbh;
1804 my $query = "DELETE FROM patronimage WHERE cardnumber = ?;";
1805 my $sth = $dbh->prepare($query);
1806 $sth->execute($cardnumber);
1807 my $dberror = $sth->errstr;
1808 warn "Database error!" if $sth->errstr;
1812 =head2 GetHideLostItemsPreference
1814 $hidelostitemspref = &GetHideLostItemsPreference($borrowernumber);
1816 Returns the HideLostItems preference for the patron category of the supplied borrowernumber
1817 C<&$hidelostitemspref>return value of function, 0 or 1
1821 sub GetHideLostItemsPreference {
1822 my ($borrowernumber) = @_;
1823 my $dbh = C4::Context->dbh;
1824 my $query = "SELECT hidelostitems FROM borrowers,categories WHERE borrowers.categorycode = categories.categorycode AND borrowernumber = ?";
1825 my $sth = $dbh->prepare($query);
1826 $sth->execute($borrowernumber);
1827 my $hidelostitems = $sth->fetchrow;
1828 return $hidelostitems;
1831 =head2 GetRoadTypeDetails (OUEST-PROVENCE)
1833 ($roadtype) = &GetRoadTypeDetails($roadtypeid);
1835 Returns the description of roadtype
1836 C<&$roadtype>return description of road type
1837 C<&$roadtypeid>this is the value of roadtype s
1841 sub GetRoadTypeDetails {
1842 my ($roadtypeid) = @_;
1843 my $dbh = C4::Context->dbh;
1847 WHERE roadtypeid=?|;
1848 my $sth = $dbh->prepare($query);
1849 $sth->execute($roadtypeid);
1850 my $roadtype = $sth->fetchrow;
1854 =head2 GetBorrowersWhoHaveNotBorrowedSince
1856 &GetBorrowersWhoHaveNotBorrowedSince($date)
1858 this function get all borrowers who haven't borrowed since the date given on input arg.
1862 sub GetBorrowersWhoHaveNotBorrowedSince {
1863 my $filterdate = shift||POSIX::strftime("%Y-%m-%d",localtime());
1864 my $filterexpiry = shift;
1865 my $filterbranch = shift ||
1866 ((C4::Context->preference('IndependantBranches')
1867 && C4::Context->userenv
1868 && C4::Context->userenv->{flags} % 2 !=1
1869 && C4::Context->userenv->{branch})
1870 ? C4::Context->userenv->{branch}
1872 my $dbh = C4::Context->dbh;
1874 SELECT borrowers.borrowernumber,
1875 max(old_issues.timestamp) as latestissue,
1876 max(issues.timestamp) as currentissue
1878 JOIN categories USING (categorycode)
1879 LEFT JOIN old_issues USING (borrowernumber)
1880 LEFT JOIN issues USING (borrowernumber)
1881 WHERE category_type <> 'S'
1882 AND borrowernumber NOT IN (SELECT guarantorid FROM borrowers WHERE guarantorid IS NOT NULL AND guarantorid <> 0)
1885 if ($filterbranch && $filterbranch ne ""){
1886 $query.=" AND borrowers.branchcode= ?";
1887 push @query_params,$filterbranch;
1890 $query .= " AND dateexpiry < ? ";
1891 push @query_params,$filterdate;
1893 $query.=" GROUP BY borrowers.borrowernumber";
1895 $query.=" HAVING (latestissue < ? OR latestissue IS NULL)
1896 AND currentissue IS NULL";
1897 push @query_params,$filterdate;
1899 warn $query if $debug;
1900 my $sth = $dbh->prepare($query);
1901 if (scalar(@query_params)>0){
1902 $sth->execute(@query_params);
1909 while ( my $data = $sth->fetchrow_hashref ) {
1910 push @results, $data;
1915 =head2 GetBorrowersWhoHaveNeverBorrowed
1917 $results = &GetBorrowersWhoHaveNeverBorrowed
1919 This function get all borrowers who have never borrowed.
1921 I<$result> is a ref to an array which all elements are a hasref.
1925 sub GetBorrowersWhoHaveNeverBorrowed {
1926 my $filterbranch = shift ||
1927 ((C4::Context->preference('IndependantBranches')
1928 && C4::Context->userenv
1929 && C4::Context->userenv->{flags} % 2 !=1
1930 && C4::Context->userenv->{branch})
1931 ? C4::Context->userenv->{branch}
1933 my $dbh = C4::Context->dbh;
1935 SELECT borrowers.borrowernumber,max(timestamp) as latestissue
1937 LEFT JOIN issues ON borrowers.borrowernumber = issues.borrowernumber
1938 WHERE issues.borrowernumber IS NULL
1941 if ($filterbranch && $filterbranch ne ""){
1942 $query.=" AND borrowers.branchcode= ?";
1943 push @query_params,$filterbranch;
1945 warn $query if $debug;
1947 my $sth = $dbh->prepare($query);
1948 if (scalar(@query_params)>0){
1949 $sth->execute(@query_params);
1956 while ( my $data = $sth->fetchrow_hashref ) {
1957 push @results, $data;
1962 =head2 GetBorrowersWithIssuesHistoryOlderThan
1964 $results = &GetBorrowersWithIssuesHistoryOlderThan($date)
1966 this function get all borrowers who has an issue history older than I<$date> given on input arg.
1968 I<$result> is a ref to an array which all elements are a hashref.
1969 This hashref is containt the number of time this borrowers has borrowed before I<$date> and the borrowernumber.
1973 sub GetBorrowersWithIssuesHistoryOlderThan {
1974 my $dbh = C4::Context->dbh;
1975 my $date = shift ||POSIX::strftime("%Y-%m-%d",localtime());
1976 my $filterbranch = shift ||
1977 ((C4::Context->preference('IndependantBranches')
1978 && C4::Context->userenv
1979 && C4::Context->userenv->{flags} % 2 !=1
1980 && C4::Context->userenv->{branch})
1981 ? C4::Context->userenv->{branch}
1984 SELECT count(borrowernumber) as n,borrowernumber
1986 WHERE returndate < ?
1987 AND borrowernumber IS NOT NULL
1990 push @query_params, $date;
1992 $query.=" AND branchcode = ?";
1993 push @query_params, $filterbranch;
1995 $query.=" GROUP BY borrowernumber ";
1996 warn $query if $debug;
1997 my $sth = $dbh->prepare($query);
1998 $sth->execute(@query_params);
2001 while ( my $data = $sth->fetchrow_hashref ) {
2002 push @results, $data;
2007 =head2 GetBorrowersNamesAndLatestIssue
2009 $results = &GetBorrowersNamesAndLatestIssueList(@borrowernumbers)
2011 this function get borrowers Names and surnames and Issue information.
2013 I<@borrowernumbers> is an array which all elements are borrowernumbers.
2014 This hashref is containt the number of time this borrowers has borrowed before I<$date> and the borrowernumber.
2018 sub GetBorrowersNamesAndLatestIssue {
2019 my $dbh = C4::Context->dbh;
2020 my @borrowernumbers=@_;
2022 SELECT surname,lastname, phone, email,max(timestamp)
2024 LEFT JOIN issues ON borrowers.borrowernumber=issues.borrowernumber
2025 GROUP BY borrowernumber
2027 my $sth = $dbh->prepare($query);
2029 my $results = $sth->fetchall_arrayref({});
2035 my $success = DebarMember( $borrowernumber );
2037 marks a Member as debarred, and therefore unable to checkout any more
2041 true on success, false on failure
2046 my $borrowernumber = shift;
2048 return unless defined $borrowernumber;
2049 return unless $borrowernumber =~ /^\d+$/;
2051 return ModMember( borrowernumber => $borrowernumber,
2060 my $success = ModPrivacy( $borrowernumber, $privacy );
2062 Update the privacy of a patron.
2065 true on success, false on failure
2072 my $borrowernumber = shift;
2073 my $privacy = shift;
2074 return unless defined $borrowernumber;
2075 return unless $borrowernumber =~ /^\d+$/;
2077 return ModMember( borrowernumber => $borrowernumber,
2078 privacy => $privacy );
2083 AddMessage( $borrowernumber, $message_type, $message, $branchcode );
2085 Adds a message to the messages table for the given borrower.
2094 my ( $borrowernumber, $message_type, $message, $branchcode ) = @_;
2096 my $dbh = C4::Context->dbh;
2098 if ( ! ( $borrowernumber && $message_type && $message && $branchcode ) ) {
2102 my $query = "INSERT INTO messages ( borrowernumber, branchcode, message_type, message ) VALUES ( ?, ?, ?, ? )";
2103 my $sth = $dbh->prepare($query);
2104 $sth->execute( $borrowernumber, $branchcode, $message_type, $message );
2111 GetMessages( $borrowernumber, $type );
2113 $type is message type, B for borrower, or L for Librarian.
2114 Empty type returns all messages of any type.
2116 Returns all messages for the given borrowernumber
2121 my ( $borrowernumber, $type, $branchcode ) = @_;
2127 my $dbh = C4::Context->dbh;
2130 branches.branchname,
2133 messages.branchcode LIKE '$branchcode' AS can_delete
2134 FROM messages, branches
2135 WHERE borrowernumber = ?
2136 AND message_type LIKE ?
2137 AND messages.branchcode = branches.branchcode
2138 ORDER BY message_date DESC";
2139 my $sth = $dbh->prepare($query);
2140 $sth->execute( $borrowernumber, $type ) ;
2143 while ( my $data = $sth->fetchrow_hashref ) {
2144 my $d = C4::Dates->new( $data->{message_date}, 'iso' );
2145 $data->{message_date_formatted} = $d->output;
2146 push @results, $data;
2154 GetMessagesCount( $borrowernumber, $type );
2156 $type is message type, B for borrower, or L for Librarian.
2157 Empty type returns all messages of any type.
2159 Returns the number of messages for the given borrowernumber
2163 sub GetMessagesCount {
2164 my ( $borrowernumber, $type, $branchcode ) = @_;
2170 my $dbh = C4::Context->dbh;
2172 my $query = "SELECT COUNT(*) as MsgCount FROM messages WHERE borrowernumber = ? AND message_type LIKE ?";
2173 my $sth = $dbh->prepare($query);
2174 $sth->execute( $borrowernumber, $type ) ;
2177 my $data = $sth->fetchrow_hashref;
2178 my $count = $data->{'MsgCount'};
2185 =head2 DeleteMessage
2187 DeleteMessage( $message_id );
2192 my ( $message_id ) = @_;
2194 my $dbh = C4::Context->dbh;
2196 my $query = "DELETE FROM messages WHERE message_id = ?";
2197 my $sth = $dbh->prepare($query);
2198 $sth->execute( $message_id );
2202 END { } # module clean-up code here (global destructor)