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 # warn Data::Dumper::Dumper(%data);
595 # warn "num user".$data{'borrowernumber'};
596 my $qborrower=$dbh->prepare("SHOW columns from borrowers");
598 my %hashborrowerfields;
599 while (my ($field)=$qborrower->fetchrow){
600 $hashborrowerfields{$field}=1;
604 $data{'userid'} = '' if ( $data{'password'} eq '' );
607 # test to know if u must update or not the borrower password
608 if ( $data{'password'} eq '****' ) {
609 delete $data{'password'};
611 {push @parameters,"$_ = ".$dbh->quote($data{$_}) if ($_ ne "flags" and $_ ne "borrowernumber" and $hashborrowerfields{$_}) } ;
612 $query = "UPDATE borrowers SET ".join (",",@parameters)
613 ." WHERE borrowernumber=$data{'borrowernumber'}";
615 $sth = $dbh->prepare($query);
619 $data{'password'} = md5_base64( $data{'password'} ) if ( $data{'password'} ne '' );
620 delete $data{'password'} if ($data{password} eq "");
622 {push @parameters,"$_ = ".$dbh->quote($data{$_}) if ($_ ne "flags" and $_ ne "borrowernumber" and $hashborrowerfields{$_})} ;
624 $query = "UPDATE borrowers SET ".join (",",@parameters)." WHERE borrowernumber=$data{'borrowernumber'}";
626 $sth = $dbh->prepare($query);
631 # ok if its an adult (type) it may have borrowers that depend on it as a guarantor
632 # so when we update information for an adult we should check for guarantees and update the relevant part
633 # of their records, ie addresses and phone numbers
634 my $borrowercategory= GetBorrowercategory( $data{'category_type'} );
635 if ( $borrowercategory->{'category_type'} eq 'A' ) {
636 # is adult check guarantees;
637 UpdateGuarantees(%data);
640 &logaction(C4::Context->userenv->{'number'},"MEMBERS","MODIFY",$data{'borrowernumber'},"")
641 if C4::Context->preference("BorrowersLog");
649 $borrowernumber = &AddMember(%borrower);
651 insert new borrower into table
652 Returns the borrowernumber
659 my $dbh = C4::Context->dbh;
660 $data{'userid'} = '' unless $data{'password'};
661 $data{'password'} = md5_base64( $data{'password'} ) if $data{'password'};
662 $data{'dateofbirth'} = format_date_in_iso( $data{'dateofbirth'} );
663 $data{'dateenrolled'} = format_date_in_iso( $data{'dateenrolled'} );
664 $data{'dateexpiry'} = format_date_in_iso( $data{'dateexpiry'} );
666 "insert into borrowers set cardnumber="
667 . $dbh->quote( $data{'cardnumber'} )
669 . $dbh->quote( $data{'surname'} )
671 . $dbh->quote( $data{'firstname'} )
673 . $dbh->quote( $data{'title'} )
675 . $dbh->quote( $data{'othernames'} )
677 . $dbh->quote( $data{'initials'} )
679 . $dbh->quote( $data{'streetnumber'} )
681 . $dbh->quote( $data{'streettype'} )
683 . $dbh->quote( $data{'address'} )
685 . $dbh->quote( $data{'address2'} )
687 . $dbh->quote( $data{'zipcode'} )
689 . $dbh->quote( $data{'city'} )
691 . $dbh->quote( $data{'phone'} )
693 . $dbh->quote( $data{'email'} )
695 . $dbh->quote( $data{'mobile'} )
697 . $dbh->quote( $data{'phonepro'} )
699 . $dbh->quote( $data{'opacnote'} )
701 . $dbh->quote( $data{'guarantorid'} )
703 . $dbh->quote( $data{'dateofbirth'} )
705 . $dbh->quote( $data{'branchcode'} )
707 . $dbh->quote( $data{'categorycode'} )
709 . $dbh->quote( $data{'dateenrolled'} )
711 . $dbh->quote( $data{'contactname'} )
713 . $dbh->quote( $data{'borrowernotes'} )
715 . $dbh->quote( $data{'dateexpiry'} )
717 . $dbh->quote( $data{'contactnote'} )
719 . $dbh->quote( $data{'B_address'} )
721 . $dbh->quote( $data{'B_zipcode'} )
723 . $dbh->quote( $data{'B_city'} )
725 . $dbh->quote( $data{'B_phone'} )
727 . $dbh->quote( $data{'B_email'}, )
729 . $dbh->quote( $data{'password'} )
731 . $dbh->quote( $data{'userid'} )
733 . $dbh->quote( $data{'sort1'} )
735 . $dbh->quote( $data{'sort2'} )
737 . $dbh->quote( $data{'contacttitle'} )
739 . $dbh->quote( $data{'emailpro'} )
740 . ",contactfirstname="
741 . $dbh->quote( $data{'contactfirstname'} ) . ",sex="
742 . $dbh->quote( $data{'sex'} ) . ",fax="
743 . $dbh->quote( $data{'fax'} )
745 . $dbh->quote( $data{'relationship'} )
747 . $dbh->quote( $data{'B_streetnumber'} )
749 . $dbh->quote( $data{'B_streettype'} )
751 . $dbh->quote( $data{'gonenoaddress'} )
753 . $dbh->quote( $data{'lost'} )
755 . $dbh->quote( $data{'debarred'} )
758 . $dbh->quote( $data{'ethnotes'} );
760 my $sth = $dbh->prepare($query);
763 $data{'borrowernumber'} = $dbh->{'mysql_insertid'};
765 &logaction(C4::Context->userenv->{'number'},"MEMBERS","CREATE",$data{'borrowernumber'},"")
766 if C4::Context->preference("BorrowersLog");
768 return $data{'borrowernumber'};
772 my ($uid,$member) = @_;
773 my $dbh = C4::Context->dbh;
774 # Make sure the userid chosen is unique and not theirs if non-empty. If it is not,
775 # Then we need to tell the user and have them create a new one.
778 "SELECT * FROM borrowers WHERE userid=? AND borrowernumber != ?");
779 $sth->execute( $uid, $member );
780 if ( ( $uid ne '' ) && ( my $row = $sth->fetchrow_hashref ) ) {
790 my ( $uid, $member, $digest ) = @_;
791 my $dbh = C4::Context->dbh;
793 #Make sure the userid chosen is unique and not theirs if non-empty. If it is not,
794 #Then we need to tell the user and have them create a new one.
797 "SELECT * FROM borrowers WHERE userid=? AND borrowernumber != ?");
798 $sth->execute( $uid, $member );
799 if ( ( $uid ne '' ) && ( my $row = $sth->fetchrow_hashref ) ) {
803 #Everything is good so we can update the information.
806 "update borrowers set userid=?, password=? where borrowernumber=?");
807 $sth->execute( $uid, $digest, $member );
811 &logaction(C4::Context->userenv->{'number'},"MEMBERS","CHANGE PASS",$member,"")
812 if C4::Context->preference("BorrowersLog");
817 =item fixup_cardnumber
819 Warning: The caller is responsible for locking the members table in write
820 mode, to avoid database corruption.
824 use vars qw( @weightings );
825 my @weightings = ( 8, 4, 6, 3, 5, 2, 1 );
827 sub fixup_cardnumber ($) {
828 my ($cardnumber) = @_;
829 my $autonumber_members = C4::Context->boolean_preference('autoMemberNum');
830 $autonumber_members = 0 unless defined $autonumber_members;
832 # Find out whether member numbers should be generated
833 # automatically. Should be either "1" or something else.
834 # Defaults to "0", which is interpreted as "no".
836 # if ($cardnumber !~ /\S/ && $autonumber_members) {
837 if ($autonumber_members) {
838 my $dbh = C4::Context->dbh;
839 if ( C4::Context->preference('checkdigit') eq 'katipo' ) {
841 # if checkdigit is selected, calculate katipo-style cardnumber.
842 # otherwise, just use the max()
843 # purpose: generate checksum'd member numbers.
844 # We'll assume we just got the max value of digits 2-8 of member #'s
845 # from the database and our job is to increment that by one,
846 # determine the 1st and 9th digits and return the full string.
849 "select max(substring(borrowers.cardnumber,2,7)) from borrowers"
853 my $data = $sth->fetchrow_hashref;
854 $cardnumber = $data->{'max(substring(borrowers.cardnumber,2,7))'};
856 if ( !$cardnumber ) { # If DB has no values,
857 $cardnumber = 1000000; # start at 1000000
864 for ( my $i = 0 ; $i < 8 ; $i += 1 ) {
866 # read weightings, left to right, 1 char at a time
867 my $temp1 = $weightings[$i];
869 # sequence left to right, 1 char at a time
870 my $temp2 = substr( $cardnumber, $i, 1 );
872 # mult each char 1-7 by its corresponding weighting
873 $sum += $temp1 * $temp2;
876 my $rem = ( $sum % 11 );
877 $rem = 'X' if $rem == 10;
879 $cardnumber = "V$cardnumber$rem";
883 # MODIFIED BY JF: mysql4.1 allows casting as an integer, which is probably
884 # better. I'll leave the original in in case it needs to be changed for you
887 "select max(cast(cardnumber as signed)) from borrowers");
889 #my $sth=$dbh->prepare("select max(borrowers.cardnumber) from borrowers");
893 my ($result) = $sth->fetchrow;
895 $cardnumber = $result + 1;
903 ($num_children, $children_arrayref) = &GetGuarantees($parent_borrno);
904 $child0_cardno = $children_arrayref->[0]{"cardnumber"};
905 $child0_borrno = $children_arrayref->[0]{"borrowernumber"};
907 C<&GetGuarantees> takes a borrower number (e.g., that of a patron
908 with children) and looks up the borrowers who are guaranteed by that
909 borrower (i.e., the patron's children).
911 C<&GetGuarantees> returns two values: an integer giving the number of
912 borrowers guaranteed by C<$parent_borrno>, and a reference to an array
913 of references to hash, which gives the actual results.
919 my ($borrowernumber) = @_;
920 my $dbh = C4::Context->dbh;
923 "select cardnumber,borrowernumber, firstname, surname from borrowers where guarantorid=?"
925 $sth->execute($borrowernumber);
928 my $data = $sth->fetchall_arrayref({});
930 return ( scalar(@$data), $data );
933 =head2 UpdateGuarantees
935 &UpdateGuarantees($parent_borrno);
938 C<&UpdateGuarantees> borrower data for an adulte and updates all the guarantees
939 with the modified information
944 sub UpdateGuarantees {
946 my $dbh = C4::Context->dbh;
947 my ( $count, $guarantees ) = GetGuarantees( $data{'borrowernumber'} );
948 for ( my $i = 0 ; $i < $count ; $i++ ) {
951 # It looks like the $i is only being returned to handle walking through
952 # the array, which is probably better done as a foreach loop.
954 my $guaquery = qq|UPDATE borrowers
955 SET address='$data{'address'}',fax='$data{'fax'}',
956 B_city='$data{'B_city'}',mobile='$data{'mobile'}',city='$data{'city'}',phone='$data{'phone'}'
957 WHERE borrowernumber='$guarantees->[$i]->{'borrowernumber'}'
959 my $sth3 = $dbh->prepare($guaquery);
964 =head2 GetPendingIssues
966 ($count, $issues) = &GetPendingIssues($borrowernumber);
968 Looks up what the patron with the given borrowernumber has borrowed.
970 C<&GetPendingIssues> returns a two-element array. C<$issues> is a
971 reference-to-array, where each element is a reference-to-hash; the
972 keys are the fields from the C<issues>, C<biblio>, and C<items> tables
973 in the Koha database. C<$count> is the number of elements in
979 sub GetPendingIssues {
980 my ($borrowernumber) = @_;
981 my $dbh = C4::Context->dbh;
983 my $sth = $dbh->prepare(
984 "SELECT * FROM issues
985 LEFT JOIN items ON issues.itemnumber=items.itemnumber
986 LEFT JOIN biblio ON items.biblionumber=biblio.biblionumber
987 LEFT JOIN biblioitems ON items.biblioitemnumber=biblioitems.biblioitemnumber
990 AND returndate IS NULL
991 ORDER BY issues.issuedate"
993 $sth->execute($borrowernumber);
994 my $data = $sth->fetchall_arrayref({});
995 my $today = POSIX::strftime("%Y%m%d", localtime);
997 my $datedue = $_->{'date_due'};
999 if ( $datedue < $today ) {
1000 $_->{'overdue'} = 1;
1004 return ( scalar(@$data), $data );
1009 ($count, $issues) = &GetAllIssues($borrowernumber, $sortkey, $limit);
1011 Looks up what the patron with the given borrowernumber has borrowed,
1012 and sorts the results.
1014 C<$sortkey> is the name of a field on which to sort the results. This
1015 should be the name of a field in the C<issues>, C<biblio>,
1016 C<biblioitems>, or C<items> table in the Koha database.
1018 C<$limit> is the maximum number of results to return.
1020 C<&GetAllIssues> returns a two-element array. C<$issues> is a
1021 reference-to-array, where each element is a reference-to-hash; the
1022 keys are the fields from the C<issues>, C<biblio>, C<biblioitems>, and
1023 C<items> tables of the Koha database. C<$count> is the number of
1024 elements in C<$issues>
1030 my ( $borrowernumber, $order, $limit ) = @_;
1032 #FIXME: sanity-check order and limit
1033 my $dbh = C4::Context->dbh;
1036 "Select *,items.timestamp AS itemstimestamp from
1038 LEFT JOIN items on items.itemnumber=issues.itemnumber
1039 LEFT JOIN biblio ON items.biblionumber=biblio.biblionumber
1040 LEFT JOIN biblioitems ON items.biblioitemnumber=biblioitems.biblioitemnumber
1041 where borrowernumber=?
1043 if ( $limit != 0 ) {
1044 $query .= " limit $limit";
1048 my $sth = $dbh->prepare($query);
1049 $sth->execute($borrowernumber);
1052 while ( my $data = $sth->fetchrow_hashref ) {
1053 $result[$i] = $data;
1058 # get all issued items for borrowernumber from oldissues table
1059 # large chunk of older issues data put into table oldissues
1060 # to speed up db calls for issuing items
1061 if ( C4::Context->preference("ReadingHistory") ) {
1062 my $query2 = "SELECT * FROM oldissues
1063 LEFT JOIN items ON items.itemnumber=oldissues.itemnumber
1064 LEFT JOIN biblio ON items.biblionumber=biblio.biblionumber
1065 LEFT JOIN biblioitems ON items.biblioitemnumber=biblioitems.biblioitemnumber
1066 WHERE borrowernumber=?
1068 if ( $limit != 0 ) {
1069 $limit = $limit - $count;
1070 $query2 .= " limit $limit";
1073 my $sth2 = $dbh->prepare($query2);
1074 $sth2->execute($borrowernumber);
1076 while ( my $data2 = $sth2->fetchrow_hashref ) {
1077 $result[$i] = $data2;
1084 return ( $i, \@result );
1088 =head2 GetMemberAccountRecords
1090 ($total, $acctlines, $count) = &GetMemberAccountRecords($borrowernumber);
1092 Looks up accounting data for the patron with the given borrowernumber.
1094 C<&GetMemberAccountRecords> returns a three-element array. C<$acctlines> is a
1095 reference-to-array, where each element is a reference-to-hash; the
1096 keys are the fields of the C<accountlines> table in the Koha database.
1097 C<$count> is the number of elements in C<$acctlines>. C<$total> is the
1098 total amount outstanding for all of the account lines.
1103 sub GetMemberAccountRecords {
1104 my ($borrowernumber,$date) = @_;
1105 my $dbh = C4::Context->dbh;
1111 WHERE borrowernumber=?);
1112 my @bind = ($borrowernumber);
1113 if ($date && $date ne ''){
1119 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 $query = qq| SELECT *
1155 WHERE borrowernumber=?
1157 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')
1158 AND amountoutstanding != '0'
1159 ORDER BY notify_id,accounttype
1161 my $sth = $dbh->prepare($query);
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 = &checkuniquemember($collectivity,$surname,$categorycode,$firstname,$dateofbirth);
1178 Checks that a member exists or not in the database.
1180 C<&result> is 1 (=exist) or 0 (=does not exist)
1181 C<&collectivity> is 1 (= we add a collectivity) or 0 (= we add a physical member)
1182 C<&surname> is the surname
1183 C<&categorycode> is from categorycode table
1184 C<&firstname> is the firstname (only if collectivity=0)
1185 C<&dateofbirth> is the date of birth (only if collectivity=0)
1189 sub checkuniquemember {
1190 my ( $collectivity, $surname, $firstname, $dateofbirth ) = @_;
1191 my $dbh = C4::Context->dbh;
1193 if ($collectivity) {
1195 # $request="select count(*) from borrowers where surname=? and categorycode=?";
1197 "select borrowernumber,categorycode from borrowers where surname=? ";
1201 # $request="select count(*) from borrowers where surname=? and categorycode=? and firstname=? and dateofbirth=?";
1203 "select borrowernumber,categorycode from borrowers where surname=? and firstname=? and dateofbirth=?";
1205 my $sth = $dbh->prepare($request);
1206 if ($collectivity) {
1207 $sth->execute( uc($surname) );
1210 $sth->execute( uc($surname), ucfirst($firstname), $dateofbirth );
1212 my @data = $sth->fetchrow;
1215 return $data[0], $data[1];
1225 sub checkcardnumber {
1226 my ($cardnumber) = @_;
1227 my $dbh = C4::Context->dbh;
1228 my $query = "SELECT * FROM borrowers WHERE cardnumber=?";
1229 my $sth = $dbh->prepare($query);
1230 $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)