3 # Copyright 2000-2003 Katipo Communications
5 # This file is part of Koha.
7 # Koha is free software; you can redistribute it and/or modify it under the
8 # terms of the GNU General Public License as published by the Free Software
9 # Foundation; either version 2 of the License, or (at your option) any later
12 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
13 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
14 # A PARTICULAR PURPOSE. See the GNU General Public License for more details.
16 # You should have received a copy of the GNU General Public License along
17 # with Koha; if not, write to the Free Software Foundation, Inc.,
18 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
22 #use warnings; FIXME - Bug 2505
24 use C4::Dates qw(format_date_in_iso);
25 use Digest::MD5 qw(md5_base64);
26 use Date::Calc qw/Today Add_Delta_YM/;
27 use C4::Log; # logaction
32 use C4::SQLHelper qw(InsertInTable UpdateInTable SearchInTable);
33 use C4::Members::Attributes qw(SearchIdMatchingAttribute);
35 our ($VERSION,@ISA,@EXPORT,@EXPORT_OK,$debug);
39 $debug = $ENV{DEBUG} || 0;
51 &GetMemberIssuesAndFines
59 &GetFirstValidEmailAddress
73 &GetMemberAccountRecords
74 &GetBorNotifyAcctRecord
78 &GetBorrowercategoryList
80 &GetBorrowersWhoHaveNotBorrowedSince
81 &GetBorrowersWhoHaveNeverBorrowed
82 &GetBorrowersWithIssuesHistoryOlderThan
109 &ExtendMemberSubscriptionTo
127 C4::Members - Perl Module containing convenience functions for member handling
135 This module contains routines for adding, modifying and deleting members/patrons/borrowers
141 ($count, $borrowers) = &SearchMember($searchstring, $type,
142 $category_type, $filter, $showallbranches);
144 Looks up patrons (borrowers) by name.
146 BUGFIX 499: C<$type> is now used to determine type of search.
147 if $type is "simple", search is performed on the first letter of the
150 $category_type is used to get a specified type of user.
151 (mainly adults when creating a child.)
153 C<$searchstring> is a space-separated list of search terms. Each term
154 must match the beginning a borrower's surname, first name, or other
157 C<$filter> is assumed to be a list of elements to filter results on
159 C<$showallbranches> is used in IndependantBranches Context to display all branches results.
161 C<&SearchMember> returns a two-element list. C<$borrowers> is a
162 reference-to-array; each element is a reference-to-hash, whose keys
163 are the fields of the C<borrowers> table in the Koha database.
164 C<$count> is the number of elements in C<$borrowers>.
169 #used by member enquiries from the intranet
171 my ($searchstring, $orderby, $type,$category_type,$filter,$showallbranches ) = @_;
172 my $dbh = C4::Context->dbh;
178 # this is used by circulation everytime a new borrowers cardnumber is scanned
179 # so we can check an exact match first, if that works return, otherwise do the rest
180 $query = "SELECT * FROM borrowers
181 LEFT JOIN categories ON borrowers.categorycode=categories.categorycode
183 my $sth = $dbh->prepare("$query WHERE cardnumber = ?");
184 $sth->execute($searchstring);
185 my $data = $sth->fetchall_arrayref({});
187 return ( scalar(@$data), $data );
190 if ( $type eq "simple" ) # simple search for one letter only
192 $query .= ($category_type ? " AND category_type = ".$dbh->quote($category_type) : "");
193 $query .= " WHERE (surname LIKE ? OR cardnumber like ?) ";
194 if (C4::Context->preference("IndependantBranches") && !$showallbranches){
195 if (C4::Context->userenv && C4::Context->userenv->{flags} % 2 !=1 && C4::Context->userenv->{'branch'}){
196 $query.=" AND borrowers.branchcode =".$dbh->quote(C4::Context->userenv->{'branch'}) unless (C4::Context->userenv->{'branch'} eq "insecure");
199 $query.=" ORDER BY $orderby";
200 @bind = ("$searchstring%","$searchstring");
202 else # advanced search looking in surname, firstname and othernames
204 @data = split( ' ', $searchstring );
207 if (C4::Context->preference("IndependantBranches") && !$showallbranches){
208 if (C4::Context->userenv && C4::Context->userenv->{flags} % 2 !=1 && C4::Context->userenv->{'branch'}){
209 $query.=" borrowers.branchcode =".$dbh->quote(C4::Context->userenv->{'branch'})." AND " unless (C4::Context->userenv->{'branch'} eq "insecure");
212 $query.="((surname LIKE ? OR surname LIKE ?
213 OR firstname LIKE ? OR firstname LIKE ?
214 OR othernames LIKE ? OR othernames LIKE ?)
216 ($category_type?" AND category_type = ".$dbh->quote($category_type):"");
218 "$data[0]%", "% $data[0]%", "$data[0]%", "% $data[0]%",
219 "$data[0]%", "% $data[0]%"
221 for ( my $i = 1 ; $i < $count ; $i++ ) {
222 $query = $query . " AND (" . " surname LIKE ? OR surname LIKE ?
223 OR firstname LIKE ? OR firstname LIKE ?
224 OR othernames LIKE ? OR othernames LIKE ?)";
226 "$data[$i]%", "% $data[$i]%", "$data[$i]%",
227 "% $data[$i]%", "$data[$i]%", "% $data[$i]%" );
231 $query = $query . ") OR cardnumber LIKE ? ";
232 push( @bind, $searchstring );
233 $query .= "order by $orderby";
238 $sth = $dbh->prepare($query);
240 $debug and print STDERR "Q $orderby : $query\n";
241 $sth->execute(@bind);
243 $data = $sth->fetchall_arrayref({});
245 return ( scalar(@$data), $data );
250 $borrowers_result_array_ref = &Search($filter,$orderby, $limit,
251 $columns_out, $search_on_fields,$searchtype);
253 Looks up patrons (borrowers) on filter.
255 BUGFIX 499: C<$type> is now used to determine type of search.
256 if $type is "simple", search is performed on the first letter of the
259 $category_type is used to get a specified type of user.
260 (mainly adults when creating a child.)
263 - a space-separated list of search terms. Implicit AND is done on them
264 - a hash ref containing fieldnames associated with queried value
265 - an array ref combining the two previous elements Implicit OR is done between each array element
268 C<$orderby> is an arrayref of hashref. Contains the name of the field and 0 or 1 depending if order is ascending or descending
270 C<$limit> is there to allow limiting number of results returned
272 C<&columns_out> is an array ref to the fieldnames you want to see in the result list
274 C<&search_on_fields> is an array ref to the fieldnames you want to limit search on when you are using string search
276 C<&searchtype> is a string telling the type of search you want todo : start_with, exact or contains are allowed
281 my ( $filter, $orderby, $limit, $columns_out, $search_on_fields, $searchtype ) = @_;
283 my %filtersmatching_record;
285 if ( ref($filter) eq "ARRAY" ) {
286 push @filters, @$filter;
288 push @filters, $filter;
290 if ( C4::Context->preference('ExtendedPatronAttributes') ) {
291 my $matching_records = C4::Members::Attributes::SearchIdMatchingAttribute($filter);
292 if(scalar(@$matching_records)>0) {
293 foreach my $matching_record (@$matching_records) {
294 $filtersmatching_record{$$matching_record[0]}=1;
296 foreach my $k (keys(%filtersmatching_record)) {
297 push @filters, {"borrowernumber"=>$k};
301 $searchtype ||= "start_with";
302 push @finalfilter, \@filters;
303 my $data = SearchInTable( "borrowers", \@finalfilter, $orderby, $limit, $columns_out, $search_on_fields, $searchtype );
307 =head2 GetMemberDetails
309 ($borrower) = &GetMemberDetails($borrowernumber, $cardnumber);
311 Looks up a patron and returns information about him or her. If
312 C<$borrowernumber> is true (nonzero), C<&GetMemberDetails> looks
313 up the borrower by number; otherwise, it looks up the borrower by card
316 C<$borrower> is a reference-to-hash whose keys are the fields of the
317 borrowers table in the Koha database. In addition,
318 C<$borrower-E<gt>{flags}> is a hash giving more detailed information
319 about the patron. Its keys act as flags :
321 if $borrower->{flags}->{LOST} {
322 # Patron's card was reported lost
325 If the state of a flag means that the patron should not be
326 allowed to borrow any more books, then it will have a C<noissues> key
329 See patronflags for more details.
331 C<$borrower-E<gt>{authflags}> is a hash giving more detailed information
332 about the top-level permissions flags set for the borrower. For example,
333 if a user has the "editcatalogue" permission,
334 C<$borrower-E<gt>{authflags}-E<gt>{editcatalogue}> will exist and have
339 sub GetMemberDetails {
340 my ( $borrowernumber, $cardnumber ) = @_;
341 my $dbh = C4::Context->dbh;
344 if ($borrowernumber) {
345 $sth = $dbh->prepare("select borrowers.*,category_type,categories.description from borrowers left join categories on borrowers.categorycode=categories.categorycode where borrowernumber=?");
346 $sth->execute($borrowernumber);
348 elsif ($cardnumber) {
349 $sth = $dbh->prepare("select borrowers.*,category_type,categories.description from borrowers left join categories on borrowers.categorycode=categories.categorycode where cardnumber=?");
350 $sth->execute($cardnumber);
355 my $borrower = $sth->fetchrow_hashref;
356 my ($amount) = GetMemberAccountRecords( $borrowernumber);
357 $borrower->{'amountoutstanding'} = $amount;
358 # FIXME - patronflags calls GetMemberAccountRecords... just have patronflags return $amount
359 my $flags = patronflags( $borrower);
362 $sth = $dbh->prepare("select bit,flag from userflags");
364 while ( my ( $bit, $flag ) = $sth->fetchrow ) {
365 if ( $borrower->{'flags'} && $borrower->{'flags'} & 2**$bit ) {
366 $accessflagshash->{$flag} = 1;
369 $borrower->{'flags'} = $flags;
370 $borrower->{'authflags'} = $accessflagshash;
372 # find out how long the membership lasts
375 "select enrolmentperiod from categories where categorycode = ?");
376 $sth->execute( $borrower->{'categorycode'} );
377 my $enrolment = $sth->fetchrow;
378 $borrower->{'enrolmentperiod'} = $enrolment;
379 return ($borrower); #, $flags, $accessflagshash);
384 $flags = &patronflags($patron);
386 This function is not exported.
388 The following will be set where applicable:
389 $flags->{CHARGES}->{amount} Amount of debt
390 $flags->{CHARGES}->{noissues} Set if debt amount >$5.00 (or syspref noissuescharge)
391 $flags->{CHARGES}->{message} Message -- deprecated
393 $flags->{CREDITS}->{amount} Amount of credit
394 $flags->{CREDITS}->{message} Message -- deprecated
396 $flags->{ GNA } Patron has no valid address
397 $flags->{ GNA }->{noissues} Set for each GNA
398 $flags->{ GNA }->{message} "Borrower has no valid address" -- deprecated
400 $flags->{ LOST } Patron's card reported lost
401 $flags->{ LOST }->{noissues} Set for each LOST
402 $flags->{ LOST }->{message} Message -- deprecated
404 $flags->{DBARRED} Set if patron debarred, no access
405 $flags->{DBARRED}->{noissues} Set for each DBARRED
406 $flags->{DBARRED}->{message} Message -- deprecated
409 $flags->{ NOTES }->{message} The note itself. NOT deprecated
411 $flags->{ ODUES } Set if patron has overdue books.
412 $flags->{ ODUES }->{message} "Yes" -- deprecated
413 $flags->{ ODUES }->{itemlist} ref-to-array: list of overdue books
414 $flags->{ ODUES }->{itemlisttext} Text list of overdue items -- deprecated
416 $flags->{WAITING} Set if any of patron's reserves are available
417 $flags->{WAITING}->{message} Message -- deprecated
418 $flags->{WAITING}->{itemlist} ref-to-array: list of available items
422 =item C<$flags-E<gt>{ODUES}-E<gt>{itemlist}> is a reference-to-array listing the
423 overdue items. Its elements are references-to-hash, each describing an
424 overdue item. The keys are selected fields from the issues, biblio,
425 biblioitems, and items tables of the Koha database.
427 =item C<$flags-E<gt>{ODUES}-E<gt>{itemlisttext}> is a string giving a text listing of
428 the overdue items, one per line. Deprecated.
430 =item C<$flags-E<gt>{WAITING}-E<gt>{itemlist}> is a reference-to-array listing the
431 available items. Each element is a reference-to-hash whose keys are
432 fields from the reserves table of the Koha database.
436 All the "message" fields that include language generated in this function are deprecated,
437 because such strings belong properly in the display layer.
439 The "message" field that comes from the DB is OK.
443 # TODO: use {anonymous => hashes} instead of a dozen %flaginfo
444 # FIXME rename this function.
447 my ( $patroninformation) = @_;
448 my $dbh=C4::Context->dbh;
449 my ($amount) = GetMemberAccountRecords( $patroninformation->{'borrowernumber'});
452 my $noissuescharge = C4::Context->preference("noissuescharge") || 5;
453 $flaginfo{'message'} = sprintf "Patron owes \$%.02f", $amount;
454 $flaginfo{'amount'} = sprintf "%.02f", $amount;
455 if ( $amount > $noissuescharge && !C4::Context->preference("AllowFineOverride") ) {
456 $flaginfo{'noissues'} = 1;
458 $flags{'CHARGES'} = \%flaginfo;
460 elsif ( $amount < 0 ) {
462 $flaginfo{'message'} = sprintf "Patron has credit of \$%.02f", -$amount;
463 $flaginfo{'amount'} = sprintf "%.02f", $amount;
464 $flags{'CREDITS'} = \%flaginfo;
466 if ( $patroninformation->{'gonenoaddress'}
467 && $patroninformation->{'gonenoaddress'} == 1 )
470 $flaginfo{'message'} = 'Borrower has no valid address.';
471 $flaginfo{'noissues'} = 1;
472 $flags{'GNA'} = \%flaginfo;
474 if ( $patroninformation->{'lost'} && $patroninformation->{'lost'} == 1 ) {
476 $flaginfo{'message'} = 'Borrower\'s card reported lost.';
477 $flaginfo{'noissues'} = 1;
478 $flags{'LOST'} = \%flaginfo;
480 if ( $patroninformation->{'debarred'}
481 && $patroninformation->{'debarred'} == 1 )
484 $flaginfo{'message'} = 'Borrower is Debarred.';
485 $flaginfo{'noissues'} = 1;
486 $flags{'DBARRED'} = \%flaginfo;
488 if ( $patroninformation->{'borrowernotes'}
489 && $patroninformation->{'borrowernotes'} )
492 $flaginfo{'message'} = $patroninformation->{'borrowernotes'};
493 $flags{'NOTES'} = \%flaginfo;
495 my ( $odues, $itemsoverdue ) = checkoverdues($patroninformation->{'borrowernumber'});
496 if ( $odues && $odues > 0 ) {
498 $flaginfo{'message'} = "Yes";
499 $flaginfo{'itemlist'} = $itemsoverdue;
500 foreach ( sort { $a->{'date_due'} cmp $b->{'date_due'} }
503 $flaginfo{'itemlisttext'} .=
504 "$_->{'date_due'} $_->{'barcode'} $_->{'title'} \n"; # newline is display layer
506 $flags{'ODUES'} = \%flaginfo;
508 my @itemswaiting = C4::Reserves::GetReservesFromBorrowernumber( $patroninformation->{'borrowernumber'},'W' );
509 my $nowaiting = scalar @itemswaiting;
510 if ( $nowaiting > 0 ) {
512 $flaginfo{'message'} = "Reserved items available";
513 $flaginfo{'itemlist'} = \@itemswaiting;
514 $flags{'WAITING'} = \%flaginfo;
522 $borrower = &GetMember(%information);
524 Retrieve the first patron record meeting on criteria listed in the
525 C<%information> hash, which should contain one or more
526 pairs of borrowers column names and values, e.g.,
528 $borrower = GetMember(borrowernumber => id);
530 C<&GetBorrower> returns a reference-to-hash whose keys are the fields of
531 the C<borrowers> table in the Koha database.
533 FIXME: GetMember() is used throughout the code as a lookup
534 on a unique key such as the borrowernumber, but this meaning is not
535 enforced in the routine itself.
541 my ( %information ) = @_;
542 if (exists $information{borrowernumber} && !defined $information{borrowernumber}) {
543 #passing mysql's kohaadmin?? Makes no sense as a query
546 my $dbh = C4::Context->dbh;
548 q{SELECT borrowers.*, categories.category_type, categories.description
550 LEFT JOIN categories on borrowers.categorycode=categories.categorycode WHERE };
553 for (keys %information ) {
561 if (defined $information{$_}) {
563 push @values, $information{$_};
566 $select .= "$_ IS NULL";
569 $debug && warn $select, " ",values %information;
570 my $sth = $dbh->prepare("$select");
571 $sth->execute(map{$information{$_}} keys %information);
572 my $data = $sth->fetchall_arrayref({});
573 #FIXME interface to this routine now allows generation of a result set
574 #so whole array should be returned but bowhere in the current code expects this
583 =head2 IsMemberBlocked
585 my ($block_status, $count) = IsMemberBlocked( $borrowernumber );
587 Returns whether a patron has overdue items that may result
588 in a block or whether the patron has active fine days
589 that would block circulation privileges.
591 C<$block_status> can have the following values:
593 1 if the patron has outstanding fine days, in which case C<$count> is the number of them
595 -1 if the patron has overdue items, in which case C<$count> is the number of them
597 0 if the patron has no overdue items or outstanding fine days, in which case C<$count> is 0
599 Outstanding fine days are checked before current overdue items
602 FIXME: this needs to be split into two functions; a potential block
603 based on the number of current overdue items could be orthogonal
604 to a block based on whether the patron has any fine days accrued.
608 sub IsMemberBlocked {
609 my $borrowernumber = shift;
610 my $dbh = C4::Context->dbh;
612 # does patron have current fine days?
615 ADDDATE(returndate, finedays * DATEDIFF(returndate,date_due) ) AS blockingdate,
616 DATEDIFF(ADDDATE(returndate, finedays * DATEDIFF(returndate,date_due)),NOW()) AS blockedcount
619 if(C4::Context->preference("item-level_itypes")){
621 qq{ LEFT JOIN items ON (items.itemnumber=old_issues.itemnumber)
622 LEFT JOIN issuingrules ON (issuingrules.itemtype=items.itype)}
625 qq{ LEFT JOIN items ON (items.itemnumber=old_issues.itemnumber)
626 LEFT JOIN biblioitems ON (biblioitems.biblioitemnumber=items.biblioitemnumber)
627 LEFT JOIN issuingrules ON (issuingrules.itemtype=biblioitems.itemtype) };
630 qq{ WHERE finedays IS NOT NULL
631 AND date_due < returndate
632 AND borrowernumber = ?
633 ORDER BY blockingdate DESC, blockedcount DESC
635 my $sth=$dbh->prepare($strsth);
636 $sth->execute($borrowernumber);
637 my $row = $sth->fetchrow_hashref;
638 my $blockeddate = $row->{'blockeddate'};
639 my $blockedcount = $row->{'blockedcount'};
641 return (1, $blockedcount) if $blockedcount > 0;
643 # if he have late issues
644 $sth = $dbh->prepare(
645 "SELECT COUNT(*) as latedocs
647 WHERE borrowernumber = ?
648 AND date_due < curdate()"
650 $sth->execute($borrowernumber);
651 my $latedocs = $sth->fetchrow_hashref->{'latedocs'};
653 return (-1, $latedocs) if $latedocs > 0;
658 =head2 GetMemberIssuesAndFines
660 ($overdue_count, $issue_count, $total_fines) = &GetMemberIssuesAndFines($borrowernumber);
662 Returns aggregate data about items borrowed by the patron with the
663 given borrowernumber.
665 C<&GetMemberIssuesAndFines> returns a three-element array. C<$overdue_count> is the
666 number of overdue items the patron currently has borrowed. C<$issue_count> is the
667 number of books the patron currently has borrowed. C<$total_fines> is
668 the total fine currently due by the borrower.
673 sub GetMemberIssuesAndFines {
674 my ( $borrowernumber ) = @_;
675 my $dbh = C4::Context->dbh;
676 my $query = "SELECT COUNT(*) FROM issues WHERE borrowernumber = ?";
678 $debug and warn $query."\n";
679 my $sth = $dbh->prepare($query);
680 $sth->execute($borrowernumber);
681 my $issue_count = $sth->fetchrow_arrayref->[0];
683 $sth = $dbh->prepare(
684 "SELECT COUNT(*) FROM issues
685 WHERE borrowernumber = ?
686 AND date_due < curdate()"
688 $sth->execute($borrowernumber);
689 my $overdue_count = $sth->fetchrow_arrayref->[0];
691 $sth = $dbh->prepare("SELECT SUM(amountoutstanding) FROM accountlines WHERE borrowernumber = ?");
692 $sth->execute($borrowernumber);
693 my $total_fines = $sth->fetchrow_arrayref->[0];
695 return ($overdue_count, $issue_count, $total_fines);
699 return @{C4::Context->dbh->selectcol_arrayref("SHOW columns from borrowers")};
704 my $success = ModMember(borrowernumber => $borrowernumber,
705 [ field => value ]... );
707 Modify borrower's data. All date fields should ALREADY be in ISO format.
710 true on success, or false on failure
716 # test to know if you must update or not the borrower password
717 if (exists $data{password}) {
718 if ($data{password} eq '****' or $data{password} eq '') {
719 delete $data{password};
721 $data{password} = md5_base64($data{password});
724 my $execute_success=UpdateInTable("borrowers",\%data);
725 # ok if its an adult (type) it may have borrowers that depend on it as a guarantor
726 # so when we update information for an adult we should check for guarantees and update the relevant part
727 # of their records, ie addresses and phone numbers
728 my $borrowercategory= GetBorrowercategory( $data{'category_type'} );
729 if ( exists $borrowercategory->{'category_type'} && $borrowercategory->{'category_type'} eq ('A' || 'S') ) {
730 # is adult check guarantees;
731 UpdateGuarantees(%data);
733 logaction("MEMBERS", "MODIFY", $data{'borrowernumber'}, "UPDATE (executed w/ arg: $data{'borrowernumber'})")
734 if C4::Context->preference("BorrowersLog");
736 return $execute_success;
742 $borrowernumber = &AddMember(%borrower);
744 insert new borrower into table
745 Returns the borrowernumber
752 my $dbh = C4::Context->dbh;
753 $data{'password'} = '!' if (not $data{'password'} and $data{'userid'});
754 $data{'password'} = md5_base64( $data{'password'} ) if $data{'password'};
755 $data{'borrowernumber'}=InsertInTable("borrowers",\%data);
756 # mysql_insertid is probably bad. not necessarily accurate and mysql-specific at best.
757 logaction("MEMBERS", "CREATE", $data{'borrowernumber'}, "") if C4::Context->preference("BorrowersLog");
759 # check for enrollment fee & add it if needed
760 my $sth = $dbh->prepare("SELECT enrolmentfee FROM categories WHERE categorycode=?");
761 $sth->execute($data{'categorycode'});
762 my ($enrolmentfee) = $sth->fetchrow;
763 if ($enrolmentfee && $enrolmentfee > 0) {
764 # insert fee in patron debts
765 manualinvoice($data{'borrowernumber'}, '', '', 'A', $enrolmentfee);
767 return $data{'borrowernumber'};
772 my ($uid,$member) = @_;
773 my $dbh = C4::Context->dbh;
774 # Make sure the userid chosen is unique and not theirs if non-empty. If it is not,
775 # Then we need to tell the user and have them create a new one.
778 "SELECT * FROM borrowers WHERE userid=? AND borrowernumber != ?");
779 $sth->execute( $uid, $member );
780 if ( ( $uid ne '' ) && ( my $row = $sth->fetchrow_hashref ) ) {
788 sub Generate_Userid {
789 my ($borrowernumber, $firstname, $surname) = @_;
793 $firstname =~ s/[[:digit:][:space:][:blank:][:punct:][:cntrl:]]//g;
794 $surname =~ s/[[:digit:][:space:][:blank:][:punct:][:cntrl:]]//g;
795 $newuid = lc("$firstname.$surname");
796 $newuid .= $offset unless $offset == 0;
799 } while (!Check_Userid($newuid,$borrowernumber));
805 my ( $uid, $member, $digest ) = @_;
806 my $dbh = C4::Context->dbh;
808 #Make sure the userid chosen is unique and not theirs if non-empty. If it is not,
809 #Then we need to tell the user and have them create a new one.
813 "SELECT * FROM borrowers WHERE userid=? AND borrowernumber != ?");
814 $sth->execute( $uid, $member );
815 if ( ( $uid ne '' ) && ( my $row = $sth->fetchrow_hashref ) ) {
819 #Everything is good so we can update the information.
822 "update borrowers set userid=?, password=? where borrowernumber=?");
823 $sth->execute( $uid, $digest, $member );
827 logaction("MEMBERS", "CHANGE PASS", $member, "") if C4::Context->preference("BorrowersLog");
833 =head2 fixup_cardnumber
835 Warning: The caller is responsible for locking the members table in write
836 mode, to avoid database corruption.
840 use vars qw( @weightings );
841 my @weightings = ( 8, 4, 6, 3, 5, 2, 1 );
843 sub fixup_cardnumber ($) {
844 my ($cardnumber) = @_;
845 my $autonumber_members = C4::Context->boolean_preference('autoMemberNum') || 0;
847 # Find out whether member numbers should be generated
848 # automatically. Should be either "1" or something else.
849 # Defaults to "0", which is interpreted as "no".
851 # if ($cardnumber !~ /\S/ && $autonumber_members) {
852 ($autonumber_members) or return $cardnumber;
853 my $checkdigit = C4::Context->preference('checkdigit');
854 my $dbh = C4::Context->dbh;
855 if ( $checkdigit and $checkdigit eq 'katipo' ) {
857 # if checkdigit is selected, calculate katipo-style cardnumber.
858 # otherwise, just use the max()
859 # purpose: generate checksum'd member numbers.
860 # We'll assume we just got the max value of digits 2-8 of member #'s
861 # from the database and our job is to increment that by one,
862 # determine the 1st and 9th digits and return the full string.
863 my $sth = $dbh->prepare(
864 "select max(substring(borrowers.cardnumber,2,7)) as new_num from borrowers"
867 my $data = $sth->fetchrow_hashref;
868 $cardnumber = $data->{new_num};
869 if ( !$cardnumber ) { # If DB has no values,
870 $cardnumber = 1000000; # start at 1000000
876 for ( my $i = 0 ; $i < 8 ; $i += 1 ) {
877 # read weightings, left to right, 1 char at a time
878 my $temp1 = $weightings[$i];
880 # sequence left to right, 1 char at a time
881 my $temp2 = substr( $cardnumber, $i, 1 );
883 # mult each char 1-7 by its corresponding weighting
884 $sum += $temp1 * $temp2;
887 my $rem = ( $sum % 11 );
888 $rem = 'X' if $rem == 10;
890 return "V$cardnumber$rem";
893 # MODIFIED BY JF: mysql4.1 allows casting as an integer, which is probably
894 # better. I'll leave the original in in case it needs to be changed for you
895 # my $sth=$dbh->prepare("select max(borrowers.cardnumber) from borrowers");
896 my $sth = $dbh->prepare(
897 "select max(cast(cardnumber as signed)) from borrowers"
900 my ($result) = $sth->fetchrow;
903 return $cardnumber; # just here as a fallback/reminder
908 ($num_children, $children_arrayref) = &GetGuarantees($parent_borrno);
909 $child0_cardno = $children_arrayref->[0]{"cardnumber"};
910 $child0_borrno = $children_arrayref->[0]{"borrowernumber"};
912 C<&GetGuarantees> takes a borrower number (e.g., that of a patron
913 with children) and looks up the borrowers who are guaranteed by that
914 borrower (i.e., the patron's children).
916 C<&GetGuarantees> returns two values: an integer giving the number of
917 borrowers guaranteed by C<$parent_borrno>, and a reference to an array
918 of references to hash, which gives the actual results.
924 my ($borrowernumber) = @_;
925 my $dbh = C4::Context->dbh;
928 "select cardnumber,borrowernumber, firstname, surname from borrowers where guarantorid=?"
930 $sth->execute($borrowernumber);
933 my $data = $sth->fetchall_arrayref({});
934 return ( scalar(@$data), $data );
937 =head2 UpdateGuarantees
939 &UpdateGuarantees($parent_borrno);
942 C<&UpdateGuarantees> borrower data for an adult and updates all the guarantees
943 with the modified information
948 sub UpdateGuarantees {
950 my $dbh = C4::Context->dbh;
951 my ( $count, $guarantees ) = GetGuarantees( $data{'borrowernumber'} );
952 foreach my $guarantee (@$guarantees){
953 my $guaquery = qq|UPDATE borrowers
954 SET address=?,fax=?,B_city=?,mobile=?,city=?,phone=?
955 WHERE borrowernumber=?
957 my $sth = $dbh->prepare($guaquery);
958 $sth->execute($data{'address'},$data{'fax'},$data{'B_city'},$data{'mobile'},$data{'city'},$data{'phone'},$guarantee->{'borrowernumber'});
961 =head2 GetPendingIssues
963 my $issues = &GetPendingIssues($borrowernumber);
965 Looks up what the patron with the given borrowernumber has borrowed.
967 C<&GetPendingIssues> returns a
968 reference-to-array where each element is a reference-to-hash; the
969 keys are the fields from the C<issues>, C<biblio>, and C<items> tables.
970 The keys include C<biblioitems> fields except marc and marcxml.
975 sub GetPendingIssues {
976 my ($borrowernumber) = @_;
977 # must avoid biblioitems.* to prevent large marc and marcxml fields from killing performance
978 # FIXME: namespace collision: each table has "timestamp" fields. Which one is "timestamp" ?
979 # FIXME: circ/ciculation.pl tries to sort by timestamp!
980 # FIXME: C4::Print::printslip tries to sort by timestamp!
981 # FIXME: namespace collision: other collisions possible.
982 # FIXME: most of this data isn't really being used by callers.
983 my $sth = C4::Context->dbh->prepare(
989 biblioitems.itemtype,
992 biblioitems.publicationyear,
993 biblioitems.publishercode,
994 biblioitems.volumedate,
995 biblioitems.volumedesc,
998 issues.timestamp AS timestamp,
999 issues.renewals AS renewals,
1000 items.renewals AS totalrenewals
1002 LEFT JOIN items ON items.itemnumber = issues.itemnumber
1003 LEFT JOIN biblio ON items.biblionumber = biblio.biblionumber
1004 LEFT JOIN biblioitems ON items.biblioitemnumber = biblioitems.biblioitemnumber
1007 ORDER BY issues.issuedate"
1009 $sth->execute($borrowernumber);
1010 my $data = $sth->fetchall_arrayref({});
1011 my $today = C4::Dates->new->output('iso');
1013 $_->{date_due} or next;
1014 ($_->{date_due} lt $today) and $_->{overdue} = 1;
1021 $issues = &GetAllIssues($borrowernumber, $sortkey, $limit);
1023 Looks up what the patron with the given borrowernumber has borrowed,
1024 and sorts the results.
1026 C<$sortkey> is the name of a field on which to sort the results. This
1027 should be the name of a field in the C<issues>, C<biblio>,
1028 C<biblioitems>, or C<items> table in the Koha database.
1030 C<$limit> is the maximum number of results to return.
1032 C<&GetAllIssues> an arrayref, C<$issues>, of hashrefs, the keys of which
1033 are the fields from the C<issues>, C<biblio>, C<biblioitems>, and
1034 C<items> tables of the Koha database.
1040 my ( $borrowernumber, $order, $limit ) = @_;
1042 #FIXME: sanity-check order and limit
1043 my $dbh = C4::Context->dbh;
1045 "SELECT *, issues.timestamp as issuestimestamp, issues.renewals AS renewals,items.renewals AS totalrenewals,items.timestamp AS itemstimestamp
1047 LEFT JOIN items on items.itemnumber=issues.itemnumber
1048 LEFT JOIN biblio ON items.biblionumber=biblio.biblionumber
1049 LEFT JOIN biblioitems ON items.biblioitemnumber=biblioitems.biblioitemnumber
1050 WHERE borrowernumber=?
1052 SELECT *, old_issues.timestamp as issuestimestamp, old_issues.renewals AS renewals,items.renewals AS totalrenewals,items.timestamp AS itemstimestamp
1054 LEFT JOIN items on items.itemnumber=old_issues.itemnumber
1055 LEFT JOIN biblio ON items.biblionumber=biblio.biblionumber
1056 LEFT JOIN biblioitems ON items.biblioitemnumber=biblioitems.biblioitemnumber
1057 WHERE borrowernumber=?
1059 if ( $limit != 0 ) {
1060 $query .= " limit $limit";
1063 my $sth = $dbh->prepare($query);
1064 $sth->execute($borrowernumber, $borrowernumber);
1067 while ( my $data = $sth->fetchrow_hashref ) {
1068 push @result, $data;
1075 =head2 GetMemberAccountRecords
1077 ($total, $acctlines, $count) = &GetMemberAccountRecords($borrowernumber);
1079 Looks up accounting data for the patron with the given borrowernumber.
1081 C<&GetMemberAccountRecords> returns a three-element array. C<$acctlines> is a
1082 reference-to-array, where each element is a reference-to-hash; the
1083 keys are the fields of the C<accountlines> table in the Koha database.
1084 C<$count> is the number of elements in C<$acctlines>. C<$total> is the
1085 total amount outstanding for all of the account lines.
1090 sub GetMemberAccountRecords {
1091 my ($borrowernumber,$date) = @_;
1092 my $dbh = C4::Context->dbh;
1098 WHERE borrowernumber=?);
1099 my @bind = ($borrowernumber);
1100 if ($date && $date ne ''){
1101 $strsth.=" AND date < ? ";
1104 $strsth.=" ORDER BY date desc,timestamp DESC";
1105 my $sth= $dbh->prepare( $strsth );
1106 $sth->execute( @bind );
1108 while ( my $data = $sth->fetchrow_hashref ) {
1109 my $biblio = GetBiblioFromItemNumber($data->{itemnumber}) if $data->{itemnumber};
1110 $data->{biblionumber} = $biblio->{biblionumber};
1111 $data->{title} = $biblio->{title};
1112 $acctlines[$numlines] = $data;
1114 $total += int(1000 * $data->{'amountoutstanding'}); # convert float to integer to avoid round-off errors
1117 return ( $total, \@acctlines,$numlines);
1120 =head2 GetBorNotifyAcctRecord
1122 ($count, $acctlines, $total) = &GetBorNotifyAcctRecord($params,$notifyid);
1124 Looks up accounting data for the patron with the given borrowernumber per file number.
1126 (FIXME - I'm not at all sure what this is about.)
1128 C<&GetBorNotifyAcctRecord> returns a three-element array. C<$acctlines> is a
1129 reference-to-array, where each element is a reference-to-hash; the
1130 keys are the fields of the C<accountlines> table in the Koha database.
1131 C<$count> is the number of elements in C<$acctlines>. C<$total> is the
1132 total amount outstanding for all of the account lines.
1136 sub GetBorNotifyAcctRecord {
1137 my ( $borrowernumber, $notifyid ) = @_;
1138 my $dbh = C4::Context->dbh;
1141 my $sth = $dbh->prepare(
1144 WHERE borrowernumber=?
1146 AND amountoutstanding != '0'
1147 ORDER BY notify_id,accounttype
1149 # 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')
1151 $sth->execute( $borrowernumber, $notifyid );
1153 while ( my $data = $sth->fetchrow_hashref ) {
1154 $acctlines[$numlines] = $data;
1156 $total += int(100 * $data->{'amountoutstanding'});
1159 return ( $total, \@acctlines, $numlines );
1162 =head2 checkuniquemember (OUEST-PROVENCE)
1164 ($result,$categorycode) = &checkuniquemember($collectivity,$surname,$firstname,$dateofbirth);
1166 Checks that a member exists or not in the database.
1168 C<&result> is nonzero (=exist) or 0 (=does not exist)
1169 C<&categorycode> is from categorycode table
1170 C<&collectivity> is 1 (= we add a collectivity) or 0 (= we add a physical member)
1171 C<&surname> is the surname
1172 C<&firstname> is the firstname (only if collectivity=0)
1173 C<&dateofbirth> is the date of birth in ISO format (only if collectivity=0)
1177 # FIXME: This function is not legitimate. Multiple patrons might have the same first/last name and birthdate.
1178 # This is especially true since first name is not even a required field.
1180 sub checkuniquemember {
1181 my ( $collectivity, $surname, $firstname, $dateofbirth ) = @_;
1182 my $dbh = C4::Context->dbh;
1183 my $request = ($collectivity) ?
1184 "SELECT borrowernumber,categorycode FROM borrowers WHERE surname=? " :
1186 "SELECT borrowernumber,categorycode FROM borrowers WHERE surname=? and firstname=? and dateofbirth=?" :
1187 "SELECT borrowernumber,categorycode FROM borrowers WHERE surname=? and firstname=?";
1188 my $sth = $dbh->prepare($request);
1189 if ($collectivity) {
1190 $sth->execute( uc($surname) );
1191 } elsif($dateofbirth){
1192 $sth->execute( uc($surname), ucfirst($firstname), $dateofbirth );
1194 $sth->execute( uc($surname), ucfirst($firstname));
1196 my @data = $sth->fetchrow;
1197 ( $data[0] ) and return $data[0], $data[1];
1201 sub checkcardnumber {
1202 my ($cardnumber,$borrowernumber) = @_;
1203 my $dbh = C4::Context->dbh;
1204 my $query = "SELECT * FROM borrowers WHERE cardnumber=?";
1205 $query .= " AND borrowernumber <> ?" if ($borrowernumber);
1206 my $sth = $dbh->prepare($query);
1207 if ($borrowernumber) {
1208 $sth->execute($cardnumber,$borrowernumber);
1210 $sth->execute($cardnumber);
1212 if (my $data= $sth->fetchrow_hashref()){
1221 =head2 getzipnamecity (OUEST-PROVENCE)
1223 take all info from table city for the fields city and zip
1224 check for the name and the zip code of the city selected
1228 sub getzipnamecity {
1230 my $dbh = C4::Context->dbh;
1233 "select city_name,city_zipcode from cities where cityid=? ");
1234 $sth->execute($cityid);
1235 my @data = $sth->fetchrow;
1236 return $data[0], $data[1];
1240 =head2 getdcity (OUEST-PROVENCE)
1242 recover cityid with city_name condition
1247 my ($city_name) = @_;
1248 my $dbh = C4::Context->dbh;
1249 my $sth = $dbh->prepare("select cityid from cities where city_name=? ");
1250 $sth->execute($city_name);
1251 my $data = $sth->fetchrow;
1255 =head2 GetFirstValidEmailAddress
1257 $email = GetFirstValidEmailAddress($borrowernumber);
1259 Return the first valid email address for a borrower, given the borrowernumber. For now, the order
1260 is defined as email, emailpro, B_email. Returns the empty string if the borrower has no email
1265 sub GetFirstValidEmailAddress {
1266 my $borrowernumber = shift;
1267 my $dbh = C4::Context->dbh;
1268 my $sth = $dbh->prepare( "SELECT email, emailpro, B_email FROM borrowers where borrowernumber = ? ");
1269 $sth->execute( $borrowernumber );
1270 my $data = $sth->fetchrow_hashref;
1272 if ($data->{'email'}) {
1273 return $data->{'email'};
1274 } elsif ($data->{'emailpro'}) {
1275 return $data->{'emailpro'};
1276 } elsif ($data->{'B_email'}) {
1277 return $data->{'B_email'};
1283 =head2 GetExpiryDate
1285 $expirydate = GetExpiryDate($categorycode, $dateenrolled);
1287 Calculate expiry date given a categorycode and starting date. Date argument must be in ISO format.
1288 Return date is also in ISO format.
1293 my ( $categorycode, $dateenrolled ) = @_;
1295 if ($categorycode) {
1296 my $dbh = C4::Context->dbh;
1297 my $sth = $dbh->prepare("SELECT enrolmentperiod,enrolmentperioddate FROM categories WHERE categorycode=?");
1298 $sth->execute($categorycode);
1299 $enrolments = $sth->fetchrow_hashref;
1301 # die "GetExpiryDate: for enrollmentperiod $enrolmentperiod (category '$categorycode') starting $dateenrolled.\n";
1302 my @date = split (/-/,$dateenrolled);
1303 if($enrolments->{enrolmentperiod}){
1304 return sprintf("%04d-%02d-%02d", Add_Delta_YM(@date,0,$enrolments->{enrolmentperiod}));
1306 return $enrolments->{enrolmentperioddate};
1310 =head2 checkuserpassword (OUEST-PROVENCE)
1312 check for the password and login are not used
1313 return the number of record
1314 0=> NOT USED 1=> USED
1318 sub checkuserpassword {
1319 my ( $borrowernumber, $userid, $password ) = @_;
1320 $password = md5_base64($password);
1321 my $dbh = C4::Context->dbh;
1324 "Select count(*) from borrowers where borrowernumber !=? and userid =? and password=? "
1326 $sth->execute( $borrowernumber, $userid, $password );
1327 my $number_rows = $sth->fetchrow;
1328 return $number_rows;
1332 =head2 GetborCatFromCatType
1334 ($codes_arrayref, $labels_hashref) = &GetborCatFromCatType();
1336 Looks up the different types of borrowers in the database. Returns two
1337 elements: a reference-to-array, which lists the borrower category
1338 codes, and a reference-to-hash, which maps the borrower category codes
1339 to category descriptions.
1344 sub GetborCatFromCatType {
1345 my ( $category_type, $action ) = @_;
1346 # FIXME - This API seems both limited and dangerous.
1347 my $dbh = C4::Context->dbh;
1348 my $request = qq| SELECT categorycode,description
1351 ORDER BY categorycode|;
1352 my $sth = $dbh->prepare($request);
1354 $sth->execute($category_type);
1363 while ( my $data = $sth->fetchrow_hashref ) {
1364 push @codes, $data->{'categorycode'};
1365 $labels{ $data->{'categorycode'} } = $data->{'description'};
1367 return ( \@codes, \%labels );
1370 =head2 GetBorrowercategory
1372 $hashref = &GetBorrowercategory($categorycode);
1374 Given the borrower's category code, the function returns the corresponding
1375 data hashref for a comprehensive information display.
1377 $arrayref_hashref = &GetBorrowercategory;
1379 If no category code provided, the function returns all the categories.
1383 sub GetBorrowercategory {
1385 my $dbh = C4::Context->dbh;
1389 "SELECT description,dateofbirthrequired,upperagelimit,category_type
1391 WHERE categorycode = ?"
1393 $sth->execute($catcode);
1395 $sth->fetchrow_hashref;
1399 } # sub getborrowercategory
1401 =head2 GetBorrowercategoryList
1403 $arrayref_hashref = &GetBorrowercategoryList;
1404 If no category code provided, the function returns all the categories.
1408 sub GetBorrowercategoryList {
1409 my $dbh = C4::Context->dbh;
1414 ORDER BY description"
1418 $sth->fetchall_arrayref({});
1420 } # sub getborrowercategory
1422 =head2 ethnicitycategories
1424 ($codes_arrayref, $labels_hashref) = ðnicitycategories();
1426 Looks up the different ethnic types in the database. Returns two
1427 elements: a reference-to-array, which lists the ethnicity codes, and a
1428 reference-to-hash, which maps the ethnicity codes to ethnicity
1435 sub ethnicitycategories {
1436 my $dbh = C4::Context->dbh;
1437 my $sth = $dbh->prepare("Select code,name from ethnicity order by name");
1441 while ( my $data = $sth->fetchrow_hashref ) {
1442 push @codes, $data->{'code'};
1443 $labels{ $data->{'code'} } = $data->{'name'};
1445 return ( \@codes, \%labels );
1450 $ethn_name = &fixEthnicity($ethn_code);
1452 Takes an ethnicity code (e.g., "european" or "pi") and returns the
1453 corresponding descriptive name from the C<ethnicity> table in the
1454 Koha database ("European" or "Pacific Islander").
1461 my $ethnicity = shift;
1462 return unless $ethnicity;
1463 my $dbh = C4::Context->dbh;
1464 my $sth = $dbh->prepare("Select name from ethnicity where code = ?");
1465 $sth->execute($ethnicity);
1466 my $data = $sth->fetchrow_hashref;
1467 return $data->{'name'};
1468 } # sub fixEthnicity
1472 $dateofbirth,$date = &GetAge($date);
1474 this function return the borrowers age with the value of dateofbirth
1480 my ( $date, $date_ref ) = @_;
1482 if ( not defined $date_ref ) {
1483 $date_ref = sprintf( '%04d-%02d-%02d', Today() );
1486 my ( $year1, $month1, $day1 ) = split /-/, $date;
1487 my ( $year2, $month2, $day2 ) = split /-/, $date_ref;
1489 my $age = $year2 - $year1;
1490 if ( $month1 . $day1 > $month2 . $day2 ) {
1497 =head2 get_institutions
1499 $insitutions = get_institutions();
1501 Just returns a list of all the borrowers of type I, borrownumber and name
1506 sub get_institutions {
1507 my $dbh = C4::Context->dbh();
1510 "SELECT borrowernumber,surname FROM borrowers WHERE categorycode=? ORDER BY surname"
1514 while ( my $data = $sth->fetchrow_hashref() ) {
1515 $orgs{ $data->{'borrowernumber'} } = $data;
1519 } # sub get_institutions
1521 =head2 add_member_orgs
1523 add_member_orgs($borrowernumber,$borrowernumbers);
1525 Takes a borrowernumber and a list of other borrowernumbers and inserts them into the borrowers_to_borrowers table
1530 sub add_member_orgs {
1531 my ( $borrowernumber, $otherborrowers ) = @_;
1532 my $dbh = C4::Context->dbh();
1534 "INSERT INTO borrowers_to_borrowers (borrower1,borrower2) VALUES (?,?)";
1535 my $sth = $dbh->prepare($query);
1536 foreach my $otherborrowernumber (@$otherborrowers) {
1537 $sth->execute( $borrowernumber, $otherborrowernumber );
1540 } # sub add_member_orgs
1544 $cityarrayref = GetCities();
1546 Returns an array_ref of the entries in the cities table
1547 If there are entries in the table an empty row is returned
1548 This is currently only used to populate a popup in memberentry
1554 my $dbh = C4::Context->dbh;
1555 my $city_arr = $dbh->selectall_arrayref(
1556 q|SELECT cityid,city_zipcode,city_name FROM cities ORDER BY city_name|,
1558 if ( @{$city_arr} ) {
1559 unshift @{$city_arr}, {
1560 city_zipcode => q{},
1569 =head2 GetSortDetails (OUEST-PROVENCE)
1571 ($lib) = &GetSortDetails($category,$sortvalue);
1573 Returns the authorized value details
1574 C<&$lib>return value of authorized value details
1575 C<&$sortvalue>this is the value of authorized value
1576 C<&$category>this is the value of authorized value category
1580 sub GetSortDetails {
1581 my ( $category, $sortvalue ) = @_;
1582 my $dbh = C4::Context->dbh;
1583 my $query = qq|SELECT lib
1584 FROM authorised_values
1586 AND authorised_value=? |;
1587 my $sth = $dbh->prepare($query);
1588 $sth->execute( $category, $sortvalue );
1589 my $lib = $sth->fetchrow;
1590 return ($lib) if ($lib);
1591 return ($sortvalue) unless ($lib);
1594 =head2 MoveMemberToDeleted
1596 $result = &MoveMemberToDeleted($borrowernumber);
1598 Copy the record from borrowers to deletedborrowers table.
1602 # FIXME: should do it in one SQL statement w/ subquery
1603 # Otherwise, we should return the @data on success
1605 sub MoveMemberToDeleted {
1606 my ($member) = shift or return;
1607 my $dbh = C4::Context->dbh;
1608 my $query = qq|SELECT *
1610 WHERE borrowernumber=?|;
1611 my $sth = $dbh->prepare($query);
1612 $sth->execute($member);
1613 my @data = $sth->fetchrow_array;
1614 (@data) or return; # if we got a bad borrowernumber, there's nothing to insert
1616 $dbh->prepare( "INSERT INTO deletedborrowers VALUES ("
1617 . ( "?," x ( scalar(@data) - 1 ) )
1619 $sth->execute(@data);
1624 DelMember($borrowernumber);
1626 This function remove directly a borrower whitout writing it on deleteborrower.
1627 + Deletes reserves for the borrower
1632 my $dbh = C4::Context->dbh;
1633 my $borrowernumber = shift;
1634 #warn "in delmember with $borrowernumber";
1635 return unless $borrowernumber; # borrowernumber is mandatory.
1637 my $query = qq|DELETE
1639 WHERE borrowernumber=?|;
1640 my $sth = $dbh->prepare($query);
1641 $sth->execute($borrowernumber);
1645 WHERE borrowernumber = ?
1647 $sth = $dbh->prepare($query);
1648 $sth->execute($borrowernumber);
1649 logaction("MEMBERS", "DELETE", $borrowernumber, "") if C4::Context->preference("BorrowersLog");
1653 =head2 ExtendMemberSubscriptionTo (OUEST-PROVENCE)
1655 $date = ExtendMemberSubscriptionTo($borrowerid, $date);
1657 Extending the subscription to a given date or to the expiry date calculated on ISO date.
1662 sub ExtendMemberSubscriptionTo {
1663 my ( $borrowerid,$date) = @_;
1664 my $dbh = C4::Context->dbh;
1665 my $borrower = GetMember('borrowernumber'=>$borrowerid);
1667 $date=POSIX::strftime("%Y-%m-%d",localtime());
1668 $date = GetExpiryDate( $borrower->{'categorycode'}, $date );
1670 my $sth = $dbh->do(<<EOF);
1672 SET dateexpiry='$date'
1673 WHERE borrowernumber='$borrowerid'
1675 # add enrolmentfee if needed
1676 $sth = $dbh->prepare("SELECT enrolmentfee FROM categories WHERE categorycode=?");
1677 $sth->execute($borrower->{'categorycode'});
1678 my ($enrolmentfee) = $sth->fetchrow;
1679 if ($enrolmentfee && $enrolmentfee > 0) {
1680 # insert fee in patron debts
1681 manualinvoice($borrower->{'borrowernumber'}, '', '', 'A', $enrolmentfee);
1683 return $date if ($sth);
1687 =head2 GetRoadTypes (OUEST-PROVENCE)
1689 ($idroadtypearrayref, $roadttype_hashref) = &GetRoadTypes();
1691 Looks up the different road type . Returns two
1692 elements: a reference-to-array, which lists the id_roadtype
1693 codes, and a reference-to-hash, which maps the road type of the road .
1698 my $dbh = C4::Context->dbh;
1700 SELECT roadtypeid,road_type
1702 ORDER BY road_type|;
1703 my $sth = $dbh->prepare($query);
1708 # insert empty value to create a empty choice in cgi popup
1710 while ( my $data = $sth->fetchrow_hashref ) {
1712 push @id, $data->{'roadtypeid'};
1713 $roadtype{ $data->{'roadtypeid'} } = $data->{'road_type'};
1716 #test to know if the table contain some records if no the function return nothing
1723 return ( \@id, \%roadtype );
1729 =head2 GetTitles (OUEST-PROVENCE)
1731 ($borrowertitle)= &GetTitles();
1733 Looks up the different title . Returns array with all borrowers title
1738 my @borrowerTitle = split (/,|\|/,C4::Context->preference('BorrowersTitles'));
1739 unshift( @borrowerTitle, "" );
1740 my $count=@borrowerTitle;
1745 return ( \@borrowerTitle);
1749 =head2 GetPatronImage
1751 my ($imagedata, $dberror) = GetPatronImage($cardnumber);
1753 Returns the mimetype and binary image data of the image for the patron with the supplied cardnumber.
1757 sub GetPatronImage {
1758 my ($cardnumber) = @_;
1759 warn "Cardnumber passed to GetPatronImage is $cardnumber" if $debug;
1760 my $dbh = C4::Context->dbh;
1761 my $query = 'SELECT mimetype, imagefile FROM patronimage WHERE cardnumber = ?';
1762 my $sth = $dbh->prepare($query);
1763 $sth->execute($cardnumber);
1764 my $imagedata = $sth->fetchrow_hashref;
1765 warn "Database error!" if $sth->errstr;
1766 return $imagedata, $sth->errstr;
1769 =head2 PutPatronImage
1771 PutPatronImage($cardnumber, $mimetype, $imgfile);
1773 Stores patron binary image data and mimetype in database.
1774 NOTE: This function is good for updating images as well as inserting new images in the database.
1778 sub PutPatronImage {
1779 my ($cardnumber, $mimetype, $imgfile) = @_;
1780 warn "Parameters passed in: Cardnumber=$cardnumber, Mimetype=$mimetype, " . ($imgfile ? "Imagefile" : "No Imagefile") if $debug;
1781 my $dbh = C4::Context->dbh;
1782 my $query = "INSERT INTO patronimage (cardnumber, mimetype, imagefile) VALUES (?,?,?) ON DUPLICATE KEY UPDATE imagefile = ?;";
1783 my $sth = $dbh->prepare($query);
1784 $sth->execute($cardnumber,$mimetype,$imgfile,$imgfile);
1785 warn "Error returned inserting $cardnumber.$mimetype." if $sth->errstr;
1786 return $sth->errstr;
1789 =head2 RmPatronImage
1791 my ($dberror) = RmPatronImage($cardnumber);
1793 Removes the image for the patron with the supplied cardnumber.
1798 my ($cardnumber) = @_;
1799 warn "Cardnumber passed to GetPatronImage is $cardnumber" if $debug;
1800 my $dbh = C4::Context->dbh;
1801 my $query = "DELETE FROM patronimage WHERE cardnumber = ?;";
1802 my $sth = $dbh->prepare($query);
1803 $sth->execute($cardnumber);
1804 my $dberror = $sth->errstr;
1805 warn "Database error!" if $sth->errstr;
1809 =head2 GetRoadTypeDetails (OUEST-PROVENCE)
1811 ($roadtype) = &GetRoadTypeDetails($roadtypeid);
1813 Returns the description of roadtype
1814 C<&$roadtype>return description of road type
1815 C<&$roadtypeid>this is the value of roadtype s
1819 sub GetRoadTypeDetails {
1820 my ($roadtypeid) = @_;
1821 my $dbh = C4::Context->dbh;
1825 WHERE roadtypeid=?|;
1826 my $sth = $dbh->prepare($query);
1827 $sth->execute($roadtypeid);
1828 my $roadtype = $sth->fetchrow;
1832 =head2 GetBorrowersWhoHaveNotBorrowedSince
1834 &GetBorrowersWhoHaveNotBorrowedSince($date)
1836 this function get all borrowers who haven't borrowed since the date given on input arg.
1840 sub GetBorrowersWhoHaveNotBorrowedSince {
1841 my $filterdate = shift||POSIX::strftime("%Y-%m-%d",localtime());
1842 my $filterexpiry = shift;
1843 my $filterbranch = shift ||
1844 ((C4::Context->preference('IndependantBranches')
1845 && C4::Context->userenv
1846 && C4::Context->userenv->{flags} % 2 !=1
1847 && C4::Context->userenv->{branch})
1848 ? C4::Context->userenv->{branch}
1850 my $dbh = C4::Context->dbh;
1852 SELECT borrowers.borrowernumber,
1853 max(old_issues.timestamp) as latestissue,
1854 max(issues.timestamp) as currentissue
1856 JOIN categories USING (categorycode)
1857 LEFT JOIN old_issues USING (borrowernumber)
1858 LEFT JOIN issues USING (borrowernumber)
1859 WHERE category_type <> 'S'
1860 AND borrowernumber NOT IN (SELECT guarantorid FROM borrowers WHERE guarantorid IS NOT NULL AND guarantorid <> 0)
1863 if ($filterbranch && $filterbranch ne ""){
1864 $query.=" AND borrowers.branchcode= ?";
1865 push @query_params,$filterbranch;
1868 $query .= " AND dateexpiry < ? ";
1869 push @query_params,$filterdate;
1871 $query.=" GROUP BY borrowers.borrowernumber";
1873 $query.=" HAVING (latestissue < ? OR latestissue IS NULL)
1874 AND currentissue IS NULL";
1875 push @query_params,$filterdate;
1877 warn $query if $debug;
1878 my $sth = $dbh->prepare($query);
1879 if (scalar(@query_params)>0){
1880 $sth->execute(@query_params);
1887 while ( my $data = $sth->fetchrow_hashref ) {
1888 push @results, $data;
1893 =head2 GetBorrowersWhoHaveNeverBorrowed
1895 $results = &GetBorrowersWhoHaveNeverBorrowed
1897 This function get all borrowers who have never borrowed.
1899 I<$result> is a ref to an array which all elements are a hasref.
1903 sub GetBorrowersWhoHaveNeverBorrowed {
1904 my $filterbranch = shift ||
1905 ((C4::Context->preference('IndependantBranches')
1906 && C4::Context->userenv
1907 && C4::Context->userenv->{flags} % 2 !=1
1908 && C4::Context->userenv->{branch})
1909 ? C4::Context->userenv->{branch}
1911 my $dbh = C4::Context->dbh;
1913 SELECT borrowers.borrowernumber,max(timestamp) as latestissue
1915 LEFT JOIN issues ON borrowers.borrowernumber = issues.borrowernumber
1916 WHERE issues.borrowernumber IS NULL
1919 if ($filterbranch && $filterbranch ne ""){
1920 $query.=" AND borrowers.branchcode= ?";
1921 push @query_params,$filterbranch;
1923 warn $query if $debug;
1925 my $sth = $dbh->prepare($query);
1926 if (scalar(@query_params)>0){
1927 $sth->execute(@query_params);
1934 while ( my $data = $sth->fetchrow_hashref ) {
1935 push @results, $data;
1940 =head2 GetBorrowersWithIssuesHistoryOlderThan
1942 $results = &GetBorrowersWithIssuesHistoryOlderThan($date)
1944 this function get all borrowers who has an issue history older than I<$date> given on input arg.
1946 I<$result> is a ref to an array which all elements are a hashref.
1947 This hashref is containt the number of time this borrowers has borrowed before I<$date> and the borrowernumber.
1951 sub GetBorrowersWithIssuesHistoryOlderThan {
1952 my $dbh = C4::Context->dbh;
1953 my $date = shift ||POSIX::strftime("%Y-%m-%d",localtime());
1954 my $filterbranch = shift ||
1955 ((C4::Context->preference('IndependantBranches')
1956 && C4::Context->userenv
1957 && C4::Context->userenv->{flags} % 2 !=1
1958 && C4::Context->userenv->{branch})
1959 ? C4::Context->userenv->{branch}
1962 SELECT count(borrowernumber) as n,borrowernumber
1964 WHERE returndate < ?
1965 AND borrowernumber IS NOT NULL
1968 push @query_params, $date;
1970 $query.=" AND branchcode = ?";
1971 push @query_params, $filterbranch;
1973 $query.=" GROUP BY borrowernumber ";
1974 warn $query if $debug;
1975 my $sth = $dbh->prepare($query);
1976 $sth->execute(@query_params);
1979 while ( my $data = $sth->fetchrow_hashref ) {
1980 push @results, $data;
1985 =head2 GetBorrowersNamesAndLatestIssue
1987 $results = &GetBorrowersNamesAndLatestIssueList(@borrowernumbers)
1989 this function get borrowers Names and surnames and Issue information.
1991 I<@borrowernumbers> is an array which all elements are borrowernumbers.
1992 This hashref is containt the number of time this borrowers has borrowed before I<$date> and the borrowernumber.
1996 sub GetBorrowersNamesAndLatestIssue {
1997 my $dbh = C4::Context->dbh;
1998 my @borrowernumbers=@_;
2000 SELECT surname,lastname, phone, email,max(timestamp)
2002 LEFT JOIN issues ON borrowers.borrowernumber=issues.borrowernumber
2003 GROUP BY borrowernumber
2005 my $sth = $dbh->prepare($query);
2007 my $results = $sth->fetchall_arrayref({});
2013 my $success = DebarMember( $borrowernumber );
2015 marks a Member as debarred, and therefore unable to checkout any more
2019 true on success, false on failure
2024 my $borrowernumber = shift;
2026 return unless defined $borrowernumber;
2027 return unless $borrowernumber =~ /^\d+$/;
2029 return ModMember( borrowernumber => $borrowernumber,
2038 my $success = ModPrivacy( $borrowernumber, $privacy );
2040 Update the privacy of a patron.
2043 true on success, false on failure
2050 my $borrowernumber = shift;
2051 my $privacy = shift;
2052 return unless defined $borrowernumber;
2053 return unless $borrowernumber =~ /^\d+$/;
2055 return ModMember( borrowernumber => $borrowernumber,
2056 privacy => $privacy );
2061 AddMessage( $borrowernumber, $message_type, $message, $branchcode );
2063 Adds a message to the messages table for the given borrower.
2072 my ( $borrowernumber, $message_type, $message, $branchcode ) = @_;
2074 my $dbh = C4::Context->dbh;
2076 if ( ! ( $borrowernumber && $message_type && $message && $branchcode ) ) {
2080 my $query = "INSERT INTO messages ( borrowernumber, branchcode, message_type, message ) VALUES ( ?, ?, ?, ? )";
2081 my $sth = $dbh->prepare($query);
2082 $sth->execute( $borrowernumber, $branchcode, $message_type, $message );
2089 GetMessages( $borrowernumber, $type );
2091 $type is message type, B for borrower, or L for Librarian.
2092 Empty type returns all messages of any type.
2094 Returns all messages for the given borrowernumber
2099 my ( $borrowernumber, $type, $branchcode ) = @_;
2105 my $dbh = C4::Context->dbh;
2108 branches.branchname,
2111 messages.branchcode LIKE '$branchcode' AS can_delete
2112 FROM messages, branches
2113 WHERE borrowernumber = ?
2114 AND message_type LIKE ?
2115 AND messages.branchcode = branches.branchcode
2116 ORDER BY message_date DESC";
2117 my $sth = $dbh->prepare($query);
2118 $sth->execute( $borrowernumber, $type ) ;
2121 while ( my $data = $sth->fetchrow_hashref ) {
2122 my $d = C4::Dates->new( $data->{message_date}, 'iso' );
2123 $data->{message_date_formatted} = $d->output;
2124 push @results, $data;
2132 GetMessagesCount( $borrowernumber, $type );
2134 $type is message type, B for borrower, or L for Librarian.
2135 Empty type returns all messages of any type.
2137 Returns the number of messages for the given borrowernumber
2141 sub GetMessagesCount {
2142 my ( $borrowernumber, $type, $branchcode ) = @_;
2148 my $dbh = C4::Context->dbh;
2150 my $query = "SELECT COUNT(*) as MsgCount FROM messages WHERE borrowernumber = ? AND message_type LIKE ?";
2151 my $sth = $dbh->prepare($query);
2152 $sth->execute( $borrowernumber, $type ) ;
2155 my $data = $sth->fetchrow_hashref;
2156 my $count = $data->{'MsgCount'};
2163 =head2 DeleteMessage
2165 DeleteMessage( $message_id );
2170 my ( $message_id ) = @_;
2172 my $dbh = C4::Context->dbh;
2174 my $query = "DELETE FROM messages WHERE message_id = ?";
2175 my $sth = $dbh->prepare($query);
2176 $sth->execute( $message_id );
2180 END { } # module clean-up code here (global destructor)