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
74 &GetMemberAccountRecords
75 &GetBorNotifyAcctRecord
79 &GetBorrowercategoryList
81 &GetBorrowersWhoHaveNotBorrowedSince
82 &GetBorrowersWhoHaveNeverBorrowed
83 &GetBorrowersWithIssuesHistoryOlderThan
110 &ExtendMemberSubscriptionTo
128 C4::Members - Perl Module containing convenience functions for member handling
136 This module contains routines for adding, modifying and deleting members/patrons/borrowers
142 ($count, $borrowers) = &SearchMember($searchstring, $type,
143 $category_type, $filter, $showallbranches);
145 Looks up patrons (borrowers) by name.
147 BUGFIX 499: C<$type> is now used to determine type of search.
148 if $type is "simple", search is performed on the first letter of the
151 $category_type is used to get a specified type of user.
152 (mainly adults when creating a child.)
154 C<$searchstring> is a space-separated list of search terms. Each term
155 must match the beginning a borrower's surname, first name, or other
158 C<$filter> is assumed to be a list of elements to filter results on
160 C<$showallbranches> is used in IndependantBranches Context to display all branches results.
162 C<&SearchMember> returns a two-element list. C<$borrowers> is a
163 reference-to-array; each element is a reference-to-hash, whose keys
164 are the fields of the C<borrowers> table in the Koha database.
165 C<$count> is the number of elements in C<$borrowers>.
170 #used by member enquiries from the intranet
172 my ($searchstring, $orderby, $type,$category_type,$filter,$showallbranches ) = @_;
173 my $dbh = C4::Context->dbh;
179 # this is used by circulation everytime a new borrowers cardnumber is scanned
180 # so we can check an exact match first, if that works return, otherwise do the rest
181 $query = "SELECT * FROM borrowers
182 LEFT JOIN categories ON borrowers.categorycode=categories.categorycode
184 my $sth = $dbh->prepare("$query WHERE cardnumber = ?");
185 $sth->execute($searchstring);
186 my $data = $sth->fetchall_arrayref({});
188 return ( scalar(@$data), $data );
191 if ( $type eq "simple" ) # simple search for one letter only
193 $query .= ($category_type ? " AND category_type = ".$dbh->quote($category_type) : "");
194 $query .= " WHERE (surname LIKE ? OR cardnumber like ?) ";
195 if (C4::Context->preference("IndependantBranches") && !$showallbranches){
196 if (C4::Context->userenv && C4::Context->userenv->{flags} % 2 !=1 && C4::Context->userenv->{'branch'}){
197 $query.=" AND borrowers.branchcode =".$dbh->quote(C4::Context->userenv->{'branch'}) unless (C4::Context->userenv->{'branch'} eq "insecure");
200 $query.=" ORDER BY $orderby";
201 @bind = ("$searchstring%","$searchstring");
203 else # advanced search looking in surname, firstname and othernames
205 @data = split( ' ', $searchstring );
208 if (C4::Context->preference("IndependantBranches") && !$showallbranches){
209 if (C4::Context->userenv && C4::Context->userenv->{flags} % 2 !=1 && C4::Context->userenv->{'branch'}){
210 $query.=" borrowers.branchcode =".$dbh->quote(C4::Context->userenv->{'branch'})." AND " unless (C4::Context->userenv->{'branch'} eq "insecure");
213 $query.="((surname LIKE ? OR surname LIKE ?
214 OR firstname LIKE ? OR firstname LIKE ?
215 OR othernames LIKE ? OR othernames LIKE ?)
217 ($category_type?" AND category_type = ".$dbh->quote($category_type):"");
219 "$data[0]%", "% $data[0]%", "$data[0]%", "% $data[0]%",
220 "$data[0]%", "% $data[0]%"
222 for ( my $i = 1 ; $i < $count ; $i++ ) {
223 $query = $query . " AND (" . " surname LIKE ? OR surname LIKE ?
224 OR firstname LIKE ? OR firstname LIKE ?
225 OR othernames LIKE ? OR othernames LIKE ?)";
227 "$data[$i]%", "% $data[$i]%", "$data[$i]%",
228 "% $data[$i]%", "$data[$i]%", "% $data[$i]%" );
232 $query = $query . ") OR cardnumber LIKE ? ";
233 push( @bind, $searchstring );
234 $query .= "order by $orderby";
239 $sth = $dbh->prepare($query);
241 $debug and print STDERR "Q $orderby : $query\n";
242 $sth->execute(@bind);
244 $data = $sth->fetchall_arrayref({});
246 return ( scalar(@$data), $data );
251 $borrowers_result_array_ref = &Search($filter,$orderby, $limit,
252 $columns_out, $search_on_fields,$searchtype);
254 Looks up patrons (borrowers) on filter.
256 BUGFIX 499: C<$type> is now used to determine type of search.
257 if $type is "simple", search is performed on the first letter of the
260 $category_type is used to get a specified type of user.
261 (mainly adults when creating a child.)
264 - a space-separated list of search terms. Implicit AND is done on them
265 - a hash ref containing fieldnames associated with queried value
266 - an array ref combining the two previous elements Implicit OR is done between each array element
269 C<$orderby> is an arrayref of hashref. Contains the name of the field and 0 or 1 depending if order is ascending or descending
271 C<$limit> is there to allow limiting number of results returned
273 C<&columns_out> is an array ref to the fieldnames you want to see in the result list
275 C<&search_on_fields> is an array ref to the fieldnames you want to limit search on when you are using string search
277 C<&searchtype> is a string telling the type of search you want todo : start_with, exact or contains are allowed
282 my ( $filter, $orderby, $limit, $columns_out, $search_on_fields, $searchtype ) = @_;
284 my %filtersmatching_record;
286 if ( ref($filter) eq "ARRAY" ) {
287 push @filters, @$filter;
289 push @filters, $filter;
291 if ( C4::Context->preference('ExtendedPatronAttributes') ) {
292 my $matching_records = C4::Members::Attributes::SearchIdMatchingAttribute($filter);
293 if(scalar(@$matching_records)>0) {
294 foreach my $matching_record (@$matching_records) {
295 $filtersmatching_record{$$matching_record[0]}=1;
297 foreach my $k (keys(%filtersmatching_record)) {
298 push @filters, {"borrowernumber"=>$k};
302 $searchtype ||= "start_with";
303 push @finalfilter, \@filters;
304 my $data = SearchInTable( "borrowers", \@finalfilter, $orderby, $limit, $columns_out, $search_on_fields, $searchtype );
308 =head2 GetMemberDetails
310 ($borrower) = &GetMemberDetails($borrowernumber, $cardnumber);
312 Looks up a patron and returns information about him or her. If
313 C<$borrowernumber> is true (nonzero), C<&GetMemberDetails> looks
314 up the borrower by number; otherwise, it looks up the borrower by card
317 C<$borrower> is a reference-to-hash whose keys are the fields of the
318 borrowers table in the Koha database. In addition,
319 C<$borrower-E<gt>{flags}> is a hash giving more detailed information
320 about the patron. Its keys act as flags :
322 if $borrower->{flags}->{LOST} {
323 # Patron's card was reported lost
326 If the state of a flag means that the patron should not be
327 allowed to borrow any more books, then it will have a C<noissues> key
330 See patronflags for more details.
332 C<$borrower-E<gt>{authflags}> is a hash giving more detailed information
333 about the top-level permissions flags set for the borrower. For example,
334 if a user has the "editcatalogue" permission,
335 C<$borrower-E<gt>{authflags}-E<gt>{editcatalogue}> will exist and have
340 sub GetMemberDetails {
341 my ( $borrowernumber, $cardnumber ) = @_;
342 my $dbh = C4::Context->dbh;
345 if ($borrowernumber) {
346 $sth = $dbh->prepare("select borrowers.*,category_type,categories.description from borrowers left join categories on borrowers.categorycode=categories.categorycode where borrowernumber=?");
347 $sth->execute($borrowernumber);
349 elsif ($cardnumber) {
350 $sth = $dbh->prepare("select borrowers.*,category_type,categories.description from borrowers left join categories on borrowers.categorycode=categories.categorycode where cardnumber=?");
351 $sth->execute($cardnumber);
356 my $borrower = $sth->fetchrow_hashref;
357 my ($amount) = GetMemberAccountRecords( $borrowernumber);
358 $borrower->{'amountoutstanding'} = $amount;
359 # FIXME - patronflags calls GetMemberAccountRecords... just have patronflags return $amount
360 my $flags = patronflags( $borrower);
363 $sth = $dbh->prepare("select bit,flag from userflags");
365 while ( my ( $bit, $flag ) = $sth->fetchrow ) {
366 if ( $borrower->{'flags'} && $borrower->{'flags'} & 2**$bit ) {
367 $accessflagshash->{$flag} = 1;
370 $borrower->{'flags'} = $flags;
371 $borrower->{'authflags'} = $accessflagshash;
373 # find out how long the membership lasts
376 "select enrolmentperiod from categories where categorycode = ?");
377 $sth->execute( $borrower->{'categorycode'} );
378 my $enrolment = $sth->fetchrow;
379 $borrower->{'enrolmentperiod'} = $enrolment;
380 return ($borrower); #, $flags, $accessflagshash);
385 $flags = &patronflags($patron);
387 This function is not exported.
389 The following will be set where applicable:
390 $flags->{CHARGES}->{amount} Amount of debt
391 $flags->{CHARGES}->{noissues} Set if debt amount >$5.00 (or syspref noissuescharge)
392 $flags->{CHARGES}->{message} Message -- deprecated
394 $flags->{CREDITS}->{amount} Amount of credit
395 $flags->{CREDITS}->{message} Message -- deprecated
397 $flags->{ GNA } Patron has no valid address
398 $flags->{ GNA }->{noissues} Set for each GNA
399 $flags->{ GNA }->{message} "Borrower has no valid address" -- deprecated
401 $flags->{ LOST } Patron's card reported lost
402 $flags->{ LOST }->{noissues} Set for each LOST
403 $flags->{ LOST }->{message} Message -- deprecated
405 $flags->{DBARRED} Set if patron debarred, no access
406 $flags->{DBARRED}->{noissues} Set for each DBARRED
407 $flags->{DBARRED}->{message} Message -- deprecated
410 $flags->{ NOTES }->{message} The note itself. NOT deprecated
412 $flags->{ ODUES } Set if patron has overdue books.
413 $flags->{ ODUES }->{message} "Yes" -- deprecated
414 $flags->{ ODUES }->{itemlist} ref-to-array: list of overdue books
415 $flags->{ ODUES }->{itemlisttext} Text list of overdue items -- deprecated
417 $flags->{WAITING} Set if any of patron's reserves are available
418 $flags->{WAITING}->{message} Message -- deprecated
419 $flags->{WAITING}->{itemlist} ref-to-array: list of available items
423 =item C<$flags-E<gt>{ODUES}-E<gt>{itemlist}> is a reference-to-array listing the
424 overdue items. Its elements are references-to-hash, each describing an
425 overdue item. The keys are selected fields from the issues, biblio,
426 biblioitems, and items tables of the Koha database.
428 =item C<$flags-E<gt>{ODUES}-E<gt>{itemlisttext}> is a string giving a text listing of
429 the overdue items, one per line. Deprecated.
431 =item C<$flags-E<gt>{WAITING}-E<gt>{itemlist}> is a reference-to-array listing the
432 available items. Each element is a reference-to-hash whose keys are
433 fields from the reserves table of the Koha database.
437 All the "message" fields that include language generated in this function are deprecated,
438 because such strings belong properly in the display layer.
440 The "message" field that comes from the DB is OK.
444 # TODO: use {anonymous => hashes} instead of a dozen %flaginfo
445 # FIXME rename this function.
448 my ( $patroninformation) = @_;
449 my $dbh=C4::Context->dbh;
450 my ($amount) = GetMemberAccountRecords( $patroninformation->{'borrowernumber'});
453 my $noissuescharge = C4::Context->preference("noissuescharge") || 5;
454 $flaginfo{'message'} = sprintf "Patron owes \$%.02f", $amount;
455 $flaginfo{'amount'} = sprintf "%.02f", $amount;
456 if ( $amount > $noissuescharge && !C4::Context->preference("AllowFineOverride") ) {
457 $flaginfo{'noissues'} = 1;
459 $flags{'CHARGES'} = \%flaginfo;
461 elsif ( $amount < 0 ) {
463 $flaginfo{'message'} = sprintf "Patron has credit of \$%.02f", -$amount;
464 $flaginfo{'amount'} = sprintf "%.02f", $amount;
465 $flags{'CREDITS'} = \%flaginfo;
467 if ( $patroninformation->{'gonenoaddress'}
468 && $patroninformation->{'gonenoaddress'} == 1 )
471 $flaginfo{'message'} = 'Borrower has no valid address.';
472 $flaginfo{'noissues'} = 1;
473 $flags{'GNA'} = \%flaginfo;
475 if ( $patroninformation->{'lost'} && $patroninformation->{'lost'} == 1 ) {
477 $flaginfo{'message'} = 'Borrower\'s card reported lost.';
478 $flaginfo{'noissues'} = 1;
479 $flags{'LOST'} = \%flaginfo;
481 if ( $patroninformation->{'debarred'}
482 && $patroninformation->{'debarred'} == 1 )
485 $flaginfo{'message'} = 'Borrower is Debarred.';
486 $flaginfo{'noissues'} = 1;
487 $flags{'DBARRED'} = \%flaginfo;
489 if ( $patroninformation->{'borrowernotes'}
490 && $patroninformation->{'borrowernotes'} )
493 $flaginfo{'message'} = $patroninformation->{'borrowernotes'};
494 $flags{'NOTES'} = \%flaginfo;
496 my ( $odues, $itemsoverdue ) = checkoverdues($patroninformation->{'borrowernumber'});
497 if ( $odues && $odues > 0 ) {
499 $flaginfo{'message'} = "Yes";
500 $flaginfo{'itemlist'} = $itemsoverdue;
501 foreach ( sort { $a->{'date_due'} cmp $b->{'date_due'} }
504 $flaginfo{'itemlisttext'} .=
505 "$_->{'date_due'} $_->{'barcode'} $_->{'title'} \n"; # newline is display layer
507 $flags{'ODUES'} = \%flaginfo;
509 my @itemswaiting = C4::Reserves::GetReservesFromBorrowernumber( $patroninformation->{'borrowernumber'},'W' );
510 my $nowaiting = scalar @itemswaiting;
511 if ( $nowaiting > 0 ) {
513 $flaginfo{'message'} = "Reserved items available";
514 $flaginfo{'itemlist'} = \@itemswaiting;
515 $flags{'WAITING'} = \%flaginfo;
523 $borrower = &GetMember(%information);
525 Retrieve the first patron record meeting on criteria listed in the
526 C<%information> hash, which should contain one or more
527 pairs of borrowers column names and values, e.g.,
529 $borrower = GetMember(borrowernumber => id);
531 C<&GetBorrower> returns a reference-to-hash whose keys are the fields of
532 the C<borrowers> table in the Koha database.
534 FIXME: GetMember() is used throughout the code as a lookup
535 on a unique key such as the borrowernumber, but this meaning is not
536 enforced in the routine itself.
542 my ( %information ) = @_;
543 if (exists $information{borrowernumber} && !defined $information{borrowernumber}) {
544 #passing mysql's kohaadmin?? Makes no sense as a query
547 my $dbh = C4::Context->dbh;
549 q{SELECT borrowers.*, categories.category_type, categories.description
551 LEFT JOIN categories on borrowers.categorycode=categories.categorycode WHERE };
554 for (keys %information ) {
562 if (defined $information{$_}) {
564 push @values, $information{$_};
567 $select .= "$_ IS NULL";
570 $debug && warn $select, " ",values %information;
571 my $sth = $dbh->prepare("$select");
572 $sth->execute(map{$information{$_}} keys %information);
573 my $data = $sth->fetchall_arrayref({});
574 #FIXME interface to this routine now allows generation of a result set
575 #so whole array should be returned but bowhere in the current code expects this
584 =head2 IsMemberBlocked
586 my ($block_status, $count) = IsMemberBlocked( $borrowernumber );
588 Returns whether a patron has overdue items that may result
589 in a block or whether the patron has active fine days
590 that would block circulation privileges.
592 C<$block_status> can have the following values:
594 1 if the patron has outstanding fine days, in which case C<$count> is the number of them
596 -1 if the patron has overdue items, in which case C<$count> is the number of them
598 0 if the patron has no overdue items or outstanding fine days, in which case C<$count> is 0
600 Outstanding fine days are checked before current overdue items
603 FIXME: this needs to be split into two functions; a potential block
604 based on the number of current overdue items could be orthogonal
605 to a block based on whether the patron has any fine days accrued.
609 sub IsMemberBlocked {
610 my $borrowernumber = shift;
611 my $dbh = C4::Context->dbh;
613 # does patron have current fine days?
616 ADDDATE(returndate, finedays * DATEDIFF(returndate,date_due) ) AS blockingdate,
617 DATEDIFF(ADDDATE(returndate, finedays * DATEDIFF(returndate,date_due)),NOW()) AS blockedcount
620 if(C4::Context->preference("item-level_itypes")){
622 qq{ LEFT JOIN items ON (items.itemnumber=old_issues.itemnumber)
623 LEFT JOIN issuingrules ON (issuingrules.itemtype=items.itype)}
626 qq{ LEFT JOIN items ON (items.itemnumber=old_issues.itemnumber)
627 LEFT JOIN biblioitems ON (biblioitems.biblioitemnumber=items.biblioitemnumber)
628 LEFT JOIN issuingrules ON (issuingrules.itemtype=biblioitems.itemtype) };
631 qq{ WHERE finedays IS NOT NULL
632 AND date_due < returndate
633 AND borrowernumber = ?
634 ORDER BY blockingdate DESC, blockedcount DESC
636 my $sth=$dbh->prepare($strsth);
637 $sth->execute($borrowernumber);
638 my $row = $sth->fetchrow_hashref;
639 my $blockeddate = $row->{'blockeddate'};
640 my $blockedcount = $row->{'blockedcount'};
642 return (1, $blockedcount) if $blockedcount > 0;
644 # if he have late issues
645 $sth = $dbh->prepare(
646 "SELECT COUNT(*) as latedocs
648 WHERE borrowernumber = ?
649 AND date_due < curdate()"
651 $sth->execute($borrowernumber);
652 my $latedocs = $sth->fetchrow_hashref->{'latedocs'};
654 return (-1, $latedocs) if $latedocs > 0;
659 =head2 GetMemberIssuesAndFines
661 ($overdue_count, $issue_count, $total_fines) = &GetMemberIssuesAndFines($borrowernumber);
663 Returns aggregate data about items borrowed by the patron with the
664 given borrowernumber.
666 C<&GetMemberIssuesAndFines> returns a three-element array. C<$overdue_count> is the
667 number of overdue items the patron currently has borrowed. C<$issue_count> is the
668 number of books the patron currently has borrowed. C<$total_fines> is
669 the total fine currently due by the borrower.
674 sub GetMemberIssuesAndFines {
675 my ( $borrowernumber ) = @_;
676 my $dbh = C4::Context->dbh;
677 my $query = "SELECT COUNT(*) FROM issues WHERE borrowernumber = ?";
679 $debug and warn $query."\n";
680 my $sth = $dbh->prepare($query);
681 $sth->execute($borrowernumber);
682 my $issue_count = $sth->fetchrow_arrayref->[0];
684 $sth = $dbh->prepare(
685 "SELECT COUNT(*) FROM issues
686 WHERE borrowernumber = ?
687 AND date_due < curdate()"
689 $sth->execute($borrowernumber);
690 my $overdue_count = $sth->fetchrow_arrayref->[0];
692 $sth = $dbh->prepare("SELECT SUM(amountoutstanding) FROM accountlines WHERE borrowernumber = ?");
693 $sth->execute($borrowernumber);
694 my $total_fines = $sth->fetchrow_arrayref->[0];
696 return ($overdue_count, $issue_count, $total_fines);
700 return @{C4::Context->dbh->selectcol_arrayref("SHOW columns from borrowers")};
705 my $success = ModMember(borrowernumber => $borrowernumber,
706 [ field => value ]... );
708 Modify borrower's data. All date fields should ALREADY be in ISO format.
711 true on success, or false on failure
717 # test to know if you must update or not the borrower password
718 if (exists $data{password}) {
719 if ($data{password} eq '****' or $data{password} eq '') {
720 delete $data{password};
722 $data{password} = md5_base64($data{password});
725 my $execute_success=UpdateInTable("borrowers",\%data);
726 # ok if its an adult (type) it may have borrowers that depend on it as a guarantor
727 # so when we update information for an adult we should check for guarantees and update the relevant part
728 # of their records, ie addresses and phone numbers
729 my $borrowercategory= GetBorrowercategory( $data{'category_type'} );
730 if ( exists $borrowercategory->{'category_type'} && $borrowercategory->{'category_type'} eq ('A' || 'S') ) {
731 # is adult check guarantees;
732 UpdateGuarantees(%data);
734 logaction("MEMBERS", "MODIFY", $data{'borrowernumber'}, "UPDATE (executed w/ arg: $data{'borrowernumber'})")
735 if C4::Context->preference("BorrowersLog");
737 return $execute_success;
743 $borrowernumber = &AddMember(%borrower);
745 insert new borrower into table
746 Returns the borrowernumber
753 my $dbh = C4::Context->dbh;
754 $data{'password'} = '!' if (not $data{'password'} and $data{'userid'});
755 $data{'password'} = md5_base64( $data{'password'} ) if $data{'password'};
756 $data{'borrowernumber'}=InsertInTable("borrowers",\%data);
757 # mysql_insertid is probably bad. not necessarily accurate and mysql-specific at best.
758 logaction("MEMBERS", "CREATE", $data{'borrowernumber'}, "") if C4::Context->preference("BorrowersLog");
760 # check for enrollment fee & add it if needed
761 my $sth = $dbh->prepare("SELECT enrolmentfee FROM categories WHERE categorycode=?");
762 $sth->execute($data{'categorycode'});
763 my ($enrolmentfee) = $sth->fetchrow;
764 if ($enrolmentfee && $enrolmentfee > 0) {
765 # insert fee in patron debts
766 manualinvoice($data{'borrowernumber'}, '', '', 'A', $enrolmentfee);
768 return $data{'borrowernumber'};
773 my ($uid,$member) = @_;
774 my $dbh = C4::Context->dbh;
775 # Make sure the userid chosen is unique and not theirs if non-empty. If it is not,
776 # Then we need to tell the user and have them create a new one.
779 "SELECT * FROM borrowers WHERE userid=? AND borrowernumber != ?");
780 $sth->execute( $uid, $member );
781 if ( ( $uid ne '' ) && ( my $row = $sth->fetchrow_hashref ) ) {
789 sub Generate_Userid {
790 my ($borrowernumber, $firstname, $surname) = @_;
794 $firstname =~ s/[[:digit:][:space:][:blank:][:punct:][:cntrl:]]//g;
795 $surname =~ s/[[:digit:][:space:][:blank:][:punct:][:cntrl:]]//g;
796 $newuid = lc("$firstname.$surname");
797 $newuid .= $offset unless $offset == 0;
800 } while (!Check_Userid($newuid,$borrowernumber));
806 my ( $uid, $member, $digest ) = @_;
807 my $dbh = C4::Context->dbh;
809 #Make sure the userid chosen is unique and not theirs if non-empty. If it is not,
810 #Then we need to tell the user and have them create a new one.
814 "SELECT * FROM borrowers WHERE userid=? AND borrowernumber != ?");
815 $sth->execute( $uid, $member );
816 if ( ( $uid ne '' ) && ( my $row = $sth->fetchrow_hashref ) ) {
820 #Everything is good so we can update the information.
823 "update borrowers set userid=?, password=? where borrowernumber=?");
824 $sth->execute( $uid, $digest, $member );
828 logaction("MEMBERS", "CHANGE PASS", $member, "") if C4::Context->preference("BorrowersLog");
834 =head2 fixup_cardnumber
836 Warning: The caller is responsible for locking the members table in write
837 mode, to avoid database corruption.
841 use vars qw( @weightings );
842 my @weightings = ( 8, 4, 6, 3, 5, 2, 1 );
844 sub fixup_cardnumber ($) {
845 my ($cardnumber) = @_;
846 my $autonumber_members = C4::Context->boolean_preference('autoMemberNum') || 0;
848 # Find out whether member numbers should be generated
849 # automatically. Should be either "1" or something else.
850 # Defaults to "0", which is interpreted as "no".
852 # if ($cardnumber !~ /\S/ && $autonumber_members) {
853 ($autonumber_members) or return $cardnumber;
854 my $checkdigit = C4::Context->preference('checkdigit');
855 my $dbh = C4::Context->dbh;
856 if ( $checkdigit and $checkdigit eq 'katipo' ) {
858 # if checkdigit is selected, calculate katipo-style cardnumber.
859 # otherwise, just use the max()
860 # purpose: generate checksum'd member numbers.
861 # We'll assume we just got the max value of digits 2-8 of member #'s
862 # from the database and our job is to increment that by one,
863 # determine the 1st and 9th digits and return the full string.
864 my $sth = $dbh->prepare(
865 "select max(substring(borrowers.cardnumber,2,7)) as new_num from borrowers"
868 my $data = $sth->fetchrow_hashref;
869 $cardnumber = $data->{new_num};
870 if ( !$cardnumber ) { # If DB has no values,
871 $cardnumber = 1000000; # start at 1000000
877 for ( my $i = 0 ; $i < 8 ; $i += 1 ) {
878 # read weightings, left to right, 1 char at a time
879 my $temp1 = $weightings[$i];
881 # sequence left to right, 1 char at a time
882 my $temp2 = substr( $cardnumber, $i, 1 );
884 # mult each char 1-7 by its corresponding weighting
885 $sum += $temp1 * $temp2;
888 my $rem = ( $sum % 11 );
889 $rem = 'X' if $rem == 10;
891 return "V$cardnumber$rem";
894 # MODIFIED BY JF: mysql4.1 allows casting as an integer, which is probably
895 # better. I'll leave the original in in case it needs to be changed for you
896 # my $sth=$dbh->prepare("select max(borrowers.cardnumber) from borrowers");
897 my $sth = $dbh->prepare(
898 "select max(cast(cardnumber as signed)) from borrowers"
901 my ($result) = $sth->fetchrow;
904 return $cardnumber; # just here as a fallback/reminder
909 ($num_children, $children_arrayref) = &GetGuarantees($parent_borrno);
910 $child0_cardno = $children_arrayref->[0]{"cardnumber"};
911 $child0_borrno = $children_arrayref->[0]{"borrowernumber"};
913 C<&GetGuarantees> takes a borrower number (e.g., that of a patron
914 with children) and looks up the borrowers who are guaranteed by that
915 borrower (i.e., the patron's children).
917 C<&GetGuarantees> returns two values: an integer giving the number of
918 borrowers guaranteed by C<$parent_borrno>, and a reference to an array
919 of references to hash, which gives the actual results.
925 my ($borrowernumber) = @_;
926 my $dbh = C4::Context->dbh;
929 "select cardnumber,borrowernumber, firstname, surname from borrowers where guarantorid=?"
931 $sth->execute($borrowernumber);
934 my $data = $sth->fetchall_arrayref({});
935 return ( scalar(@$data), $data );
938 =head2 UpdateGuarantees
940 &UpdateGuarantees($parent_borrno);
943 C<&UpdateGuarantees> borrower data for an adult and updates all the guarantees
944 with the modified information
949 sub UpdateGuarantees {
951 my $dbh = C4::Context->dbh;
952 my ( $count, $guarantees ) = GetGuarantees( $data{'borrowernumber'} );
953 foreach my $guarantee (@$guarantees){
954 my $guaquery = qq|UPDATE borrowers
955 SET address=?,fax=?,B_city=?,mobile=?,city=?,phone=?
956 WHERE borrowernumber=?
958 my $sth = $dbh->prepare($guaquery);
959 $sth->execute($data{'address'},$data{'fax'},$data{'B_city'},$data{'mobile'},$data{'city'},$data{'phone'},$guarantee->{'borrowernumber'});
962 =head2 GetPendingIssues
964 my $issues = &GetPendingIssues($borrowernumber);
966 Looks up what the patron with the given borrowernumber has borrowed.
968 C<&GetPendingIssues> returns a
969 reference-to-array where each element is a reference-to-hash; the
970 keys are the fields from the C<issues>, C<biblio>, and C<items> tables.
971 The keys include C<biblioitems> fields except marc and marcxml.
976 sub GetPendingIssues {
977 my ($borrowernumber) = @_;
978 # must avoid biblioitems.* to prevent large marc and marcxml fields from killing performance
979 # FIXME: namespace collision: each table has "timestamp" fields. Which one is "timestamp" ?
980 # FIXME: circ/ciculation.pl tries to sort by timestamp!
981 # FIXME: C4::Print::printslip tries to sort by timestamp!
982 # FIXME: namespace collision: other collisions possible.
983 # FIXME: most of this data isn't really being used by callers.
984 my $sth = C4::Context->dbh->prepare(
990 biblioitems.itemtype,
993 biblioitems.publicationyear,
994 biblioitems.publishercode,
995 biblioitems.volumedate,
996 biblioitems.volumedesc,
999 issues.timestamp AS timestamp,
1000 issues.renewals AS renewals,
1001 items.renewals AS totalrenewals
1003 LEFT JOIN items ON items.itemnumber = issues.itemnumber
1004 LEFT JOIN biblio ON items.biblionumber = biblio.biblionumber
1005 LEFT JOIN biblioitems ON items.biblioitemnumber = biblioitems.biblioitemnumber
1008 ORDER BY issues.issuedate"
1010 $sth->execute($borrowernumber);
1011 my $data = $sth->fetchall_arrayref({});
1012 my $today = C4::Dates->new->output('iso');
1014 $_->{date_due} or next;
1015 ($_->{date_due} lt $today) and $_->{overdue} = 1;
1022 $issues = &GetAllIssues($borrowernumber, $sortkey, $limit);
1024 Looks up what the patron with the given borrowernumber has borrowed,
1025 and sorts the results.
1027 C<$sortkey> is the name of a field on which to sort the results. This
1028 should be the name of a field in the C<issues>, C<biblio>,
1029 C<biblioitems>, or C<items> table in the Koha database.
1031 C<$limit> is the maximum number of results to return.
1033 C<&GetAllIssues> an arrayref, C<$issues>, of hashrefs, the keys of which
1034 are the fields from the C<issues>, C<biblio>, C<biblioitems>, and
1035 C<items> tables of the Koha database.
1041 my ( $borrowernumber, $order, $limit ) = @_;
1043 #FIXME: sanity-check order and limit
1044 my $dbh = C4::Context->dbh;
1046 "SELECT *, issues.timestamp as issuestimestamp, issues.renewals AS renewals,items.renewals AS totalrenewals,items.timestamp AS itemstimestamp
1048 LEFT JOIN items on items.itemnumber=issues.itemnumber
1049 LEFT JOIN biblio ON items.biblionumber=biblio.biblionumber
1050 LEFT JOIN biblioitems ON items.biblioitemnumber=biblioitems.biblioitemnumber
1051 WHERE borrowernumber=?
1053 SELECT *, old_issues.timestamp as issuestimestamp, old_issues.renewals AS renewals,items.renewals AS totalrenewals,items.timestamp AS itemstimestamp
1055 LEFT JOIN items on items.itemnumber=old_issues.itemnumber
1056 LEFT JOIN biblio ON items.biblionumber=biblio.biblionumber
1057 LEFT JOIN biblioitems ON items.biblioitemnumber=biblioitems.biblioitemnumber
1058 WHERE borrowernumber=?
1060 if ( $limit != 0 ) {
1061 $query .= " limit $limit";
1064 my $sth = $dbh->prepare($query);
1065 $sth->execute($borrowernumber, $borrowernumber);
1068 while ( my $data = $sth->fetchrow_hashref ) {
1069 push @result, $data;
1076 =head2 GetMemberAccountRecords
1078 ($total, $acctlines, $count) = &GetMemberAccountRecords($borrowernumber);
1080 Looks up accounting data for the patron with the given borrowernumber.
1082 C<&GetMemberAccountRecords> returns a three-element array. C<$acctlines> is a
1083 reference-to-array, where each element is a reference-to-hash; the
1084 keys are the fields of the C<accountlines> table in the Koha database.
1085 C<$count> is the number of elements in C<$acctlines>. C<$total> is the
1086 total amount outstanding for all of the account lines.
1091 sub GetMemberAccountRecords {
1092 my ($borrowernumber,$date) = @_;
1093 my $dbh = C4::Context->dbh;
1099 WHERE borrowernumber=?);
1100 my @bind = ($borrowernumber);
1101 if ($date && $date ne ''){
1102 $strsth.=" AND date < ? ";
1105 $strsth.=" ORDER BY date desc,timestamp DESC";
1106 my $sth= $dbh->prepare( $strsth );
1107 $sth->execute( @bind );
1109 while ( my $data = $sth->fetchrow_hashref ) {
1110 my $biblio = GetBiblioFromItemNumber($data->{itemnumber}) if $data->{itemnumber};
1111 $data->{biblionumber} = $biblio->{biblionumber};
1112 $data->{title} = $biblio->{title};
1113 $acctlines[$numlines] = $data;
1115 $total += int(1000 * $data->{'amountoutstanding'}); # convert float to integer to avoid round-off errors
1118 return ( $total, \@acctlines,$numlines);
1121 =head2 GetBorNotifyAcctRecord
1123 ($count, $acctlines, $total) = &GetBorNotifyAcctRecord($params,$notifyid);
1125 Looks up accounting data for the patron with the given borrowernumber per file number.
1127 (FIXME - I'm not at all sure what this is about.)
1129 C<&GetBorNotifyAcctRecord> returns a three-element array. C<$acctlines> is a
1130 reference-to-array, where each element is a reference-to-hash; the
1131 keys are the fields of the C<accountlines> table in the Koha database.
1132 C<$count> is the number of elements in C<$acctlines>. C<$total> is the
1133 total amount outstanding for all of the account lines.
1137 sub GetBorNotifyAcctRecord {
1138 my ( $borrowernumber, $notifyid ) = @_;
1139 my $dbh = C4::Context->dbh;
1142 my $sth = $dbh->prepare(
1145 WHERE borrowernumber=?
1147 AND amountoutstanding != '0'
1148 ORDER BY notify_id,accounttype
1150 # 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')
1152 $sth->execute( $borrowernumber, $notifyid );
1154 while ( my $data = $sth->fetchrow_hashref ) {
1155 $acctlines[$numlines] = $data;
1157 $total += int(100 * $data->{'amountoutstanding'});
1160 return ( $total, \@acctlines, $numlines );
1163 =head2 checkuniquemember (OUEST-PROVENCE)
1165 ($result,$categorycode) = &checkuniquemember($collectivity,$surname,$firstname,$dateofbirth);
1167 Checks that a member exists or not in the database.
1169 C<&result> is nonzero (=exist) or 0 (=does not exist)
1170 C<&categorycode> is from categorycode table
1171 C<&collectivity> is 1 (= we add a collectivity) or 0 (= we add a physical member)
1172 C<&surname> is the surname
1173 C<&firstname> is the firstname (only if collectivity=0)
1174 C<&dateofbirth> is the date of birth in ISO format (only if collectivity=0)
1178 # FIXME: This function is not legitimate. Multiple patrons might have the same first/last name and birthdate.
1179 # This is especially true since first name is not even a required field.
1181 sub checkuniquemember {
1182 my ( $collectivity, $surname, $firstname, $dateofbirth ) = @_;
1183 my $dbh = C4::Context->dbh;
1184 my $request = ($collectivity) ?
1185 "SELECT borrowernumber,categorycode FROM borrowers WHERE surname=? " :
1187 "SELECT borrowernumber,categorycode FROM borrowers WHERE surname=? and firstname=? and dateofbirth=?" :
1188 "SELECT borrowernumber,categorycode FROM borrowers WHERE surname=? and firstname=?";
1189 my $sth = $dbh->prepare($request);
1190 if ($collectivity) {
1191 $sth->execute( uc($surname) );
1192 } elsif($dateofbirth){
1193 $sth->execute( uc($surname), ucfirst($firstname), $dateofbirth );
1195 $sth->execute( uc($surname), ucfirst($firstname));
1197 my @data = $sth->fetchrow;
1198 ( $data[0] ) and return $data[0], $data[1];
1202 sub checkcardnumber {
1203 my ($cardnumber,$borrowernumber) = @_;
1204 my $dbh = C4::Context->dbh;
1205 my $query = "SELECT * FROM borrowers WHERE cardnumber=?";
1206 $query .= " AND borrowernumber <> ?" if ($borrowernumber);
1207 my $sth = $dbh->prepare($query);
1208 if ($borrowernumber) {
1209 $sth->execute($cardnumber,$borrowernumber);
1211 $sth->execute($cardnumber);
1213 if (my $data= $sth->fetchrow_hashref()){
1222 =head2 getzipnamecity (OUEST-PROVENCE)
1224 take all info from table city for the fields city and zip
1225 check for the name and the zip code of the city selected
1229 sub getzipnamecity {
1231 my $dbh = C4::Context->dbh;
1234 "select city_name,city_zipcode from cities where cityid=? ");
1235 $sth->execute($cityid);
1236 my @data = $sth->fetchrow;
1237 return $data[0], $data[1];
1241 =head2 getdcity (OUEST-PROVENCE)
1243 recover cityid with city_name condition
1248 my ($city_name) = @_;
1249 my $dbh = C4::Context->dbh;
1250 my $sth = $dbh->prepare("select cityid from cities where city_name=? ");
1251 $sth->execute($city_name);
1252 my $data = $sth->fetchrow;
1256 =head2 GetFirstValidEmailAddress
1258 $email = GetFirstValidEmailAddress($borrowernumber);
1260 Return the first valid email address for a borrower, given the borrowernumber. For now, the order
1261 is defined as email, emailpro, B_email. Returns the empty string if the borrower has no email
1266 sub GetFirstValidEmailAddress {
1267 my $borrowernumber = shift;
1268 my $dbh = C4::Context->dbh;
1269 my $sth = $dbh->prepare( "SELECT email, emailpro, B_email FROM borrowers where borrowernumber = ? ");
1270 $sth->execute( $borrowernumber );
1271 my $data = $sth->fetchrow_hashref;
1273 if ($data->{'email'}) {
1274 return $data->{'email'};
1275 } elsif ($data->{'emailpro'}) {
1276 return $data->{'emailpro'};
1277 } elsif ($data->{'B_email'}) {
1278 return $data->{'B_email'};
1284 =head2 GetExpiryDate
1286 $expirydate = GetExpiryDate($categorycode, $dateenrolled);
1288 Calculate expiry date given a categorycode and starting date. Date argument must be in ISO format.
1289 Return date is also in ISO format.
1294 my ( $categorycode, $dateenrolled ) = @_;
1296 if ($categorycode) {
1297 my $dbh = C4::Context->dbh;
1298 my $sth = $dbh->prepare("SELECT enrolmentperiod,enrolmentperioddate FROM categories WHERE categorycode=?");
1299 $sth->execute($categorycode);
1300 $enrolments = $sth->fetchrow_hashref;
1302 # die "GetExpiryDate: for enrollmentperiod $enrolmentperiod (category '$categorycode') starting $dateenrolled.\n";
1303 my @date = split (/-/,$dateenrolled);
1304 if($enrolments->{enrolmentperiod}){
1305 return sprintf("%04d-%02d-%02d", Add_Delta_YM(@date,0,$enrolments->{enrolmentperiod}));
1307 return $enrolments->{enrolmentperioddate};
1311 =head2 checkuserpassword (OUEST-PROVENCE)
1313 check for the password and login are not used
1314 return the number of record
1315 0=> NOT USED 1=> USED
1319 sub checkuserpassword {
1320 my ( $borrowernumber, $userid, $password ) = @_;
1321 $password = md5_base64($password);
1322 my $dbh = C4::Context->dbh;
1325 "Select count(*) from borrowers where borrowernumber !=? and userid =? and password=? "
1327 $sth->execute( $borrowernumber, $userid, $password );
1328 my $number_rows = $sth->fetchrow;
1329 return $number_rows;
1333 =head2 GetborCatFromCatType
1335 ($codes_arrayref, $labels_hashref) = &GetborCatFromCatType();
1337 Looks up the different types of borrowers in the database. Returns two
1338 elements: a reference-to-array, which lists the borrower category
1339 codes, and a reference-to-hash, which maps the borrower category codes
1340 to category descriptions.
1345 sub GetborCatFromCatType {
1346 my ( $category_type, $action ) = @_;
1347 # FIXME - This API seems both limited and dangerous.
1348 my $dbh = C4::Context->dbh;
1349 my $request = qq| SELECT categorycode,description
1352 ORDER BY categorycode|;
1353 my $sth = $dbh->prepare($request);
1355 $sth->execute($category_type);
1364 while ( my $data = $sth->fetchrow_hashref ) {
1365 push @codes, $data->{'categorycode'};
1366 $labels{ $data->{'categorycode'} } = $data->{'description'};
1368 return ( \@codes, \%labels );
1371 =head2 GetBorrowercategory
1373 $hashref = &GetBorrowercategory($categorycode);
1375 Given the borrower's category code, the function returns the corresponding
1376 data hashref for a comprehensive information display.
1378 $arrayref_hashref = &GetBorrowercategory;
1380 If no category code provided, the function returns all the categories.
1384 sub GetBorrowercategory {
1386 my $dbh = C4::Context->dbh;
1390 "SELECT description,dateofbirthrequired,upperagelimit,category_type
1392 WHERE categorycode = ?"
1394 $sth->execute($catcode);
1396 $sth->fetchrow_hashref;
1400 } # sub getborrowercategory
1402 =head2 GetBorrowercategoryList
1404 $arrayref_hashref = &GetBorrowercategoryList;
1405 If no category code provided, the function returns all the categories.
1409 sub GetBorrowercategoryList {
1410 my $dbh = C4::Context->dbh;
1415 ORDER BY description"
1419 $sth->fetchall_arrayref({});
1421 } # sub getborrowercategory
1423 =head2 ethnicitycategories
1425 ($codes_arrayref, $labels_hashref) = ðnicitycategories();
1427 Looks up the different ethnic types in the database. Returns two
1428 elements: a reference-to-array, which lists the ethnicity codes, and a
1429 reference-to-hash, which maps the ethnicity codes to ethnicity
1436 sub ethnicitycategories {
1437 my $dbh = C4::Context->dbh;
1438 my $sth = $dbh->prepare("Select code,name from ethnicity order by name");
1442 while ( my $data = $sth->fetchrow_hashref ) {
1443 push @codes, $data->{'code'};
1444 $labels{ $data->{'code'} } = $data->{'name'};
1446 return ( \@codes, \%labels );
1451 $ethn_name = &fixEthnicity($ethn_code);
1453 Takes an ethnicity code (e.g., "european" or "pi") and returns the
1454 corresponding descriptive name from the C<ethnicity> table in the
1455 Koha database ("European" or "Pacific Islander").
1462 my $ethnicity = shift;
1463 return unless $ethnicity;
1464 my $dbh = C4::Context->dbh;
1465 my $sth = $dbh->prepare("Select name from ethnicity where code = ?");
1466 $sth->execute($ethnicity);
1467 my $data = $sth->fetchrow_hashref;
1468 return $data->{'name'};
1469 } # sub fixEthnicity
1473 $dateofbirth,$date = &GetAge($date);
1475 this function return the borrowers age with the value of dateofbirth
1481 my ( $date, $date_ref ) = @_;
1483 if ( not defined $date_ref ) {
1484 $date_ref = sprintf( '%04d-%02d-%02d', Today() );
1487 my ( $year1, $month1, $day1 ) = split /-/, $date;
1488 my ( $year2, $month2, $day2 ) = split /-/, $date_ref;
1490 my $age = $year2 - $year1;
1491 if ( $month1 . $day1 > $month2 . $day2 ) {
1498 =head2 get_institutions
1500 $insitutions = get_institutions();
1502 Just returns a list of all the borrowers of type I, borrownumber and name
1507 sub get_institutions {
1508 my $dbh = C4::Context->dbh();
1511 "SELECT borrowernumber,surname FROM borrowers WHERE categorycode=? ORDER BY surname"
1515 while ( my $data = $sth->fetchrow_hashref() ) {
1516 $orgs{ $data->{'borrowernumber'} } = $data;
1520 } # sub get_institutions
1522 =head2 add_member_orgs
1524 add_member_orgs($borrowernumber,$borrowernumbers);
1526 Takes a borrowernumber and a list of other borrowernumbers and inserts them into the borrowers_to_borrowers table
1531 sub add_member_orgs {
1532 my ( $borrowernumber, $otherborrowers ) = @_;
1533 my $dbh = C4::Context->dbh();
1535 "INSERT INTO borrowers_to_borrowers (borrower1,borrower2) VALUES (?,?)";
1536 my $sth = $dbh->prepare($query);
1537 foreach my $otherborrowernumber (@$otherborrowers) {
1538 $sth->execute( $borrowernumber, $otherborrowernumber );
1541 } # sub add_member_orgs
1545 $cityarrayref = GetCities();
1547 Returns an array_ref of the entries in the cities table
1548 If there are entries in the table an empty row is returned
1549 This is currently only used to populate a popup in memberentry
1555 my $dbh = C4::Context->dbh;
1556 my $city_arr = $dbh->selectall_arrayref(
1557 q|SELECT cityid,city_zipcode,city_name FROM cities ORDER BY city_name|,
1559 if ( @{$city_arr} ) {
1560 unshift @{$city_arr}, {
1561 city_zipcode => q{},
1570 =head2 GetSortDetails (OUEST-PROVENCE)
1572 ($lib) = &GetSortDetails($category,$sortvalue);
1574 Returns the authorized value details
1575 C<&$lib>return value of authorized value details
1576 C<&$sortvalue>this is the value of authorized value
1577 C<&$category>this is the value of authorized value category
1581 sub GetSortDetails {
1582 my ( $category, $sortvalue ) = @_;
1583 my $dbh = C4::Context->dbh;
1584 my $query = qq|SELECT lib
1585 FROM authorised_values
1587 AND authorised_value=? |;
1588 my $sth = $dbh->prepare($query);
1589 $sth->execute( $category, $sortvalue );
1590 my $lib = $sth->fetchrow;
1591 return ($lib) if ($lib);
1592 return ($sortvalue) unless ($lib);
1595 =head2 MoveMemberToDeleted
1597 $result = &MoveMemberToDeleted($borrowernumber);
1599 Copy the record from borrowers to deletedborrowers table.
1603 # FIXME: should do it in one SQL statement w/ subquery
1604 # Otherwise, we should return the @data on success
1606 sub MoveMemberToDeleted {
1607 my ($member) = shift or return;
1608 my $dbh = C4::Context->dbh;
1609 my $query = qq|SELECT *
1611 WHERE borrowernumber=?|;
1612 my $sth = $dbh->prepare($query);
1613 $sth->execute($member);
1614 my @data = $sth->fetchrow_array;
1615 (@data) or return; # if we got a bad borrowernumber, there's nothing to insert
1617 $dbh->prepare( "INSERT INTO deletedborrowers VALUES ("
1618 . ( "?," x ( scalar(@data) - 1 ) )
1620 $sth->execute(@data);
1625 DelMember($borrowernumber);
1627 This function remove directly a borrower whitout writing it on deleteborrower.
1628 + Deletes reserves for the borrower
1633 my $dbh = C4::Context->dbh;
1634 my $borrowernumber = shift;
1635 #warn "in delmember with $borrowernumber";
1636 return unless $borrowernumber; # borrowernumber is mandatory.
1638 my $query = qq|DELETE
1640 WHERE borrowernumber=?|;
1641 my $sth = $dbh->prepare($query);
1642 $sth->execute($borrowernumber);
1646 WHERE borrowernumber = ?
1648 $sth = $dbh->prepare($query);
1649 $sth->execute($borrowernumber);
1650 logaction("MEMBERS", "DELETE", $borrowernumber, "") if C4::Context->preference("BorrowersLog");
1654 =head2 ExtendMemberSubscriptionTo (OUEST-PROVENCE)
1656 $date = ExtendMemberSubscriptionTo($borrowerid, $date);
1658 Extending the subscription to a given date or to the expiry date calculated on ISO date.
1663 sub ExtendMemberSubscriptionTo {
1664 my ( $borrowerid,$date) = @_;
1665 my $dbh = C4::Context->dbh;
1666 my $borrower = GetMember('borrowernumber'=>$borrowerid);
1668 $date=POSIX::strftime("%Y-%m-%d",localtime());
1669 $date = GetExpiryDate( $borrower->{'categorycode'}, $date );
1671 my $sth = $dbh->do(<<EOF);
1673 SET dateexpiry='$date'
1674 WHERE borrowernumber='$borrowerid'
1676 # add enrolmentfee if needed
1677 $sth = $dbh->prepare("SELECT enrolmentfee FROM categories WHERE categorycode=?");
1678 $sth->execute($borrower->{'categorycode'});
1679 my ($enrolmentfee) = $sth->fetchrow;
1680 if ($enrolmentfee && $enrolmentfee > 0) {
1681 # insert fee in patron debts
1682 manualinvoice($borrower->{'borrowernumber'}, '', '', 'A', $enrolmentfee);
1684 return $date if ($sth);
1688 =head2 GetRoadTypes (OUEST-PROVENCE)
1690 ($idroadtypearrayref, $roadttype_hashref) = &GetRoadTypes();
1692 Looks up the different road type . Returns two
1693 elements: a reference-to-array, which lists the id_roadtype
1694 codes, and a reference-to-hash, which maps the road type of the road .
1699 my $dbh = C4::Context->dbh;
1701 SELECT roadtypeid,road_type
1703 ORDER BY road_type|;
1704 my $sth = $dbh->prepare($query);
1709 # insert empty value to create a empty choice in cgi popup
1711 while ( my $data = $sth->fetchrow_hashref ) {
1713 push @id, $data->{'roadtypeid'};
1714 $roadtype{ $data->{'roadtypeid'} } = $data->{'road_type'};
1717 #test to know if the table contain some records if no the function return nothing
1724 return ( \@id, \%roadtype );
1730 =head2 GetTitles (OUEST-PROVENCE)
1732 ($borrowertitle)= &GetTitles();
1734 Looks up the different title . Returns array with all borrowers title
1739 my @borrowerTitle = split (/,|\|/,C4::Context->preference('BorrowersTitles'));
1740 unshift( @borrowerTitle, "" );
1741 my $count=@borrowerTitle;
1746 return ( \@borrowerTitle);
1750 =head2 GetPatronImage
1752 my ($imagedata, $dberror) = GetPatronImage($cardnumber);
1754 Returns the mimetype and binary image data of the image for the patron with the supplied cardnumber.
1758 sub GetPatronImage {
1759 my ($cardnumber) = @_;
1760 warn "Cardnumber passed to GetPatronImage is $cardnumber" if $debug;
1761 my $dbh = C4::Context->dbh;
1762 my $query = 'SELECT mimetype, imagefile FROM patronimage WHERE cardnumber = ?';
1763 my $sth = $dbh->prepare($query);
1764 $sth->execute($cardnumber);
1765 my $imagedata = $sth->fetchrow_hashref;
1766 warn "Database error!" if $sth->errstr;
1767 return $imagedata, $sth->errstr;
1770 =head2 PutPatronImage
1772 PutPatronImage($cardnumber, $mimetype, $imgfile);
1774 Stores patron binary image data and mimetype in database.
1775 NOTE: This function is good for updating images as well as inserting new images in the database.
1779 sub PutPatronImage {
1780 my ($cardnumber, $mimetype, $imgfile) = @_;
1781 warn "Parameters passed in: Cardnumber=$cardnumber, Mimetype=$mimetype, " . ($imgfile ? "Imagefile" : "No Imagefile") if $debug;
1782 my $dbh = C4::Context->dbh;
1783 my $query = "INSERT INTO patronimage (cardnumber, mimetype, imagefile) VALUES (?,?,?) ON DUPLICATE KEY UPDATE imagefile = ?;";
1784 my $sth = $dbh->prepare($query);
1785 $sth->execute($cardnumber,$mimetype,$imgfile,$imgfile);
1786 warn "Error returned inserting $cardnumber.$mimetype." if $sth->errstr;
1787 return $sth->errstr;
1790 =head2 RmPatronImage
1792 my ($dberror) = RmPatronImage($cardnumber);
1794 Removes the image for the patron with the supplied cardnumber.
1799 my ($cardnumber) = @_;
1800 warn "Cardnumber passed to GetPatronImage is $cardnumber" if $debug;
1801 my $dbh = C4::Context->dbh;
1802 my $query = "DELETE FROM patronimage WHERE cardnumber = ?;";
1803 my $sth = $dbh->prepare($query);
1804 $sth->execute($cardnumber);
1805 my $dberror = $sth->errstr;
1806 warn "Database error!" if $sth->errstr;
1810 =head2 GetRoadTypeDetails (OUEST-PROVENCE)
1812 ($roadtype) = &GetRoadTypeDetails($roadtypeid);
1814 Returns the description of roadtype
1815 C<&$roadtype>return description of road type
1816 C<&$roadtypeid>this is the value of roadtype s
1820 sub GetRoadTypeDetails {
1821 my ($roadtypeid) = @_;
1822 my $dbh = C4::Context->dbh;
1826 WHERE roadtypeid=?|;
1827 my $sth = $dbh->prepare($query);
1828 $sth->execute($roadtypeid);
1829 my $roadtype = $sth->fetchrow;
1833 =head2 GetBorrowersWhoHaveNotBorrowedSince
1835 &GetBorrowersWhoHaveNotBorrowedSince($date)
1837 this function get all borrowers who haven't borrowed since the date given on input arg.
1841 sub GetBorrowersWhoHaveNotBorrowedSince {
1842 my $filterdate = shift||POSIX::strftime("%Y-%m-%d",localtime());
1843 my $filterexpiry = shift;
1844 my $filterbranch = shift ||
1845 ((C4::Context->preference('IndependantBranches')
1846 && C4::Context->userenv
1847 && C4::Context->userenv->{flags} % 2 !=1
1848 && C4::Context->userenv->{branch})
1849 ? C4::Context->userenv->{branch}
1851 my $dbh = C4::Context->dbh;
1853 SELECT borrowers.borrowernumber,
1854 max(old_issues.timestamp) as latestissue,
1855 max(issues.timestamp) as currentissue
1857 JOIN categories USING (categorycode)
1858 LEFT JOIN old_issues USING (borrowernumber)
1859 LEFT JOIN issues USING (borrowernumber)
1860 WHERE category_type <> 'S'
1861 AND borrowernumber NOT IN (SELECT guarantorid FROM borrowers WHERE guarantorid IS NOT NULL AND guarantorid <> 0)
1864 if ($filterbranch && $filterbranch ne ""){
1865 $query.=" AND borrowers.branchcode= ?";
1866 push @query_params,$filterbranch;
1869 $query .= " AND dateexpiry < ? ";
1870 push @query_params,$filterdate;
1872 $query.=" GROUP BY borrowers.borrowernumber";
1874 $query.=" HAVING (latestissue < ? OR latestissue IS NULL)
1875 AND currentissue IS NULL";
1876 push @query_params,$filterdate;
1878 warn $query if $debug;
1879 my $sth = $dbh->prepare($query);
1880 if (scalar(@query_params)>0){
1881 $sth->execute(@query_params);
1888 while ( my $data = $sth->fetchrow_hashref ) {
1889 push @results, $data;
1894 =head2 GetBorrowersWhoHaveNeverBorrowed
1896 $results = &GetBorrowersWhoHaveNeverBorrowed
1898 This function get all borrowers who have never borrowed.
1900 I<$result> is a ref to an array which all elements are a hasref.
1904 sub GetBorrowersWhoHaveNeverBorrowed {
1905 my $filterbranch = shift ||
1906 ((C4::Context->preference('IndependantBranches')
1907 && C4::Context->userenv
1908 && C4::Context->userenv->{flags} % 2 !=1
1909 && C4::Context->userenv->{branch})
1910 ? C4::Context->userenv->{branch}
1912 my $dbh = C4::Context->dbh;
1914 SELECT borrowers.borrowernumber,max(timestamp) as latestissue
1916 LEFT JOIN issues ON borrowers.borrowernumber = issues.borrowernumber
1917 WHERE issues.borrowernumber IS NULL
1920 if ($filterbranch && $filterbranch ne ""){
1921 $query.=" AND borrowers.branchcode= ?";
1922 push @query_params,$filterbranch;
1924 warn $query if $debug;
1926 my $sth = $dbh->prepare($query);
1927 if (scalar(@query_params)>0){
1928 $sth->execute(@query_params);
1935 while ( my $data = $sth->fetchrow_hashref ) {
1936 push @results, $data;
1941 =head2 GetBorrowersWithIssuesHistoryOlderThan
1943 $results = &GetBorrowersWithIssuesHistoryOlderThan($date)
1945 this function get all borrowers who has an issue history older than I<$date> given on input arg.
1947 I<$result> is a ref to an array which all elements are a hashref.
1948 This hashref is containt the number of time this borrowers has borrowed before I<$date> and the borrowernumber.
1952 sub GetBorrowersWithIssuesHistoryOlderThan {
1953 my $dbh = C4::Context->dbh;
1954 my $date = shift ||POSIX::strftime("%Y-%m-%d",localtime());
1955 my $filterbranch = shift ||
1956 ((C4::Context->preference('IndependantBranches')
1957 && C4::Context->userenv
1958 && C4::Context->userenv->{flags} % 2 !=1
1959 && C4::Context->userenv->{branch})
1960 ? C4::Context->userenv->{branch}
1963 SELECT count(borrowernumber) as n,borrowernumber
1965 WHERE returndate < ?
1966 AND borrowernumber IS NOT NULL
1969 push @query_params, $date;
1971 $query.=" AND branchcode = ?";
1972 push @query_params, $filterbranch;
1974 $query.=" GROUP BY borrowernumber ";
1975 warn $query if $debug;
1976 my $sth = $dbh->prepare($query);
1977 $sth->execute(@query_params);
1980 while ( my $data = $sth->fetchrow_hashref ) {
1981 push @results, $data;
1986 =head2 GetBorrowersNamesAndLatestIssue
1988 $results = &GetBorrowersNamesAndLatestIssueList(@borrowernumbers)
1990 this function get borrowers Names and surnames and Issue information.
1992 I<@borrowernumbers> is an array which all elements are borrowernumbers.
1993 This hashref is containt the number of time this borrowers has borrowed before I<$date> and the borrowernumber.
1997 sub GetBorrowersNamesAndLatestIssue {
1998 my $dbh = C4::Context->dbh;
1999 my @borrowernumbers=@_;
2001 SELECT surname,lastname, phone, email,max(timestamp)
2003 LEFT JOIN issues ON borrowers.borrowernumber=issues.borrowernumber
2004 GROUP BY borrowernumber
2006 my $sth = $dbh->prepare($query);
2008 my $results = $sth->fetchall_arrayref({});
2014 my $success = DebarMember( $borrowernumber );
2016 marks a Member as debarred, and therefore unable to checkout any more
2020 true on success, false on failure
2025 my $borrowernumber = shift;
2027 return unless defined $borrowernumber;
2028 return unless $borrowernumber =~ /^\d+$/;
2030 return ModMember( borrowernumber => $borrowernumber,
2039 my $success = ModPrivacy( $borrowernumber, $privacy );
2041 Update the privacy of a patron.
2044 true on success, false on failure
2051 my $borrowernumber = shift;
2052 my $privacy = shift;
2053 return unless defined $borrowernumber;
2054 return unless $borrowernumber =~ /^\d+$/;
2056 return ModMember( borrowernumber => $borrowernumber,
2057 privacy => $privacy );
2062 AddMessage( $borrowernumber, $message_type, $message, $branchcode );
2064 Adds a message to the messages table for the given borrower.
2073 my ( $borrowernumber, $message_type, $message, $branchcode ) = @_;
2075 my $dbh = C4::Context->dbh;
2077 if ( ! ( $borrowernumber && $message_type && $message && $branchcode ) ) {
2081 my $query = "INSERT INTO messages ( borrowernumber, branchcode, message_type, message ) VALUES ( ?, ?, ?, ? )";
2082 my $sth = $dbh->prepare($query);
2083 $sth->execute( $borrowernumber, $branchcode, $message_type, $message );
2090 GetMessages( $borrowernumber, $type );
2092 $type is message type, B for borrower, or L for Librarian.
2093 Empty type returns all messages of any type.
2095 Returns all messages for the given borrowernumber
2100 my ( $borrowernumber, $type, $branchcode ) = @_;
2106 my $dbh = C4::Context->dbh;
2109 branches.branchname,
2112 messages.branchcode LIKE '$branchcode' AS can_delete
2113 FROM messages, branches
2114 WHERE borrowernumber = ?
2115 AND message_type LIKE ?
2116 AND messages.branchcode = branches.branchcode
2117 ORDER BY message_date DESC";
2118 my $sth = $dbh->prepare($query);
2119 $sth->execute( $borrowernumber, $type ) ;
2122 while ( my $data = $sth->fetchrow_hashref ) {
2123 my $d = C4::Dates->new( $data->{message_date}, 'iso' );
2124 $data->{message_date_formatted} = $d->output;
2125 push @results, $data;
2133 GetMessagesCount( $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 the number of messages for the given borrowernumber
2142 sub GetMessagesCount {
2143 my ( $borrowernumber, $type, $branchcode ) = @_;
2149 my $dbh = C4::Context->dbh;
2151 my $query = "SELECT COUNT(*) as MsgCount FROM messages WHERE borrowernumber = ? AND message_type LIKE ?";
2152 my $sth = $dbh->prepare($query);
2153 $sth->execute( $borrowernumber, $type ) ;
2156 my $data = $sth->fetchrow_hashref;
2157 my $count = $data->{'MsgCount'};
2164 =head2 DeleteMessage
2166 DeleteMessage( $message_id );
2171 my ( $message_id ) = @_;
2173 my $dbh = C4::Context->dbh;
2175 my $query = "DELETE FROM messages WHERE message_id = ?";
2176 my $sth = $dbh->prepare($query);
2177 $sth->execute( $message_id );
2181 END { } # module clean-up code here (global destructor)