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
26 use Digest::MD5 qw(md5_base64);
27 use Date::Calc qw/Today Add_Delta_YM/;
28 use C4::Log; # logaction
32 our ($VERSION,@ISA,@EXPORT,@EXPORT_OK);
34 $VERSION = do { my @v = '$Revision$' =~ /\d+/g; shift(@v) . "." . join( "_", map { sprintf "%03d", $_ } @v ); };
38 C4::Members - Perl Module containing convenience functions for member handling
46 This module contains routines for adding, modifying and deleting members/patrons/borrowers
64 &GetMemberIssuesAndFines
79 &GetMemberAccountRecords
80 &GetBorNotifyAcctRecord
86 &GetBorrowersWhoHaveNotBorrowedSince
87 &GetBorrowersWhoHaveNeverBorrowed
88 &GetBorrowersWithIssuesHistoryOlderThan
109 &ExtendMemberSubscriptionTo
125 ($count, $borrowers) = &SearchMember($searchstring, $type,$category_type);
127 Looks up patrons (borrowers) by name.
129 BUGFIX 499: C<$type> is now used to determine type of search.
130 if $type is "simple", search is performed on the first letter of the
133 $category_type is used to get a specified type of user.
134 (mainly adults when creating a child.)
136 C<$searchstring> is a space-separated list of search terms. Each term
137 must match the beginning a borrower's surname, first name, or other
140 C<&SearchMember> returns a two-element list. C<$borrowers> is a
141 reference-to-array; each element is a reference-to-hash, whose keys
142 are the fields of the C<borrowers> table in the Koha database.
143 C<$count> is the number of elements in C<$borrowers>.
148 #used by member enquiries from the intranet
151 my ($searchstring, $orderby, $type,$category_type ) = @_;
152 my $dbh = C4::Context->dbh;
158 if ( $type eq "simple" ) # simple search for one letter only
161 "SELECT * FROM borrowers
162 LEFT JOIN categories ON borrowers.categorycode=categories.categorycode ".
163 ($category_type?" AND category_type = ".$dbh->quote($category_type):"").
164 " WHERE surname LIKE ? OR cardnumber like ? ORDER BY $orderby";
165 @bind = ("$searchstring%","$searchstring");
167 else # advanced search looking in surname, firstname and othernames
169 @data = split( ' ', $searchstring );
171 $query = "SELECT * FROM borrowers
172 LEFT JOIN categories ON borrowers.categorycode=categories.categorycode
173 WHERE ((surname LIKE ? OR surname LIKE ?
174 OR firstname LIKE ? OR firstname LIKE ?
175 OR othernames LIKE ? OR othernames LIKE ?)
177 ($category_type?" AND category_type = ".$dbh->quote($category_type):"");
179 "$data[0]%", "% $data[0]%", "$data[0]%", "% $data[0]%",
180 "$data[0]%", "% $data[0]%"
182 for ( my $i = 1 ; $i < $count ; $i++ ) {
183 $query = $query . " AND (" . " surname LIKE ? OR surname LIKE ?
184 OR firstname LIKE ? OR firstname LIKE ?
185 OR othernames LIKE ? OR othernames LIKE ?)";
187 "$data[$i]%", "% $data[$i]%", "$data[$i]%",
188 "% $data[$i]%", "$data[$i]%", "% $data[$i]%" );
192 $query = $query . ") OR cardnumber LIKE ?
194 push( @bind, $searchstring );
199 my $sth = $dbh->prepare($query);
201 # warn "Q $orderby : $query";
202 $sth->execute(@bind);
204 my $data = $sth->fetchall_arrayref({});
207 return ( scalar(@$data), $data );
210 =head2 GetMemberDetails
212 ($borrower, $flags) = &GetMemberDetails($borrowernumber, $cardnumber);
214 Looks up a patron and returns information about him or her. If
215 C<$borrowernumber> is true (nonzero), C<&GetMemberDetails> looks
216 up the borrower by number; otherwise, it looks up the borrower by card
219 C<$borrower> is a reference-to-hash whose keys are the fields of the
220 borrowers table in the Koha database. In addition,
221 C<$borrower-E<gt>{flags}> is a hash giving more detailed information
222 about the patron. Its keys act as flags :
224 if $borrower->{flags}->{LOST} {
225 # Patron's card was reported lost
228 Each flag has a C<message> key, giving a human-readable explanation of
229 the flag. If the state of a flag means that the patron should not be
230 allowed to borrow any more books, then it will have a C<noissues> key
233 The possible flags are:
239 =item Shows the patron's credit or debt, if any.
247 =item (Gone, no address.) Set if the patron has left without giving a
256 =item Set if the patron's card has been reported as lost.
264 =item Set if the patron has been debarred.
272 =item Any additional notes about the patron.
280 =item Set if the patron has overdue items. This flag has several keys:
282 C<$flags-E<gt>{ODUES}{itemlist}> is a reference-to-array listing the
283 overdue items. Its elements are references-to-hash, each describing an
284 overdue item. The keys are selected fields from the issues, biblio,
285 biblioitems, and items tables of the Koha database.
287 C<$flags-E<gt>{ODUES}{itemlist}> is a string giving a text listing of
288 the overdue items, one per line.
296 =item Set if any items that the patron has reserved are available.
298 C<$flags-E<gt>{WAITING}{itemlist}> is a reference-to-array listing the
299 available items. Each element is a reference-to-hash whose keys are
300 fields from the reserves table of the Koha database.
306 sub GetMemberDetails {
307 my ( $borrowernumber, $cardnumber ) = @_;
308 my $dbh = C4::Context->dbh;
311 if ($borrowernumber) {
312 $sth = $dbh->prepare("select * from borrowers where borrowernumber=?");
313 $sth->execute($borrowernumber);
315 elsif ($cardnumber) {
316 $sth = $dbh->prepare("select * from borrowers where cardnumber=?");
317 $sth->execute($cardnumber);
322 my $borrower = $sth->fetchrow_hashref;
323 my ($amount) = GetMemberAccountRecords( $borrowernumber);
324 $borrower->{'amountoutstanding'} = $amount;
325 my $flags = patronflags( $borrower);
328 $sth = $dbh->prepare("select bit,flag from userflags");
330 while ( my ( $bit, $flag ) = $sth->fetchrow ) {
331 if ( $borrower->{'flags'} && $borrower->{'flags'} & 2**$bit ) {
332 $accessflagshash->{$flag} = 1;
336 $borrower->{'flags'} = $flags;
337 $borrower->{'authflags'} = $accessflagshash;
339 # find out how long the membership lasts
342 "select enrolmentperiod from categories where categorycode = ?");
343 $sth->execute( $borrower->{'categorycode'} );
344 my $enrolment = $sth->fetchrow;
345 $borrower->{'enrolmentperiod'} = $enrolment;
346 return ($borrower); #, $flags, $accessflagshash);
353 NOTE!: If you change this function, be sure to update the POD for
356 $flags = &patronflags($patron);
359 {message} Message showing patron's credit or debt
360 {noissues} Set if patron owes >$5.00
361 {GNA} Set if patron gone w/o address
362 {message} "Borrower has no valid address"
364 {LOST} Set if patron's card reported lost
365 {message} Message to this effect
367 {DBARRED} Set is patron is debarred
368 {message} Message to this effect
370 {NOTES} Set if patron has notes
371 {message} Notes about patron
372 {ODUES} Set if patron has overdue books
374 {itemlist} ref-to-array: list of overdue books
375 {itemlisttext} Text list of overdue items
376 {WAITING} Set if there are items available that the
378 {message} Message to this effect
379 {itemlist} ref-to-array: list of available items
385 my ( $patroninformation) = @_;
386 my $dbh=C4::Context->dbh;
387 my ($amount) = GetMemberAccountRecords( $patroninformation->{'borrowernumber'});
390 my $noissuescharge = C4::Context->preference("noissuescharge");
391 $flaginfo{'message'} = sprintf "Patron owes \$%.02f", $amount;
392 if ( $amount > $noissuescharge ) {
393 $flaginfo{'noissues'} = 1;
395 $flags{'CHARGES'} = \%flaginfo;
397 elsif ( $amount < 0 ) {
399 $flaginfo{'message'} = sprintf "Patron has credit of \$%.02f", -$amount;
400 $flags{'CHARGES'} = \%flaginfo;
402 if ( $patroninformation->{'gonenoaddress'}
403 && $patroninformation->{'gonenoaddress'} == 1 )
406 $flaginfo{'message'} = 'Borrower has no valid address.';
407 $flaginfo{'noissues'} = 1;
408 $flags{'GNA'} = \%flaginfo;
410 if ( $patroninformation->{'lost'} && $patroninformation->{'lost'} == 1 ) {
412 $flaginfo{'message'} = 'Borrower\'s card reported lost.';
413 $flaginfo{'noissues'} = 1;
414 $flags{'LOST'} = \%flaginfo;
416 if ( $patroninformation->{'debarred'}
417 && $patroninformation->{'debarred'} == 1 )
420 $flaginfo{'message'} = 'Borrower is Debarred.';
421 $flaginfo{'noissues'} = 1;
422 $flags{'DBARRED'} = \%flaginfo;
424 if ( $patroninformation->{'borrowernotes'}
425 && $patroninformation->{'borrowernotes'} )
428 $flaginfo{'message'} = "$patroninformation->{'borrowernotes'}";
429 $flags{'NOTES'} = \%flaginfo;
431 my ( $odues, $itemsoverdue ) =
432 checkoverdues( $patroninformation->{'borrowernumber'}, $dbh );
435 $flaginfo{'message'} = "Yes";
436 $flaginfo{'itemlist'} = $itemsoverdue;
437 foreach ( sort { $a->{'date_due'} cmp $b->{'date_due'} }
440 $flaginfo{'itemlisttext'} .=
441 "$_->{'date_due'} $_->{'barcode'} $_->{'title'} \n";
443 $flags{'ODUES'} = \%flaginfo;
445 my @itemswaiting = C4::Reserves::GetReservesFromBorrowernumber( $patroninformation->{'borrowernumber'},'W' );
446 my $nowaiting = scalar @itemswaiting;
447 if ( $nowaiting > 0 ) {
449 $flaginfo{'message'} = "Reserved items available";
450 $flaginfo{'itemlist'} = \@itemswaiting;
451 $flags{'WAITING'} = \%flaginfo;
459 $borrower = &GetMember($information, $type);
461 Looks up information about a patron (borrower) by either card number
462 ,firstname, or borrower number, depending on $type value.
463 If C<$type> == 'cardnumber', C<&GetBorrower>
464 searches by cardnumber then by firstname if not found in cardnumber;
465 otherwise, it searches by borrowernumber.
467 C<&GetBorrower> returns a reference-to-hash whose keys are the fields of
468 the C<borrowers> table in the Koha database.
474 my ( $information, $type ) = @_;
475 my $dbh = C4::Context->dbh;
477 if ($type eq 'cardnumber' || $type eq 'firstname'|| $type eq 'userid'|| $type eq 'borrowernumber'){
478 $information = uc $information;
481 "Select borrowers.*,categories.category_type,categories.description from borrowers left join categories on borrowers.categorycode=categories.categorycode where $type=?"
483 $sth->execute($information);
488 "Select borrowers.*,categories.category_type, categories.description from borrowers left join categories on borrowers.categorycode=categories.categorycode where borrowernumber=?"
490 $sth->execute($information);
492 my $data = $sth->fetchrow_hashref;
498 elsif ($type eq 'cardnumber' ||$type eq 'firstname') { # try with firstname
501 "Select borrowers.*,categories.category_type,categories.description from borrowers left join categories on borrowers.categorycode=categories.categorycode where firstname like ?"
503 $sth->execute($information);
504 my $data = $sth->fetchrow_hashref;
513 =item GetMemberIssuesAndFines
515 ($borrowed, $due, $fine) = &GetMemberIssuesAndFines($borrowernumber);
517 Returns aggregate data about items borrowed by the patron with the
518 given borrowernumber.
520 C<&GetMemberIssuesAndFines> returns a three-element array. C<$borrowed> is the
521 number of books the patron currently has borrowed. C<$due> is the
522 number of overdue items the patron currently has borrowed. C<$fine> is
523 the total fine currently due by the borrower.
528 sub GetMemberIssuesAndFines {
529 my ( $borrowernumber ) = @_;
530 my $dbh = C4::Context->dbh;
532 "Select count(*) from issues where borrowernumber='$borrowernumber' and
536 my $sth = $dbh->prepare($query);
538 my $data = $sth->fetchrow_hashref;
540 $sth = $dbh->prepare(
541 "Select count(*) from issues where
542 borrowernumber='$borrowernumber' and date_due < now() and returndate is NULL"
545 my $data2 = $sth->fetchrow_hashref;
547 $sth = $dbh->prepare(
548 "Select sum(amountoutstanding) from accountlines where
549 borrowernumber='$borrowernumber'"
552 my $data3 = $sth->fetchrow_hashref;
555 return ( $data2->{'count(*)'}, $data->{'count(*)'},
556 $data3->{'sum(amountoutstanding)'} );
563 &ModMember($borrowernumber);
565 Modify borrower's data
572 my $dbh = C4::Context->dbh;
573 $data{'dateofbirth'} = format_date_in_iso( $data{'dateofbirth'} ) if ($data{'dateofbirth'} );
574 $data{'dateexpiry'} = format_date_in_iso( $data{'dateexpiry'} ) if ($data{'dateexpiry'} );
575 $data{'dateenrolled'} = format_date_in_iso( $data{'dateenrolled'} ) if ($data{'dateenrolled'} );
576 # warn Data::Dumper::Dumper(%data);
577 # warn "num user".$data{'borrowernumber'};
578 my $qborrower=$dbh->prepare("SHOW columns from borrowers");
580 my %hashborrowerfields;
581 while (my ($field)=$qborrower->fetchrow){
582 $hashborrowerfields{$field}=1;
586 $data{'userid'} = '' if ( $data{'password'} eq '' );
589 # test to know if u must update or not the borrower password
590 if ( $data{'password'} eq '****' ) {
591 delete $data{'password'};
593 {push @parameters,"$_ = ".$dbh->quote($data{$_}) if ($_ ne "borrowernumber" and $hashborrowerfields{$_}) } ;
594 $query = "UPDATE borrowers SET ".join (",",@parameters)
595 ." WHERE borrowernumber=$data{'borrowernumber'}";
597 $sth = $dbh->prepare($query);
601 $data{'password'} = md5_base64( $data{'password'} ) if ( $data{'password'} ne '' );
602 delete $data{'password'} if ($data{password} eq "");
604 {push @parameters,"$_ = ".$dbh->quote($data{$_}) if ($_ ne "borrowernumber" and $hashborrowerfields{$_})} ;
606 $query = "UPDATE borrowers SET ".join (",",@parameters)." WHERE borrowernumber=$data{'borrowernumber'}";
608 $sth = $dbh->prepare($query);
613 # ok if its an adult (type) it may have borrowers that depend on it as a guarantor
614 # so when we update information for an adult we should check for guarantees and update the relevant part
615 # of their records, ie addresses and phone numbers
616 my $borrowercategory= GetBorrowercategory( $data{'category_type'} );
617 if ( $borrowercategory->{'category_type'} eq 'A' ) {
618 # is adult check guarantees;
619 UpdateGuarantees(%data);
622 &logaction(C4::Context->userenv->{'number'},"MEMBERS","MODIFY",$data{'borrowernumber'},"")
623 if C4::Context->preference("BorrowersLog");
631 $borrowernumber = &AddMember(%borrower);
633 insert new borrower into table
634 Returns the borrowernumber
641 my $dbh = C4::Context->dbh;
642 $data{'userid'} = '' unless $data{'password'};
643 $data{'password'} = md5_base64( $data{'password'} ) if $data{'password'};
644 $data{'dateofbirth'} = format_date_in_iso( $data{'dateofbirth'} );
645 $data{'dateenrolled'} = format_date_in_iso( $data{'dateenrolled'} );
646 $data{'dateexpiry'} = format_date_in_iso( $data{'dateexpiry'} );
648 "insert into borrowers set cardnumber="
649 . $dbh->quote( $data{'cardnumber'} )
651 . $dbh->quote( $data{'surname'} )
653 . $dbh->quote( $data{'firstname'} )
655 . $dbh->quote( $data{'title'} )
657 . $dbh->quote( $data{'othernames'} )
659 . $dbh->quote( $data{'initials'} )
661 . $dbh->quote( $data{'streetnumber'} )
663 . $dbh->quote( $data{'streettype'} )
665 . $dbh->quote( $data{'address'} )
667 . $dbh->quote( $data{'address2'} )
669 . $dbh->quote( $data{'zipcode'} )
671 . $dbh->quote( $data{'city'} )
673 . $dbh->quote( $data{'phone'} )
675 . $dbh->quote( $data{'email'} )
677 . $dbh->quote( $data{'mobile'} )
679 . $dbh->quote( $data{'phonepro'} )
681 . $dbh->quote( $data{'opacnote'} )
683 . $dbh->quote( $data{'guarantorid'} )
685 . $dbh->quote( $data{'dateofbirth'} )
687 . $dbh->quote( $data{'branchcode'} )
689 . $dbh->quote( $data{'categorycode'} )
691 . $dbh->quote( $data{'dateenrolled'} )
693 . $dbh->quote( $data{'contactname'} )
695 . $dbh->quote( $data{'borrowernotes'} )
697 . $dbh->quote( $data{'dateexpiry'} )
699 . $dbh->quote( $data{'contactnote'} )
701 . $dbh->quote( $data{'B_address'} )
703 . $dbh->quote( $data{'B_zipcode'} )
705 . $dbh->quote( $data{'B_city'} )
707 . $dbh->quote( $data{'B_phone'} )
709 . $dbh->quote( $data{'B_email'}, )
711 . $dbh->quote( $data{'password'} )
713 . $dbh->quote( $data{'userid'} )
715 . $dbh->quote( $data{'sort1'} )
717 . $dbh->quote( $data{'sort2'} )
719 . $dbh->quote( $data{'contacttitle'} )
721 . $dbh->quote( $data{'emailpro'} )
722 . ",contactfirstname="
723 . $dbh->quote( $data{'contactfirstname'} ) . ",sex="
724 . $dbh->quote( $data{'sex'} ) . ",fax="
725 . $dbh->quote( $data{'fax'} )
727 . $dbh->quote( $data{'relationship'} )
729 . $dbh->quote( $data{'B_streetnumber'} )
731 . $dbh->quote( $data{'B_streettype'} )
733 . $dbh->quote( $data{'gonenoaddress'} )
735 . $dbh->quote( $data{'lost'} )
737 . $dbh->quote( $data{'debarred'} )
739 . $dbh->quote( $data{'ethnicity'} )
741 . $dbh->quote( $data{'ethnotes'} );
743 my $sth = $dbh->prepare($query);
746 $data{'borrowernumber'} = $dbh->{'mysql_insertid'};
748 &logaction(C4::Context->userenv->{'number'},"MEMBERS","CREATE",$data{'borrowernumber'},"")
749 if C4::Context->preference("BorrowersLog");
751 return $data{'borrowernumber'};
755 my ($uid,$member) = @_;
756 my $dbh = C4::Context->dbh;
757 # Make sure the userid chosen is unique and not theirs if non-empty. If it is not,
758 # Then we need to tell the user and have them create a new one.
761 "SELECT * FROM borrowers WHERE userid=? AND borrowernumber != ?");
762 $sth->execute( $uid, $member );
763 if ( ( $uid ne '' ) && ( my $row = $sth->fetchrow_hashref ) ) {
773 my ( $uid, $member, $digest ) = @_;
774 my $dbh = C4::Context->dbh;
776 #Make sure the userid chosen is unique and not theirs if non-empty. If it is not,
777 #Then we need to tell the user and have them create a new one.
780 "SELECT * FROM borrowers WHERE userid=? AND borrowernumber != ?");
781 $sth->execute( $uid, $member );
782 if ( ( $uid ne '' ) && ( my $row = $sth->fetchrow_hashref ) ) {
786 #Everything is good so we can update the information.
789 "update borrowers set userid=?, password=? where borrowernumber=?");
790 $sth->execute( $uid, $digest, $member );
794 &logaction(C4::Context->userenv->{'number'},"MEMBERS","CHANGE PASS",$member,"")
795 if C4::Context->preference("BorrowersLog");
800 =item fixup_cardnumber
802 Warning: The caller is responsible for locking the members table in write
803 mode, to avoid database corruption.
807 use vars qw( @weightings );
808 my @weightings = ( 8, 4, 6, 3, 5, 2, 1 );
810 sub fixup_cardnumber ($) {
811 my ($cardnumber) = @_;
812 my $autonumber_members = C4::Context->boolean_preference('autoMemberNum');
813 $autonumber_members = 0 unless defined $autonumber_members;
815 # Find out whether member numbers should be generated
816 # automatically. Should be either "1" or something else.
817 # Defaults to "0", which is interpreted as "no".
819 # if ($cardnumber !~ /\S/ && $autonumber_members) {
820 if ($autonumber_members) {
821 my $dbh = C4::Context->dbh;
822 if ( C4::Context->preference('checkdigit') eq 'katipo' ) {
824 # if checkdigit is selected, calculate katipo-style cardnumber.
825 # otherwise, just use the max()
826 # purpose: generate checksum'd member numbers.
827 # We'll assume we just got the max value of digits 2-8 of member #'s
828 # from the database and our job is to increment that by one,
829 # determine the 1st and 9th digits and return the full string.
832 "select max(substring(borrowers.cardnumber,2,7)) from borrowers"
836 my $data = $sth->fetchrow_hashref;
837 $cardnumber = $data->{'max(substring(borrowers.cardnumber,2,7))'};
839 if ( !$cardnumber ) { # If DB has no values,
840 $cardnumber = 1000000; # start at 1000000
847 for ( my $i = 0 ; $i < 8 ; $i += 1 ) {
849 # read weightings, left to right, 1 char at a time
850 my $temp1 = $weightings[$i];
852 # sequence left to right, 1 char at a time
853 my $temp2 = substr( $cardnumber, $i, 1 );
855 # mult each char 1-7 by its corresponding weighting
856 $sum += $temp1 * $temp2;
859 my $rem = ( $sum % 11 );
860 $rem = 'X' if $rem == 10;
862 $cardnumber = "V$cardnumber$rem";
866 # MODIFIED BY JF: mysql4.1 allows casting as an integer, which is probably
867 # better. I'll leave the original in in case it needs to be changed for you
870 "select max(cast(cardnumber as signed)) from borrowers");
872 #my $sth=$dbh->prepare("select max(borrowers.cardnumber) from borrowers");
876 my ($result) = $sth->fetchrow;
878 $cardnumber = $result + 1;
886 ($num_children, $children_arrayref) = &GetGuarantees($parent_borrno);
887 $child0_cardno = $children_arrayref->[0]{"cardnumber"};
888 $child0_borrno = $children_arrayref->[0]{"borrowernumber"};
890 C<&GetGuarantees> takes a borrower number (e.g., that of a patron
891 with children) and looks up the borrowers who are guaranteed by that
892 borrower (i.e., the patron's children).
894 C<&GetGuarantees> returns two values: an integer giving the number of
895 borrowers guaranteed by C<$parent_borrno>, and a reference to an array
896 of references to hash, which gives the actual results.
902 my ($borrowernumber) = @_;
903 my $dbh = C4::Context->dbh;
906 "select cardnumber,borrowernumber, firstname, surname from borrowers where guarantorid=?"
908 $sth->execute($borrowernumber);
911 my $data = $sth->fetchall_arrayref({});
913 return ( scalar(@$data), $data );
916 =head2 UpdateGuarantees
918 &UpdateGuarantees($parent_borrno);
921 C<&UpdateGuarantees> borrower data for an adulte and updates all the guarantees
922 with the modified information
927 sub UpdateGuarantees {
929 my $dbh = C4::Context->dbh;
930 my ( $count, $guarantees ) = GetGuarantees( $data{'borrowernumber'} );
931 for ( my $i = 0 ; $i < $count ; $i++ ) {
934 # It looks like the $i is only being returned to handle walking through
935 # the array, which is probably better done as a foreach loop.
937 my $guaquery = qq|UPDATE borrowers
938 SET address='$data{'address'}',fax='$data{'fax'}',
939 B_city='$data{'B_city'}',mobile='$data{'mobile'}',city='$data{'city'}',phone='$data{'phone'}'
940 WHERE borrowernumber='$guarantees->[$i]->{'borrowernumber'}'
942 my $sth3 = $dbh->prepare($guaquery);
947 =head2 GetPendingIssues
949 ($count, $issues) = &GetPendingIssues($borrowernumber);
951 Looks up what the patron with the given borrowernumber has borrowed.
953 C<&GetPendingIssues> returns a two-element array. C<$issues> is a
954 reference-to-array, where each element is a reference-to-hash; the
955 keys are the fields from the C<issues>, C<biblio>, and C<items> tables
956 in the Koha database. C<$count> is the number of elements in
962 sub GetPendingIssues {
963 my ($borrowernumber) = @_;
964 my $dbh = C4::Context->dbh;
966 my $sth = $dbh->prepare(
967 "SELECT * FROM issues
968 LEFT JOIN items ON issues.itemnumber=items.itemnumber
969 LEFT JOIN biblio ON items.biblionumber=biblio.biblionumber
970 LEFT JOIN biblioitems ON items.biblioitemnumber=biblioitems.biblioitemnumber
973 AND returndate IS NULL
974 ORDER BY issues.issuedate"
976 $sth->execute($borrowernumber);
977 my $data = $sth->fetchall_arrayref({});
978 my $today = POSIX::strftime("%Y%m%d", localtime);
980 my $datedue = $_->{'date_due'};
982 if ( $datedue < $today ) {
987 return ( scalar(@$data), $data );
992 ($count, $issues) = &GetAllIssues($borrowernumber, $sortkey, $limit);
994 Looks up what the patron with the given borrowernumber has borrowed,
995 and sorts the results.
997 C<$sortkey> is the name of a field on which to sort the results. This
998 should be the name of a field in the C<issues>, C<biblio>,
999 C<biblioitems>, or C<items> table in the Koha database.
1001 C<$limit> is the maximum number of results to return.
1003 C<&GetAllIssues> returns a two-element array. C<$issues> is a
1004 reference-to-array, where each element is a reference-to-hash; the
1005 keys are the fields from the C<issues>, C<biblio>, C<biblioitems>, and
1006 C<items> tables of the Koha database. C<$count> is the number of
1007 elements in C<$issues>
1013 my ( $borrowernumber, $order, $limit ) = @_;
1015 #FIXME: sanity-check order and limit
1016 my $dbh = C4::Context->dbh;
1019 "Select *,items.timestamp AS itemstimestamp from
1021 LEFT JOIN items on items.itemnumber=issues.itemnumber
1022 LEFT JOIN biblio ON items.biblionumber=biblio.biblionumber
1023 LEFT JOIN biblioitems ON items.biblioitemnumber=biblioitems.biblioitemnumber
1024 where borrowernumber=?
1026 if ( $limit != 0 ) {
1027 $query .= " limit $limit";
1031 my $sth = $dbh->prepare($query);
1032 $sth->execute($borrowernumber);
1035 while ( my $data = $sth->fetchrow_hashref ) {
1036 $result[$i] = $data;
1041 # get all issued items for borrowernumber from oldissues table
1042 # large chunk of older issues data put into table oldissues
1043 # to speed up db calls for issuing items
1044 if ( C4::Context->preference("ReadingHistory") ) {
1045 my $query2 = "SELECT * FROM oldissues
1046 LEFT JOIN items ON items.itemnumber=oldissues.itemnumber
1047 LEFT JOIN biblio ON items.biblionumber=biblio.biblionumber
1048 LEFT JOIN biblioitems ON items.biblioitemnumber=biblioitems.biblioitemnumber
1049 WHERE borrowernumber=?
1051 if ( $limit != 0 ) {
1052 $limit = $limit - $count;
1053 $query2 .= " limit $limit";
1056 my $sth2 = $dbh->prepare($query2);
1057 $sth2->execute($borrowernumber);
1059 while ( my $data2 = $sth2->fetchrow_hashref ) {
1060 $result[$i] = $data2;
1067 return ( $i, \@result );
1071 =head2 GetMemberAccountRecords
1073 ($total, $acctlines, $count) = &GetMemberAccountRecords($borrowernumber);
1075 Looks up accounting data for the patron with the given borrowernumber.
1077 C<&GetMemberAccountRecords> returns a three-element array. C<$acctlines> is a
1078 reference-to-array, where each element is a reference-to-hash; the
1079 keys are the fields of the C<accountlines> table in the Koha database.
1080 C<$count> is the number of elements in C<$acctlines>. C<$total> is the
1081 total amount outstanding for all of the account lines.
1086 sub GetMemberAccountRecords {
1087 my ($borrowernumber,$date) = @_;
1088 my $dbh = C4::Context->dbh;
1094 WHERE borrowernumber=?);
1095 my @bind = ($borrowernumber);
1096 if ($date && $date ne ''){
1102 ORDER BY date desc,timestamp DESC";
1103 my $sth= $dbh->prepare( $strsth );
1104 $sth->execute( @bind );
1106 while ( my $data = $sth->fetchrow_hashref ) {
1107 $acctlines[$numlines] = $data;
1109 $total += $data->{'amountoutstanding'};
1112 return ( $total, \@acctlines,$numlines);
1115 =head2 GetBorNotifyAcctRecord
1117 ($count, $acctlines, $total) = &GetBorNotifyAcctRecord($params,$notifyid);
1119 Looks up accounting data for the patron with the given borrowernumber per file number.
1121 (FIXME - I'm not at all sure what this is about.)
1123 C<&GetBorNotifyAcctRecord> returns a three-element array. C<$acctlines> is a
1124 reference-to-array, where each element is a reference-to-hash; the
1125 keys are the fields of the C<accountlines> table in the Koha database.
1126 C<$count> is the number of elements in C<$acctlines>. C<$total> is the
1127 total amount outstanding for all of the account lines.
1131 sub GetBorNotifyAcctRecord {
1132 my ( $borrowernumber, $notifyid ) = @_;
1133 my $dbh = C4::Context->dbh;
1136 my $query = qq| SELECT *
1138 WHERE borrowernumber=?
1140 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')
1141 AND amountoutstanding != '0'
1142 ORDER BY notify_id,accounttype
1144 my $sth = $dbh->prepare($query);
1146 $sth->execute( $borrowernumber, $notifyid );
1148 while ( my $data = $sth->fetchrow_hashref ) {
1149 $acctlines[$numlines] = $data;
1151 $total += $data->{'amountoutstanding'};
1154 return ( $total, \@acctlines, $numlines );
1157 =head2 checkuniquemember (OUEST-PROVENCE)
1159 $result = &checkuniquemember($collectivity,$surname,$categorycode,$firstname,$dateofbirth);
1161 Checks that a member exists or not in the database.
1163 C<&result> is 1 (=exist) or 0 (=does not exist)
1164 C<&collectivity> is 1 (= we add a collectivity) or 0 (= we add a physical member)
1165 C<&surname> is the surname
1166 C<&categorycode> is from categorycode table
1167 C<&firstname> is the firstname (only if collectivity=0)
1168 C<&dateofbirth> is the date of birth (only if collectivity=0)
1172 sub checkuniquemember {
1173 my ( $collectivity, $surname, $firstname, $dateofbirth ) = @_;
1174 my $dbh = C4::Context->dbh;
1176 if ($collectivity) {
1178 # $request="select count(*) from borrowers where surname=? and categorycode=?";
1180 "select borrowernumber,categorycode from borrowers where surname=? ";
1184 # $request="select count(*) from borrowers where surname=? and categorycode=? and firstname=? and dateofbirth=?";
1186 "select borrowernumber,categorycode from borrowers where surname=? and firstname=? and dateofbirth=?";
1188 my $sth = $dbh->prepare($request);
1189 if ($collectivity) {
1190 $sth->execute( uc($surname) );
1193 $sth->execute( uc($surname), ucfirst($firstname), $dateofbirth );
1195 my @data = $sth->fetchrow;
1198 return $data[0], $data[1];
1208 sub checkcardnumber {
1209 my ($cardnumber) = @_;
1210 my $dbh = C4::Context->dbh;
1211 my $query = "SELECT * FROM borrowers WHERE cardnumber=?";
1212 my $sth = $dbh->prepare($query);
1213 $sth->execute($cardnumber);
1214 if (my $data= $sth->fetchrow_hashref()){
1224 =head2 getzipnamecity (OUEST-PROVENCE)
1226 take all info from table city for the fields city and zip
1227 check for the name and the zip code of the city selected
1231 sub getzipnamecity {
1233 my $dbh = C4::Context->dbh;
1236 "select city_name,city_zipcode from cities where cityid=? ");
1237 $sth->execute($cityid);
1238 my @data = $sth->fetchrow;
1239 return $data[0], $data[1];
1243 =head2 getdcity (OUEST-PROVENCE)
1245 recover cityid with city_name condition
1250 my ($city_name) = @_;
1251 my $dbh = C4::Context->dbh;
1252 my $sth = $dbh->prepare("select cityid from cities where city_name=? ");
1253 $sth->execute($city_name);
1254 my $data = $sth->fetchrow;
1259 =head2 GetExpiryDate
1261 $expirydate = GetExpiryDate($categorycode, $dateenrolled);
1262 process expiry date given a date and a categorycode
1266 my ( $categorycode, $dateenrolled ) = @_;
1267 my $dbh = C4::Context->dbh;
1270 "select enrolmentperiod from categories where categorycode=?");
1271 $sth->execute($categorycode);
1272 my ($enrolmentperiod) = $sth->fetchrow;
1273 $enrolmentperiod = 12 unless ($enrolmentperiod);
1274 my @date=split /-/,format_date_in_iso($dateenrolled);
1275 @date=Add_Delta_YM($date[0],$date[1],$date[2],0,$enrolmentperiod);
1276 return sprintf("%04d-%02d-%02d",$date[0],$date[1],$date[2]);
1279 =head2 checkuserpassword (OUEST-PROVENCE)
1281 check for the password and login are not used
1282 return the number of record
1283 0=> NOT USED 1=> USED
1287 sub checkuserpassword {
1288 my ( $borrowernumber, $userid, $password ) = @_;
1289 $password = md5_base64($password);
1290 my $dbh = C4::Context->dbh;
1293 "Select count(*) from borrowers where borrowernumber !=? and userid =? and password=? "
1295 $sth->execute( $borrowernumber, $userid, $password );
1296 my $number_rows = $sth->fetchrow;
1297 return $number_rows;
1301 =head2 GetborCatFromCatType
1303 ($codes_arrayref, $labels_hashref) = &GetborCatFromCatType();
1305 Looks up the different types of borrowers in the database. Returns two
1306 elements: a reference-to-array, which lists the borrower category
1307 codes, and a reference-to-hash, which maps the borrower category codes
1308 to category descriptions.
1313 sub GetborCatFromCatType {
1314 my ( $category_type, $action ) = @_;
1315 my $dbh = C4::Context->dbh;
1316 my $request = qq| SELECT categorycode,description
1319 ORDER BY categorycode|;
1320 my $sth = $dbh->prepare($request);
1322 $sth->execute($category_type);
1331 while ( my $data = $sth->fetchrow_hashref ) {
1332 push @codes, $data->{'categorycode'};
1333 $labels{ $data->{'categorycode'} } = $data->{'description'};
1336 return ( \@codes, \%labels );
1339 =head2 GetBorrowercategory
1341 $hashref = &GetBorrowercategory($categorycode);
1343 Given the borrower's category code, the function returns the corresponding
1344 data hashref for a comprehensive information display.
1348 sub GetBorrowercategory {
1350 my $dbh = C4::Context->dbh;
1353 "SELECT description,dateofbirthrequired,upperagelimit,category_type
1355 WHERE categorycode = ?"
1357 $sth->execute($catcode);
1359 $sth->fetchrow_hashref;
1362 } # sub getborrowercategory
1364 =head2 ethnicitycategories
1366 ($codes_arrayref, $labels_hashref) = ðnicitycategories();
1368 Looks up the different ethnic types in the database. Returns two
1369 elements: a reference-to-array, which lists the ethnicity codes, and a
1370 reference-to-hash, which maps the ethnicity codes to ethnicity
1377 sub ethnicitycategories {
1378 my $dbh = C4::Context->dbh;
1379 my $sth = $dbh->prepare("Select code,name from ethnicity order by name");
1383 while ( my $data = $sth->fetchrow_hashref ) {
1384 push @codes, $data->{'code'};
1385 $labels{ $data->{'code'} } = $data->{'name'};
1388 return ( \@codes, \%labels );
1393 $ethn_name = &fixEthnicity($ethn_code);
1395 Takes an ethnicity code (e.g., "european" or "pi") and returns the
1396 corresponding descriptive name from the C<ethnicity> table in the
1397 Koha database ("European" or "Pacific Islander").
1404 my $ethnicity = shift;
1405 return unless $ethnicity;
1406 my $dbh = C4::Context->dbh;
1407 my $sth = $dbh->prepare("Select name from ethnicity where code = ?");
1408 $sth->execute($ethnicity);
1409 my $data = $sth->fetchrow_hashref;
1411 return $data->{'name'};
1412 } # sub fixEthnicity
1416 $dateofbirth,$date = &GetAge($date);
1418 this function return the borrowers age with the value of dateofbirth
1424 my ( $date, $date_ref ) = @_;
1426 if ( not defined $date_ref ) {
1427 $date_ref = sprintf( '%04d-%02d-%02d', Today() );
1430 my ( $year1, $month1, $day1 ) = split /-/, $date;
1431 my ( $year2, $month2, $day2 ) = split /-/, $date_ref;
1433 my $age = $year2 - $year1;
1434 if ( $month1 . $day1 > $month2 . $day2 ) {
1441 =head2 get_institutions
1442 $insitutions = get_institutions();
1444 Just returns a list of all the borrowers of type I, borrownumber and name
1449 sub get_institutions {
1450 my $dbh = C4::Context->dbh();
1453 "SELECT borrowernumber,surname FROM borrowers WHERE categorycode=? ORDER BY surname"
1457 while ( my $data = $sth->fetchrow_hashref() ) {
1458 $orgs{ $data->{'borrowernumber'} } = $data;
1463 } # sub get_institutions
1465 =head2 add_member_orgs
1467 add_member_orgs($borrowernumber,$borrowernumbers);
1469 Takes a borrowernumber and a list of other borrowernumbers and inserts them into the borrowers_to_borrowers table
1474 sub add_member_orgs {
1475 my ( $borrowernumber, $otherborrowers ) = @_;
1476 my $dbh = C4::Context->dbh();
1478 "INSERT INTO borrowers_to_borrowers (borrower1,borrower2) VALUES (?,?)";
1479 my $sth = $dbh->prepare($query);
1480 foreach my $otherborrowernumber (@$otherborrowers) {
1481 $sth->execute( $borrowernumber, $otherborrowernumber );
1485 } # sub add_member_orgs
1487 =head2 GetCities (OUEST-PROVENCE)
1489 ($id_cityarrayref, $city_hashref) = &GetCities();
1491 Looks up the different city and zip in the database. Returns two
1492 elements: a reference-to-array, which lists the zip city
1493 codes, and a reference-to-hash, which maps the name of the city.
1494 WHERE =>OUEST PROVENCE OR EXTERIEUR
1500 #my ($type_city) = @_;
1501 my $dbh = C4::Context->dbh;
1502 my $query = qq|SELECT cityid,city_name
1504 ORDER BY city_name|;
1505 my $sth = $dbh->prepare($query);
1507 #$sth->execute($type_city);
1512 # insert empty value to create a empty choice in cgi popup
1514 while ( my $data = $sth->fetchrow_hashref ) {
1516 push @id, $data->{'cityid'};
1517 $city{ $data->{'cityid'} } = $data->{'city_name'};
1520 #test to know if the table contain some records if no the function return nothing
1528 return ( \@id, \%city );
1532 =head2 GetSortDetails (OUEST-PROVENCE)
1534 ($lib) = &GetSortDetails($category,$sortvalue);
1536 Returns the authorized value details
1537 C<&$lib>return value of authorized value details
1538 C<&$sortvalue>this is the value of authorized value
1539 C<&$category>this is the value of authorized value category
1543 sub GetSortDetails {
1544 my ( $category, $sortvalue ) = @_;
1545 my $dbh = C4::Context->dbh;
1546 my $query = qq|SELECT lib
1547 FROM authorised_values
1549 AND authorised_value=? |;
1550 my $sth = $dbh->prepare($query);
1551 $sth->execute( $category, $sortvalue );
1552 my $lib = $sth->fetchrow;
1556 =head2 DeleteBorrower
1558 () = &DeleteBorrower($member);
1560 delete all data fo borrowers and add record to deletedborrowers table
1561 C<&$member>this is the borrowernumber
1565 sub MoveMemberToDeleted {
1567 my $dbh = C4::Context->dbh;
1569 $query = qq|SELECT *
1571 WHERE borrowernumber=?|;
1572 my $sth = $dbh->prepare($query);
1573 $sth->execute($member);
1574 my @data = $sth->fetchrow_array;
1577 $dbh->prepare( "INSERT INTO deletedborrowers VALUES ("
1578 . ( "?," x ( scalar(@data) - 1 ) )
1580 $sth->execute(@data);
1586 DelMember($borrowernumber);
1588 This function remove directly a borrower whitout writing it on deleteborrower.
1589 + Deletes reserves for the borrower
1594 my $dbh = C4::Context->dbh;
1595 my $borrowernumber = shift;
1596 warn "in delmember with $borrowernumber";
1597 return unless $borrowernumber; # borrowernumber is mandatory.
1599 my $query = qq|DELETE
1601 WHERE borrowernumber=?|;
1602 my $sth = $dbh->prepare($query);
1603 $sth->execute($borrowernumber);
1608 WHERE borrowernumber = ?
1610 $sth = $dbh->prepare($query);
1611 $sth->execute($borrowernumber);
1613 &logaction(C4::Context->userenv->{'number'},"MEMBERS","DELETE",$borrowernumber,"")
1614 if C4::Context->preference("BorrowersLog");
1618 =head2 ExtendMemberSubscriptionTo (OUEST-PROVENCE)
1620 $date= ExtendMemberSubscriptionTo($borrowerid, $date);
1621 Extending the subscription to a given date or to the expiry date calculated on local date.
1625 sub ExtendMemberSubscriptionTo {
1626 my ( $borrowerid,$date) = @_;
1627 my $dbh = C4::Context->dbh;
1629 $date=POSIX::strftime("%Y-%m-%d",localtime(time));
1630 my $borrower = GetMember($borrowerid,'borrowernumber');
1631 $date = GetExpiryDate( $borrower->{'categorycode'}, $date );
1633 my $sth = $dbh->do(<<EOF);
1635 SET dateexpiry='$date'
1636 WHERE borrowernumber='$borrowerid'
1638 return $date if ($sth);
1642 =head2 GetRoadTypes (OUEST-PROVENCE)
1644 ($idroadtypearrayref, $roadttype_hashref) = &GetRoadTypes();
1646 Looks up the different road type . Returns two
1647 elements: a reference-to-array, which lists the id_roadtype
1648 codes, and a reference-to-hash, which maps the road type of the road .
1654 my $dbh = C4::Context->dbh;
1656 SELECT roadtypeid,road_type
1658 ORDER BY road_type|;
1659 my $sth = $dbh->prepare($query);
1664 # insert empty value to create a empty choice in cgi popup
1666 while ( my $data = $sth->fetchrow_hashref ) {
1668 push @id, $data->{'roadtypeid'};
1669 $roadtype{ $data->{'roadtypeid'} } = $data->{'road_type'};
1672 #test to know if the table contain some records if no the function return nothing
1680 return ( \@id, \%roadtype );
1686 =head2 GetTitles (OUEST-PROVENCE)
1688 ($borrowertitle)= &GetTitles();
1690 Looks up the different title . Returns array with all borrowers title
1695 my @borrowerTitle = split /,|\|/,C4::Context->preference('BorrowersTitles');
1696 unshift( @borrowerTitle, "" );
1697 return ( \@borrowerTitle);
1702 =head2 GetRoadTypeDetails (OUEST-PROVENCE)
1704 ($roadtype) = &GetRoadTypeDetails($roadtypeid);
1706 Returns the description of roadtype
1707 C<&$roadtype>return description of road type
1708 C<&$roadtypeid>this is the value of roadtype s
1712 sub GetRoadTypeDetails {
1713 my ($roadtypeid) = @_;
1714 my $dbh = C4::Context->dbh;
1718 WHERE roadtypeid=?|;
1719 my $sth = $dbh->prepare($query);
1720 $sth->execute($roadtypeid);
1721 my $roadtype = $sth->fetchrow;
1725 =head2 GetBorrowersWhoHaveNotBorrowedSince
1727 &GetBorrowersWhoHaveNotBorrowedSince($date)
1729 this function get all borrowers who haven't borrowed since the date given on input arg.
1733 sub GetBorrowersWhoHaveNotBorrowedSince {
1735 return unless $date; # date is mandatory.
1736 my $dbh = C4::Context->dbh;
1738 SELECT borrowers.borrowernumber,max(timestamp)
1740 LEFT JOIN issues ON borrowers.borrowernumber = issues.borrowernumber
1741 WHERE issues.borrowernumber IS NOT NULL
1742 GROUP BY borrowers.borrowernumber
1744 my $sth = $dbh->prepare($query);
1748 while ( my $data = $sth->fetchrow_hashref ) {
1749 push @results, $data;
1754 =head2 GetBorrowersWhoHaveNeverBorrowed
1756 $results = &GetBorrowersWhoHaveNeverBorrowed
1758 this function get all borrowers who have never borrowed.
1760 I<$result> is a ref to an array which all elements are a hasref.
1764 sub GetBorrowersWhoHaveNeverBorrowed {
1765 my $dbh = C4::Context->dbh;
1767 SELECT borrowers.borrowernumber,max(timestamp)
1769 LEFT JOIN issues ON borrowers.borrowernumber = issues.borrowernumber
1770 WHERE issues.borrowernumber IS NULL
1772 my $sth = $dbh->prepare($query);
1775 while ( my $data = $sth->fetchrow_hashref ) {
1776 push @results, $data;
1781 =head2 GetBorrowersWithIssuesHistoryOlderThan
1783 $results = &GetBorrowersWithIssuesHistoryOlderThan($date)
1785 this function get all borrowers who has an issue history older than I<$date> given on input arg.
1787 I<$result> is a ref to an array which all elements are a hashref.
1788 This hashref is containt the number of time this borrowers has borrowed before I<$date> and the borrowernumber.
1792 sub GetBorrowersWithIssuesHistoryOlderThan {
1793 my $dbh = C4::Context->dbh;
1795 return unless $date; # date is mandatory.
1797 SELECT count(borrowernumber) as n,borrowernumber
1799 WHERE returndate < ?
1800 AND borrowernumber IS NOT NULL
1801 GROUP BY borrowernumber
1803 my $sth = $dbh->prepare($query);
1804 $sth->execute($date);
1807 while ( my $data = $sth->fetchrow_hashref ) {
1808 push @results, $data;
1813 END { } # module clean-up code here (global destructor)