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 with
17 # Koha; if not, write to the Free Software Foundation, Inc., 59 Temple Place,
18 # Suite 330, Boston, MA 02111-1307 USA
23 use C4::Dates qw(format_date_in_iso);
24 use Digest::MD5 qw(md5_base64);
25 use Date::Calc qw/Today Add_Delta_YM/;
26 use C4::Log; # logaction
31 our ($VERSION,@ISA,@EXPORT,@EXPORT_OK,$debug);
35 $debug = $ENV{DEBUG} || 0;
46 &GetMemberIssuesAndFines
65 &GetMemberAccountRecords
66 &GetBorNotifyAcctRecord
70 &GetBorrowercategoryList
72 &GetBorrowersWhoHaveNotBorrowedSince
73 &GetBorrowersWhoHaveNeverBorrowed
74 &GetBorrowersWithIssuesHistoryOlderThan
95 &ExtendMemberSubscriptionTo
112 C4::Members - Perl Module containing convenience functions for member handling
120 This module contains routines for adding, modifying and deleting members/patrons/borrowers
128 ($count, $borrowers) = &SearchMember($searchstring, $type,$category_type,$filter,$showallbranches);
130 Looks up patrons (borrowers) by name.
132 BUGFIX 499: C<$type> is now used to determine type of search.
133 if $type is "simple", search is performed on the first letter of the
136 $category_type is used to get a specified type of user.
137 (mainly adults when creating a child.)
139 C<$searchstring> is a space-separated list of search terms. Each term
140 must match the beginning a borrower's surname, first name, or other
143 C<$filter> is assumed to be a list of elements to filter results on
145 C<$showallbranches> is used in IndependantBranches Context to display all branches results.
147 C<&SearchMember> returns a two-element list. C<$borrowers> is a
148 reference-to-array; each element is a reference-to-hash, whose keys
149 are the fields of the C<borrowers> table in the Koha database.
150 C<$count> is the number of elements in C<$borrowers>.
155 #used by member enquiries from the intranet
156 #called by member.pl and circ/circulation.pl
158 my ($searchstring, $orderby, $type,$category_type,$filter,$showallbranches ) = @_;
159 my $dbh = C4::Context->dbh;
165 # this is used by circulation everytime a new borrowers cardnumber is scanned
166 # so we can check an exact match first, if that works return, otherwise do the rest
167 $query = "SELECT * FROM borrowers
168 LEFT JOIN categories ON borrowers.categorycode=categories.categorycode
170 my $sth = $dbh->prepare("$query WHERE cardnumber = ?");
171 $sth->execute($searchstring);
172 my $data = $sth->fetchall_arrayref({});
174 return ( scalar(@$data), $data );
178 if ( $type eq "simple" ) # simple search for one letter only
180 $query .= ($category_type ? " AND category_type = ".$dbh->quote($category_type) : "");
181 $query .= " WHERE (surname LIKE ? OR cardnumber like ?) ";
182 if (C4::Context->preference("IndependantBranches") && !$showallbranches){
183 if (C4::Context->userenv && C4::Context->userenv->{flags}!=1 && C4::Context->userenv->{'branch'}){
184 $query.=" AND borrowers.branchcode =".$dbh->quote(C4::Context->userenv->{'branch'}) unless (C4::Context->userenv->{'branch'} eq "insecure");
187 $query.=" ORDER BY $orderby";
188 @bind = ("$searchstring%","$searchstring");
190 else # advanced search looking in surname, firstname and othernames
192 @data = split( ' ', $searchstring );
195 if (C4::Context->preference("IndependantBranches") && !$showallbranches){
196 if (C4::Context->userenv && C4::Context->userenv->{flags}!=1 && C4::Context->userenv->{'branch'}){
197 $query.=" borrowers.branchcode =".$dbh->quote(C4::Context->userenv->{'branch'})." AND " unless (C4::Context->userenv->{'branch'} eq "insecure");
200 $query.="((surname LIKE ? OR surname LIKE ?
201 OR firstname LIKE ? OR firstname LIKE ?
202 OR othernames LIKE ? OR othernames LIKE ?)
204 ($category_type?" AND category_type = ".$dbh->quote($category_type):"");
206 "$data[0]%", "% $data[0]%", "$data[0]%", "% $data[0]%",
207 "$data[0]%", "% $data[0]%"
209 for ( my $i = 1 ; $i < $count ; $i++ ) {
210 $query = $query . " AND (" . " surname LIKE ? OR surname LIKE ?
211 OR firstname LIKE ? OR firstname LIKE ?
212 OR othernames LIKE ? OR othernames LIKE ?)";
214 "$data[$i]%", "% $data[$i]%", "$data[$i]%",
215 "% $data[$i]%", "$data[$i]%", "% $data[$i]%" );
219 $query = $query . ") OR cardnumber LIKE ? ";
220 push( @bind, $searchstring );
221 if (C4::Context->preference('ExtendedPatronAttributes')) {
222 $query .= "OR borrowernumber IN (
223 SELECT borrowernumber
224 FROM borrower_attributes
225 JOIN borrower_attribute_types USING (code)
226 WHERE staff_searchable = 1
229 push (@bind, $searchstring);
231 $query .= "order by $orderby";
236 $sth = $dbh->prepare($query);
238 $debug and print STDERR "Q $orderby : $query\n";
239 $sth->execute(@bind);
241 $data = $sth->fetchall_arrayref({});
244 return ( scalar(@$data), $data );
247 =head2 GetMemberDetails
249 ($borrower, $flags) = &GetMemberDetails($borrowernumber, $cardnumber);
251 Looks up a patron and returns information about him or her. If
252 C<$borrowernumber> is true (nonzero), C<&GetMemberDetails> looks
253 up the borrower by number; otherwise, it looks up the borrower by card
256 C<$borrower> is a reference-to-hash whose keys are the fields of the
257 borrowers table in the Koha database. In addition,
258 C<$borrower-E<gt>{flags}> is a hash giving more detailed information
259 about the patron. Its keys act as flags :
261 if $borrower->{flags}->{LOST} {
262 # Patron's card was reported lost
265 Each flag has a C<message> key, giving a human-readable explanation of
266 the flag. If the state of a flag means that the patron should not be
267 allowed to borrow any more books, then it will have a C<noissues> key
270 The possible flags are:
276 =item Shows the patron's credit or debt, if any.
284 =item (Gone, no address.) Set if the patron has left without giving a
293 =item Set if the patron's card has been reported as lost.
301 =item Set if the patron has been debarred.
309 =item Any additional notes about the patron.
317 =item Set if the patron has overdue items. This flag has several keys:
319 C<$flags-E<gt>{ODUES}{itemlist}> is a reference-to-array listing the
320 overdue items. Its elements are references-to-hash, each describing an
321 overdue item. The keys are selected fields from the issues, biblio,
322 biblioitems, and items tables of the Koha database.
324 C<$flags-E<gt>{ODUES}{itemlist}> is a string giving a text listing of
325 the overdue items, one per line.
333 =item Set if any items that the patron has reserved are available.
335 C<$flags-E<gt>{WAITING}{itemlist}> is a reference-to-array listing the
336 available items. Each element is a reference-to-hash whose keys are
337 fields from the reserves table of the Koha database.
343 sub GetMemberDetails {
344 my ( $borrowernumber, $cardnumber ) = @_;
345 my $dbh = C4::Context->dbh;
348 if ($borrowernumber) {
349 $sth = $dbh->prepare("select borrowers.*,category_type from borrowers left join categories on borrowers.categorycode=categories.categorycode where borrowernumber=?");
350 $sth->execute($borrowernumber);
352 elsif ($cardnumber) {
353 $sth = $dbh->prepare("select borrowers.*,category_type from borrowers left join categories on borrowers.categorycode=categories.categorycode where cardnumber=?");
354 $sth->execute($cardnumber);
359 my $borrower = $sth->fetchrow_hashref;
360 my ($amount) = GetMemberAccountRecords( $borrowernumber);
361 $borrower->{'amountoutstanding'} = $amount;
362 # FIXME - patronflags calls GetMemberAccountRecords... just have patronflags return $amount
363 my $flags = patronflags( $borrower);
366 $sth = $dbh->prepare("select bit,flag from userflags");
368 while ( my ( $bit, $flag ) = $sth->fetchrow ) {
369 if ( $borrower->{'flags'} && $borrower->{'flags'} & 2**$bit ) {
370 $accessflagshash->{$flag} = 1;
374 $borrower->{'flags'} = $flags;
375 $borrower->{'authflags'} = $accessflagshash;
377 # find out how long the membership lasts
380 "select enrolmentperiod from categories where categorycode = ?");
381 $sth->execute( $borrower->{'categorycode'} );
382 my $enrolment = $sth->fetchrow;
383 $borrower->{'enrolmentperiod'} = $enrolment;
384 return ($borrower); #, $flags, $accessflagshash);
391 NOTE!: If you change this function, be sure to update the POD for
394 $flags = &patronflags($patron);
397 {message} Message showing patron's credit or debt
398 {noissues} Set if patron owes >$5.00
399 {GNA} Set if patron gone w/o address
400 {message} "Borrower has no valid address"
402 {LOST} Set if patron's card reported lost
403 {message} Message to this effect
405 {DBARRED} Set is patron is debarred
406 {message} Message to this effect
408 {NOTES} Set if patron has notes
409 {message} Notes about patron
410 {ODUES} Set if patron has overdue books
412 {itemlist} ref-to-array: list of overdue books
413 {itemlisttext} Text list of overdue items
414 {WAITING} Set if there are items available that the
416 {message} Message to this effect
417 {itemlist} ref-to-array: list of available items
420 # FIXME rename this function.
423 my ( $patroninformation) = @_;
424 my $dbh=C4::Context->dbh;
425 my ($amount) = GetMemberAccountRecords( $patroninformation->{'borrowernumber'});
428 my $noissuescharge = C4::Context->preference("noissuescharge");
429 $flaginfo{'message'} = sprintf "Patron owes \$%.02f", $amount;
430 $flaginfo{'amount'} = sprintf "%.02f",$amount;
431 if ( $amount > $noissuescharge ) {
432 $flaginfo{'noissues'} = 1;
434 $flags{'CHARGES'} = \%flaginfo;
436 elsif ( $amount < 0 ) {
438 $flaginfo{'message'} = sprintf "Patron has credit of \$%.02f", -$amount;
439 $flags{'CREDITS'} = \%flaginfo;
441 if ( $patroninformation->{'gonenoaddress'}
442 && $patroninformation->{'gonenoaddress'} == 1 )
445 $flaginfo{'message'} = 'Borrower has no valid address.';
446 $flaginfo{'noissues'} = 1;
447 $flags{'GNA'} = \%flaginfo;
449 if ( $patroninformation->{'lost'} && $patroninformation->{'lost'} == 1 ) {
451 $flaginfo{'message'} = 'Borrower\'s card reported lost.';
452 $flaginfo{'noissues'} = 1;
453 $flags{'LOST'} = \%flaginfo;
455 if ( $patroninformation->{'debarred'}
456 && $patroninformation->{'debarred'} == 1 )
459 $flaginfo{'message'} = 'Borrower is Debarred.';
460 $flaginfo{'noissues'} = 1;
461 $flags{'DBARRED'} = \%flaginfo;
463 if ( $patroninformation->{'borrowernotes'}
464 && $patroninformation->{'borrowernotes'} )
467 $flaginfo{'message'} = "$patroninformation->{'borrowernotes'}";
468 $flags{'NOTES'} = \%flaginfo;
470 my ( $odues, $itemsoverdue ) =
471 checkoverdues( $patroninformation->{'borrowernumber'}, $dbh );
474 $flaginfo{'message'} = "Yes";
475 $flaginfo{'itemlist'} = $itemsoverdue;
476 foreach ( sort { $a->{'date_due'} cmp $b->{'date_due'} }
479 $flaginfo{'itemlisttext'} .=
480 "$_->{'date_due'} $_->{'barcode'} $_->{'title'} \n";
482 $flags{'ODUES'} = \%flaginfo;
484 my @itemswaiting = C4::Reserves::GetReservesFromBorrowernumber( $patroninformation->{'borrowernumber'},'W' );
485 my $nowaiting = scalar @itemswaiting;
486 if ( $nowaiting > 0 ) {
488 $flaginfo{'message'} = "Reserved items available";
489 $flaginfo{'itemlist'} = \@itemswaiting;
490 $flags{'WAITING'} = \%flaginfo;
498 $borrower = &GetMember($information, $type);
500 Looks up information about a patron (borrower) by either card number
501 ,firstname, or borrower number, depending on $type value.
502 If C<$type> == 'cardnumber', C<&GetBorrower>
503 searches by cardnumber then by firstname if not found in cardnumber;
504 otherwise, it searches by borrowernumber.
506 C<&GetBorrower> returns a reference-to-hash whose keys are the fields of
507 the C<borrowers> table in the Koha database.
513 my ( $information, $type ) = @_;
514 my $dbh = C4::Context->dbh;
517 SELECT borrowers.*, categories.category_type, categories.description
519 LEFT JOIN categories on borrowers.categorycode=categories.categorycode
521 if ( defined $type && ( $type eq 'cardnumber' || $type eq 'firstname'|| $type eq 'userid'|| $type eq 'borrowernumber' ) ){
522 $information = uc $information;
523 $sth = $dbh->prepare("$select WHERE $type=?");
525 $sth = $dbh->prepare("$select WHERE borrowernumber=?");
527 $sth->execute($information);
528 my $data = $sth->fetchrow_hashref;
530 ($data) and return ($data);
532 if ($type eq 'cardnumber' || $type eq 'firstname') { # otherwise, try with firstname
533 $sth = $dbh->prepare("$select WHERE firstname like ?");
534 $sth->execute($information);
535 $data = $sth->fetchrow_hashref;
537 ($data) and return ($data);
542 =item GetMemberIssuesAndFines
544 ($overdue_count, $issue_count, $total_fines) = &GetMemberIssuesAndFines($borrowernumber);
546 Returns aggregate data about items borrowed by the patron with the
547 given borrowernumber.
549 C<&GetMemberIssuesAndFines> returns a three-element array. C<$overdue_count> is the
550 number of overdue items the patron currently has borrowed. C<$issue_count> is the
551 number of books the patron currently has borrowed. C<$total_fines> is
552 the total fine currently due by the borrower.
557 sub GetMemberIssuesAndFines {
558 my ( $borrowernumber ) = @_;
559 my $dbh = C4::Context->dbh;
560 my $query = "SELECT COUNT(*) FROM issues WHERE borrowernumber = ?";
562 $debug and warn $query."\n";
563 my $sth = $dbh->prepare($query);
564 $sth->execute($borrowernumber);
565 my $issue_count = $sth->fetchrow_arrayref->[0];
568 $sth = $dbh->prepare(
569 "SELECT COUNT(*) FROM issues
570 WHERE borrowernumber = ?
571 AND date_due < now()"
573 $sth->execute($borrowernumber);
574 my $overdue_count = $sth->fetchrow_arrayref->[0];
577 $sth = $dbh->prepare("SELECT SUM(amountoutstanding) FROM accountlines WHERE borrowernumber = ?");
578 $sth->execute($borrowernumber);
579 my $total_fines = $sth->fetchrow_arrayref->[0];
582 return ($overdue_count, $issue_count, $total_fines);
589 &ModMember($borrowernumber);
591 Modify borrower's data. All date fields should ALREADY be in ISO format.
598 my $dbh = C4::Context->dbh;
599 my $iso_re = C4::Dates->new()->regexp('iso');
600 foreach (qw(dateofbirth dateexpiry dateenrolled)) {
601 if (my $tempdate = $data{$_}) { # assignment, not comparison
602 ($tempdate =~ /$iso_re/) and next; # Congatulations, you sent a valid ISO date.
603 warn "ModMember given $_ not in ISO format ($tempdate)";
604 if (my $tempdate2 = format_date_in_iso($tempdate)) { # assignment, not comparison
605 $data{$_} = $tempdate2;
607 warn "ModMember cannot convert '$tempdate' (from syspref)";
611 if (!$data{'dateofbirth'}){
612 undef $data{'dateofbirth'};
614 my $qborrower=$dbh->prepare("SHOW columns from borrowers");
616 my %hashborrowerfields;
617 while (my ($field)=$qborrower->fetchrow){
618 $hashborrowerfields{$field}=1;
620 my $query = "UPDATE borrowers SET \n";
624 # test to know if you must update or not the borrower password
625 if ( $data{'password'} eq '****' ) {
626 delete $data{'password'};
628 $data{'password'} = md5_base64( $data{'password'} ) if ($data{'password'} ne "");
629 delete $data{'password'} if ($data{password} eq "");
631 foreach (keys %data){
632 if ($_ ne 'borrowernumber' and $_ ne 'flags' and $hashborrowerfields{$_}){
634 push @parameters,$data{$_};
638 $query .= " WHERE borrowernumber=?";
639 push @parameters, $data{'borrowernumber'};
640 $debug and print STDERR "$query (executed w/ arg: $data{'borrowernumber'})";
641 $sth = $dbh->prepare($query);
642 $sth->execute(@parameters);
645 # ok if its an adult (type) it may have borrowers that depend on it as a guarantor
646 # so when we update information for an adult we should check for guarantees and update the relevant part
647 # of their records, ie addresses and phone numbers
648 my $borrowercategory= GetBorrowercategory( $data{'category_type'} );
649 if ( $borrowercategory->{'category_type'} eq ('A' || 'S') ) {
650 # is adult check guarantees;
651 UpdateGuarantees(%data);
653 logaction("MEMBERS", "MODIFY", $data{'borrowernumber'}, "$query (executed w/ arg: $data{'borrowernumber'})")
654 if C4::Context->preference("BorrowersLog");
662 $borrowernumber = &AddMember(%borrower);
664 insert new borrower into table
665 Returns the borrowernumber
672 my $dbh = C4::Context->dbh;
673 $data{'userid'} = '' unless $data{'password'};
674 $data{'password'} = md5_base64( $data{'password'} ) if $data{'password'};
676 # WE SHOULD NEVER PASS THIS SUBROUTINE ANYTHING OTHER THAN ISO DATES
677 # IF YOU UNCOMMENT THESE LINES YOU BETTER HAVE A DARN COMPELLING REASON
678 # $data{'dateofbirth'} = format_date_in_iso( $data{'dateofbirth'} );
679 # $data{'dateenrolled'} = format_date_in_iso( $data{'dateenrolled'});
680 # $data{'dateexpiry'} = format_date_in_iso( $data{'dateexpiry'} );
681 # This query should be rewritten to use "?" at execute.
682 if (!$data{'dateofbirth'}){
683 undef ($data{'dateofbirth'});
686 "insert into borrowers set cardnumber=" . $dbh->quote( $data{'cardnumber'} )
687 . ",surname=" . $dbh->quote( $data{'surname'} )
688 . ",firstname=" . $dbh->quote( $data{'firstname'} )
689 . ",title=" . $dbh->quote( $data{'title'} )
690 . ",othernames=" . $dbh->quote( $data{'othernames'} )
691 . ",initials=" . $dbh->quote( $data{'initials'} )
692 . ",streetnumber=". $dbh->quote( $data{'streetnumber'} )
693 . ",streettype=" . $dbh->quote( $data{'streettype'} )
694 . ",address=" . $dbh->quote( $data{'address'} )
695 . ",address2=" . $dbh->quote( $data{'address2'} )
696 . ",zipcode=" . $dbh->quote( $data{'zipcode'} )
697 . ",city=" . $dbh->quote( $data{'city'} )
698 . ",phone=" . $dbh->quote( $data{'phone'} )
699 . ",email=" . $dbh->quote( $data{'email'} )
700 . ",mobile=" . $dbh->quote( $data{'mobile'} )
701 . ",phonepro=" . $dbh->quote( $data{'phonepro'} )
702 . ",opacnote=" . $dbh->quote( $data{'opacnote'} )
703 . ",guarantorid=" . $dbh->quote( $data{'guarantorid'} )
704 . ",dateofbirth=" . $dbh->quote( $data{'dateofbirth'} )
705 . ",branchcode=" . $dbh->quote( $data{'branchcode'} )
706 . ",categorycode=" . $dbh->quote( $data{'categorycode'} )
707 . ",dateenrolled=" . $dbh->quote( $data{'dateenrolled'} )
708 . ",contactname=" . $dbh->quote( $data{'contactname'} )
709 . ",borrowernotes=" . $dbh->quote( $data{'borrowernotes'} )
710 . ",dateexpiry=" . $dbh->quote( $data{'dateexpiry'} )
711 . ",contactnote=" . $dbh->quote( $data{'contactnote'} )
712 . ",B_address=" . $dbh->quote( $data{'B_address'} )
713 . ",B_zipcode=" . $dbh->quote( $data{'B_zipcode'} )
714 . ",B_city=" . $dbh->quote( $data{'B_city'} )
715 . ",B_phone=" . $dbh->quote( $data{'B_phone'} )
716 . ",B_email=" . $dbh->quote( $data{'B_email'} )
717 . ",password=" . $dbh->quote( $data{'password'} )
718 . ",userid=" . $dbh->quote( $data{'userid'} )
719 . ",sort1=" . $dbh->quote( $data{'sort1'} )
720 . ",sort2=" . $dbh->quote( $data{'sort2'} )
721 . ",contacttitle=" . $dbh->quote( $data{'contacttitle'} )
722 . ",emailpro=" . $dbh->quote( $data{'emailpro'} )
723 . ",contactfirstname=" . $dbh->quote( $data{'contactfirstname'} )
724 . ",sex=" . $dbh->quote( $data{'sex'} )
725 . ",fax=" . $dbh->quote( $data{'fax'} )
726 . ",relationship=" . $dbh->quote( $data{'relationship'} )
727 . ",B_streetnumber=" . $dbh->quote( $data{'B_streetnumber'} )
728 . ",B_streettype=" . $dbh->quote( $data{'B_streettype'} )
729 . ",gonenoaddress=" . $dbh->quote( $data{'gonenoaddress'} )
730 . ",lost=" . $dbh->quote( $data{'lost'} )
731 . ",debarred=" . $dbh->quote( $data{'debarred'} )
732 . ",ethnicity=" . $dbh->quote( $data{'ethnicity'} )
733 . ",ethnotes=" . $dbh->quote( $data{'ethnotes'} )
734 . ",altcontactsurname=" . $dbh->quote( $data{'altcontactsurname'} )
735 . ",altcontactfirstname=" . $dbh->quote( $data{'altcontactfirstname'} )
736 . ",altcontactaddress1=" . $dbh->quote( $data{'altcontactaddress1'} )
737 . ",altcontactaddress2=" . $dbh->quote( $data{'altcontactaddress2'} )
738 . ",altcontactaddress3=" . $dbh->quote( $data{'altcontactaddress3'} )
739 . ",altcontactzipcode=" . $dbh->quote( $data{'altcontactzipcode'} )
740 . ",altcontactphone=" . $dbh->quote( $data{'altcontactphone'} ) ;
741 $debug and print STDERR "AddMember SQL: ($query)\n";
742 my $sth = $dbh->prepare($query);
743 # print "Executing SQL: $query\n";
746 $data{'borrowernumber'} = $dbh->{'mysql_insertid'}; # unneeded w/ autoincrement ?
747 # mysql_insertid is probably bad. not necessarily accurate and mysql-specific at best.
749 logaction("MEMBERS", "CREATE", $data{'borrowernumber'}, "") if C4::Context->preference("BorrowersLog");
751 # check for enrollment fee & add it if needed
752 $sth = $dbh->prepare("SELECT enrolmentfee FROM categories WHERE categorycode=?");
753 $sth->execute($data{'categorycode'});
754 my ($enrolmentfee) = $sth->fetchrow;
756 # insert fee in patron debts
757 manualinvoice($data{'borrowernumber'}, '', '', 'A', $enrolmentfee);
759 return $data{'borrowernumber'};
763 my ($uid,$member) = @_;
764 my $dbh = C4::Context->dbh;
765 # Make sure the userid chosen is unique and not theirs if non-empty. If it is not,
766 # Then we need to tell the user and have them create a new one.
769 "SELECT * FROM borrowers WHERE userid=? AND borrowernumber != ?");
770 $sth->execute( $uid, $member );
771 if ( ( $uid ne '' ) && ( my $row = $sth->fetchrow_hashref ) ) {
781 my ( $uid, $member, $digest ) = @_;
782 my $dbh = C4::Context->dbh;
784 #Make sure the userid chosen is unique and not theirs if non-empty. If it is not,
785 #Then we need to tell the user and have them create a new one.
789 "SELECT * FROM borrowers WHERE userid=? AND borrowernumber != ?");
790 $sth->execute( $uid, $member );
791 if ( ( $uid ne '' ) && ( my $row = $sth->fetchrow_hashref ) ) {
795 #Everything is good so we can update the information.
798 "update borrowers set userid=?, password=? where borrowernumber=?");
799 $sth->execute( $uid, $digest, $member );
803 logaction("MEMBERS", "CHANGE PASS", $member, "") if C4::Context->preference("BorrowersLog");
809 =item fixup_cardnumber
811 Warning: The caller is responsible for locking the members table in write
812 mode, to avoid database corruption.
816 use vars qw( @weightings );
817 my @weightings = ( 8, 4, 6, 3, 5, 2, 1 );
819 sub fixup_cardnumber ($) {
820 my ($cardnumber) = @_;
821 my $autonumber_members = C4::Context->boolean_preference('autoMemberNum');
822 $autonumber_members = 0 unless defined $autonumber_members;
824 # Find out whether member numbers should be generated
825 # automatically. Should be either "1" or something else.
826 # Defaults to "0", which is interpreted as "no".
828 # if ($cardnumber !~ /\S/ && $autonumber_members) {
829 if ($autonumber_members) {
830 my $dbh = C4::Context->dbh;
831 if ( C4::Context->preference('checkdigit') eq 'katipo' ) {
833 # if checkdigit is selected, calculate katipo-style cardnumber.
834 # otherwise, just use the max()
835 # purpose: generate checksum'd member numbers.
836 # We'll assume we just got the max value of digits 2-8 of member #'s
837 # from the database and our job is to increment that by one,
838 # determine the 1st and 9th digits and return the full string.
841 "select max(substring(borrowers.cardnumber,2,7)) from borrowers"
845 my $data = $sth->fetchrow_hashref;
846 $cardnumber = $data->{'max(substring(borrowers.cardnumber,2,7))'};
848 if ( !$cardnumber ) { # If DB has no values,
849 $cardnumber = 1000000; # start at 1000000
856 for ( my $i = 0 ; $i < 8 ; $i += 1 ) {
858 # read weightings, left to right, 1 char at a time
859 my $temp1 = $weightings[$i];
861 # sequence left to right, 1 char at a time
862 my $temp2 = substr( $cardnumber, $i, 1 );
864 # mult each char 1-7 by its corresponding weighting
865 $sum += $temp1 * $temp2;
868 my $rem = ( $sum % 11 );
869 $rem = 'X' if $rem == 10;
871 $cardnumber = "V$cardnumber$rem";
875 # MODIFIED BY JF: mysql4.1 allows casting as an integer, which is probably
876 # better. I'll leave the original in in case it needs to be changed for you
879 "select max(cast(cardnumber as signed)) from borrowers");
881 #my $sth=$dbh->prepare("select max(borrowers.cardnumber) from borrowers");
885 my ($result) = $sth->fetchrow;
887 $cardnumber = $result + 1;
895 ($num_children, $children_arrayref) = &GetGuarantees($parent_borrno);
896 $child0_cardno = $children_arrayref->[0]{"cardnumber"};
897 $child0_borrno = $children_arrayref->[0]{"borrowernumber"};
899 C<&GetGuarantees> takes a borrower number (e.g., that of a patron
900 with children) and looks up the borrowers who are guaranteed by that
901 borrower (i.e., the patron's children).
903 C<&GetGuarantees> returns two values: an integer giving the number of
904 borrowers guaranteed by C<$parent_borrno>, and a reference to an array
905 of references to hash, which gives the actual results.
911 my ($borrowernumber) = @_;
912 my $dbh = C4::Context->dbh;
915 "select cardnumber,borrowernumber, firstname, surname from borrowers where guarantorid=?"
917 $sth->execute($borrowernumber);
920 my $data = $sth->fetchall_arrayref({});
922 return ( scalar(@$data), $data );
925 =head2 UpdateGuarantees
927 &UpdateGuarantees($parent_borrno);
930 C<&UpdateGuarantees> borrower data for an adulte and updates all the guarantees
931 with the modified information
936 sub UpdateGuarantees {
938 my $dbh = C4::Context->dbh;
939 my ( $count, $guarantees ) = GetGuarantees( $data{'borrowernumber'} );
940 for ( my $i = 0 ; $i < $count ; $i++ ) {
943 # It looks like the $i is only being returned to handle walking through
944 # the array, which is probably better done as a foreach loop.
946 my $guaquery = qq|UPDATE borrowers
947 SET address='$data{'address'}',fax='$data{'fax'}',
948 B_city='$data{'B_city'}',mobile='$data{'mobile'}',city='$data{'city'}',phone='$data{'phone'}'
949 WHERE borrowernumber='$guarantees->[$i]->{'borrowernumber'}'
951 my $sth3 = $dbh->prepare($guaquery);
956 =head2 GetPendingIssues
958 ($count, $issues) = &GetPendingIssues($borrowernumber);
960 Looks up what the patron with the given borrowernumber has borrowed.
962 C<&GetPendingIssues> returns a two-element array. C<$issues> is a
963 reference-to-array, where each element is a reference-to-hash; the
964 keys are the fields from the C<issues>, C<biblio>, and C<items> tables
965 in the Koha database. C<$count> is the number of elements in
971 sub GetPendingIssues {
972 my ($borrowernumber) = @_;
973 my $dbh = C4::Context->dbh;
975 my $sth = $dbh->prepare(
976 "SELECT * FROM issues
977 LEFT JOIN items ON issues.itemnumber=items.itemnumber
978 LEFT JOIN biblio ON items.biblionumber=biblio.biblionumber
979 LEFT JOIN biblioitems ON items.biblioitemnumber=biblioitems.biblioitemnumber
982 ORDER BY issues.issuedate"
984 $sth->execute($borrowernumber);
985 my $data = $sth->fetchall_arrayref({});
986 my $today = POSIX::strftime("%Y%m%d", localtime);
988 my $datedue = $_->{'date_due'};
990 if ( $datedue < $today ) {
995 return ( scalar(@$data), $data );
1000 ($count, $issues) = &GetAllIssues($borrowernumber, $sortkey, $limit);
1002 Looks up what the patron with the given borrowernumber has borrowed,
1003 and sorts the results.
1005 C<$sortkey> is the name of a field on which to sort the results. This
1006 should be the name of a field in the C<issues>, C<biblio>,
1007 C<biblioitems>, or C<items> table in the Koha database.
1009 C<$limit> is the maximum number of results to return.
1011 C<&GetAllIssues> returns a two-element array. C<$issues> is a
1012 reference-to-array, where each element is a reference-to-hash; the
1013 keys are the fields from the C<issues>, C<biblio>, C<biblioitems>, and
1014 C<items> tables of the Koha database. C<$count> is the number of
1015 elements in C<$issues>
1021 my ( $borrowernumber, $order, $limit ) = @_;
1023 #FIXME: sanity-check order and limit
1024 my $dbh = C4::Context->dbh;
1027 "SELECT *,items.timestamp AS itemstimestamp
1029 LEFT JOIN items on items.itemnumber=issues.itemnumber
1030 LEFT JOIN biblio ON items.biblionumber=biblio.biblionumber
1031 LEFT JOIN biblioitems ON items.biblioitemnumber=biblioitems.biblioitemnumber
1032 WHERE borrowernumber=?
1034 SELECT *,items.timestamp AS itemstimestamp
1036 LEFT JOIN items on items.itemnumber=old_issues.itemnumber
1037 LEFT JOIN biblio ON items.biblionumber=biblio.biblionumber
1038 LEFT JOIN biblioitems ON items.biblioitemnumber=biblioitems.biblioitemnumber
1039 WHERE borrowernumber=?
1041 if ( $limit != 0 ) {
1042 $query .= " limit $limit";
1046 my $sth = $dbh->prepare($query);
1047 $sth->execute($borrowernumber, $borrowernumber);
1050 while ( my $data = $sth->fetchrow_hashref ) {
1051 $result[$i] = $data;
1056 # get all issued items for borrowernumber from oldissues table
1057 # large chunk of older issues data put into table oldissues
1058 # to speed up db calls for issuing items
1059 if ( C4::Context->preference("ReadingHistory") ) {
1060 # FIXME oldissues (not to be confused with old_issues) is
1061 # apparently specific to HLT. Not sure if the ReadingHistory
1062 # syspref is still required, as old_issues by design
1063 # is no longer checked with each loan.
1064 my $query2 = "SELECT * FROM oldissues
1065 LEFT JOIN items ON items.itemnumber=oldissues.itemnumber
1066 LEFT JOIN biblio ON items.biblionumber=biblio.biblionumber
1067 LEFT JOIN biblioitems ON items.biblioitemnumber=biblioitems.biblioitemnumber
1068 WHERE borrowernumber=?
1070 if ( $limit != 0 ) {
1071 $limit = $limit - $count;
1072 $query2 .= " limit $limit";
1075 my $sth2 = $dbh->prepare($query2);
1076 $sth2->execute($borrowernumber);
1078 while ( my $data2 = $sth2->fetchrow_hashref ) {
1079 $result[$i] = $data2;
1086 return ( $i, \@result );
1090 =head2 GetMemberAccountRecords
1092 ($total, $acctlines, $count) = &GetMemberAccountRecords($borrowernumber);
1094 Looks up accounting data for the patron with the given borrowernumber.
1096 C<&GetMemberAccountRecords> returns a three-element array. C<$acctlines> is a
1097 reference-to-array, where each element is a reference-to-hash; the
1098 keys are the fields of the C<accountlines> table in the Koha database.
1099 C<$count> is the number of elements in C<$acctlines>. C<$total> is the
1100 total amount outstanding for all of the account lines.
1105 sub GetMemberAccountRecords {
1106 my ($borrowernumber,$date) = @_;
1107 my $dbh = C4::Context->dbh;
1113 WHERE borrowernumber=?);
1114 my @bind = ($borrowernumber);
1115 if ($date && $date ne ''){
1116 $strsth.=" AND date < ? ";
1119 $strsth.=" ORDER BY date desc,timestamp DESC";
1120 my $sth= $dbh->prepare( $strsth );
1121 $sth->execute( @bind );
1123 while ( my $data = $sth->fetchrow_hashref ) {
1124 $acctlines[$numlines] = $data;
1126 $total += $data->{'amountoutstanding'};
1129 return ( $total, \@acctlines,$numlines);
1132 =head2 GetBorNotifyAcctRecord
1134 ($count, $acctlines, $total) = &GetBorNotifyAcctRecord($params,$notifyid);
1136 Looks up accounting data for the patron with the given borrowernumber per file number.
1138 (FIXME - I'm not at all sure what this is about.)
1140 C<&GetBorNotifyAcctRecord> returns a three-element array. C<$acctlines> is a
1141 reference-to-array, where each element is a reference-to-hash; the
1142 keys are the fields of the C<accountlines> table in the Koha database.
1143 C<$count> is the number of elements in C<$acctlines>. C<$total> is the
1144 total amount outstanding for all of the account lines.
1148 sub GetBorNotifyAcctRecord {
1149 my ( $borrowernumber, $notifyid ) = @_;
1150 my $dbh = C4::Context->dbh;
1153 my $sth = $dbh->prepare(
1156 WHERE borrowernumber=?
1158 AND amountoutstanding != '0'
1159 ORDER BY notify_id,accounttype
1161 # 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')
1163 $sth->execute( $borrowernumber, $notifyid );
1165 while ( my $data = $sth->fetchrow_hashref ) {
1166 $acctlines[$numlines] = $data;
1168 $total += $data->{'amountoutstanding'};
1171 return ( $total, \@acctlines, $numlines );
1174 =head2 checkuniquemember (OUEST-PROVENCE)
1176 ($result,$categorycode) = &checkuniquemember($collectivity,$surname,$firstname,$dateofbirth);
1178 Checks that a member exists or not in the database.
1180 C<&result> is nonzero (=exist) or 0 (=does not exist)
1181 C<&categorycode> is from categorycode table
1182 C<&collectivity> is 1 (= we add a collectivity) or 0 (= we add a physical member)
1183 C<&surname> is the surname
1184 C<&firstname> is the firstname (only if collectivity=0)
1185 C<&dateofbirth> is the date of birth in ISO format (only if collectivity=0)
1189 # FIXME: This function is not legitimate. Multiple patrons might have the same first/last name and birthdate.
1190 # This is especially true since first name is not even a required field.
1192 sub checkuniquemember {
1193 my ( $collectivity, $surname, $firstname, $dateofbirth ) = @_;
1194 my $dbh = C4::Context->dbh;
1195 my $request = ($collectivity) ?
1196 "SELECT borrowernumber,categorycode FROM borrowers WHERE surname=? " :
1197 "SELECT borrowernumber,categorycode FROM borrowers WHERE surname=? and firstname=? and dateofbirth=? ";
1198 my $sth = $dbh->prepare($request);
1199 if ($collectivity) {
1200 $sth->execute( uc($surname) );
1202 $sth->execute( uc($surname), ucfirst($firstname), $dateofbirth );
1204 my @data = $sth->fetchrow;
1206 ( $data[0] ) and return $data[0], $data[1];
1210 sub checkcardnumber {
1211 my ($cardnumber,$borrowernumber) = @_;
1212 my $dbh = C4::Context->dbh;
1213 my $query = "SELECT * FROM borrowers WHERE cardnumber=?";
1214 $query .= " AND borrowernumber <> ?" if ($borrowernumber);
1215 my $sth = $dbh->prepare($query);
1216 if ($borrowernumber) {
1217 $sth->execute($cardnumber,$borrowernumber);
1219 $sth->execute($cardnumber);
1221 if (my $data= $sth->fetchrow_hashref()){
1231 =head2 getzipnamecity (OUEST-PROVENCE)
1233 take all info from table city for the fields city and zip
1234 check for the name and the zip code of the city selected
1238 sub getzipnamecity {
1240 my $dbh = C4::Context->dbh;
1243 "select city_name,city_zipcode from cities where cityid=? ");
1244 $sth->execute($cityid);
1245 my @data = $sth->fetchrow;
1246 return $data[0], $data[1];
1250 =head2 getdcity (OUEST-PROVENCE)
1252 recover cityid with city_name condition
1257 my ($city_name) = @_;
1258 my $dbh = C4::Context->dbh;
1259 my $sth = $dbh->prepare("select cityid from cities where city_name=? ");
1260 $sth->execute($city_name);
1261 my $data = $sth->fetchrow;
1266 =head2 GetExpiryDate
1268 $expirydate = GetExpiryDate($categorycode, $dateenrolled);
1270 Calculate expiry date given a categorycode and starting date. Date argument must be in ISO format.
1271 Return date is also in ISO format.
1276 my ( $categorycode, $dateenrolled ) = @_;
1277 my $enrolmentperiod = 12; # reasonable default
1278 if ($categorycode) {
1279 my $dbh = C4::Context->dbh;
1280 my $sth = $dbh->prepare("select enrolmentperiod from categories where categorycode=?");
1281 $sth->execute($categorycode);
1282 $enrolmentperiod = $sth->fetchrow;
1284 # die "GetExpiryDate: for enrollmentperiod $enrolmentperiod (category '$categorycode') starting $dateenrolled.\n";
1285 my @date = split /-/,$dateenrolled;
1286 return sprintf("%04d-%02d-%02d", Add_Delta_YM(@date,0,$enrolmentperiod));
1289 =head2 checkuserpassword (OUEST-PROVENCE)
1291 check for the password and login are not used
1292 return the number of record
1293 0=> NOT USED 1=> USED
1297 sub checkuserpassword {
1298 my ( $borrowernumber, $userid, $password ) = @_;
1299 $password = md5_base64($password);
1300 my $dbh = C4::Context->dbh;
1303 "Select count(*) from borrowers where borrowernumber !=? and userid =? and password=? "
1305 $sth->execute( $borrowernumber, $userid, $password );
1306 my $number_rows = $sth->fetchrow;
1307 return $number_rows;
1311 =head2 GetborCatFromCatType
1313 ($codes_arrayref, $labels_hashref) = &GetborCatFromCatType();
1315 Looks up the different types of borrowers in the database. Returns two
1316 elements: a reference-to-array, which lists the borrower category
1317 codes, and a reference-to-hash, which maps the borrower category codes
1318 to category descriptions.
1323 sub GetborCatFromCatType {
1324 my ( $category_type, $action ) = @_;
1325 # FIXME - This API seems both limited and dangerous.
1326 my $dbh = C4::Context->dbh;
1327 my $request = qq| SELECT categorycode,description
1330 ORDER BY categorycode|;
1331 my $sth = $dbh->prepare($request);
1333 $sth->execute($category_type);
1342 while ( my $data = $sth->fetchrow_hashref ) {
1343 push @codes, $data->{'categorycode'};
1344 $labels{ $data->{'categorycode'} } = $data->{'description'};
1347 return ( \@codes, \%labels );
1350 =head2 GetBorrowercategory
1352 $hashref = &GetBorrowercategory($categorycode);
1354 Given the borrower's category code, the function returns the corresponding
1355 data hashref for a comprehensive information display.
1357 $arrayref_hashref = &GetBorrowercategory;
1358 If no category code provided, the function returns all the categories.
1362 sub GetBorrowercategory {
1364 my $dbh = C4::Context->dbh;
1368 "SELECT description,dateofbirthrequired,upperagelimit,category_type
1370 WHERE categorycode = ?"
1372 $sth->execute($catcode);
1374 $sth->fetchrow_hashref;
1379 } # sub getborrowercategory
1381 =head2 GetBorrowercategoryList
1383 $arrayref_hashref = &GetBorrowercategoryList;
1384 If no category code provided, the function returns all the categories.
1388 sub GetBorrowercategoryList {
1389 my $dbh = C4::Context->dbh;
1394 ORDER BY description"
1398 $sth->fetchall_arrayref({});
1401 } # sub getborrowercategory
1403 =head2 ethnicitycategories
1405 ($codes_arrayref, $labels_hashref) = ðnicitycategories();
1407 Looks up the different ethnic types in the database. Returns two
1408 elements: a reference-to-array, which lists the ethnicity codes, and a
1409 reference-to-hash, which maps the ethnicity codes to ethnicity
1416 sub ethnicitycategories {
1417 my $dbh = C4::Context->dbh;
1418 my $sth = $dbh->prepare("Select code,name from ethnicity order by name");
1422 while ( my $data = $sth->fetchrow_hashref ) {
1423 push @codes, $data->{'code'};
1424 $labels{ $data->{'code'} } = $data->{'name'};
1427 return ( \@codes, \%labels );
1432 $ethn_name = &fixEthnicity($ethn_code);
1434 Takes an ethnicity code (e.g., "european" or "pi") and returns the
1435 corresponding descriptive name from the C<ethnicity> table in the
1436 Koha database ("European" or "Pacific Islander").
1443 my $ethnicity = shift;
1444 return unless $ethnicity;
1445 my $dbh = C4::Context->dbh;
1446 my $sth = $dbh->prepare("Select name from ethnicity where code = ?");
1447 $sth->execute($ethnicity);
1448 my $data = $sth->fetchrow_hashref;
1450 return $data->{'name'};
1451 } # sub fixEthnicity
1455 $dateofbirth,$date = &GetAge($date);
1457 this function return the borrowers age with the value of dateofbirth
1463 my ( $date, $date_ref ) = @_;
1465 if ( not defined $date_ref ) {
1466 $date_ref = sprintf( '%04d-%02d-%02d', Today() );
1469 my ( $year1, $month1, $day1 ) = split /-/, $date;
1470 my ( $year2, $month2, $day2 ) = split /-/, $date_ref;
1472 my $age = $year2 - $year1;
1473 if ( $month1 . $day1 > $month2 . $day2 ) {
1480 =head2 get_institutions
1481 $insitutions = get_institutions();
1483 Just returns a list of all the borrowers of type I, borrownumber and name
1488 sub get_institutions {
1489 my $dbh = C4::Context->dbh();
1492 "SELECT borrowernumber,surname FROM borrowers WHERE categorycode=? ORDER BY surname"
1496 while ( my $data = $sth->fetchrow_hashref() ) {
1497 $orgs{ $data->{'borrowernumber'} } = $data;
1502 } # sub get_institutions
1504 =head2 add_member_orgs
1506 add_member_orgs($borrowernumber,$borrowernumbers);
1508 Takes a borrowernumber and a list of other borrowernumbers and inserts them into the borrowers_to_borrowers table
1513 sub add_member_orgs {
1514 my ( $borrowernumber, $otherborrowers ) = @_;
1515 my $dbh = C4::Context->dbh();
1517 "INSERT INTO borrowers_to_borrowers (borrower1,borrower2) VALUES (?,?)";
1518 my $sth = $dbh->prepare($query);
1519 foreach my $otherborrowernumber (@$otherborrowers) {
1520 $sth->execute( $borrowernumber, $otherborrowernumber );
1524 } # sub add_member_orgs
1526 =head2 GetCities (OUEST-PROVENCE)
1528 ($id_cityarrayref, $city_hashref) = &GetCities();
1530 Looks up the different city and zip in the database. Returns two
1531 elements: a reference-to-array, which lists the zip city
1532 codes, and a reference-to-hash, which maps the name of the city.
1533 WHERE =>OUEST PROVENCE OR EXTERIEUR
1539 #my ($type_city) = @_;
1540 my $dbh = C4::Context->dbh;
1541 my $query = qq|SELECT cityid,city_zipcode,city_name
1543 ORDER BY city_name|;
1544 my $sth = $dbh->prepare($query);
1546 #$sth->execute($type_city);
1550 # insert empty value to create a empty choice in cgi popup
1553 while ( my $data = $sth->fetchrow_hashref ) {
1554 push @id, $data->{'city_zipcode'}."|".$data->{'city_name'};
1555 $city{ $data->{'city_zipcode'}."|".$data->{'city_name'} } = $data->{'city_name'};
1558 #test to know if the table contain some records if no the function return nothing
1562 # all we have is the one blank row
1567 return ( \@id, \%city );
1571 =head2 GetSortDetails (OUEST-PROVENCE)
1573 ($lib) = &GetSortDetails($category,$sortvalue);
1575 Returns the authorized value details
1576 C<&$lib>return value of authorized value details
1577 C<&$sortvalue>this is the value of authorized value
1578 C<&$category>this is the value of authorized value category
1582 sub GetSortDetails {
1583 my ( $category, $sortvalue ) = @_;
1584 my $dbh = C4::Context->dbh;
1585 my $query = qq|SELECT lib
1586 FROM authorised_values
1588 AND authorised_value=? |;
1589 my $sth = $dbh->prepare($query);
1590 $sth->execute( $category, $sortvalue );
1591 my $lib = $sth->fetchrow;
1592 return ($lib) if ($lib);
1593 return ($sortvalue) unless ($lib);
1596 =head2 DeleteBorrower
1598 () = &DeleteBorrower($member);
1600 delete all data fo borrowers and add record to deletedborrowers table
1601 C<&$member>this is the borrowernumber
1605 sub MoveMemberToDeleted {
1607 my $dbh = C4::Context->dbh;
1609 $query = qq|SELECT *
1611 WHERE borrowernumber=?|;
1612 my $sth = $dbh->prepare($query);
1613 $sth->execute($member);
1614 my @data = $sth->fetchrow_array;
1617 $dbh->prepare( "INSERT INTO deletedborrowers VALUES ("
1618 . ( "?," x ( scalar(@data) - 1 ) )
1620 $sth->execute(@data);
1626 DelMember($borrowernumber);
1628 This function remove directly a borrower whitout writing it on deleteborrower.
1629 + Deletes reserves for the borrower
1634 my $dbh = C4::Context->dbh;
1635 my $borrowernumber = shift;
1636 #warn "in delmember with $borrowernumber";
1637 return unless $borrowernumber; # borrowernumber is mandatory.
1639 my $query = qq|DELETE
1641 WHERE borrowernumber=?|;
1642 my $sth = $dbh->prepare($query);
1643 $sth->execute($borrowernumber);
1648 WHERE borrowernumber = ?
1650 $sth = $dbh->prepare($query);
1651 $sth->execute($borrowernumber);
1653 logaction("MEMBERS", "DELETE", $borrowernumber, "") if C4::Context->preference("BorrowersLog");
1657 =head2 ExtendMemberSubscriptionTo (OUEST-PROVENCE)
1659 $date = ExtendMemberSubscriptionTo($borrowerid, $date);
1661 Extending the subscription to a given date or to the expiry date calculated on ISO date.
1666 sub ExtendMemberSubscriptionTo {
1667 my ( $borrowerid,$date) = @_;
1668 my $dbh = C4::Context->dbh;
1669 my $borrower = GetMember($borrowerid,'borrowernumber');
1671 $date=POSIX::strftime("%Y-%m-%d",localtime());
1672 my $borrower = GetMember($borrowerid,'borrowernumber');
1673 $date = GetExpiryDate( $borrower->{'categorycode'}, $date );
1675 my $sth = $dbh->do(<<EOF);
1677 SET dateexpiry='$date'
1678 WHERE borrowernumber='$borrowerid'
1680 # add enrolmentfee if needed
1681 $sth = $dbh->prepare("SELECT enrolmentfee FROM categories WHERE categorycode=?");
1682 $sth->execute($borrower->{'categorycode'});
1683 my ($enrolmentfee) = $sth->fetchrow;
1684 if ($enrolmentfee) {
1685 # insert fee in patron debts
1686 manualinvoice($borrower->{'borrowernumber'}, '', '', 'A', $enrolmentfee);
1688 return $date if ($sth);
1692 =head2 GetRoadTypes (OUEST-PROVENCE)
1694 ($idroadtypearrayref, $roadttype_hashref) = &GetRoadTypes();
1696 Looks up the different road type . Returns two
1697 elements: a reference-to-array, which lists the id_roadtype
1698 codes, and a reference-to-hash, which maps the road type of the road .
1703 my $dbh = C4::Context->dbh;
1705 SELECT roadtypeid,road_type
1707 ORDER BY road_type|;
1708 my $sth = $dbh->prepare($query);
1713 # insert empty value to create a empty choice in cgi popup
1715 while ( my $data = $sth->fetchrow_hashref ) {
1717 push @id, $data->{'roadtypeid'};
1718 $roadtype{ $data->{'roadtypeid'} } = $data->{'road_type'};
1721 #test to know if the table contain some records if no the function return nothing
1729 return ( \@id, \%roadtype );
1735 =head2 GetTitles (OUEST-PROVENCE)
1737 ($borrowertitle)= &GetTitles();
1739 Looks up the different title . Returns array with all borrowers title
1744 my @borrowerTitle = split /,|\|/,C4::Context->preference('BorrowersTitles');
1745 unshift( @borrowerTitle, "" );
1746 my $count=@borrowerTitle;
1751 return ( \@borrowerTitle);
1755 =head2 GetPatronImage
1757 my ($imagedata, $dberror) = GetPatronImage($cardnumber);
1759 Returns the mimetype and binary image data of the image for the patron with the supplied cardnumber.
1763 sub GetPatronImage {
1764 my ($cardnumber) = @_;
1765 warn "Cardnumber passed to GetPatronImage is $cardnumber" if $debug;
1766 my $dbh = C4::Context->dbh;
1767 my $query = "SELECT mimetype, imagefile FROM patronimage WHERE cardnumber = ?;";
1768 my $sth = $dbh->prepare($query);
1769 $sth->execute($cardnumber);
1770 my $imagedata = $sth->fetchrow_hashref;
1771 my $dberror = $sth->errstr;
1772 warn "Database error!" if $sth->errstr;
1774 return $imagedata, $dberror;
1777 =head2 PutPatronImage
1779 PutPatronImage($cardnumber, $mimetype, $imgfile);
1781 Stores patron binary image data and mimetype in database.
1782 NOTE: This function is good for updating images as well as inserting new images in the database.
1786 sub PutPatronImage {
1787 my ($cardnumber, $mimetype, $imgfile) = @_;
1788 warn "Parameters passed in: Cardnumber=$cardnumber, Mimetype=$mimetype, " . ($imgfile ? "Imagefile" : "No Imagefile") if $debug;
1789 my $dbh = C4::Context->dbh;
1790 my $query = "INSERT INTO patronimage (cardnumber, mimetype, imagefile) VALUES (?,?,?) ON DUPLICATE KEY UPDATE imagefile = ?;";
1791 my $sth = $dbh->prepare($query);
1792 $sth->execute($cardnumber,$mimetype,$imgfile,$imgfile);
1793 warn "Error returned inserting $cardnumber.$mimetype." if $sth->errstr;
1794 my $dberror = $sth->errstr;
1799 =head2 RmPatronImage
1801 my ($dberror) = RmPatronImage($cardnumber);
1803 Removes the image for the patron with the supplied cardnumber.
1808 my ($cardnumber) = @_;
1809 warn "Cardnumber passed to GetPatronImage is $cardnumber" if $debug;
1810 my $dbh = C4::Context->dbh;
1811 my $query = "DELETE FROM patronimage WHERE cardnumber = ?;";
1812 my $sth = $dbh->prepare($query);
1813 $sth->execute($cardnumber);
1814 my $dberror = $sth->errstr;
1815 warn "Database error!" if $sth->errstr;
1820 =head2 GetRoadTypeDetails (OUEST-PROVENCE)
1822 ($roadtype) = &GetRoadTypeDetails($roadtypeid);
1824 Returns the description of roadtype
1825 C<&$roadtype>return description of road type
1826 C<&$roadtypeid>this is the value of roadtype s
1830 sub GetRoadTypeDetails {
1831 my ($roadtypeid) = @_;
1832 my $dbh = C4::Context->dbh;
1836 WHERE roadtypeid=?|;
1837 my $sth = $dbh->prepare($query);
1838 $sth->execute($roadtypeid);
1839 my $roadtype = $sth->fetchrow;
1843 =head2 GetBorrowersWhoHaveNotBorrowedSince
1845 &GetBorrowersWhoHaveNotBorrowedSince($date)
1847 this function get all borrowers who haven't borrowed since the date given on input arg.
1851 sub GetBorrowersWhoHaveNotBorrowedSince {
1852 ### TODO : It could be dangerous to delete Borrowers who have just been entered and who have not yet borrowed any book. May be good to add a dateexpiry or dateenrolled filter.
1854 my $filterdate = shift||POSIX::strftime("%Y-%m-%d",localtime());
1855 my $filterbranch = shift ||
1856 ((C4::Context->preference('IndependantBranches')
1857 && C4::Context->userenv
1858 && C4::Context->userenv->{flags}!=1
1859 && C4::Context->userenv->{branch})
1860 ? C4::Context->userenv->{branch}
1862 my $dbh = C4::Context->dbh;
1864 SELECT borrowers.borrowernumber,max(issues.timestamp) as latestissue
1866 JOIN categories USING (categorycode)
1867 LEFT JOIN issues ON borrowers.borrowernumber = issues.borrowernumber
1868 WHERE category_type <> 'S'
1871 if ($filterbranch && $filterbranch ne ""){
1872 $query.=" AND borrowers.branchcode= ?";
1873 push @query_params,$filterbranch;
1875 $query.=" GROUP BY borrowers.borrowernumber";
1877 $query.=" HAVING latestissue <? OR latestissue IS NULL";
1878 push @query_params,$filterdate;
1880 warn $query if $debug;
1881 my $sth = $dbh->prepare($query);
1882 if (scalar(@query_params)>0){
1883 $sth->execute(@query_params);
1890 while ( my $data = $sth->fetchrow_hashref ) {
1891 push @results, $data;
1896 =head2 GetBorrowersWhoHaveNeverBorrowed
1898 $results = &GetBorrowersWhoHaveNeverBorrowed
1900 this function get all borrowers who have never borrowed.
1902 I<$result> is a ref to an array which all elements are a hasref.
1906 sub GetBorrowersWhoHaveNeverBorrowed {
1907 my $filterbranch = shift ||
1908 ((C4::Context->preference('IndependantBranches')
1909 && C4::Context->userenv
1910 && C4::Context->userenv->{flags}!=1
1911 && C4::Context->userenv->{branch})
1912 ? C4::Context->userenv->{branch}
1914 my $dbh = C4::Context->dbh;
1916 SELECT borrowers.borrowernumber,max(timestamp) as latestissue
1918 LEFT JOIN issues ON borrowers.borrowernumber = issues.borrowernumber
1919 WHERE issues.borrowernumber IS NULL
1922 if ($filterbranch && $filterbranch ne ""){
1923 $query.=" AND borrowers.branchcode= ?";
1924 push @query_params,$filterbranch;
1926 warn $query if $debug;
1928 my $sth = $dbh->prepare($query);
1929 if (scalar(@query_params)>0){
1930 $sth->execute(@query_params);
1937 while ( my $data = $sth->fetchrow_hashref ) {
1938 push @results, $data;
1943 =head2 GetBorrowersWithIssuesHistoryOlderThan
1945 $results = &GetBorrowersWithIssuesHistoryOlderThan($date)
1947 this function get all borrowers who has an issue history older than I<$date> given on input arg.
1949 I<$result> is a ref to an array which all elements are a hashref.
1950 This hashref is containt the number of time this borrowers has borrowed before I<$date> and the borrowernumber.
1954 sub GetBorrowersWithIssuesHistoryOlderThan {
1955 my $dbh = C4::Context->dbh;
1956 my $date = shift ||POSIX::strftime("%Y-%m-%d",localtime());
1957 my $filterbranch = shift ||
1958 ((C4::Context->preference('IndependantBranches')
1959 && C4::Context->userenv
1960 && C4::Context->userenv->{flags}!=1
1961 && C4::Context->userenv->{branch})
1962 ? C4::Context->userenv->{branch}
1965 SELECT count(borrowernumber) as n,borrowernumber
1967 WHERE returndate < ?
1968 AND borrowernumber IS NOT NULL
1971 push @query_params, $date;
1973 $query.=" AND branchcode = ?";
1974 push @query_params, $filterbranch;
1976 $query.=" GROUP BY borrowernumber ";
1977 warn $query if $debug;
1978 my $sth = $dbh->prepare($query);
1979 $sth->execute(@query_params);
1982 while ( my $data = $sth->fetchrow_hashref ) {
1983 push @results, $data;
1988 =head2 GetBorrowersNamesAndLatestIssue
1990 $results = &GetBorrowersNamesAndLatestIssueList(@borrowernumbers)
1992 this function get borrowers Names and surnames and Issue information.
1994 I<@borrowernumbers> is an array which all elements are borrowernumbers.
1995 This hashref is containt the number of time this borrowers has borrowed before I<$date> and the borrowernumber.
1999 sub GetBorrowersNamesAndLatestIssue {
2000 my $dbh = C4::Context->dbh;
2001 my @borrowernumbers=@_;
2003 SELECT surname,lastname, phone, email,max(timestamp)
2005 LEFT JOIN issues ON borrowers.borrowernumber=issues.borrowernumber
2006 GROUP BY borrowernumber
2008 my $sth = $dbh->prepare($query);
2010 my $results = $sth->fetchall_arrayref({});
2013 END { } # module clean-up code here (global destructor)