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,$filter,$showallbranches);
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<$filter> is assumed to be a list of elements to filter results on
142 C<$showallbranches> is used in IndependantBranches Context to display all branches results.
144 C<&SearchMember> returns a two-element list. C<$borrowers> is a
145 reference-to-array; each element is a reference-to-hash, whose keys
146 are the fields of the C<borrowers> table in the Koha database.
147 C<$count> is the number of elements in C<$borrowers>.
152 #used by member enquiries from the intranet
155 my ($searchstring, $orderby, $type,$category_type,$filter,$showallbranches ) = @_;
156 my $dbh = C4::Context->dbh;
162 if ( $type eq "simple" ) # simple search for one letter only
167 LEFT JOIN categories ON borrowers.categorycode=categories.categorycode ".
168 ($category_type?" AND category_type = ".$dbh->quote($category_type):"");
170 " WHERE (surname LIKE ? OR cardnumber like ?) ";
171 if (C4::Context->preference("IndependantBranches") && !$showallbranches){
172 if (C4::Context->userenv && C4::Context->userenv->{flags}!=1 && C4::Context->userenv->{'branch'}){
173 $query.=" AND borrowers.branchcode =".$dbh->quote(C4::Context->userenv->{'branch'}) unless (C4::Context->userenv->{'branch'} eq "insecure");
176 $query.=" ORDER BY $orderby";
177 @bind = ("$searchstring%","$searchstring");
179 else # advanced search looking in surname, firstname and othernames
181 @data = split( ' ', $searchstring );
183 $query = "SELECT * FROM borrowers
184 LEFT JOIN categories ON borrowers.categorycode=categories.categorycode
186 if (C4::Context->preference("IndependantBranches") && !$showallbranches){
187 if (C4::Context->userenv && C4::Context->userenv->{flags}!=1 && C4::Context->userenv->{'branch'}){
188 $query.=" borrowers.branchcode =".$dbh->quote(C4::Context->userenv->{'branch'})." AND " unless (C4::Context->userenv->{'branch'} eq "insecure");
191 $query.="((surname LIKE ? OR surname LIKE ?
192 OR firstname LIKE ? OR firstname LIKE ?
193 OR othernames LIKE ? OR othernames LIKE ?)
195 ($category_type?" AND category_type = ".$dbh->quote($category_type):"");
197 "$data[0]%", "% $data[0]%", "$data[0]%", "% $data[0]%",
198 "$data[0]%", "% $data[0]%"
200 for ( my $i = 1 ; $i < $count ; $i++ ) {
201 $query = $query . " AND (" . " surname LIKE ? OR surname LIKE ?
202 OR firstname LIKE ? OR firstname LIKE ?
203 OR othernames LIKE ? OR othernames LIKE ?)";
205 "$data[$i]%", "% $data[$i]%", "$data[$i]%",
206 "% $data[$i]%", "$data[$i]%", "% $data[$i]%" );
210 $query = $query . ") OR cardnumber LIKE ?
212 push( @bind, $searchstring );
217 my $sth = $dbh->prepare($query);
219 # warn "Q $orderby : $query";
220 $sth->execute(@bind);
222 my $data = $sth->fetchall_arrayref({});
225 return ( scalar(@$data), $data );
228 =head2 GetMemberDetails
230 ($borrower, $flags) = &GetMemberDetails($borrowernumber, $cardnumber);
232 Looks up a patron and returns information about him or her. If
233 C<$borrowernumber> is true (nonzero), C<&GetMemberDetails> looks
234 up the borrower by number; otherwise, it looks up the borrower by card
237 C<$borrower> is a reference-to-hash whose keys are the fields of the
238 borrowers table in the Koha database. In addition,
239 C<$borrower-E<gt>{flags}> is a hash giving more detailed information
240 about the patron. Its keys act as flags :
242 if $borrower->{flags}->{LOST} {
243 # Patron's card was reported lost
246 Each flag has a C<message> key, giving a human-readable explanation of
247 the flag. If the state of a flag means that the patron should not be
248 allowed to borrow any more books, then it will have a C<noissues> key
251 The possible flags are:
257 =item Shows the patron's credit or debt, if any.
265 =item (Gone, no address.) Set if the patron has left without giving a
274 =item Set if the patron's card has been reported as lost.
282 =item Set if the patron has been debarred.
290 =item Any additional notes about the patron.
298 =item Set if the patron has overdue items. This flag has several keys:
300 C<$flags-E<gt>{ODUES}{itemlist}> is a reference-to-array listing the
301 overdue items. Its elements are references-to-hash, each describing an
302 overdue item. The keys are selected fields from the issues, biblio,
303 biblioitems, and items tables of the Koha database.
305 C<$flags-E<gt>{ODUES}{itemlist}> is a string giving a text listing of
306 the overdue items, one per line.
314 =item Set if any items that the patron has reserved are available.
316 C<$flags-E<gt>{WAITING}{itemlist}> is a reference-to-array listing the
317 available items. Each element is a reference-to-hash whose keys are
318 fields from the reserves table of the Koha database.
324 sub GetMemberDetails {
325 my ( $borrowernumber, $cardnumber ) = @_;
326 my $dbh = C4::Context->dbh;
329 if ($borrowernumber) {
330 $sth = $dbh->prepare("select * from borrowers where borrowernumber=?");
331 $sth->execute($borrowernumber);
333 elsif ($cardnumber) {
334 $sth = $dbh->prepare("select * from borrowers where cardnumber=?");
335 $sth->execute($cardnumber);
340 my $borrower = $sth->fetchrow_hashref;
341 my ($amount) = GetMemberAccountRecords( $borrowernumber);
342 $borrower->{'amountoutstanding'} = $amount;
343 my $flags = patronflags( $borrower);
346 $sth = $dbh->prepare("select bit,flag from userflags");
348 while ( my ( $bit, $flag ) = $sth->fetchrow ) {
349 if ( $borrower->{'flags'} && $borrower->{'flags'} & 2**$bit ) {
350 $accessflagshash->{$flag} = 1;
354 $borrower->{'flags'} = $flags;
355 $borrower->{'authflags'} = $accessflagshash;
357 # find out how long the membership lasts
360 "select enrolmentperiod from categories where categorycode = ?");
361 $sth->execute( $borrower->{'categorycode'} );
362 my $enrolment = $sth->fetchrow;
363 $borrower->{'enrolmentperiod'} = $enrolment;
364 return ($borrower); #, $flags, $accessflagshash);
371 NOTE!: If you change this function, be sure to update the POD for
374 $flags = &patronflags($patron);
377 {message} Message showing patron's credit or debt
378 {noissues} Set if patron owes >$5.00
379 {GNA} Set if patron gone w/o address
380 {message} "Borrower has no valid address"
382 {LOST} Set if patron's card reported lost
383 {message} Message to this effect
385 {DBARRED} Set is patron is debarred
386 {message} Message to this effect
388 {NOTES} Set if patron has notes
389 {message} Notes about patron
390 {ODUES} Set if patron has overdue books
392 {itemlist} ref-to-array: list of overdue books
393 {itemlisttext} Text list of overdue items
394 {WAITING} Set if there are items available that the
396 {message} Message to this effect
397 {itemlist} ref-to-array: list of available items
403 my ( $patroninformation) = @_;
404 my $dbh=C4::Context->dbh;
405 my ($amount) = GetMemberAccountRecords( $patroninformation->{'borrowernumber'});
408 my $noissuescharge = C4::Context->preference("noissuescharge");
409 $flaginfo{'message'} = sprintf "Patron owes \$%.02f", $amount;
410 if ( $amount > $noissuescharge ) {
411 $flaginfo{'noissues'} = 1;
413 $flags{'CHARGES'} = \%flaginfo;
415 elsif ( $amount < 0 ) {
417 $flaginfo{'message'} = sprintf "Patron has credit of \$%.02f", -$amount;
418 $flags{'CHARGES'} = \%flaginfo;
420 if ( $patroninformation->{'gonenoaddress'}
421 && $patroninformation->{'gonenoaddress'} == 1 )
424 $flaginfo{'message'} = 'Borrower has no valid address.';
425 $flaginfo{'noissues'} = 1;
426 $flags{'GNA'} = \%flaginfo;
428 if ( $patroninformation->{'lost'} && $patroninformation->{'lost'} == 1 ) {
430 $flaginfo{'message'} = 'Borrower\'s card reported lost.';
431 $flaginfo{'noissues'} = 1;
432 $flags{'LOST'} = \%flaginfo;
434 if ( $patroninformation->{'debarred'}
435 && $patroninformation->{'debarred'} == 1 )
438 $flaginfo{'message'} = 'Borrower is Debarred.';
439 $flaginfo{'noissues'} = 1;
440 $flags{'DBARRED'} = \%flaginfo;
442 if ( $patroninformation->{'borrowernotes'}
443 && $patroninformation->{'borrowernotes'} )
446 $flaginfo{'message'} = "$patroninformation->{'borrowernotes'}";
447 $flags{'NOTES'} = \%flaginfo;
449 my ( $odues, $itemsoverdue ) =
450 checkoverdues( $patroninformation->{'borrowernumber'}, $dbh );
453 $flaginfo{'message'} = "Yes";
454 $flaginfo{'itemlist'} = $itemsoverdue;
455 foreach ( sort { $a->{'date_due'} cmp $b->{'date_due'} }
458 $flaginfo{'itemlisttext'} .=
459 "$_->{'date_due'} $_->{'barcode'} $_->{'title'} \n";
461 $flags{'ODUES'} = \%flaginfo;
463 my @itemswaiting = C4::Reserves::GetReservesFromBorrowernumber( $patroninformation->{'borrowernumber'},'W' );
464 my $nowaiting = scalar @itemswaiting;
465 if ( $nowaiting > 0 ) {
467 $flaginfo{'message'} = "Reserved items available";
468 $flaginfo{'itemlist'} = \@itemswaiting;
469 $flags{'WAITING'} = \%flaginfo;
477 $borrower = &GetMember($information, $type);
479 Looks up information about a patron (borrower) by either card number
480 ,firstname, or borrower number, depending on $type value.
481 If C<$type> == 'cardnumber', C<&GetBorrower>
482 searches by cardnumber then by firstname if not found in cardnumber;
483 otherwise, it searches by borrowernumber.
485 C<&GetBorrower> returns a reference-to-hash whose keys are the fields of
486 the C<borrowers> table in the Koha database.
492 my ( $information, $type ) = @_;
493 my $dbh = C4::Context->dbh;
495 if ($type eq 'cardnumber' || $type eq 'firstname'|| $type eq 'userid'|| $type eq 'borrowernumber'){
496 $information = uc $information;
499 "Select borrowers.*,categories.category_type,categories.description from borrowers left join categories on borrowers.categorycode=categories.categorycode where $type=?"
501 $sth->execute($information);
506 "Select borrowers.*,categories.category_type, categories.description from borrowers left join categories on borrowers.categorycode=categories.categorycode where borrowernumber=?"
508 $sth->execute($information);
510 my $data = $sth->fetchrow_hashref;
516 elsif ($type eq 'cardnumber' ||$type eq 'firstname') { # try with firstname
519 "Select borrowers.*,categories.category_type,categories.description from borrowers left join categories on borrowers.categorycode=categories.categorycode where firstname like ?"
521 $sth->execute($information);
522 my $data = $sth->fetchrow_hashref;
531 =item GetMemberIssuesAndFines
533 ($borrowed, $due, $fine) = &GetMemberIssuesAndFines($borrowernumber);
535 Returns aggregate data about items borrowed by the patron with the
536 given borrowernumber.
538 C<&GetMemberIssuesAndFines> returns a three-element array. C<$borrowed> is the
539 number of books the patron currently has borrowed. C<$due> is the
540 number of overdue items the patron currently has borrowed. C<$fine> is
541 the total fine currently due by the borrower.
546 sub GetMemberIssuesAndFines {
547 my ( $borrowernumber ) = @_;
548 my $dbh = C4::Context->dbh;
550 "Select count(*) from issues where borrowernumber='$borrowernumber' and
554 my $sth = $dbh->prepare($query);
556 my $data = $sth->fetchrow_hashref;
558 $sth = $dbh->prepare(
559 "Select count(*) from issues where
560 borrowernumber='$borrowernumber' and date_due < now() and returndate is NULL"
563 my $data2 = $sth->fetchrow_hashref;
565 $sth = $dbh->prepare(
566 "Select sum(amountoutstanding) from accountlines where
567 borrowernumber='$borrowernumber'"
570 my $data3 = $sth->fetchrow_hashref;
573 return ( $data2->{'count(*)'}, $data->{'count(*)'},
574 $data3->{'sum(amountoutstanding)'} );
581 &ModMember($borrowernumber);
583 Modify borrower's data
590 my $dbh = C4::Context->dbh;
591 $data{'dateofbirth'} = format_date_in_iso( $data{'dateofbirth'} ) if ($data{'dateofbirth'} );
592 $data{'dateexpiry'} = format_date_in_iso( $data{'dateexpiry'} ) if ($data{'dateexpiry'} );
593 $data{'dateenrolled'} = format_date_in_iso( $data{'dateenrolled'} ) if ($data{'dateenrolled'} );
594 my $qborrower=$dbh->prepare("SHOW columns from borrowers");
596 my %hashborrowerfields;
597 while (my ($field)=$qborrower->fetchrow){
598 $hashborrowerfields{$field}=1;
604 # test to know if u must update or not the borrower password
605 if ( $data{'password'} eq '****' ) {
606 delete $data{'password'};
608 {push @parameters,"$_ = ".$dbh->quote($data{$_}) if ($_ ne "borrowernumber" and $_ ne "flags" and $hashborrowerfields{$_}) } ;
609 $query = "UPDATE borrowers SET ".join (",",@parameters)
610 ." WHERE borrowernumber=$data{'borrowernumber'}";
612 $sth = $dbh->prepare($query);
616 $data{'password'} = md5_base64( $data{'password'} ) if ( $data{'password'} ne '' );
617 delete $data{'password'} if ($data{password} eq "");
619 {push @parameters,"$_ = ".$dbh->quote($data{$_}) if ($_ ne "borrowernumber" and $_ ne "flags" and $hashborrowerfields{$_})} ;
621 $query = "UPDATE borrowers SET ".join (",",@parameters)." WHERE borrowernumber=$data{'borrowernumber'}";
623 $sth = $dbh->prepare($query);
628 # ok if its an adult (type) it may have borrowers that depend on it as a guarantor
629 # so when we update information for an adult we should check for guarantees and update the relevant part
630 # of their records, ie addresses and phone numbers
631 my $borrowercategory= GetBorrowercategory( $data{'category_type'} );
632 if ( $borrowercategory->{'category_type'} eq 'A' ) {
633 # is adult check guarantees;
634 UpdateGuarantees(%data);
637 &logaction(C4::Context->userenv->{'number'},"MEMBERS","MODIFY",$data{'borrowernumber'},"")
638 if C4::Context->preference("BorrowersLog");
646 $borrowernumber = &AddMember(%borrower);
648 insert new borrower into table
649 Returns the borrowernumber
656 my $dbh = C4::Context->dbh;
657 $data{'userid'} = '' unless $data{'password'};
658 $data{'password'} = md5_base64( $data{'password'} ) if $data{'password'};
659 $data{'dateofbirth'} = format_date_in_iso( $data{'dateofbirth'} );
660 $data{'dateenrolled'} = format_date_in_iso( $data{'dateenrolled'} );
661 $data{'dateexpiry'} = format_date_in_iso( $data{'dateexpiry'} );
663 "insert into borrowers set cardnumber="
664 . $dbh->quote( $data{'cardnumber'} )
666 . $dbh->quote( $data{'surname'} )
668 . $dbh->quote( $data{'firstname'} )
670 . $dbh->quote( $data{'title'} )
672 . $dbh->quote( $data{'othernames'} )
674 . $dbh->quote( $data{'initials'} )
676 . $dbh->quote( $data{'streetnumber'} )
678 . $dbh->quote( $data{'streettype'} )
680 . $dbh->quote( $data{'address'} )
682 . $dbh->quote( $data{'address2'} )
684 . $dbh->quote( $data{'zipcode'} )
686 . $dbh->quote( $data{'city'} )
688 . $dbh->quote( $data{'phone'} )
690 . $dbh->quote( $data{'email'} )
692 . $dbh->quote( $data{'mobile'} )
694 . $dbh->quote( $data{'phonepro'} )
696 . $dbh->quote( $data{'opacnote'} )
698 . $dbh->quote( $data{'guarantorid'} )
700 . $dbh->quote( $data{'dateofbirth'} )
702 . $dbh->quote( $data{'branchcode'} )
704 . $dbh->quote( $data{'categorycode'} )
706 . $dbh->quote( $data{'dateenrolled'} )
708 . $dbh->quote( $data{'contactname'} )
710 . $dbh->quote( $data{'borrowernotes'} )
712 . $dbh->quote( $data{'dateexpiry'} )
714 . $dbh->quote( $data{'contactnote'} )
716 . $dbh->quote( $data{'B_address'} )
718 . $dbh->quote( $data{'B_zipcode'} )
720 . $dbh->quote( $data{'B_city'} )
722 . $dbh->quote( $data{'B_phone'} )
724 . $dbh->quote( $data{'B_email'}, )
726 . $dbh->quote( $data{'password'} )
728 . $dbh->quote( $data{'userid'} )
730 . $dbh->quote( $data{'sort1'} )
732 . $dbh->quote( $data{'sort2'} )
734 . $dbh->quote( $data{'contacttitle'} )
736 . $dbh->quote( $data{'emailpro'} )
737 . ",contactfirstname="
738 . $dbh->quote( $data{'contactfirstname'} ) . ",sex="
739 . $dbh->quote( $data{'sex'} ) . ",fax="
740 . $dbh->quote( $data{'fax'} )
742 . $dbh->quote( $data{'relationship'} )
744 . $dbh->quote( $data{'B_streetnumber'} )
746 . $dbh->quote( $data{'B_streettype'} )
748 . $dbh->quote( $data{'gonenoaddress'} )
750 . $dbh->quote( $data{'lost'} )
752 . $dbh->quote( $data{'debarred'} )
754 . $dbh->quote( $data{'ethnicity'} )
756 . $dbh->quote( $data{'ethnotes'} );
758 my $sth = $dbh->prepare($query);
761 $data{'borrowernumber'} = $dbh->{'mysql_insertid'};
763 &logaction(C4::Context->userenv->{'number'},"MEMBERS","CREATE",$data{'borrowernumber'},"")
764 if C4::Context->preference("BorrowersLog");
766 return $data{'borrowernumber'};
770 my ($uid,$member) = @_;
771 my $dbh = C4::Context->dbh;
772 # Make sure the userid chosen is unique and not theirs if non-empty. If it is not,
773 # Then we need to tell the user and have them create a new one.
776 "SELECT * FROM borrowers WHERE userid=? AND borrowernumber != ?");
777 $sth->execute( $uid, $member );
778 if ( ( $uid ne '' ) && ( my $row = $sth->fetchrow_hashref ) ) {
788 my ( $uid, $member, $digest ) = @_;
789 my $dbh = C4::Context->dbh;
791 #Make sure the userid chosen is unique and not theirs if non-empty. If it is not,
792 #Then we need to tell the user and have them create a new one.
795 "SELECT * FROM borrowers WHERE userid=? AND borrowernumber != ?");
796 $sth->execute( $uid, $member );
797 if ( ( $uid ne '' ) && ( my $row = $sth->fetchrow_hashref ) ) {
801 #Everything is good so we can update the information.
804 "update borrowers set userid=?, password=? where borrowernumber=?");
805 $sth->execute( $uid, $digest, $member );
809 &logaction(C4::Context->userenv->{'number'},"MEMBERS","CHANGE PASS",$member,"")
810 if C4::Context->preference("BorrowersLog");
815 =item fixup_cardnumber
817 Warning: The caller is responsible for locking the members table in write
818 mode, to avoid database corruption.
822 use vars qw( @weightings );
823 my @weightings = ( 8, 4, 6, 3, 5, 2, 1 );
825 sub fixup_cardnumber ($) {
826 my ($cardnumber) = @_;
827 my $autonumber_members = C4::Context->boolean_preference('autoMemberNum');
828 $autonumber_members = 0 unless defined $autonumber_members;
830 # Find out whether member numbers should be generated
831 # automatically. Should be either "1" or something else.
832 # Defaults to "0", which is interpreted as "no".
834 # if ($cardnumber !~ /\S/ && $autonumber_members) {
835 if ($autonumber_members) {
836 my $dbh = C4::Context->dbh;
837 if ( C4::Context->preference('checkdigit') eq 'katipo' ) {
839 # if checkdigit is selected, calculate katipo-style cardnumber.
840 # otherwise, just use the max()
841 # purpose: generate checksum'd member numbers.
842 # We'll assume we just got the max value of digits 2-8 of member #'s
843 # from the database and our job is to increment that by one,
844 # determine the 1st and 9th digits and return the full string.
847 "select max(substring(borrowers.cardnumber,2,7)) from borrowers"
851 my $data = $sth->fetchrow_hashref;
852 $cardnumber = $data->{'max(substring(borrowers.cardnumber,2,7))'};
854 if ( !$cardnumber ) { # If DB has no values,
855 $cardnumber = 1000000; # start at 1000000
862 for ( my $i = 0 ; $i < 8 ; $i += 1 ) {
864 # read weightings, left to right, 1 char at a time
865 my $temp1 = $weightings[$i];
867 # sequence left to right, 1 char at a time
868 my $temp2 = substr( $cardnumber, $i, 1 );
870 # mult each char 1-7 by its corresponding weighting
871 $sum += $temp1 * $temp2;
874 my $rem = ( $sum % 11 );
875 $rem = 'X' if $rem == 10;
877 $cardnumber = "V$cardnumber$rem";
881 # MODIFIED BY JF: mysql4.1 allows casting as an integer, which is probably
882 # better. I'll leave the original in in case it needs to be changed for you
885 "select max(cast(cardnumber as signed)) from borrowers");
887 #my $sth=$dbh->prepare("select max(borrowers.cardnumber) from borrowers");
891 my ($result) = $sth->fetchrow;
893 $cardnumber = $result + 1;
901 ($num_children, $children_arrayref) = &GetGuarantees($parent_borrno);
902 $child0_cardno = $children_arrayref->[0]{"cardnumber"};
903 $child0_borrno = $children_arrayref->[0]{"borrowernumber"};
905 C<&GetGuarantees> takes a borrower number (e.g., that of a patron
906 with children) and looks up the borrowers who are guaranteed by that
907 borrower (i.e., the patron's children).
909 C<&GetGuarantees> returns two values: an integer giving the number of
910 borrowers guaranteed by C<$parent_borrno>, and a reference to an array
911 of references to hash, which gives the actual results.
917 my ($borrowernumber) = @_;
918 my $dbh = C4::Context->dbh;
921 "select cardnumber,borrowernumber, firstname, surname from borrowers where guarantorid=?"
923 $sth->execute($borrowernumber);
926 my $data = $sth->fetchall_arrayref({});
928 return ( scalar(@$data), $data );
931 =head2 UpdateGuarantees
933 &UpdateGuarantees($parent_borrno);
936 C<&UpdateGuarantees> borrower data for an adulte and updates all the guarantees
937 with the modified information
942 sub UpdateGuarantees {
944 my $dbh = C4::Context->dbh;
945 my ( $count, $guarantees ) = GetGuarantees( $data{'borrowernumber'} );
946 for ( my $i = 0 ; $i < $count ; $i++ ) {
949 # It looks like the $i is only being returned to handle walking through
950 # the array, which is probably better done as a foreach loop.
952 my $guaquery = qq|UPDATE borrowers
953 SET address='$data{'address'}',fax='$data{'fax'}',
954 B_city='$data{'B_city'}',mobile='$data{'mobile'}',city='$data{'city'}',phone='$data{'phone'}'
955 WHERE borrowernumber='$guarantees->[$i]->{'borrowernumber'}'
957 my $sth3 = $dbh->prepare($guaquery);
962 =head2 GetPendingIssues
964 ($count, $issues) = &GetPendingIssues($borrowernumber);
966 Looks up what the patron with the given borrowernumber has borrowed.
968 C<&GetPendingIssues> returns a two-element array. C<$issues> is a
969 reference-to-array, where each element is a reference-to-hash; the
970 keys are the fields from the C<issues>, C<biblio>, and C<items> tables
971 in the Koha database. C<$count> is the number of elements in
977 sub GetPendingIssues {
978 my ($borrowernumber) = @_;
979 my $dbh = C4::Context->dbh;
981 my $sth = $dbh->prepare(
982 "SELECT * FROM issues
983 LEFT JOIN items ON issues.itemnumber=items.itemnumber
984 LEFT JOIN biblio ON items.biblionumber=biblio.biblionumber
985 LEFT JOIN biblioitems ON items.biblioitemnumber=biblioitems.biblioitemnumber
988 AND returndate IS NULL
989 ORDER BY issues.issuedate"
991 $sth->execute($borrowernumber);
992 my $data = $sth->fetchall_arrayref({});
993 my $today = POSIX::strftime("%Y%m%d", localtime);
995 my $datedue = $_->{'date_due'};
997 if ( $datedue < $today ) {
1002 return ( scalar(@$data), $data );
1007 ($count, $issues) = &GetAllIssues($borrowernumber, $sortkey, $limit);
1009 Looks up what the patron with the given borrowernumber has borrowed,
1010 and sorts the results.
1012 C<$sortkey> is the name of a field on which to sort the results. This
1013 should be the name of a field in the C<issues>, C<biblio>,
1014 C<biblioitems>, or C<items> table in the Koha database.
1016 C<$limit> is the maximum number of results to return.
1018 C<&GetAllIssues> returns a two-element array. C<$issues> is a
1019 reference-to-array, where each element is a reference-to-hash; the
1020 keys are the fields from the C<issues>, C<biblio>, C<biblioitems>, and
1021 C<items> tables of the Koha database. C<$count> is the number of
1022 elements in C<$issues>
1028 my ( $borrowernumber, $order, $limit ) = @_;
1030 #FIXME: sanity-check order and limit
1031 my $dbh = C4::Context->dbh;
1034 "Select *,items.timestamp AS itemstimestamp from
1036 LEFT JOIN items on items.itemnumber=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);
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 my $query2 = "SELECT * FROM oldissues
1061 LEFT JOIN items ON items.itemnumber=oldissues.itemnumber
1062 LEFT JOIN biblio ON items.biblionumber=biblio.biblionumber
1063 LEFT JOIN biblioitems ON items.biblioitemnumber=biblioitems.biblioitemnumber
1064 WHERE borrowernumber=?
1066 if ( $limit != 0 ) {
1067 $limit = $limit - $count;
1068 $query2 .= " limit $limit";
1071 my $sth2 = $dbh->prepare($query2);
1072 $sth2->execute($borrowernumber);
1074 while ( my $data2 = $sth2->fetchrow_hashref ) {
1075 $result[$i] = $data2;
1082 return ( $i, \@result );
1086 =head2 GetMemberAccountRecords
1088 ($total, $acctlines, $count) = &GetMemberAccountRecords($borrowernumber);
1090 Looks up accounting data for the patron with the given borrowernumber.
1092 C<&GetMemberAccountRecords> returns a three-element array. C<$acctlines> is a
1093 reference-to-array, where each element is a reference-to-hash; the
1094 keys are the fields of the C<accountlines> table in the Koha database.
1095 C<$count> is the number of elements in C<$acctlines>. C<$total> is the
1096 total amount outstanding for all of the account lines.
1101 sub GetMemberAccountRecords {
1102 my ($borrowernumber,$date) = @_;
1103 my $dbh = C4::Context->dbh;
1109 WHERE borrowernumber=?);
1110 my @bind = ($borrowernumber);
1111 if ($date && $date ne ''){
1112 $strsth.=" AND date < ? ";
1115 $strsth.=" ORDER BY date desc,timestamp DESC";
1116 my $sth= $dbh->prepare( $strsth );
1117 $sth->execute( @bind );
1119 while ( my $data = $sth->fetchrow_hashref ) {
1120 $acctlines[$numlines] = $data;
1122 $total += $data->{'amountoutstanding'};
1125 return ( $total, \@acctlines,$numlines);
1128 =head2 GetBorNotifyAcctRecord
1130 ($count, $acctlines, $total) = &GetBorNotifyAcctRecord($params,$notifyid);
1132 Looks up accounting data for the patron with the given borrowernumber per file number.
1134 (FIXME - I'm not at all sure what this is about.)
1136 C<&GetBorNotifyAcctRecord> returns a three-element array. C<$acctlines> is a
1137 reference-to-array, where each element is a reference-to-hash; the
1138 keys are the fields of the C<accountlines> table in the Koha database.
1139 C<$count> is the number of elements in C<$acctlines>. C<$total> is the
1140 total amount outstanding for all of the account lines.
1144 sub GetBorNotifyAcctRecord {
1145 my ( $borrowernumber, $notifyid ) = @_;
1146 my $dbh = C4::Context->dbh;
1149 my $sth = $dbh->prepare(
1152 WHERE borrowernumber=?
1154 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')
1155 AND amountoutstanding != '0'
1156 ORDER BY notify_id,accounttype
1158 $sth->execute( $borrowernumber, $notifyid );
1160 while ( my $data = $sth->fetchrow_hashref ) {
1161 $acctlines[$numlines] = $data;
1163 $total += $data->{'amountoutstanding'};
1166 return ( $total, \@acctlines, $numlines );
1169 =head2 checkuniquemember (OUEST-PROVENCE)
1171 $result = &checkuniquemember($collectivity,$surname,$categorycode,$firstname,$dateofbirth);
1173 Checks that a member exists or not in the database.
1175 C<&result> is 1 (=exist) or 0 (=does not exist)
1176 C<&collectivity> is 1 (= we add a collectivity) or 0 (= we add a physical member)
1177 C<&surname> is the surname
1178 C<&categorycode> is from categorycode table
1179 C<&firstname> is the firstname (only if collectivity=0)
1180 C<&dateofbirth> is the date of birth (only if collectivity=0)
1184 sub checkuniquemember {
1185 my ( $collectivity, $surname, $firstname, $dateofbirth ) = @_;
1186 my $dbh = C4::Context->dbh;
1188 if ($collectivity) {
1190 # $request="select count(*) from borrowers where surname=? and categorycode=?";
1192 "select borrowernumber,categorycode from borrowers where surname=? ";
1196 # $request="select count(*) from borrowers where surname=? and categorycode=? and firstname=? and dateofbirth=?";
1198 "select borrowernumber,categorycode from borrowers where surname=? and firstname=? and dateofbirth=?";
1200 my $sth = $dbh->prepare($request);
1201 if ($collectivity) {
1202 $sth->execute( uc($surname) );
1205 $sth->execute( uc($surname), ucfirst($firstname), $dateofbirth );
1207 my @data = $sth->fetchrow;
1210 return $data[0], $data[1];
1220 sub checkcardnumber {
1221 my ($cardnumber,$borrowernumber) = @_;
1222 my $dbh = C4::Context->dbh;
1223 my $query = "SELECT * FROM borrowers WHERE cardnumber=?";
1224 $query .= " AND borrowernumber <> ?" if ($borrowernumber);
1225 my $sth = $dbh->prepare($query);
1226 if ($borrowernumber) {
1227 $sth->execute($cardnumber,$borrowernumber);
1229 $sth->execute($cardnumber);
1231 if (my $data= $sth->fetchrow_hashref()){
1241 =head2 getzipnamecity (OUEST-PROVENCE)
1243 take all info from table city for the fields city and zip
1244 check for the name and the zip code of the city selected
1248 sub getzipnamecity {
1250 my $dbh = C4::Context->dbh;
1253 "select city_name,city_zipcode from cities where cityid=? ");
1254 $sth->execute($cityid);
1255 my @data = $sth->fetchrow;
1256 return $data[0], $data[1];
1260 =head2 getdcity (OUEST-PROVENCE)
1262 recover cityid with city_name condition
1267 my ($city_name) = @_;
1268 my $dbh = C4::Context->dbh;
1269 my $sth = $dbh->prepare("select cityid from cities where city_name=? ");
1270 $sth->execute($city_name);
1271 my $data = $sth->fetchrow;
1276 =head2 GetExpiryDate
1278 $expirydate = GetExpiryDate($categorycode, $dateenrolled);
1279 process expiry date given a date and a categorycode
1283 my ( $categorycode, $dateenrolled ) = @_;
1284 my $dbh = C4::Context->dbh;
1287 "select enrolmentperiod from categories where categorycode=?");
1288 $sth->execute($categorycode);
1289 my ($enrolmentperiod) = $sth->fetchrow;
1290 $enrolmentperiod = 12 unless ($enrolmentperiod);
1291 my @date=split /-/,format_date_in_iso($dateenrolled);
1292 @date=Add_Delta_YM($date[0],$date[1],$date[2],0,$enrolmentperiod);
1293 return sprintf("%04d-%02d-%02d",$date[0],$date[1],$date[2]);
1296 =head2 checkuserpassword (OUEST-PROVENCE)
1298 check for the password and login are not used
1299 return the number of record
1300 0=> NOT USED 1=> USED
1304 sub checkuserpassword {
1305 my ( $borrowernumber, $userid, $password ) = @_;
1306 $password = md5_base64($password);
1307 my $dbh = C4::Context->dbh;
1310 "Select count(*) from borrowers where borrowernumber !=? and userid =? and password=? "
1312 $sth->execute( $borrowernumber, $userid, $password );
1313 my $number_rows = $sth->fetchrow;
1314 return $number_rows;
1318 =head2 GetborCatFromCatType
1320 ($codes_arrayref, $labels_hashref) = &GetborCatFromCatType();
1322 Looks up the different types of borrowers in the database. Returns two
1323 elements: a reference-to-array, which lists the borrower category
1324 codes, and a reference-to-hash, which maps the borrower category codes
1325 to category descriptions.
1330 sub GetborCatFromCatType {
1331 my ( $category_type, $action ) = @_;
1332 my $dbh = C4::Context->dbh;
1333 my $request = qq| SELECT categorycode,description
1336 ORDER BY categorycode|;
1337 my $sth = $dbh->prepare($request);
1339 $sth->execute($category_type);
1348 while ( my $data = $sth->fetchrow_hashref ) {
1349 push @codes, $data->{'categorycode'};
1350 $labels{ $data->{'categorycode'} } = $data->{'description'};
1353 return ( \@codes, \%labels );
1356 =head2 GetBorrowercategory
1358 $hashref = &GetBorrowercategory($categorycode);
1360 Given the borrower's category code, the function returns the corresponding
1361 data hashref for a comprehensive information display.
1365 sub GetBorrowercategory {
1367 my $dbh = C4::Context->dbh;
1370 "SELECT description,dateofbirthrequired,upperagelimit,category_type
1372 WHERE categorycode = ?"
1374 $sth->execute($catcode);
1376 $sth->fetchrow_hashref;
1379 } # sub getborrowercategory
1381 =head2 ethnicitycategories
1383 ($codes_arrayref, $labels_hashref) = ðnicitycategories();
1385 Looks up the different ethnic types in the database. Returns two
1386 elements: a reference-to-array, which lists the ethnicity codes, and a
1387 reference-to-hash, which maps the ethnicity codes to ethnicity
1394 sub ethnicitycategories {
1395 my $dbh = C4::Context->dbh;
1396 my $sth = $dbh->prepare("Select code,name from ethnicity order by name");
1400 while ( my $data = $sth->fetchrow_hashref ) {
1401 push @codes, $data->{'code'};
1402 $labels{ $data->{'code'} } = $data->{'name'};
1405 return ( \@codes, \%labels );
1410 $ethn_name = &fixEthnicity($ethn_code);
1412 Takes an ethnicity code (e.g., "european" or "pi") and returns the
1413 corresponding descriptive name from the C<ethnicity> table in the
1414 Koha database ("European" or "Pacific Islander").
1421 my $ethnicity = shift;
1422 return unless $ethnicity;
1423 my $dbh = C4::Context->dbh;
1424 my $sth = $dbh->prepare("Select name from ethnicity where code = ?");
1425 $sth->execute($ethnicity);
1426 my $data = $sth->fetchrow_hashref;
1428 return $data->{'name'};
1429 } # sub fixEthnicity
1433 $dateofbirth,$date = &GetAge($date);
1435 this function return the borrowers age with the value of dateofbirth
1441 my ( $date, $date_ref ) = @_;
1443 if ( not defined $date_ref ) {
1444 $date_ref = sprintf( '%04d-%02d-%02d', Today() );
1447 my ( $year1, $month1, $day1 ) = split /-/, $date;
1448 my ( $year2, $month2, $day2 ) = split /-/, $date_ref;
1450 my $age = $year2 - $year1;
1451 if ( $month1 . $day1 > $month2 . $day2 ) {
1458 =head2 get_institutions
1459 $insitutions = get_institutions();
1461 Just returns a list of all the borrowers of type I, borrownumber and name
1466 sub get_institutions {
1467 my $dbh = C4::Context->dbh();
1470 "SELECT borrowernumber,surname FROM borrowers WHERE categorycode=? ORDER BY surname"
1474 while ( my $data = $sth->fetchrow_hashref() ) {
1475 $orgs{ $data->{'borrowernumber'} } = $data;
1480 } # sub get_institutions
1482 =head2 add_member_orgs
1484 add_member_orgs($borrowernumber,$borrowernumbers);
1486 Takes a borrowernumber and a list of other borrowernumbers and inserts them into the borrowers_to_borrowers table
1491 sub add_member_orgs {
1492 my ( $borrowernumber, $otherborrowers ) = @_;
1493 my $dbh = C4::Context->dbh();
1495 "INSERT INTO borrowers_to_borrowers (borrower1,borrower2) VALUES (?,?)";
1496 my $sth = $dbh->prepare($query);
1497 foreach my $otherborrowernumber (@$otherborrowers) {
1498 $sth->execute( $borrowernumber, $otherborrowernumber );
1502 } # sub add_member_orgs
1504 =head2 GetCities (OUEST-PROVENCE)
1506 ($id_cityarrayref, $city_hashref) = &GetCities();
1508 Looks up the different city and zip in the database. Returns two
1509 elements: a reference-to-array, which lists the zip city
1510 codes, and a reference-to-hash, which maps the name of the city.
1511 WHERE =>OUEST PROVENCE OR EXTERIEUR
1517 #my ($type_city) = @_;
1518 my $dbh = C4::Context->dbh;
1519 my $query = qq|SELECT cityid,city_name
1521 ORDER BY city_name|;
1522 my $sth = $dbh->prepare($query);
1524 #$sth->execute($type_city);
1529 # insert empty value to create a empty choice in cgi popup
1531 while ( my $data = $sth->fetchrow_hashref ) {
1533 push @id, $data->{'cityid'};
1534 $city{ $data->{'cityid'} } = $data->{'city_name'};
1537 #test to know if the table contain some records if no the function return nothing
1545 return ( \@id, \%city );
1549 =head2 GetSortDetails (OUEST-PROVENCE)
1551 ($lib) = &GetSortDetails($category,$sortvalue);
1553 Returns the authorized value details
1554 C<&$lib>return value of authorized value details
1555 C<&$sortvalue>this is the value of authorized value
1556 C<&$category>this is the value of authorized value category
1560 sub GetSortDetails {
1561 my ( $category, $sortvalue ) = @_;
1562 my $dbh = C4::Context->dbh;
1563 my $query = qq|SELECT lib
1564 FROM authorised_values
1566 AND authorised_value=? |;
1567 my $sth = $dbh->prepare($query);
1568 $sth->execute( $category, $sortvalue );
1569 my $lib = $sth->fetchrow;
1573 =head2 DeleteBorrower
1575 () = &DeleteBorrower($member);
1577 delete all data fo borrowers and add record to deletedborrowers table
1578 C<&$member>this is the borrowernumber
1582 sub MoveMemberToDeleted {
1584 my $dbh = C4::Context->dbh;
1586 $query = qq|SELECT *
1588 WHERE borrowernumber=?|;
1589 my $sth = $dbh->prepare($query);
1590 $sth->execute($member);
1591 my @data = $sth->fetchrow_array;
1594 $dbh->prepare( "INSERT INTO deletedborrowers VALUES ("
1595 . ( "?," x ( scalar(@data) - 1 ) )
1597 $sth->execute(@data);
1603 DelMember($borrowernumber);
1605 This function remove directly a borrower whitout writing it on deleteborrower.
1606 + Deletes reserves for the borrower
1611 my $dbh = C4::Context->dbh;
1612 my $borrowernumber = shift;
1613 warn "in delmember with $borrowernumber";
1614 return unless $borrowernumber; # borrowernumber is mandatory.
1616 my $query = qq|DELETE
1618 WHERE borrowernumber=?|;
1619 my $sth = $dbh->prepare($query);
1620 $sth->execute($borrowernumber);
1625 WHERE borrowernumber = ?
1627 $sth = $dbh->prepare($query);
1628 $sth->execute($borrowernumber);
1630 &logaction(C4::Context->userenv->{'number'},"MEMBERS","DELETE",$borrowernumber,"")
1631 if C4::Context->preference("BorrowersLog");
1635 =head2 ExtendMemberSubscriptionTo (OUEST-PROVENCE)
1637 $date= ExtendMemberSubscriptionTo($borrowerid, $date);
1638 Extending the subscription to a given date or to the expiry date calculated on local date.
1642 sub ExtendMemberSubscriptionTo {
1643 my ( $borrowerid,$date) = @_;
1644 my $dbh = C4::Context->dbh;
1646 $date=POSIX::strftime("%Y-%m-%d",localtime(time));
1647 my $borrower = GetMember($borrowerid,'borrowernumber');
1648 $date = GetExpiryDate( $borrower->{'categorycode'}, $date );
1650 my $sth = $dbh->do(<<EOF);
1652 SET dateexpiry='$date'
1653 WHERE borrowernumber='$borrowerid'
1655 return $date if ($sth);
1659 =head2 GetRoadTypes (OUEST-PROVENCE)
1661 ($idroadtypearrayref, $roadttype_hashref) = &GetRoadTypes();
1663 Looks up the different road type . Returns two
1664 elements: a reference-to-array, which lists the id_roadtype
1665 codes, and a reference-to-hash, which maps the road type of the road .
1671 my $dbh = C4::Context->dbh;
1673 SELECT roadtypeid,road_type
1675 ORDER BY road_type|;
1676 my $sth = $dbh->prepare($query);
1681 # insert empty value to create a empty choice in cgi popup
1683 while ( my $data = $sth->fetchrow_hashref ) {
1685 push @id, $data->{'roadtypeid'};
1686 $roadtype{ $data->{'roadtypeid'} } = $data->{'road_type'};
1689 #test to know if the table contain some records if no the function return nothing
1697 return ( \@id, \%roadtype );
1703 =head2 GetTitles (OUEST-PROVENCE)
1705 ($borrowertitle)= &GetTitles();
1707 Looks up the different title . Returns array with all borrowers title
1712 my @borrowerTitle = split /,|\|/,C4::Context->preference('BorrowersTitles');
1713 unshift( @borrowerTitle, "" );
1714 return ( \@borrowerTitle);
1719 =head2 GetRoadTypeDetails (OUEST-PROVENCE)
1721 ($roadtype) = &GetRoadTypeDetails($roadtypeid);
1723 Returns the description of roadtype
1724 C<&$roadtype>return description of road type
1725 C<&$roadtypeid>this is the value of roadtype s
1729 sub GetRoadTypeDetails {
1730 my ($roadtypeid) = @_;
1731 my $dbh = C4::Context->dbh;
1735 WHERE roadtypeid=?|;
1736 my $sth = $dbh->prepare($query);
1737 $sth->execute($roadtypeid);
1738 my $roadtype = $sth->fetchrow;
1742 =head2 GetBorrowersWhoHaveNotBorrowedSince
1744 &GetBorrowersWhoHaveNotBorrowedSince($date)
1746 this function get all borrowers who haven't borrowed since the date given on input arg.
1750 sub GetBorrowersWhoHaveNotBorrowedSince {
1752 return unless $date; # date is mandatory.
1753 my $dbh = C4::Context->dbh;
1755 SELECT borrowers.borrowernumber,max(timestamp)
1757 LEFT JOIN issues ON borrowers.borrowernumber = issues.borrowernumber
1758 WHERE issues.borrowernumber IS NOT NULL
1759 GROUP BY borrowers.borrowernumber
1761 my $sth = $dbh->prepare($query);
1765 while ( my $data = $sth->fetchrow_hashref ) {
1766 push @results, $data;
1771 =head2 GetBorrowersWhoHaveNeverBorrowed
1773 $results = &GetBorrowersWhoHaveNeverBorrowed
1775 this function get all borrowers who have never borrowed.
1777 I<$result> is a ref to an array which all elements are a hasref.
1781 sub GetBorrowersWhoHaveNeverBorrowed {
1782 my $dbh = C4::Context->dbh;
1784 SELECT borrowers.borrowernumber,max(timestamp)
1786 LEFT JOIN issues ON borrowers.borrowernumber = issues.borrowernumber
1787 WHERE issues.borrowernumber IS NULL
1789 my $sth = $dbh->prepare($query);
1792 while ( my $data = $sth->fetchrow_hashref ) {
1793 push @results, $data;
1798 =head2 GetBorrowersWithIssuesHistoryOlderThan
1800 $results = &GetBorrowersWithIssuesHistoryOlderThan($date)
1802 this function get all borrowers who has an issue history older than I<$date> given on input arg.
1804 I<$result> is a ref to an array which all elements are a hashref.
1805 This hashref is containt the number of time this borrowers has borrowed before I<$date> and the borrowernumber.
1809 sub GetBorrowersWithIssuesHistoryOlderThan {
1810 my $dbh = C4::Context->dbh;
1812 return unless $date; # date is mandatory.
1814 SELECT count(borrowernumber) as n,borrowernumber
1816 WHERE returndate < ?
1817 AND borrowernumber IS NOT NULL
1818 GROUP BY borrowernumber
1820 my $sth = $dbh->prepare($query);
1821 $sth->execute($date);
1824 while ( my $data = $sth->fetchrow_hashref ) {
1825 push @results, $data;
1830 END { } # module clean-up code here (global destructor)