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;
53 &GetMemberIssuesAndFines
61 &GetFirstValidEmailAddress
74 &GetHideLostItemsPreference
77 &GetMemberAccountRecords
78 &GetBorNotifyAcctRecord
82 &GetBorrowercategoryList
84 &GetBorrowersWhoHaveNotBorrowedSince
85 &GetBorrowersWhoHaveNeverBorrowed
86 &GetBorrowersWithIssuesHistoryOlderThan
113 &ExtendMemberSubscriptionTo
131 C4::Members - Perl Module containing convenience functions for member handling
139 This module contains routines for adding, modifying and deleting members/patrons/borrowers
145 ($count, $borrowers) = &SearchMember($searchstring, $type,
146 $category_type, $filter, $showallbranches);
148 Looks up patrons (borrowers) by name.
150 BUGFIX 499: C<$type> is now used to determine type of search.
151 if $type is "simple", search is performed on the first letter of the
154 $category_type is used to get a specified type of user.
155 (mainly adults when creating a child.)
157 C<$searchstring> is a space-separated list of search terms. Each term
158 must match the beginning a borrower's surname, first name, or other
161 C<$filter> is assumed to be a list of elements to filter results on
163 C<$showallbranches> is used in IndependantBranches Context to display all branches results.
165 C<&SearchMember> returns a two-element list. C<$borrowers> is a
166 reference-to-array; each element is a reference-to-hash, whose keys
167 are the fields of the C<borrowers> table in the Koha database.
168 C<$count> is the number of elements in C<$borrowers>.
173 #used by member enquiries from the intranet
175 my ($searchstring, $orderby, $type,$category_type,$filter,$showallbranches ) = @_;
176 my $dbh = C4::Context->dbh;
182 # this is used by circulation everytime a new borrowers cardnumber is scanned
183 # so we can check an exact match first, if that works return, otherwise do the rest
184 $query = "SELECT * FROM borrowers
185 LEFT JOIN categories ON borrowers.categorycode=categories.categorycode
187 my $sth = $dbh->prepare("$query WHERE cardnumber = ?");
188 $sth->execute($searchstring);
189 my $data = $sth->fetchall_arrayref({});
191 return ( scalar(@$data), $data );
194 if ( $type eq "simple" ) # simple search for one letter only
196 $query .= ($category_type ? " AND category_type = ".$dbh->quote($category_type) : "");
197 $query .= " WHERE (surname LIKE ? OR cardnumber like ?) ";
198 if (C4::Context->preference("IndependantBranches") && !$showallbranches){
199 if (C4::Context->userenv && C4::Context->userenv->{flags} % 2 !=1 && C4::Context->userenv->{'branch'}){
200 $query.=" AND borrowers.branchcode =".$dbh->quote(C4::Context->userenv->{'branch'}) unless (C4::Context->userenv->{'branch'} eq "insecure");
203 $query.=" ORDER BY $orderby";
204 @bind = ("$searchstring%","$searchstring");
206 else # advanced search looking in surname, firstname and othernames
208 @data = split( ' ', $searchstring );
211 if (C4::Context->preference("IndependantBranches") && !$showallbranches){
212 if (C4::Context->userenv && C4::Context->userenv->{flags} % 2 !=1 && C4::Context->userenv->{'branch'}){
213 $query.=" borrowers.branchcode =".$dbh->quote(C4::Context->userenv->{'branch'})." AND " unless (C4::Context->userenv->{'branch'} eq "insecure");
216 $query.="((surname LIKE ? OR (surname LIKE ? AND surname REGEXP ?)
217 OR firstname LIKE ? OR (firstname LIKE ? AND firstname REGEXP ?)
218 OR othernames LIKE ? OR (othernames LIKE ? AND othernames REGEXP ?))
220 ($category_type?" AND category_type = ".$dbh->quote($category_type):"");
221 my $regex = '[[:punct:][:space:]]'.$data[0];
223 "$data[0]%", "%$data[0]%", $regex,
224 "$data[0]%", "%$data[0]%", $regex,
225 "$data[0]%", "%$data[0]%", $regex
227 for ( my $i = 1 ; $i < $count ; $i++ ) {
228 $query = $query . " AND (" . " surname LIKE ? OR (surname LIKE ? AND surname REGEXP ?)
229 OR firstname LIKE ? OR (firstname LIKE ? AND firstname REGEXP ?)
230 OR othernames LIKE ? OR (othernames LIKE ? AND othernames REGEXP ?))";
231 $regex = '[[:punct:][:space:]]'.$data[$i];
233 "$data[$i]%", "%$data[$i]%", $regex,
234 "$data[$i]%", "%$data[$i]%", $regex,
235 "$data[$i]%", "%$data[$i]%", $regex
241 $query = $query . ") OR cardnumber LIKE ? ";
242 push( @bind, $searchstring );
243 $query .= "order by $orderby";
248 $sth = $dbh->prepare($query);
250 $debug and print STDERR "Q $orderby : $query\n";
251 $sth->execute(@bind);
253 $data = $sth->fetchall_arrayref({});
255 return ( scalar(@$data), $data );
260 $borrowers_result_array_ref = &Search($filter,$orderby, $limit,
261 $columns_out, $search_on_fields,$searchtype);
263 Looks up patrons (borrowers) on filter.
265 BUGFIX 499: C<$type> is now used to determine type of search.
266 if $type is "simple", search is performed on the first letter of the
269 $category_type is used to get a specified type of user.
270 (mainly adults when creating a child.)
273 - a space-separated list of search terms. Implicit AND is done on them
274 - a hash ref containing fieldnames associated with queried value
275 - an array ref combining the two previous elements Implicit OR is done between each array element
278 C<$orderby> is an arrayref of hashref. Contains the name of the field and 0 or 1 depending if order is ascending or descending
280 C<$limit> is there to allow limiting number of results returned
282 C<&columns_out> is an array ref to the fieldnames you want to see in the result list
284 C<&search_on_fields> is an array ref to the fieldnames you want to limit search on when you are using string search
286 C<&searchtype> is a string telling the type of search you want todo : start_with, exact or contains are allowed
291 my ( $filter, $orderby, $limit, $columns_out, $search_on_fields, $searchtype ) = @_;
293 my %filtersmatching_record;
295 if ( ref($filter) eq "ARRAY" ) {
296 push @filters, @$filter;
298 push @filters, $filter;
300 if ( C4::Context->preference('ExtendedPatronAttributes') ) {
301 my $matching_records = C4::Members::Attributes::SearchIdMatchingAttribute($filter);
302 if(scalar(@$matching_records)>0) {
303 foreach my $matching_record (@$matching_records) {
304 $filtersmatching_record{$$matching_record[0]}=1;
306 foreach my $k (keys(%filtersmatching_record)) {
307 push @filters, {"borrowernumber"=>$k};
311 $searchtype ||= "start_with";
312 push @finalfilter, \@filters;
313 my $data = SearchInTable( "borrowers", \@finalfilter, $orderby, $limit, $columns_out, $search_on_fields, $searchtype );
317 =head2 GetMemberDetails
319 ($borrower) = &GetMemberDetails($borrowernumber, $cardnumber);
321 Looks up a patron and returns information about him or her. If
322 C<$borrowernumber> is true (nonzero), C<&GetMemberDetails> looks
323 up the borrower by number; otherwise, it looks up the borrower by card
326 C<$borrower> is a reference-to-hash whose keys are the fields of the
327 borrowers table in the Koha database. In addition,
328 C<$borrower-E<gt>{flags}> is a hash giving more detailed information
329 about the patron. Its keys act as flags :
331 if $borrower->{flags}->{LOST} {
332 # Patron's card was reported lost
335 If the state of a flag means that the patron should not be
336 allowed to borrow any more books, then it will have a C<noissues> key
339 See patronflags for more details.
341 C<$borrower-E<gt>{authflags}> is a hash giving more detailed information
342 about the top-level permissions flags set for the borrower. For example,
343 if a user has the "editcatalogue" permission,
344 C<$borrower-E<gt>{authflags}-E<gt>{editcatalogue}> will exist and have
349 sub GetMemberDetails {
350 my ( $borrowernumber, $cardnumber ) = @_;
351 my $dbh = C4::Context->dbh;
354 if ($borrowernumber) {
355 $sth = $dbh->prepare("select borrowers.*,category_type,categories.description from borrowers left join categories on borrowers.categorycode=categories.categorycode where borrowernumber=?");
356 $sth->execute($borrowernumber);
358 elsif ($cardnumber) {
359 $sth = $dbh->prepare("select borrowers.*,category_type,categories.description from borrowers left join categories on borrowers.categorycode=categories.categorycode where cardnumber=?");
360 $sth->execute($cardnumber);
365 my $borrower = $sth->fetchrow_hashref;
366 my ($amount) = GetMemberAccountRecords( $borrowernumber);
367 $borrower->{'amountoutstanding'} = $amount;
368 # FIXME - patronflags calls GetMemberAccountRecords... just have patronflags return $amount
369 my $flags = patronflags( $borrower);
372 $sth = $dbh->prepare("select bit,flag from userflags");
374 while ( my ( $bit, $flag ) = $sth->fetchrow ) {
375 if ( $borrower->{'flags'} && $borrower->{'flags'} & 2**$bit ) {
376 $accessflagshash->{$flag} = 1;
379 $borrower->{'flags'} = $flags;
380 $borrower->{'authflags'} = $accessflagshash;
382 # find out how long the membership lasts
385 "select enrolmentperiod from categories where categorycode = ?");
386 $sth->execute( $borrower->{'categorycode'} );
387 my $enrolment = $sth->fetchrow;
388 $borrower->{'enrolmentperiod'} = $enrolment;
389 return ($borrower); #, $flags, $accessflagshash);
394 $flags = &patronflags($patron);
396 This function is not exported.
398 The following will be set where applicable:
399 $flags->{CHARGES}->{amount} Amount of debt
400 $flags->{CHARGES}->{noissues} Set if debt amount >$5.00 (or syspref noissuescharge)
401 $flags->{CHARGES}->{message} Message -- deprecated
403 $flags->{CREDITS}->{amount} Amount of credit
404 $flags->{CREDITS}->{message} Message -- deprecated
406 $flags->{ GNA } Patron has no valid address
407 $flags->{ GNA }->{noissues} Set for each GNA
408 $flags->{ GNA }->{message} "Borrower has no valid address" -- deprecated
410 $flags->{ LOST } Patron's card reported lost
411 $flags->{ LOST }->{noissues} Set for each LOST
412 $flags->{ LOST }->{message} Message -- deprecated
414 $flags->{DBARRED} Set if patron debarred, no access
415 $flags->{DBARRED}->{noissues} Set for each DBARRED
416 $flags->{DBARRED}->{message} Message -- deprecated
419 $flags->{ NOTES }->{message} The note itself. NOT deprecated
421 $flags->{ ODUES } Set if patron has overdue books.
422 $flags->{ ODUES }->{message} "Yes" -- deprecated
423 $flags->{ ODUES }->{itemlist} ref-to-array: list of overdue books
424 $flags->{ ODUES }->{itemlisttext} Text list of overdue items -- deprecated
426 $flags->{WAITING} Set if any of patron's reserves are available
427 $flags->{WAITING}->{message} Message -- deprecated
428 $flags->{WAITING}->{itemlist} ref-to-array: list of available items
432 =item C<$flags-E<gt>{ODUES}-E<gt>{itemlist}> is a reference-to-array listing the
433 overdue items. Its elements are references-to-hash, each describing an
434 overdue item. The keys are selected fields from the issues, biblio,
435 biblioitems, and items tables of the Koha database.
437 =item C<$flags-E<gt>{ODUES}-E<gt>{itemlisttext}> is a string giving a text listing of
438 the overdue items, one per line. Deprecated.
440 =item C<$flags-E<gt>{WAITING}-E<gt>{itemlist}> is a reference-to-array listing the
441 available items. Each element is a reference-to-hash whose keys are
442 fields from the reserves table of the Koha database.
446 All the "message" fields that include language generated in this function are deprecated,
447 because such strings belong properly in the display layer.
449 The "message" field that comes from the DB is OK.
453 # TODO: use {anonymous => hashes} instead of a dozen %flaginfo
454 # FIXME rename this function.
457 my ( $patroninformation) = @_;
458 my $dbh=C4::Context->dbh;
459 my ($amount) = GetMemberAccountRecords( $patroninformation->{'borrowernumber'});
462 my $noissuescharge = C4::Context->preference("noissuescharge") || 5;
463 $flaginfo{'message'} = sprintf "Patron owes \$%.02f", $amount;
464 $flaginfo{'amount'} = sprintf "%.02f", $amount;
465 if ( $amount > $noissuescharge && !C4::Context->preference("AllowFineOverride") ) {
466 $flaginfo{'noissues'} = 1;
468 $flags{'CHARGES'} = \%flaginfo;
470 elsif ( $amount < 0 ) {
472 $flaginfo{'message'} = sprintf "Patron has credit of \$%.02f", -$amount;
473 $flaginfo{'amount'} = sprintf "%.02f", $amount;
474 $flags{'CREDITS'} = \%flaginfo;
476 if ( $patroninformation->{'gonenoaddress'}
477 && $patroninformation->{'gonenoaddress'} == 1 )
480 $flaginfo{'message'} = 'Borrower has no valid address.';
481 $flaginfo{'noissues'} = 1;
482 $flags{'GNA'} = \%flaginfo;
484 if ( $patroninformation->{'lost'} && $patroninformation->{'lost'} == 1 ) {
486 $flaginfo{'message'} = 'Borrower\'s card reported lost.';
487 $flaginfo{'noissues'} = 1;
488 $flags{'LOST'} = \%flaginfo;
490 if ( $patroninformation->{'debarred'}
491 && $patroninformation->{'debarred'} == 1 )
494 $flaginfo{'message'} = 'Borrower is Debarred.';
495 $flaginfo{'noissues'} = 1;
496 $flags{'DBARRED'} = \%flaginfo;
498 if ( $patroninformation->{'borrowernotes'}
499 && $patroninformation->{'borrowernotes'} )
502 $flaginfo{'message'} = $patroninformation->{'borrowernotes'};
503 $flags{'NOTES'} = \%flaginfo;
505 my ( $odues, $itemsoverdue ) = checkoverdues($patroninformation->{'borrowernumber'});
506 if ( $odues && $odues > 0 ) {
508 $flaginfo{'message'} = "Yes";
509 $flaginfo{'itemlist'} = $itemsoverdue;
510 foreach ( sort { $a->{'date_due'} cmp $b->{'date_due'} }
513 $flaginfo{'itemlisttext'} .=
514 "$_->{'date_due'} $_->{'barcode'} $_->{'title'} \n"; # newline is display layer
516 $flags{'ODUES'} = \%flaginfo;
518 my @itemswaiting = C4::Reserves::GetReservesFromBorrowernumber( $patroninformation->{'borrowernumber'},'W' );
519 my $nowaiting = scalar @itemswaiting;
520 if ( $nowaiting > 0 ) {
522 $flaginfo{'message'} = "Reserved items available";
523 $flaginfo{'itemlist'} = \@itemswaiting;
524 $flags{'WAITING'} = \%flaginfo;
532 $borrower = &GetMember(%information);
534 Retrieve the first patron record meeting on criteria listed in the
535 C<%information> hash, which should contain one or more
536 pairs of borrowers column names and values, e.g.,
538 $borrower = GetMember(borrowernumber => id);
540 C<&GetBorrower> returns a reference-to-hash whose keys are the fields of
541 the C<borrowers> table in the Koha database.
543 FIXME: GetMember() is used throughout the code as a lookup
544 on a unique key such as the borrowernumber, but this meaning is not
545 enforced in the routine itself.
551 my ( %information ) = @_;
552 if (exists $information{borrowernumber} && !defined $information{borrowernumber}) {
553 #passing mysql's kohaadmin?? Makes no sense as a query
556 my $dbh = C4::Context->dbh;
558 q{SELECT borrowers.*, categories.category_type, categories.description
560 LEFT JOIN categories on borrowers.categorycode=categories.categorycode WHERE };
563 for (keys %information ) {
571 if (defined $information{$_}) {
573 push @values, $information{$_};
576 $select .= "$_ IS NULL";
579 $debug && warn $select, " ",values %information;
580 my $sth = $dbh->prepare("$select");
581 $sth->execute(map{$information{$_}} keys %information);
582 my $data = $sth->fetchall_arrayref({});
583 #FIXME interface to this routine now allows generation of a result set
584 #so whole array should be returned but bowhere in the current code expects this
592 =head2 GetMemberRelatives
594 @borrowernumbers = GetMemberRelatives($borrowernumber);
596 C<GetMemberRelatives> returns a borrowersnumber's list of guarantor/guarantees of the member given in parameter
599 sub GetMemberRelatives {
600 my $borrowernumber = shift;
601 my $dbh = C4::Context->dbh;
605 my $query = "SELECT guarantorid FROM borrowers WHERE borrowernumber=?";
606 my $sth = $dbh->prepare($query);
607 $sth->execute($borrowernumber);
608 my $data = $sth->fetchrow_arrayref();
609 push @glist, $data->[0] if $data->[0];
610 my $guarantor = $data->[0] if $data->[0];
613 $query = "SELECT borrowernumber FROM borrowers WHERE guarantorid=?";
614 $sth = $dbh->prepare($query);
615 $sth->execute($borrowernumber);
616 while ($data = $sth->fetchrow_arrayref()) {
617 push @glist, $data->[0];
620 # Getting sibling guarantees
622 $query = "SELECT borrowernumber FROM borrowers WHERE guarantorid=?";
623 $sth = $dbh->prepare($query);
624 $sth->execute($guarantor);
625 while ($data = $sth->fetchrow_arrayref()) {
626 push @glist, $data->[0] if ($data->[0] != $borrowernumber);
633 =head2 IsMemberBlocked
635 my ($block_status, $count) = IsMemberBlocked( $borrowernumber );
637 Returns whether a patron has overdue items that may result
638 in a block or whether the patron has active fine days
639 that would block circulation privileges.
641 C<$block_status> can have the following values:
643 1 if the patron has outstanding fine days, in which case C<$count> is the number of them
645 -1 if the patron has overdue items, in which case C<$count> is the number of them
647 0 if the patron has no overdue items or outstanding fine days, in which case C<$count> is 0
649 Outstanding fine days are checked before current overdue items
652 FIXME: this needs to be split into two functions; a potential block
653 based on the number of current overdue items could be orthogonal
654 to a block based on whether the patron has any fine days accrued.
658 sub IsMemberBlocked {
659 my $borrowernumber = shift;
660 my $dbh = C4::Context->dbh;
662 # does patron have current fine days?
665 ADDDATE(returndate, finedays * DATEDIFF(returndate,date_due) ) AS blockingdate,
666 DATEDIFF(ADDDATE(returndate, finedays * DATEDIFF(returndate,date_due)),NOW()) AS blockedcount
669 if(C4::Context->preference("item-level_itypes")){
671 qq{ LEFT JOIN items ON (items.itemnumber=old_issues.itemnumber)
672 LEFT JOIN issuingrules ON (issuingrules.itemtype=items.itype)}
675 qq{ LEFT JOIN items ON (items.itemnumber=old_issues.itemnumber)
676 LEFT JOIN biblioitems ON (biblioitems.biblioitemnumber=items.biblioitemnumber)
677 LEFT JOIN issuingrules ON (issuingrules.itemtype=biblioitems.itemtype) };
680 qq{ WHERE finedays IS NOT NULL
681 AND date_due < returndate
682 AND borrowernumber = ?
683 ORDER BY blockingdate DESC, blockedcount DESC
685 my $sth=$dbh->prepare($strsth);
686 $sth->execute($borrowernumber);
687 my $row = $sth->fetchrow_hashref;
688 my $blockeddate = $row->{'blockeddate'};
689 my $blockedcount = $row->{'blockedcount'};
691 return (1, $blockedcount) if $blockedcount > 0;
693 # if he have late issues
694 $sth = $dbh->prepare(
695 "SELECT COUNT(*) as latedocs
697 WHERE borrowernumber = ?
698 AND date_due < curdate()"
700 $sth->execute($borrowernumber);
701 my $latedocs = $sth->fetchrow_hashref->{'latedocs'};
703 return (-1, $latedocs) if $latedocs > 0;
708 =head2 GetMemberIssuesAndFines
710 ($overdue_count, $issue_count, $total_fines) = &GetMemberIssuesAndFines($borrowernumber);
712 Returns aggregate data about items borrowed by the patron with the
713 given borrowernumber.
715 C<&GetMemberIssuesAndFines> returns a three-element array. C<$overdue_count> is the
716 number of overdue items the patron currently has borrowed. C<$issue_count> is the
717 number of books the patron currently has borrowed. C<$total_fines> is
718 the total fine currently due by the borrower.
723 sub GetMemberIssuesAndFines {
724 my ( $borrowernumber ) = @_;
725 my $dbh = C4::Context->dbh;
726 my $query = "SELECT COUNT(*) FROM issues WHERE borrowernumber = ?";
728 $debug and warn $query."\n";
729 my $sth = $dbh->prepare($query);
730 $sth->execute($borrowernumber);
731 my $issue_count = $sth->fetchrow_arrayref->[0];
733 $sth = $dbh->prepare(
734 "SELECT COUNT(*) FROM issues
735 WHERE borrowernumber = ?
736 AND date_due < curdate()"
738 $sth->execute($borrowernumber);
739 my $overdue_count = $sth->fetchrow_arrayref->[0];
741 $sth = $dbh->prepare("SELECT SUM(amountoutstanding) FROM accountlines WHERE borrowernumber = ?");
742 $sth->execute($borrowernumber);
743 my $total_fines = $sth->fetchrow_arrayref->[0];
745 return ($overdue_count, $issue_count, $total_fines);
749 return @{C4::Context->dbh->selectcol_arrayref("SHOW columns from borrowers")};
754 my $success = ModMember(borrowernumber => $borrowernumber,
755 [ field => value ]... );
757 Modify borrower's data. All date fields should ALREADY be in ISO format.
760 true on success, or false on failure
766 # test to know if you must update or not the borrower password
767 if (exists $data{password}) {
768 if ($data{password} eq '****' or $data{password} eq '') {
769 delete $data{password};
771 $data{password} = md5_base64($data{password});
774 my $execute_success=UpdateInTable("borrowers",\%data);
775 # ok if its an adult (type) it may have borrowers that depend on it as a guarantor
776 # so when we update information for an adult we should check for guarantees and update the relevant part
777 # of their records, ie addresses and phone numbers
778 my $borrowercategory= GetBorrowercategory( $data{'category_type'} );
779 if ( exists $borrowercategory->{'category_type'} && $borrowercategory->{'category_type'} eq ('A' || 'S') ) {
780 # is adult check guarantees;
781 UpdateGuarantees(%data);
783 logaction("MEMBERS", "MODIFY", $data{'borrowernumber'}, "UPDATE (executed w/ arg: $data{'borrowernumber'})")
784 if C4::Context->preference("BorrowersLog");
786 return $execute_success;
792 $borrowernumber = &AddMember(%borrower);
794 insert new borrower into table
795 Returns the borrowernumber
802 my $dbh = C4::Context->dbh;
803 $data{'password'} = '!' if (not $data{'password'} and $data{'userid'});
804 $data{'password'} = md5_base64( $data{'password'} ) if $data{'password'};
805 $data{'borrowernumber'}=InsertInTable("borrowers",\%data);
806 # mysql_insertid is probably bad. not necessarily accurate and mysql-specific at best.
807 logaction("MEMBERS", "CREATE", $data{'borrowernumber'}, "") if C4::Context->preference("BorrowersLog");
809 # check for enrollment fee & add it if needed
810 my $sth = $dbh->prepare("SELECT enrolmentfee FROM categories WHERE categorycode=?");
811 $sth->execute($data{'categorycode'});
812 my ($enrolmentfee) = $sth->fetchrow;
813 if ($enrolmentfee && $enrolmentfee > 0) {
814 # insert fee in patron debts
815 manualinvoice($data{'borrowernumber'}, '', '', 'A', $enrolmentfee);
817 return $data{'borrowernumber'};
822 my ($uid,$member) = @_;
823 my $dbh = C4::Context->dbh;
824 # Make sure the userid chosen is unique and not theirs if non-empty. If it is not,
825 # Then we need to tell the user and have them create a new one.
828 "SELECT * FROM borrowers WHERE userid=? AND borrowernumber != ?");
829 $sth->execute( $uid, $member );
830 if ( ( $uid ne '' ) && ( my $row = $sth->fetchrow_hashref ) ) {
838 sub Generate_Userid {
839 my ($borrowernumber, $firstname, $surname) = @_;
843 $firstname =~ s/[[:digit:][:space:][:blank:][:punct:][:cntrl:]]//g;
844 $surname =~ s/[[:digit:][:space:][:blank:][:punct:][:cntrl:]]//g;
845 $newuid = lc("$firstname.$surname");
846 $newuid .= $offset unless $offset == 0;
849 } while (!Check_Userid($newuid,$borrowernumber));
855 my ( $uid, $member, $digest ) = @_;
856 my $dbh = C4::Context->dbh;
858 #Make sure the userid chosen is unique and not theirs if non-empty. If it is not,
859 #Then we need to tell the user and have them create a new one.
863 "SELECT * FROM borrowers WHERE userid=? AND borrowernumber != ?");
864 $sth->execute( $uid, $member );
865 if ( ( $uid ne '' ) && ( my $row = $sth->fetchrow_hashref ) ) {
869 #Everything is good so we can update the information.
872 "update borrowers set userid=?, password=? where borrowernumber=?");
873 $sth->execute( $uid, $digest, $member );
877 logaction("MEMBERS", "CHANGE PASS", $member, "") if C4::Context->preference("BorrowersLog");
883 =head2 fixup_cardnumber
885 Warning: The caller is responsible for locking the members table in write
886 mode, to avoid database corruption.
890 use vars qw( @weightings );
891 my @weightings = ( 8, 4, 6, 3, 5, 2, 1 );
893 sub fixup_cardnumber ($) {
894 my ($cardnumber) = @_;
895 my $autonumber_members = C4::Context->boolean_preference('autoMemberNum') || 0;
897 # Find out whether member numbers should be generated
898 # automatically. Should be either "1" or something else.
899 # Defaults to "0", which is interpreted as "no".
901 # if ($cardnumber !~ /\S/ && $autonumber_members) {
902 ($autonumber_members) or return $cardnumber;
903 my $checkdigit = C4::Context->preference('checkdigit');
904 my $dbh = C4::Context->dbh;
905 if ( $checkdigit and $checkdigit eq 'katipo' ) {
907 # if checkdigit is selected, calculate katipo-style cardnumber.
908 # otherwise, just use the max()
909 # purpose: generate checksum'd member numbers.
910 # We'll assume we just got the max value of digits 2-8 of member #'s
911 # from the database and our job is to increment that by one,
912 # determine the 1st and 9th digits and return the full string.
913 my $sth = $dbh->prepare(
914 "select max(substring(borrowers.cardnumber,2,7)) as new_num from borrowers"
917 my $data = $sth->fetchrow_hashref;
918 $cardnumber = $data->{new_num};
919 if ( !$cardnumber ) { # If DB has no values,
920 $cardnumber = 1000000; # start at 1000000
926 for ( my $i = 0 ; $i < 8 ; $i += 1 ) {
927 # read weightings, left to right, 1 char at a time
928 my $temp1 = $weightings[$i];
930 # sequence left to right, 1 char at a time
931 my $temp2 = substr( $cardnumber, $i, 1 );
933 # mult each char 1-7 by its corresponding weighting
934 $sum += $temp1 * $temp2;
937 my $rem = ( $sum % 11 );
938 $rem = 'X' if $rem == 10;
940 return "V$cardnumber$rem";
943 # MODIFIED BY JF: mysql4.1 allows casting as an integer, which is probably
944 # better. I'll leave the original in in case it needs to be changed for you
945 # my $sth=$dbh->prepare("select max(borrowers.cardnumber) from borrowers");
946 my $sth = $dbh->prepare(
947 "select max(cast(cardnumber as signed)) from borrowers"
950 my ($result) = $sth->fetchrow;
953 return $cardnumber; # just here as a fallback/reminder
958 ($num_children, $children_arrayref) = &GetGuarantees($parent_borrno);
959 $child0_cardno = $children_arrayref->[0]{"cardnumber"};
960 $child0_borrno = $children_arrayref->[0]{"borrowernumber"};
962 C<&GetGuarantees> takes a borrower number (e.g., that of a patron
963 with children) and looks up the borrowers who are guaranteed by that
964 borrower (i.e., the patron's children).
966 C<&GetGuarantees> returns two values: an integer giving the number of
967 borrowers guaranteed by C<$parent_borrno>, and a reference to an array
968 of references to hash, which gives the actual results.
974 my ($borrowernumber) = @_;
975 my $dbh = C4::Context->dbh;
978 "select cardnumber,borrowernumber, firstname, surname from borrowers where guarantorid=?"
980 $sth->execute($borrowernumber);
983 my $data = $sth->fetchall_arrayref({});
984 return ( scalar(@$data), $data );
987 =head2 UpdateGuarantees
989 &UpdateGuarantees($parent_borrno);
992 C<&UpdateGuarantees> borrower data for an adult and updates all the guarantees
993 with the modified information
998 sub UpdateGuarantees {
1000 my $dbh = C4::Context->dbh;
1001 my ( $count, $guarantees ) = GetGuarantees( $data{'borrowernumber'} );
1002 foreach my $guarantee (@$guarantees){
1003 my $guaquery = qq|UPDATE borrowers
1004 SET address=?,fax=?,B_city=?,mobile=?,city=?,phone=?
1005 WHERE borrowernumber=?
1007 my $sth = $dbh->prepare($guaquery);
1008 $sth->execute($data{'address'},$data{'fax'},$data{'B_city'},$data{'mobile'},$data{'city'},$data{'phone'},$guarantee->{'borrowernumber'});
1011 =head2 GetPendingIssues
1013 my $issues = &GetPendingIssues(@borrowernumber);
1015 Looks up what the patron with the given borrowernumber has borrowed.
1017 C<&GetPendingIssues> returns a
1018 reference-to-array where each element is a reference-to-hash; the
1019 keys are the fields from the C<issues>, C<biblio>, and C<items> tables.
1020 The keys include C<biblioitems> fields except marc and marcxml.
1025 sub GetPendingIssues {
1026 my (@borrowernumbers) = @_;
1028 # Borrowers part of the query
1030 for (my $i = 0; $i < @borrowernumbers; $i++) {
1031 $bquery .= " borrowernumber = ?";
1032 $bquery .= " OR" if ($i < (scalar(@borrowernumbers) - 1));
1035 # must avoid biblioitems.* to prevent large marc and marcxml fields from killing performance
1036 # FIXME: namespace collision: each table has "timestamp" fields. Which one is "timestamp" ?
1037 # FIXME: circ/ciculation.pl tries to sort by timestamp!
1038 # FIXME: C4::Print::printslip tries to sort by timestamp!
1039 # FIXME: namespace collision: other collisions possible.
1040 # FIXME: most of this data isn't really being used by callers.
1047 biblioitems.itemtype,
1050 biblioitems.publicationyear,
1051 biblioitems.publishercode,
1052 biblioitems.volumedate,
1053 biblioitems.volumedesc,
1056 issues.timestamp AS timestamp,
1057 issues.renewals AS renewals,
1058 issues.borrowernumber AS borrowernumber,
1059 items.renewals AS totalrenewals
1061 LEFT JOIN items ON items.itemnumber = issues.itemnumber
1062 LEFT JOIN biblio ON items.biblionumber = biblio.biblionumber
1063 LEFT JOIN biblioitems ON items.biblioitemnumber = biblioitems.biblioitemnumber
1066 ORDER BY issues.issuedate"
1069 my $sth = C4::Context->dbh->prepare($query);
1070 $sth->execute(@borrowernumbers);
1071 my $data = $sth->fetchall_arrayref({});
1072 my $today = C4::Dates->new->output('iso');
1074 $_->{date_due} or next;
1075 ($_->{date_due} lt $today) and $_->{overdue} = 1;
1082 $issues = &GetAllIssues($borrowernumber, $sortkey, $limit);
1084 Looks up what the patron with the given borrowernumber has borrowed,
1085 and sorts the results.
1087 C<$sortkey> is the name of a field on which to sort the results. This
1088 should be the name of a field in the C<issues>, C<biblio>,
1089 C<biblioitems>, or C<items> table in the Koha database.
1091 C<$limit> is the maximum number of results to return.
1093 C<&GetAllIssues> an arrayref, C<$issues>, of hashrefs, the keys of which
1094 are the fields from the C<issues>, C<biblio>, C<biblioitems>, and
1095 C<items> tables of the Koha database.
1101 my ( $borrowernumber, $order, $limit ) = @_;
1103 #FIXME: sanity-check order and limit
1104 my $dbh = C4::Context->dbh;
1106 "SELECT *, issues.timestamp as issuestimestamp, issues.renewals AS renewals,items.renewals AS totalrenewals,items.timestamp AS itemstimestamp
1108 LEFT JOIN items on items.itemnumber=issues.itemnumber
1109 LEFT JOIN biblio ON items.biblionumber=biblio.biblionumber
1110 LEFT JOIN biblioitems ON items.biblioitemnumber=biblioitems.biblioitemnumber
1111 WHERE borrowernumber=?
1113 SELECT *, old_issues.timestamp as issuestimestamp, old_issues.renewals AS renewals,items.renewals AS totalrenewals,items.timestamp AS itemstimestamp
1115 LEFT JOIN items on items.itemnumber=old_issues.itemnumber
1116 LEFT JOIN biblio ON items.biblionumber=biblio.biblionumber
1117 LEFT JOIN biblioitems ON items.biblioitemnumber=biblioitems.biblioitemnumber
1118 WHERE borrowernumber=?
1120 if ( $limit != 0 ) {
1121 $query .= " limit $limit";
1124 my $sth = $dbh->prepare($query);
1125 $sth->execute($borrowernumber, $borrowernumber);
1128 while ( my $data = $sth->fetchrow_hashref ) {
1129 push @result, $data;
1136 =head2 GetMemberAccountRecords
1138 ($total, $acctlines, $count) = &GetMemberAccountRecords($borrowernumber);
1140 Looks up accounting data for the patron with the given borrowernumber.
1142 C<&GetMemberAccountRecords> returns a three-element array. C<$acctlines> is a
1143 reference-to-array, where each element is a reference-to-hash; the
1144 keys are the fields of the C<accountlines> table in the Koha database.
1145 C<$count> is the number of elements in C<$acctlines>. C<$total> is the
1146 total amount outstanding for all of the account lines.
1151 sub GetMemberAccountRecords {
1152 my ($borrowernumber,$date) = @_;
1153 my $dbh = C4::Context->dbh;
1159 WHERE borrowernumber=?);
1160 my @bind = ($borrowernumber);
1161 if ($date && $date ne ''){
1162 $strsth.=" AND date < ? ";
1165 $strsth.=" ORDER BY date desc,timestamp DESC";
1166 my $sth= $dbh->prepare( $strsth );
1167 $sth->execute( @bind );
1169 while ( my $data = $sth->fetchrow_hashref ) {
1170 my $biblio = GetBiblioFromItemNumber($data->{itemnumber}) if $data->{itemnumber};
1171 $data->{biblionumber} = $biblio->{biblionumber};
1172 $data->{title} = $biblio->{title};
1173 $acctlines[$numlines] = $data;
1175 $total += int(1000 * $data->{'amountoutstanding'}); # convert float to integer to avoid round-off errors
1178 return ( $total, \@acctlines,$numlines);
1181 =head2 GetBorNotifyAcctRecord
1183 ($count, $acctlines, $total) = &GetBorNotifyAcctRecord($params,$notifyid);
1185 Looks up accounting data for the patron with the given borrowernumber per file number.
1187 (FIXME - I'm not at all sure what this is about.)
1189 C<&GetBorNotifyAcctRecord> returns a three-element array. C<$acctlines> is a
1190 reference-to-array, where each element is a reference-to-hash; the
1191 keys are the fields of the C<accountlines> table in the Koha database.
1192 C<$count> is the number of elements in C<$acctlines>. C<$total> is the
1193 total amount outstanding for all of the account lines.
1197 sub GetBorNotifyAcctRecord {
1198 my ( $borrowernumber, $notifyid ) = @_;
1199 my $dbh = C4::Context->dbh;
1202 my $sth = $dbh->prepare(
1205 WHERE borrowernumber=?
1207 AND amountoutstanding != '0'
1208 ORDER BY notify_id,accounttype
1210 # 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')
1212 $sth->execute( $borrowernumber, $notifyid );
1214 while ( my $data = $sth->fetchrow_hashref ) {
1215 $acctlines[$numlines] = $data;
1217 $total += int(100 * $data->{'amountoutstanding'});
1220 return ( $total, \@acctlines, $numlines );
1223 =head2 checkuniquemember (OUEST-PROVENCE)
1225 ($result,$categorycode) = &checkuniquemember($collectivity,$surname,$firstname,$dateofbirth);
1227 Checks that a member exists or not in the database.
1229 C<&result> is nonzero (=exist) or 0 (=does not exist)
1230 C<&categorycode> is from categorycode table
1231 C<&collectivity> is 1 (= we add a collectivity) or 0 (= we add a physical member)
1232 C<&surname> is the surname
1233 C<&firstname> is the firstname (only if collectivity=0)
1234 C<&dateofbirth> is the date of birth in ISO format (only if collectivity=0)
1238 # FIXME: This function is not legitimate. Multiple patrons might have the same first/last name and birthdate.
1239 # This is especially true since first name is not even a required field.
1241 sub checkuniquemember {
1242 my ( $collectivity, $surname, $firstname, $dateofbirth ) = @_;
1243 my $dbh = C4::Context->dbh;
1244 my $request = ($collectivity) ?
1245 "SELECT borrowernumber,categorycode FROM borrowers WHERE surname=? " :
1247 "SELECT borrowernumber,categorycode FROM borrowers WHERE surname=? and firstname=? and dateofbirth=?" :
1248 "SELECT borrowernumber,categorycode FROM borrowers WHERE surname=? and firstname=?";
1249 my $sth = $dbh->prepare($request);
1250 if ($collectivity) {
1251 $sth->execute( uc($surname) );
1252 } elsif($dateofbirth){
1253 $sth->execute( uc($surname), ucfirst($firstname), $dateofbirth );
1255 $sth->execute( uc($surname), ucfirst($firstname));
1257 my @data = $sth->fetchrow;
1258 ( $data[0] ) and return $data[0], $data[1];
1262 sub checkcardnumber {
1263 my ($cardnumber,$borrowernumber) = @_;
1264 my $dbh = C4::Context->dbh;
1265 my $query = "SELECT * FROM borrowers WHERE cardnumber=?";
1266 $query .= " AND borrowernumber <> ?" if ($borrowernumber);
1267 my $sth = $dbh->prepare($query);
1268 if ($borrowernumber) {
1269 $sth->execute($cardnumber,$borrowernumber);
1271 $sth->execute($cardnumber);
1273 if (my $data= $sth->fetchrow_hashref()){
1282 =head2 getzipnamecity (OUEST-PROVENCE)
1284 take all info from table city for the fields city and zip
1285 check for the name and the zip code of the city selected
1289 sub getzipnamecity {
1291 my $dbh = C4::Context->dbh;
1294 "select city_name,city_zipcode from cities where cityid=? ");
1295 $sth->execute($cityid);
1296 my @data = $sth->fetchrow;
1297 return $data[0], $data[1];
1301 =head2 getdcity (OUEST-PROVENCE)
1303 recover cityid with city_name condition
1308 my ($city_name) = @_;
1309 my $dbh = C4::Context->dbh;
1310 my $sth = $dbh->prepare("select cityid from cities where city_name=? ");
1311 $sth->execute($city_name);
1312 my $data = $sth->fetchrow;
1316 =head2 GetFirstValidEmailAddress
1318 $email = GetFirstValidEmailAddress($borrowernumber);
1320 Return the first valid email address for a borrower, given the borrowernumber. For now, the order
1321 is defined as email, emailpro, B_email. Returns the empty string if the borrower has no email
1326 sub GetFirstValidEmailAddress {
1327 my $borrowernumber = shift;
1328 my $dbh = C4::Context->dbh;
1329 my $sth = $dbh->prepare( "SELECT email, emailpro, B_email FROM borrowers where borrowernumber = ? ");
1330 $sth->execute( $borrowernumber );
1331 my $data = $sth->fetchrow_hashref;
1333 if ($data->{'email'}) {
1334 return $data->{'email'};
1335 } elsif ($data->{'emailpro'}) {
1336 return $data->{'emailpro'};
1337 } elsif ($data->{'B_email'}) {
1338 return $data->{'B_email'};
1344 =head2 GetExpiryDate
1346 $expirydate = GetExpiryDate($categorycode, $dateenrolled);
1348 Calculate expiry date given a categorycode and starting date. Date argument must be in ISO format.
1349 Return date is also in ISO format.
1354 my ( $categorycode, $dateenrolled ) = @_;
1356 if ($categorycode) {
1357 my $dbh = C4::Context->dbh;
1358 my $sth = $dbh->prepare("SELECT enrolmentperiod,enrolmentperioddate FROM categories WHERE categorycode=?");
1359 $sth->execute($categorycode);
1360 $enrolments = $sth->fetchrow_hashref;
1362 # die "GetExpiryDate: for enrollmentperiod $enrolmentperiod (category '$categorycode') starting $dateenrolled.\n";
1363 my @date = split (/-/,$dateenrolled);
1364 if($enrolments->{enrolmentperiod}){
1365 return sprintf("%04d-%02d-%02d", Add_Delta_YM(@date,0,$enrolments->{enrolmentperiod}));
1367 return $enrolments->{enrolmentperioddate};
1371 =head2 checkuserpassword (OUEST-PROVENCE)
1373 check for the password and login are not used
1374 return the number of record
1375 0=> NOT USED 1=> USED
1379 sub checkuserpassword {
1380 my ( $borrowernumber, $userid, $password ) = @_;
1381 $password = md5_base64($password);
1382 my $dbh = C4::Context->dbh;
1385 "Select count(*) from borrowers where borrowernumber !=? and userid =? and password=? "
1387 $sth->execute( $borrowernumber, $userid, $password );
1388 my $number_rows = $sth->fetchrow;
1389 return $number_rows;
1393 =head2 GetborCatFromCatType
1395 ($codes_arrayref, $labels_hashref) = &GetborCatFromCatType();
1397 Looks up the different types of borrowers in the database. Returns two
1398 elements: a reference-to-array, which lists the borrower category
1399 codes, and a reference-to-hash, which maps the borrower category codes
1400 to category descriptions.
1405 sub GetborCatFromCatType {
1406 my ( $category_type, $action ) = @_;
1407 # FIXME - This API seems both limited and dangerous.
1408 my $dbh = C4::Context->dbh;
1409 my $request = qq| SELECT categorycode,description
1412 ORDER BY categorycode|;
1413 my $sth = $dbh->prepare($request);
1415 $sth->execute($category_type);
1424 while ( my $data = $sth->fetchrow_hashref ) {
1425 push @codes, $data->{'categorycode'};
1426 $labels{ $data->{'categorycode'} } = $data->{'description'};
1428 return ( \@codes, \%labels );
1431 =head2 GetBorrowercategory
1433 $hashref = &GetBorrowercategory($categorycode);
1435 Given the borrower's category code, the function returns the corresponding
1436 data hashref for a comprehensive information display.
1438 $arrayref_hashref = &GetBorrowercategory;
1440 If no category code provided, the function returns all the categories.
1444 sub GetBorrowercategory {
1446 my $dbh = C4::Context->dbh;
1450 "SELECT description,dateofbirthrequired,upperagelimit,category_type
1452 WHERE categorycode = ?"
1454 $sth->execute($catcode);
1456 $sth->fetchrow_hashref;
1460 } # sub getborrowercategory
1462 =head2 GetBorrowercategoryList
1464 $arrayref_hashref = &GetBorrowercategoryList;
1465 If no category code provided, the function returns all the categories.
1469 sub GetBorrowercategoryList {
1470 my $dbh = C4::Context->dbh;
1475 ORDER BY description"
1479 $sth->fetchall_arrayref({});
1481 } # sub getborrowercategory
1483 =head2 ethnicitycategories
1485 ($codes_arrayref, $labels_hashref) = ðnicitycategories();
1487 Looks up the different ethnic types in the database. Returns two
1488 elements: a reference-to-array, which lists the ethnicity codes, and a
1489 reference-to-hash, which maps the ethnicity codes to ethnicity
1496 sub ethnicitycategories {
1497 my $dbh = C4::Context->dbh;
1498 my $sth = $dbh->prepare("Select code,name from ethnicity order by name");
1502 while ( my $data = $sth->fetchrow_hashref ) {
1503 push @codes, $data->{'code'};
1504 $labels{ $data->{'code'} } = $data->{'name'};
1506 return ( \@codes, \%labels );
1511 $ethn_name = &fixEthnicity($ethn_code);
1513 Takes an ethnicity code (e.g., "european" or "pi") and returns the
1514 corresponding descriptive name from the C<ethnicity> table in the
1515 Koha database ("European" or "Pacific Islander").
1522 my $ethnicity = shift;
1523 return unless $ethnicity;
1524 my $dbh = C4::Context->dbh;
1525 my $sth = $dbh->prepare("Select name from ethnicity where code = ?");
1526 $sth->execute($ethnicity);
1527 my $data = $sth->fetchrow_hashref;
1528 return $data->{'name'};
1529 } # sub fixEthnicity
1533 $dateofbirth,$date = &GetAge($date);
1535 this function return the borrowers age with the value of dateofbirth
1541 my ( $date, $date_ref ) = @_;
1543 if ( not defined $date_ref ) {
1544 $date_ref = sprintf( '%04d-%02d-%02d', Today() );
1547 my ( $year1, $month1, $day1 ) = split /-/, $date;
1548 my ( $year2, $month2, $day2 ) = split /-/, $date_ref;
1550 my $age = $year2 - $year1;
1551 if ( $month1 . $day1 > $month2 . $day2 ) {
1558 =head2 get_institutions
1560 $insitutions = get_institutions();
1562 Just returns a list of all the borrowers of type I, borrownumber and name
1567 sub get_institutions {
1568 my $dbh = C4::Context->dbh();
1571 "SELECT borrowernumber,surname FROM borrowers WHERE categorycode=? ORDER BY surname"
1575 while ( my $data = $sth->fetchrow_hashref() ) {
1576 $orgs{ $data->{'borrowernumber'} } = $data;
1580 } # sub get_institutions
1582 =head2 add_member_orgs
1584 add_member_orgs($borrowernumber,$borrowernumbers);
1586 Takes a borrowernumber and a list of other borrowernumbers and inserts them into the borrowers_to_borrowers table
1591 sub add_member_orgs {
1592 my ( $borrowernumber, $otherborrowers ) = @_;
1593 my $dbh = C4::Context->dbh();
1595 "INSERT INTO borrowers_to_borrowers (borrower1,borrower2) VALUES (?,?)";
1596 my $sth = $dbh->prepare($query);
1597 foreach my $otherborrowernumber (@$otherborrowers) {
1598 $sth->execute( $borrowernumber, $otherborrowernumber );
1601 } # sub add_member_orgs
1605 $cityarrayref = GetCities();
1607 Returns an array_ref of the entries in the cities table
1608 If there are entries in the table an empty row is returned
1609 This is currently only used to populate a popup in memberentry
1615 my $dbh = C4::Context->dbh;
1616 my $city_arr = $dbh->selectall_arrayref(
1617 q|SELECT cityid,city_zipcode,city_name FROM cities ORDER BY city_name|,
1619 if ( @{$city_arr} ) {
1620 unshift @{$city_arr}, {
1621 city_zipcode => q{},
1630 =head2 GetSortDetails (OUEST-PROVENCE)
1632 ($lib) = &GetSortDetails($category,$sortvalue);
1634 Returns the authorized value details
1635 C<&$lib>return value of authorized value details
1636 C<&$sortvalue>this is the value of authorized value
1637 C<&$category>this is the value of authorized value category
1641 sub GetSortDetails {
1642 my ( $category, $sortvalue ) = @_;
1643 my $dbh = C4::Context->dbh;
1644 my $query = qq|SELECT lib
1645 FROM authorised_values
1647 AND authorised_value=? |;
1648 my $sth = $dbh->prepare($query);
1649 $sth->execute( $category, $sortvalue );
1650 my $lib = $sth->fetchrow;
1651 return ($lib) if ($lib);
1652 return ($sortvalue) unless ($lib);
1655 =head2 MoveMemberToDeleted
1657 $result = &MoveMemberToDeleted($borrowernumber);
1659 Copy the record from borrowers to deletedborrowers table.
1663 # FIXME: should do it in one SQL statement w/ subquery
1664 # Otherwise, we should return the @data on success
1666 sub MoveMemberToDeleted {
1667 my ($member) = shift or return;
1668 my $dbh = C4::Context->dbh;
1669 my $query = qq|SELECT *
1671 WHERE borrowernumber=?|;
1672 my $sth = $dbh->prepare($query);
1673 $sth->execute($member);
1674 my @data = $sth->fetchrow_array;
1675 (@data) or return; # if we got a bad borrowernumber, there's nothing to insert
1677 $dbh->prepare( "INSERT INTO deletedborrowers VALUES ("
1678 . ( "?," x ( scalar(@data) - 1 ) )
1680 $sth->execute(@data);
1685 DelMember($borrowernumber);
1687 This function remove directly a borrower whitout writing it on deleteborrower.
1688 + Deletes reserves for the borrower
1693 my $dbh = C4::Context->dbh;
1694 my $borrowernumber = shift;
1695 #warn "in delmember with $borrowernumber";
1696 return unless $borrowernumber; # borrowernumber is mandatory.
1698 my $query = qq|DELETE
1700 WHERE borrowernumber=?|;
1701 my $sth = $dbh->prepare($query);
1702 $sth->execute($borrowernumber);
1706 WHERE borrowernumber = ?
1708 $sth = $dbh->prepare($query);
1709 $sth->execute($borrowernumber);
1710 logaction("MEMBERS", "DELETE", $borrowernumber, "") if C4::Context->preference("BorrowersLog");
1714 =head2 ExtendMemberSubscriptionTo (OUEST-PROVENCE)
1716 $date = ExtendMemberSubscriptionTo($borrowerid, $date);
1718 Extending the subscription to a given date or to the expiry date calculated on ISO date.
1723 sub ExtendMemberSubscriptionTo {
1724 my ( $borrowerid,$date) = @_;
1725 my $dbh = C4::Context->dbh;
1726 my $borrower = GetMember('borrowernumber'=>$borrowerid);
1728 $date=POSIX::strftime("%Y-%m-%d",localtime());
1729 $date = GetExpiryDate( $borrower->{'categorycode'}, $date );
1731 my $sth = $dbh->do(<<EOF);
1733 SET dateexpiry='$date'
1734 WHERE borrowernumber='$borrowerid'
1736 # add enrolmentfee if needed
1737 $sth = $dbh->prepare("SELECT enrolmentfee FROM categories WHERE categorycode=?");
1738 $sth->execute($borrower->{'categorycode'});
1739 my ($enrolmentfee) = $sth->fetchrow;
1740 if ($enrolmentfee && $enrolmentfee > 0) {
1741 # insert fee in patron debts
1742 manualinvoice($borrower->{'borrowernumber'}, '', '', 'A', $enrolmentfee);
1744 return $date if ($sth);
1748 =head2 GetRoadTypes (OUEST-PROVENCE)
1750 ($idroadtypearrayref, $roadttype_hashref) = &GetRoadTypes();
1752 Looks up the different road type . Returns two
1753 elements: a reference-to-array, which lists the id_roadtype
1754 codes, and a reference-to-hash, which maps the road type of the road .
1759 my $dbh = C4::Context->dbh;
1761 SELECT roadtypeid,road_type
1763 ORDER BY road_type|;
1764 my $sth = $dbh->prepare($query);
1769 # insert empty value to create a empty choice in cgi popup
1771 while ( my $data = $sth->fetchrow_hashref ) {
1773 push @id, $data->{'roadtypeid'};
1774 $roadtype{ $data->{'roadtypeid'} } = $data->{'road_type'};
1777 #test to know if the table contain some records if no the function return nothing
1784 return ( \@id, \%roadtype );
1790 =head2 GetTitles (OUEST-PROVENCE)
1792 ($borrowertitle)= &GetTitles();
1794 Looks up the different title . Returns array with all borrowers title
1799 my @borrowerTitle = split (/,|\|/,C4::Context->preference('BorrowersTitles'));
1800 unshift( @borrowerTitle, "" );
1801 my $count=@borrowerTitle;
1806 return ( \@borrowerTitle);
1810 =head2 GetPatronImage
1812 my ($imagedata, $dberror) = GetPatronImage($cardnumber);
1814 Returns the mimetype and binary image data of the image for the patron with the supplied cardnumber.
1818 sub GetPatronImage {
1819 my ($cardnumber) = @_;
1820 warn "Cardnumber passed to GetPatronImage is $cardnumber" if $debug;
1821 my $dbh = C4::Context->dbh;
1822 my $query = 'SELECT mimetype, imagefile FROM patronimage WHERE cardnumber = ?';
1823 my $sth = $dbh->prepare($query);
1824 $sth->execute($cardnumber);
1825 my $imagedata = $sth->fetchrow_hashref;
1826 warn "Database error!" if $sth->errstr;
1827 return $imagedata, $sth->errstr;
1830 =head2 PutPatronImage
1832 PutPatronImage($cardnumber, $mimetype, $imgfile);
1834 Stores patron binary image data and mimetype in database.
1835 NOTE: This function is good for updating images as well as inserting new images in the database.
1839 sub PutPatronImage {
1840 my ($cardnumber, $mimetype, $imgfile) = @_;
1841 warn "Parameters passed in: Cardnumber=$cardnumber, Mimetype=$mimetype, " . ($imgfile ? "Imagefile" : "No Imagefile") if $debug;
1842 my $dbh = C4::Context->dbh;
1843 my $query = "INSERT INTO patronimage (cardnumber, mimetype, imagefile) VALUES (?,?,?) ON DUPLICATE KEY UPDATE imagefile = ?;";
1844 my $sth = $dbh->prepare($query);
1845 $sth->execute($cardnumber,$mimetype,$imgfile,$imgfile);
1846 warn "Error returned inserting $cardnumber.$mimetype." if $sth->errstr;
1847 return $sth->errstr;
1850 =head2 RmPatronImage
1852 my ($dberror) = RmPatronImage($cardnumber);
1854 Removes the image for the patron with the supplied cardnumber.
1859 my ($cardnumber) = @_;
1860 warn "Cardnumber passed to GetPatronImage is $cardnumber" if $debug;
1861 my $dbh = C4::Context->dbh;
1862 my $query = "DELETE FROM patronimage WHERE cardnumber = ?;";
1863 my $sth = $dbh->prepare($query);
1864 $sth->execute($cardnumber);
1865 my $dberror = $sth->errstr;
1866 warn "Database error!" if $sth->errstr;
1870 =head2 GetHideLostItemsPreference
1872 $hidelostitemspref = &GetHideLostItemsPreference($borrowernumber);
1874 Returns the HideLostItems preference for the patron category of the supplied borrowernumber
1875 C<&$hidelostitemspref>return value of function, 0 or 1
1879 sub GetHideLostItemsPreference {
1880 my ($borrowernumber) = @_;
1881 my $dbh = C4::Context->dbh;
1882 my $query = "SELECT hidelostitems FROM borrowers,categories WHERE borrowers.categorycode = categories.categorycode AND borrowernumber = ?";
1883 my $sth = $dbh->prepare($query);
1884 $sth->execute($borrowernumber);
1885 my $hidelostitems = $sth->fetchrow;
1886 return $hidelostitems;
1889 =head2 GetRoadTypeDetails (OUEST-PROVENCE)
1891 ($roadtype) = &GetRoadTypeDetails($roadtypeid);
1893 Returns the description of roadtype
1894 C<&$roadtype>return description of road type
1895 C<&$roadtypeid>this is the value of roadtype s
1899 sub GetRoadTypeDetails {
1900 my ($roadtypeid) = @_;
1901 my $dbh = C4::Context->dbh;
1905 WHERE roadtypeid=?|;
1906 my $sth = $dbh->prepare($query);
1907 $sth->execute($roadtypeid);
1908 my $roadtype = $sth->fetchrow;
1912 =head2 GetBorrowersWhoHaveNotBorrowedSince
1914 &GetBorrowersWhoHaveNotBorrowedSince($date)
1916 this function get all borrowers who haven't borrowed since the date given on input arg.
1920 sub GetBorrowersWhoHaveNotBorrowedSince {
1921 my $filterdate = shift||POSIX::strftime("%Y-%m-%d",localtime());
1922 my $filterexpiry = shift;
1923 my $filterbranch = shift ||
1924 ((C4::Context->preference('IndependantBranches')
1925 && C4::Context->userenv
1926 && C4::Context->userenv->{flags} % 2 !=1
1927 && C4::Context->userenv->{branch})
1928 ? C4::Context->userenv->{branch}
1930 my $dbh = C4::Context->dbh;
1932 SELECT borrowers.borrowernumber,
1933 max(old_issues.timestamp) as latestissue,
1934 max(issues.timestamp) as currentissue
1936 JOIN categories USING (categorycode)
1937 LEFT JOIN old_issues USING (borrowernumber)
1938 LEFT JOIN issues USING (borrowernumber)
1939 WHERE category_type <> 'S'
1940 AND borrowernumber NOT IN (SELECT guarantorid FROM borrowers WHERE guarantorid IS NOT NULL AND guarantorid <> 0)
1943 if ($filterbranch && $filterbranch ne ""){
1944 $query.=" AND borrowers.branchcode= ?";
1945 push @query_params,$filterbranch;
1948 $query .= " AND dateexpiry < ? ";
1949 push @query_params,$filterdate;
1951 $query.=" GROUP BY borrowers.borrowernumber";
1953 $query.=" HAVING (latestissue < ? OR latestissue IS NULL)
1954 AND currentissue IS NULL";
1955 push @query_params,$filterdate;
1957 warn $query if $debug;
1958 my $sth = $dbh->prepare($query);
1959 if (scalar(@query_params)>0){
1960 $sth->execute(@query_params);
1967 while ( my $data = $sth->fetchrow_hashref ) {
1968 push @results, $data;
1973 =head2 GetBorrowersWhoHaveNeverBorrowed
1975 $results = &GetBorrowersWhoHaveNeverBorrowed
1977 This function get all borrowers who have never borrowed.
1979 I<$result> is a ref to an array which all elements are a hasref.
1983 sub GetBorrowersWhoHaveNeverBorrowed {
1984 my $filterbranch = shift ||
1985 ((C4::Context->preference('IndependantBranches')
1986 && C4::Context->userenv
1987 && C4::Context->userenv->{flags} % 2 !=1
1988 && C4::Context->userenv->{branch})
1989 ? C4::Context->userenv->{branch}
1991 my $dbh = C4::Context->dbh;
1993 SELECT borrowers.borrowernumber,max(timestamp) as latestissue
1995 LEFT JOIN issues ON borrowers.borrowernumber = issues.borrowernumber
1996 WHERE issues.borrowernumber IS NULL
1999 if ($filterbranch && $filterbranch ne ""){
2000 $query.=" AND borrowers.branchcode= ?";
2001 push @query_params,$filterbranch;
2003 warn $query if $debug;
2005 my $sth = $dbh->prepare($query);
2006 if (scalar(@query_params)>0){
2007 $sth->execute(@query_params);
2014 while ( my $data = $sth->fetchrow_hashref ) {
2015 push @results, $data;
2020 =head2 GetBorrowersWithIssuesHistoryOlderThan
2022 $results = &GetBorrowersWithIssuesHistoryOlderThan($date)
2024 this function get all borrowers who has an issue history older than I<$date> given on input arg.
2026 I<$result> is a ref to an array which all elements are a hashref.
2027 This hashref is containt the number of time this borrowers has borrowed before I<$date> and the borrowernumber.
2031 sub GetBorrowersWithIssuesHistoryOlderThan {
2032 my $dbh = C4::Context->dbh;
2033 my $date = shift ||POSIX::strftime("%Y-%m-%d",localtime());
2034 my $filterbranch = shift ||
2035 ((C4::Context->preference('IndependantBranches')
2036 && C4::Context->userenv
2037 && C4::Context->userenv->{flags} % 2 !=1
2038 && C4::Context->userenv->{branch})
2039 ? C4::Context->userenv->{branch}
2042 SELECT count(borrowernumber) as n,borrowernumber
2044 WHERE returndate < ?
2045 AND borrowernumber IS NOT NULL
2048 push @query_params, $date;
2050 $query.=" AND branchcode = ?";
2051 push @query_params, $filterbranch;
2053 $query.=" GROUP BY borrowernumber ";
2054 warn $query if $debug;
2055 my $sth = $dbh->prepare($query);
2056 $sth->execute(@query_params);
2059 while ( my $data = $sth->fetchrow_hashref ) {
2060 push @results, $data;
2065 =head2 GetBorrowersNamesAndLatestIssue
2067 $results = &GetBorrowersNamesAndLatestIssueList(@borrowernumbers)
2069 this function get borrowers Names and surnames and Issue information.
2071 I<@borrowernumbers> is an array which all elements are borrowernumbers.
2072 This hashref is containt the number of time this borrowers has borrowed before I<$date> and the borrowernumber.
2076 sub GetBorrowersNamesAndLatestIssue {
2077 my $dbh = C4::Context->dbh;
2078 my @borrowernumbers=@_;
2080 SELECT surname,lastname, phone, email,max(timestamp)
2082 LEFT JOIN issues ON borrowers.borrowernumber=issues.borrowernumber
2083 GROUP BY borrowernumber
2085 my $sth = $dbh->prepare($query);
2087 my $results = $sth->fetchall_arrayref({});
2093 my $success = DebarMember( $borrowernumber );
2095 marks a Member as debarred, and therefore unable to checkout any more
2099 true on success, false on failure
2104 my $borrowernumber = shift;
2106 return unless defined $borrowernumber;
2107 return unless $borrowernumber =~ /^\d+$/;
2109 return ModMember( borrowernumber => $borrowernumber,
2118 my $success = ModPrivacy( $borrowernumber, $privacy );
2120 Update the privacy of a patron.
2123 true on success, false on failure
2130 my $borrowernumber = shift;
2131 my $privacy = shift;
2132 return unless defined $borrowernumber;
2133 return unless $borrowernumber =~ /^\d+$/;
2135 return ModMember( borrowernumber => $borrowernumber,
2136 privacy => $privacy );
2141 AddMessage( $borrowernumber, $message_type, $message, $branchcode );
2143 Adds a message to the messages table for the given borrower.
2152 my ( $borrowernumber, $message_type, $message, $branchcode ) = @_;
2154 my $dbh = C4::Context->dbh;
2156 if ( ! ( $borrowernumber && $message_type && $message && $branchcode ) ) {
2160 my $query = "INSERT INTO messages ( borrowernumber, branchcode, message_type, message ) VALUES ( ?, ?, ?, ? )";
2161 my $sth = $dbh->prepare($query);
2162 $sth->execute( $borrowernumber, $branchcode, $message_type, $message );
2169 GetMessages( $borrowernumber, $type );
2171 $type is message type, B for borrower, or L for Librarian.
2172 Empty type returns all messages of any type.
2174 Returns all messages for the given borrowernumber
2179 my ( $borrowernumber, $type, $branchcode ) = @_;
2185 my $dbh = C4::Context->dbh;
2188 branches.branchname,
2191 messages.branchcode LIKE '$branchcode' AS can_delete
2192 FROM messages, branches
2193 WHERE borrowernumber = ?
2194 AND message_type LIKE ?
2195 AND messages.branchcode = branches.branchcode
2196 ORDER BY message_date DESC";
2197 my $sth = $dbh->prepare($query);
2198 $sth->execute( $borrowernumber, $type ) ;
2201 while ( my $data = $sth->fetchrow_hashref ) {
2202 my $d = C4::Dates->new( $data->{message_date}, 'iso' );
2203 $data->{message_date_formatted} = $d->output;
2204 push @results, $data;
2212 GetMessagesCount( $borrowernumber, $type );
2214 $type is message type, B for borrower, or L for Librarian.
2215 Empty type returns all messages of any type.
2217 Returns the number of messages for the given borrowernumber
2221 sub GetMessagesCount {
2222 my ( $borrowernumber, $type, $branchcode ) = @_;
2228 my $dbh = C4::Context->dbh;
2230 my $query = "SELECT COUNT(*) as MsgCount FROM messages WHERE borrowernumber = ? AND message_type LIKE ?";
2231 my $sth = $dbh->prepare($query);
2232 $sth->execute( $borrowernumber, $type ) ;
2235 my $data = $sth->fetchrow_hashref;
2236 my $count = $data->{'MsgCount'};
2243 =head2 DeleteMessage
2245 DeleteMessage( $message_id );
2250 my ( $message_id ) = @_;
2252 my $dbh = C4::Context->dbh;
2254 my $query = "DELETE FROM messages WHERE message_id = ?";
2255 my $sth = $dbh->prepare($query);
2256 $sth->execute( $message_id );
2260 END { } # module clean-up code here (global destructor)