kohabug 2379 When a borrower is added manually in Koha...
[koha.git] / C4 / Members.pm
blob70a85c354301ab055e94a39f769868309a09d889
1 package C4::Members;
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
10 # version.
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
21 use strict;
22 use C4::Context;
23 use C4::Dates qw(format_date_in_iso);
24 use Digest::MD5 qw(md5_base64);
25 use Date::Calc qw/Today Add_Delta_YM/;
26 use C4::Log; # logaction
27 use C4::Overdues;
28 use C4::Reserves;
29 use C4::Accounts;
31 our ($VERSION,@ISA,@EXPORT,@EXPORT_OK,$debug);
33 BEGIN {
34 $VERSION = 3.02;
35 $debug = $ENV{DEBUG} || 0;
36 require Exporter;
37 @ISA = qw(Exporter);
38 #Get data
39 push @EXPORT, qw(
40 &SearchMember
41 &GetMemberDetails
42 &GetMember
44 &GetGuarantees
46 &GetMemberIssuesAndFines
47 &GetPendingIssues
48 &GetAllIssues
50 &get_institutions
51 &getzipnamecity
52 &getidcity
54 &GetAge
55 &GetCities
56 &GetRoadTypes
57 &GetRoadTypeDetails
58 &GetSortDetails
59 &GetTitles
61 &GetPatronImage
62 &PutPatronImage
63 &RmPatronImage
65 &GetMemberAccountRecords
66 &GetBorNotifyAcctRecord
68 &GetborCatFromCatType
69 &GetBorrowercategory
70 &GetBorrowercategoryList
72 &GetBorrowersWhoHaveNotBorrowedSince
73 &GetBorrowersWhoHaveNeverBorrowed
74 &GetBorrowersWithIssuesHistoryOlderThan
76 &GetExpiryDate
79 #Modify data
80 push @EXPORT, qw(
81 &ModMember
82 &changepassword
85 #Delete data
86 push @EXPORT, qw(
87 &DelMember
90 #Insert data
91 push @EXPORT, qw(
92 &AddMember
93 &add_member_orgs
94 &MoveMemberToDeleted
95 &ExtendMemberSubscriptionTo
98 #Check data
99 push @EXPORT, qw(
100 &checkuniquemember
101 &checkuserpassword
102 &Check_Userid
103 &fixEthnicity
104 &ethnicitycategories
105 &fixup_cardnumber
106 &checkcardnumber
110 =head1 NAME
112 C4::Members - Perl Module containing convenience functions for member handling
114 =head1 SYNOPSIS
116 use C4::Members;
118 =head1 DESCRIPTION
120 This module contains routines for adding, modifying and deleting members/patrons/borrowers
122 =head1 FUNCTIONS
124 =over 2
126 =item SearchMember
128 ($count, $borrowers) = &SearchMember($searchstring, $type,$category_type,$filter,$showallbranches);
130 =back
132 Looks up patrons (borrowers) by name.
134 BUGFIX 499: C<$type> is now used to determine type of search.
135 if $type is "simple", search is performed on the first letter of the
136 surname only.
138 $category_type is used to get a specified type of user.
139 (mainly adults when creating a child.)
141 C<$searchstring> is a space-separated list of search terms. Each term
142 must match the beginning a borrower's surname, first name, or other
143 name.
145 C<$filter> is assumed to be a list of elements to filter results on
147 C<$showallbranches> is used in IndependantBranches Context to display all branches results.
149 C<&SearchMember> returns a two-element list. C<$borrowers> is a
150 reference-to-array; each element is a reference-to-hash, whose keys
151 are the fields of the C<borrowers> table in the Koha database.
152 C<$count> is the number of elements in C<$borrowers>.
154 =cut
157 #used by member enquiries from the intranet
158 #called by member.pl and circ/circulation.pl
159 sub SearchMember {
160 my ($searchstring, $orderby, $type,$category_type,$filter,$showallbranches ) = @_;
161 my $dbh = C4::Context->dbh;
162 my $query = "";
163 my $count;
164 my @data;
165 my @bind = ();
167 # this is used by circulation everytime a new borrowers cardnumber is scanned
168 # so we can check an exact match first, if that works return, otherwise do the rest
169 $query = "SELECT * FROM borrowers
170 LEFT JOIN categories ON borrowers.categorycode=categories.categorycode
172 my $sth = $dbh->prepare("$query WHERE cardnumber = ?");
173 $sth->execute($searchstring);
174 my $data = $sth->fetchall_arrayref({});
175 if (@$data){
176 return ( scalar(@$data), $data );
178 $sth->finish;
180 if ( $type eq "simple" ) # simple search for one letter only
182 $query .= ($category_type ? " AND category_type = ".$dbh->quote($category_type) : "");
183 $query .= " WHERE (surname LIKE ? OR cardnumber like ?) ";
184 if (C4::Context->preference("IndependantBranches") && !$showallbranches){
185 if (C4::Context->userenv && C4::Context->userenv->{flags}!=1 && C4::Context->userenv->{'branch'}){
186 $query.=" AND borrowers.branchcode =".$dbh->quote(C4::Context->userenv->{'branch'}) unless (C4::Context->userenv->{'branch'} eq "insecure");
189 $query.=" ORDER BY $orderby";
190 @bind = ("$searchstring%","$searchstring");
192 else # advanced search looking in surname, firstname and othernames
194 @data = split( ' ', $searchstring );
195 $count = @data;
196 $query .= " WHERE ";
197 if (C4::Context->preference("IndependantBranches") && !$showallbranches){
198 if (C4::Context->userenv && C4::Context->userenv->{flags}!=1 && C4::Context->userenv->{'branch'}){
199 $query.=" borrowers.branchcode =".$dbh->quote(C4::Context->userenv->{'branch'})." AND " unless (C4::Context->userenv->{'branch'} eq "insecure");
202 $query.="((surname LIKE ? OR surname LIKE ?
203 OR firstname LIKE ? OR firstname LIKE ?
204 OR othernames LIKE ? OR othernames LIKE ?)
206 ($category_type?" AND category_type = ".$dbh->quote($category_type):"");
207 @bind = (
208 "$data[0]%", "% $data[0]%", "$data[0]%", "% $data[0]%",
209 "$data[0]%", "% $data[0]%"
211 for ( my $i = 1 ; $i < $count ; $i++ ) {
212 $query = $query . " AND (" . " surname LIKE ? OR surname LIKE ?
213 OR firstname LIKE ? OR firstname LIKE ?
214 OR othernames LIKE ? OR othernames LIKE ?)";
215 push( @bind,
216 "$data[$i]%", "% $data[$i]%", "$data[$i]%",
217 "% $data[$i]%", "$data[$i]%", "% $data[$i]%" );
219 # FIXME - .= <<EOT;
221 $query = $query . ") OR cardnumber LIKE ? ";
222 push( @bind, $searchstring );
223 if (C4::Context->preference('ExtendedPatronAttributes')) {
224 $query .= "OR borrowernumber IN (
225 SELECT borrowernumber
226 FROM borrower_attributes
227 JOIN borrower_attribute_types USING (code)
228 WHERE staff_searchable = 1
229 AND attribute like ?
231 push (@bind, $searchstring);
233 $query .= "order by $orderby";
235 # FIXME - .= <<EOT;
238 $sth = $dbh->prepare($query);
240 $debug and print STDERR "Q $orderby : $query\n";
241 $sth->execute(@bind);
242 my @results;
243 $data = $sth->fetchall_arrayref({});
245 $sth->finish;
246 return ( scalar(@$data), $data );
249 =head2 GetMemberDetails
251 ($borrower) = &GetMemberDetails($borrowernumber, $cardnumber);
253 Looks up a patron and returns information about him or her. If
254 C<$borrowernumber> is true (nonzero), C<&GetMemberDetails> looks
255 up the borrower by number; otherwise, it looks up the borrower by card
256 number.
258 C<$borrower> is a reference-to-hash whose keys are the fields of the
259 borrowers table in the Koha database. In addition,
260 C<$borrower-E<gt>{flags}> is a hash giving more detailed information
261 about the patron. Its keys act as flags :
263 if $borrower->{flags}->{LOST} {
264 # Patron's card was reported lost
267 Each flag has a C<message> key, giving a human-readable explanation of
268 the flag. If the state of a flag means that the patron should not be
269 allowed to borrow any more books, then it will have a C<noissues> key
270 with a true value.
272 The possible flags are:
274 =head3 CHARGES
276 =over 4
278 =item Shows the patron's credit or debt, if any.
280 =back
282 =head3 GNA
284 =over 4
286 =item (Gone, no address.) Set if the patron has left without giving a
287 forwarding address.
289 =back
291 =head3 LOST
293 =over 4
295 =item Set if the patron's card has been reported as lost.
297 =back
299 =head3 DBARRED
301 =over 4
303 =item Set if the patron has been debarred.
305 =back
307 =head3 NOTES
309 =over 4
311 =item Any additional notes about the patron.
313 =back
315 =head3 ODUES
317 =over 4
319 =item Set if the patron has overdue items. This flag has several keys:
321 C<$flags-E<gt>{ODUES}{itemlist}> is a reference-to-array listing the
322 overdue items. Its elements are references-to-hash, each describing an
323 overdue item. The keys are selected fields from the issues, biblio,
324 biblioitems, and items tables of the Koha database.
326 C<$flags-E<gt>{ODUES}{itemlist}> is a string giving a text listing of
327 the overdue items, one per line.
329 =back
331 =head3 WAITING
333 =over 4
335 =item Set if any items that the patron has reserved are available.
337 C<$flags-E<gt>{WAITING}{itemlist}> is a reference-to-array listing the
338 available items. Each element is a reference-to-hash whose keys are
339 fields from the reserves table of the Koha database.
341 =back
343 C<$borrower-E<gt>{authflags}> is a hash giving more detailed information
344 about the top-level permissions flags set for the borrower. For example,
345 if a user has the "editcatalogue" permission,
346 C<$borrower-E<gt>{authflags}-E<gt>{editcatalogue}> will exist and have
347 the value "1".
349 =cut
351 sub GetMemberDetails {
352 my ( $borrowernumber, $cardnumber ) = @_;
353 my $dbh = C4::Context->dbh;
354 my $query;
355 my $sth;
356 if ($borrowernumber) {
357 $sth = $dbh->prepare("select borrowers.*,category_type from borrowers left join categories on borrowers.categorycode=categories.categorycode where borrowernumber=?");
358 $sth->execute($borrowernumber);
360 elsif ($cardnumber) {
361 $sth = $dbh->prepare("select borrowers.*,category_type from borrowers left join categories on borrowers.categorycode=categories.categorycode where cardnumber=?");
362 $sth->execute($cardnumber);
364 else {
365 return undef;
367 my $borrower = $sth->fetchrow_hashref;
368 my ($amount) = GetMemberAccountRecords( $borrowernumber);
369 $borrower->{'amountoutstanding'} = $amount;
370 # FIXME - patronflags calls GetMemberAccountRecords... just have patronflags return $amount
371 my $flags = patronflags( $borrower);
372 my $accessflagshash;
374 $sth = $dbh->prepare("select bit,flag from userflags");
375 $sth->execute;
376 while ( my ( $bit, $flag ) = $sth->fetchrow ) {
377 if ( $borrower->{'flags'} && $borrower->{'flags'} & 2**$bit ) {
378 $accessflagshash->{$flag} = 1;
381 $sth->finish;
382 $borrower->{'flags'} = $flags;
383 $borrower->{'authflags'} = $accessflagshash;
385 # find out how long the membership lasts
386 $sth =
387 $dbh->prepare(
388 "select enrolmentperiod from categories where categorycode = ?");
389 $sth->execute( $borrower->{'categorycode'} );
390 my $enrolment = $sth->fetchrow;
391 $borrower->{'enrolmentperiod'} = $enrolment;
392 return ($borrower); #, $flags, $accessflagshash);
395 =head2 patronflags
397 Not exported
399 NOTE!: If you change this function, be sure to update the POD for
400 &GetMemberDetails.
402 $flags = &patronflags($patron);
404 $flags->{CHARGES}
405 {message} Message showing patron's credit or debt
406 {noissues} Set if patron owes >$5.00
407 {GNA} Set if patron gone w/o address
408 {message} "Borrower has no valid address"
409 {noissues} Set.
410 {LOST} Set if patron's card reported lost
411 {message} Message to this effect
412 {noissues} Set.
413 {DBARRED} Set is patron is debarred
414 {message} Message to this effect
415 {noissues} Set.
416 {NOTES} Set if patron has notes
417 {message} Notes about patron
418 {ODUES} Set if patron has overdue books
419 {message} "Yes"
420 {itemlist} ref-to-array: list of overdue books
421 {itemlisttext} Text list of overdue items
422 {WAITING} Set if there are items available that the
423 patron reserved
424 {message} Message to this effect
425 {itemlist} ref-to-array: list of available items
427 =cut
428 # FIXME rename this function.
429 sub patronflags {
430 my %flags;
431 my ( $patroninformation) = @_;
432 my $dbh=C4::Context->dbh;
433 my ($amount) = GetMemberAccountRecords( $patroninformation->{'borrowernumber'});
434 if ( $amount > 0 ) {
435 my %flaginfo;
436 my $noissuescharge = C4::Context->preference("noissuescharge");
437 $flaginfo{'message'} = sprintf "Patron owes \$%.02f", $amount;
438 $flaginfo{'amount'} = sprintf "%.02f",$amount;
439 if ( $amount > $noissuescharge ) {
440 $flaginfo{'noissues'} = 1;
442 $flags{'CHARGES'} = \%flaginfo;
444 elsif ( $amount < 0 ) {
445 my %flaginfo;
446 $flaginfo{'message'} = sprintf "Patron has credit of \$%.02f", -$amount;
447 $flags{'CREDITS'} = \%flaginfo;
449 if ( $patroninformation->{'gonenoaddress'}
450 && $patroninformation->{'gonenoaddress'} == 1 )
452 my %flaginfo;
453 $flaginfo{'message'} = 'Borrower has no valid address.';
454 $flaginfo{'noissues'} = 1;
455 $flags{'GNA'} = \%flaginfo;
457 if ( $patroninformation->{'lost'} && $patroninformation->{'lost'} == 1 ) {
458 my %flaginfo;
459 $flaginfo{'message'} = 'Borrower\'s card reported lost.';
460 $flaginfo{'noissues'} = 1;
461 $flags{'LOST'} = \%flaginfo;
463 if ( $patroninformation->{'debarred'}
464 && $patroninformation->{'debarred'} == 1 )
466 my %flaginfo;
467 $flaginfo{'message'} = 'Borrower is Debarred.';
468 $flaginfo{'noissues'} = 1;
469 $flags{'DBARRED'} = \%flaginfo;
471 if ( $patroninformation->{'borrowernotes'}
472 && $patroninformation->{'borrowernotes'} )
474 my %flaginfo;
475 $flaginfo{'message'} = "$patroninformation->{'borrowernotes'}";
476 $flags{'NOTES'} = \%flaginfo;
478 my ( $odues, $itemsoverdue ) =
479 checkoverdues( $patroninformation->{'borrowernumber'}, $dbh );
480 if ( $odues > 0 ) {
481 my %flaginfo;
482 $flaginfo{'message'} = "Yes";
483 $flaginfo{'itemlist'} = $itemsoverdue;
484 foreach ( sort { $a->{'date_due'} cmp $b->{'date_due'} }
485 @$itemsoverdue )
487 $flaginfo{'itemlisttext'} .=
488 "$_->{'date_due'} $_->{'barcode'} $_->{'title'} \n";
490 $flags{'ODUES'} = \%flaginfo;
492 my @itemswaiting = C4::Reserves::GetReservesFromBorrowernumber( $patroninformation->{'borrowernumber'},'W' );
493 my $nowaiting = scalar @itemswaiting;
494 if ( $nowaiting > 0 ) {
495 my %flaginfo;
496 $flaginfo{'message'} = "Reserved items available";
497 $flaginfo{'itemlist'} = \@itemswaiting;
498 $flags{'WAITING'} = \%flaginfo;
500 return ( \%flags );
504 =head2 GetMember
506 $borrower = &GetMember($information, $type);
508 Looks up information about a patron (borrower) by either card number
509 ,firstname, or borrower number, depending on $type value.
510 If C<$type> == 'cardnumber', C<&GetBorrower>
511 searches by cardnumber then by firstname if not found in cardnumber;
512 otherwise, it searches by borrowernumber.
514 C<&GetBorrower> returns a reference-to-hash whose keys are the fields of
515 the C<borrowers> table in the Koha database.
517 =cut
520 sub GetMember {
521 my ( $information, $type ) = @_;
522 my $dbh = C4::Context->dbh;
523 my $sth;
524 my $select = "
525 SELECT borrowers.*, categories.category_type, categories.description
526 FROM borrowers
527 LEFT JOIN categories on borrowers.categorycode=categories.categorycode
529 if ( defined $type && ( $type eq 'cardnumber' || $type eq 'firstname'|| $type eq 'userid'|| $type eq 'borrowernumber' ) ){
530 $information = uc $information;
531 $sth = $dbh->prepare("$select WHERE $type=?");
532 } else {
533 $sth = $dbh->prepare("$select WHERE borrowernumber=?");
535 $sth->execute($information);
536 my $data = $sth->fetchrow_hashref;
537 $sth->finish;
538 ($data) and return ($data);
540 if ($type eq 'cardnumber' || $type eq 'firstname') { # otherwise, try with firstname
541 $sth = $dbh->prepare("$select WHERE firstname like ?");
542 $sth->execute($information);
543 $data = $sth->fetchrow_hashref;
544 $sth->finish;
545 ($data) and return ($data);
547 return undef;
550 =head2 GetMemberIssuesAndFines
552 ($overdue_count, $issue_count, $total_fines) = &GetMemberIssuesAndFines($borrowernumber);
554 Returns aggregate data about items borrowed by the patron with the
555 given borrowernumber.
557 C<&GetMemberIssuesAndFines> returns a three-element array. C<$overdue_count> is the
558 number of overdue items the patron currently has borrowed. C<$issue_count> is the
559 number of books the patron currently has borrowed. C<$total_fines> is
560 the total fine currently due by the borrower.
562 =cut
565 sub GetMemberIssuesAndFines {
566 my ( $borrowernumber ) = @_;
567 my $dbh = C4::Context->dbh;
568 my $query = "SELECT COUNT(*) FROM issues WHERE borrowernumber = ?";
570 $debug and warn $query."\n";
571 my $sth = $dbh->prepare($query);
572 $sth->execute($borrowernumber);
573 my $issue_count = $sth->fetchrow_arrayref->[0];
574 $sth->finish;
576 $sth = $dbh->prepare(
577 "SELECT COUNT(*) FROM issues
578 WHERE borrowernumber = ?
579 AND date_due < now()"
581 $sth->execute($borrowernumber);
582 my $overdue_count = $sth->fetchrow_arrayref->[0];
583 $sth->finish;
585 $sth = $dbh->prepare("SELECT SUM(amountoutstanding) FROM accountlines WHERE borrowernumber = ?");
586 $sth->execute($borrowernumber);
587 my $total_fines = $sth->fetchrow_arrayref->[0];
588 $sth->finish;
590 return ($overdue_count, $issue_count, $total_fines);
593 =head2
595 =head2 ModMember
597 =over 4
599 my $success = ModMember(borrowernumber => $borrowernumber, [ field => value ]... );
601 Modify borrower's data. All date fields should ALREADY be in ISO format.
603 return :
604 true on success, or false on failure
606 =back
608 =cut
611 sub ModMember {
612 my (%data) = @_;
613 my $dbh = C4::Context->dbh;
614 my $iso_re = C4::Dates->new()->regexp('iso');
615 foreach (qw(dateofbirth dateexpiry dateenrolled)) {
616 if (my $tempdate = $data{$_}) { # assignment, not comparison
617 ($tempdate =~ /$iso_re/) and next; # Congatulations, you sent a valid ISO date.
618 warn "ModMember given $_ not in ISO format ($tempdate)";
619 if (my $tempdate2 = format_date_in_iso($tempdate)) { # assignment, not comparison
620 $data{$_} = $tempdate2;
621 } else {
622 warn "ModMember cannot convert '$tempdate' (from syspref)";
626 if (!$data{'dateofbirth'}){
627 delete $data{'dateofbirth'};
629 my $qborrower=$dbh->prepare("SHOW columns from borrowers");
630 $qborrower->execute;
631 my %hashborrowerfields;
632 while (my ($field)=$qborrower->fetchrow){
633 $hashborrowerfields{$field}=1;
635 my $query = "UPDATE borrowers SET \n";
636 my $sth;
637 my @parameters;
639 # test to know if you must update or not the borrower password
640 if ( exists $data{'password'} ) {
641 if ( $data{'password'} eq '****' ) {
642 delete $data{'password'};
643 } else {
644 $data{'password'} = md5_base64( $data{'password'} ) if ( $data{'password'} ne "" );
645 delete $data{'password'} if ( $data{password} eq "" );
648 foreach (keys %data){
649 if ($_ ne 'borrowernumber' and $_ ne 'flags' and $hashborrowerfields{$_}){
650 $query .= " $_=?, ";
651 push @parameters,$data{$_};
654 $query =~ s/, $//;
655 $query .= " WHERE borrowernumber=?";
656 push @parameters, $data{'borrowernumber'};
657 $debug and print STDERR "$query (executed w/ arg: $data{'borrowernumber'})";
658 $sth = $dbh->prepare($query);
659 my $execute_success = $sth->execute(@parameters);
660 $sth->finish;
662 # ok if its an adult (type) it may have borrowers that depend on it as a guarantor
663 # so when we update information for an adult we should check for guarantees and update the relevant part
664 # of their records, ie addresses and phone numbers
665 my $borrowercategory= GetBorrowercategory( $data{'category_type'} );
666 if ( exists $borrowercategory->{'category_type'} && $borrowercategory->{'category_type'} eq ('A' || 'S') ) {
667 # is adult check guarantees;
668 UpdateGuarantees(%data);
670 logaction("MEMBERS", "MODIFY", $data{'borrowernumber'}, "$query (executed w/ arg: $data{'borrowernumber'})")
671 if C4::Context->preference("BorrowersLog");
673 return $execute_success;
677 =head2
679 =head2 AddMember
681 $borrowernumber = &AddMember(%borrower);
683 insert new borrower into table
684 Returns the borrowernumber
686 =cut
689 sub AddMember {
690 my (%data) = @_;
691 my $dbh = C4::Context->dbh;
692 $data{'userid'} = '' unless $data{'password'};
693 $data{'password'} = md5_base64( $data{'password'} ) if $data{'password'};
695 # WE SHOULD NEVER PASS THIS SUBROUTINE ANYTHING OTHER THAN ISO DATES
696 # IF YOU UNCOMMENT THESE LINES YOU BETTER HAVE A DARN COMPELLING REASON
697 # $data{'dateofbirth'} = format_date_in_iso( $data{'dateofbirth'} );
698 # $data{'dateenrolled'} = format_date_in_iso( $data{'dateenrolled'});
699 # $data{'dateexpiry'} = format_date_in_iso( $data{'dateexpiry'} );
700 # This query should be rewritten to use "?" at execute.
701 if (!$data{'dateofbirth'}){
702 undef ($data{'dateofbirth'});
704 my $query =
705 "insert into borrowers set cardnumber=" . $dbh->quote( $data{'cardnumber'} )
706 . ",surname=" . $dbh->quote( $data{'surname'} )
707 . ",firstname=" . $dbh->quote( $data{'firstname'} )
708 . ",title=" . $dbh->quote( $data{'title'} )
709 . ",othernames=" . $dbh->quote( $data{'othernames'} )
710 . ",initials=" . $dbh->quote( $data{'initials'} )
711 . ",streetnumber=". $dbh->quote( $data{'streetnumber'} )
712 . ",streettype=" . $dbh->quote( $data{'streettype'} )
713 . ",address=" . $dbh->quote( $data{'address'} )
714 . ",address2=" . $dbh->quote( $data{'address2'} )
715 . ",zipcode=" . $dbh->quote( $data{'zipcode'} )
716 . ",city=" . $dbh->quote( $data{'city'} )
717 . ",phone=" . $dbh->quote( $data{'phone'} )
718 . ",email=" . $dbh->quote( $data{'email'} )
719 . ",mobile=" . $dbh->quote( $data{'mobile'} )
720 . ",phonepro=" . $dbh->quote( $data{'phonepro'} )
721 . ",opacnote=" . $dbh->quote( $data{'opacnote'} )
722 . ",guarantorid=" . $dbh->quote( $data{'guarantorid'} )
723 . ",dateofbirth=" . $dbh->quote( $data{'dateofbirth'} )
724 . ",branchcode=" . $dbh->quote( $data{'branchcode'} )
725 . ",categorycode=" . $dbh->quote( $data{'categorycode'} )
726 . ",dateenrolled=" . $dbh->quote( $data{'dateenrolled'} )
727 . ",contactname=" . $dbh->quote( $data{'contactname'} )
728 . ",borrowernotes=" . $dbh->quote( $data{'borrowernotes'} )
729 . ",dateexpiry=" . $dbh->quote( $data{'dateexpiry'} )
730 . ",contactnote=" . $dbh->quote( $data{'contactnote'} )
731 . ",B_address=" . $dbh->quote( $data{'B_address'} )
732 . ",B_zipcode=" . $dbh->quote( $data{'B_zipcode'} )
733 . ",B_city=" . $dbh->quote( $data{'B_city'} )
734 . ",B_phone=" . $dbh->quote( $data{'B_phone'} )
735 . ",B_email=" . $dbh->quote( $data{'B_email'} )
736 . ",password=" . $dbh->quote( $data{'password'} )
737 . ",userid=" . $dbh->quote( $data{'userid'} )
738 . ",sort1=" . $dbh->quote( $data{'sort1'} )
739 . ",sort2=" . $dbh->quote( $data{'sort2'} )
740 . ",contacttitle=" . $dbh->quote( $data{'contacttitle'} )
741 . ",emailpro=" . $dbh->quote( $data{'emailpro'} )
742 . ",contactfirstname=" . $dbh->quote( $data{'contactfirstname'} )
743 . ",sex=" . $dbh->quote( $data{'sex'} )
744 . ",fax=" . $dbh->quote( $data{'fax'} )
745 . ",relationship=" . $dbh->quote( $data{'relationship'} )
746 . ",B_streetnumber=" . $dbh->quote( $data{'B_streetnumber'} )
747 . ",B_streettype=" . $dbh->quote( $data{'B_streettype'} )
748 . ",gonenoaddress=" . $dbh->quote( $data{'gonenoaddress'} )
749 . ",lost=" . $dbh->quote( $data{'lost'} )
750 . ",debarred=" . $dbh->quote( $data{'debarred'} )
751 . ",ethnicity=" . $dbh->quote( $data{'ethnicity'} )
752 . ",ethnotes=" . $dbh->quote( $data{'ethnotes'} )
753 . ",altcontactsurname=" . $dbh->quote( $data{'altcontactsurname'} )
754 . ",altcontactfirstname=" . $dbh->quote( $data{'altcontactfirstname'} )
755 . ",altcontactaddress1=" . $dbh->quote( $data{'altcontactaddress1'} )
756 . ",altcontactaddress2=" . $dbh->quote( $data{'altcontactaddress2'} )
757 . ",altcontactaddress3=" . $dbh->quote( $data{'altcontactaddress3'} )
758 . ",altcontactzipcode=" . $dbh->quote( $data{'altcontactzipcode'} )
759 . ",altcontactphone=" . $dbh->quote( $data{'altcontactphone'} ) ;
760 $debug and print STDERR "AddMember SQL: ($query)\n";
761 my $sth = $dbh->prepare($query);
762 # print "Executing SQL: $query\n";
763 $sth->execute();
764 $sth->finish;
765 $data{'borrowernumber'} = $dbh->{'mysql_insertid'}; # unneeded w/ autoincrement ?
766 # mysql_insertid is probably bad. not necessarily accurate and mysql-specific at best.
768 logaction("MEMBERS", "CREATE", $data{'borrowernumber'}, "") if C4::Context->preference("BorrowersLog");
770 # check for enrollment fee & add it if needed
771 $sth = $dbh->prepare("SELECT enrolmentfee FROM categories WHERE categorycode=?");
772 $sth->execute($data{'categorycode'});
773 my ($enrolmentfee) = $sth->fetchrow;
774 if ($enrolmentfee && $enrolmentfee > 0) {
775 # insert fee in patron debts
776 manualinvoice($data{'borrowernumber'}, '', '', 'A', $enrolmentfee);
778 return $data{'borrowernumber'};
781 sub Check_Userid {
782 my ($uid,$member) = @_;
783 my $dbh = C4::Context->dbh;
784 # Make sure the userid chosen is unique and not theirs if non-empty. If it is not,
785 # Then we need to tell the user and have them create a new one.
786 my $sth =
787 $dbh->prepare(
788 "SELECT * FROM borrowers WHERE userid=? AND borrowernumber != ?");
789 $sth->execute( $uid, $member );
790 if ( ( $uid ne '' ) && ( my $row = $sth->fetchrow_hashref ) ) {
791 return 0;
793 else {
794 return 1;
799 sub changepassword {
800 my ( $uid, $member, $digest ) = @_;
801 my $dbh = C4::Context->dbh;
803 #Make sure the userid chosen is unique and not theirs if non-empty. If it is not,
804 #Then we need to tell the user and have them create a new one.
805 my $resultcode;
806 my $sth =
807 $dbh->prepare(
808 "SELECT * FROM borrowers WHERE userid=? AND borrowernumber != ?");
809 $sth->execute( $uid, $member );
810 if ( ( $uid ne '' ) && ( my $row = $sth->fetchrow_hashref ) ) {
811 $resultcode=0;
813 else {
814 #Everything is good so we can update the information.
815 $sth =
816 $dbh->prepare(
817 "update borrowers set userid=?, password=? where borrowernumber=?");
818 $sth->execute( $uid, $digest, $member );
819 $resultcode=1;
822 logaction("MEMBERS", "CHANGE PASS", $member, "") if C4::Context->preference("BorrowersLog");
823 return $resultcode;
828 =head2 fixup_cardnumber
830 Warning: The caller is responsible for locking the members table in write
831 mode, to avoid database corruption.
833 =cut
835 use vars qw( @weightings );
836 my @weightings = ( 8, 4, 6, 3, 5, 2, 1 );
838 sub fixup_cardnumber ($) {
839 my ($cardnumber) = @_;
840 my $autonumber_members = C4::Context->boolean_preference('autoMemberNum');
841 $autonumber_members = 0 unless defined $autonumber_members;
843 # Find out whether member numbers should be generated
844 # automatically. Should be either "1" or something else.
845 # Defaults to "0", which is interpreted as "no".
847 # if ($cardnumber !~ /\S/ && $autonumber_members) {
848 if ($autonumber_members) {
849 my $dbh = C4::Context->dbh;
850 if ( C4::Context->preference('checkdigit') eq 'katipo' ) {
852 # if checkdigit is selected, calculate katipo-style cardnumber.
853 # otherwise, just use the max()
854 # purpose: generate checksum'd member numbers.
855 # We'll assume we just got the max value of digits 2-8 of member #'s
856 # from the database and our job is to increment that by one,
857 # determine the 1st and 9th digits and return the full string.
858 my $sth =
859 $dbh->prepare(
860 "select max(substring(borrowers.cardnumber,2,7)) from borrowers"
862 $sth->execute;
864 my $data = $sth->fetchrow_hashref;
865 $cardnumber = $data->{'max(substring(borrowers.cardnumber,2,7))'};
866 $sth->finish;
867 if ( !$cardnumber ) { # If DB has no values,
868 $cardnumber = 1000000; # start at 1000000
870 else {
871 $cardnumber += 1;
874 my $sum = 0;
875 for ( my $i = 0 ; $i < 8 ; $i += 1 ) {
877 # read weightings, left to right, 1 char at a time
878 my $temp1 = $weightings[$i];
880 # sequence left to right, 1 char at a time
881 my $temp2 = substr( $cardnumber, $i, 1 );
883 # mult each char 1-7 by its corresponding weighting
884 $sum += $temp1 * $temp2;
887 my $rem = ( $sum % 11 );
888 $rem = 'X' if $rem == 10;
890 $cardnumber = "V$cardnumber$rem";
892 else {
894 # MODIFIED BY JF: mysql4.1 allows casting as an integer, which is probably
895 # better. I'll leave the original in in case it needs to be changed for you
896 my $sth =
897 $dbh->prepare(
898 "select max(cast(cardnumber as signed)) from borrowers");
900 #my $sth=$dbh->prepare("select max(borrowers.cardnumber) from borrowers");
902 $sth->execute;
904 my ($result) = $sth->fetchrow;
905 $sth->finish;
906 $cardnumber = $result + 1;
909 return $cardnumber;
912 =head2 GetGuarantees
914 ($num_children, $children_arrayref) = &GetGuarantees($parent_borrno);
915 $child0_cardno = $children_arrayref->[0]{"cardnumber"};
916 $child0_borrno = $children_arrayref->[0]{"borrowernumber"};
918 C<&GetGuarantees> takes a borrower number (e.g., that of a patron
919 with children) and looks up the borrowers who are guaranteed by that
920 borrower (i.e., the patron's children).
922 C<&GetGuarantees> returns two values: an integer giving the number of
923 borrowers guaranteed by C<$parent_borrno>, and a reference to an array
924 of references to hash, which gives the actual results.
926 =cut
929 sub GetGuarantees {
930 my ($borrowernumber) = @_;
931 my $dbh = C4::Context->dbh;
932 my $sth =
933 $dbh->prepare(
934 "select cardnumber,borrowernumber, firstname, surname from borrowers where guarantorid=?"
936 $sth->execute($borrowernumber);
938 my @dat;
939 my $data = $sth->fetchall_arrayref({});
940 $sth->finish;
941 return ( scalar(@$data), $data );
944 =head2 UpdateGuarantees
946 &UpdateGuarantees($parent_borrno);
949 C<&UpdateGuarantees> borrower data for an adulte and updates all the guarantees
950 with the modified information
952 =cut
955 sub UpdateGuarantees {
956 my (%data) = @_;
957 my $dbh = C4::Context->dbh;
958 my ( $count, $guarantees ) = GetGuarantees( $data{'borrowernumber'} );
959 for ( my $i = 0 ; $i < $count ; $i++ ) {
961 # FIXME
962 # It looks like the $i is only being returned to handle walking through
963 # the array, which is probably better done as a foreach loop.
965 my $guaquery = qq|UPDATE borrowers
966 SET address='$data{'address'}',fax='$data{'fax'}',
967 B_city='$data{'B_city'}',mobile='$data{'mobile'}',city='$data{'city'}',phone='$data{'phone'}'
968 WHERE borrowernumber='$guarantees->[$i]->{'borrowernumber'}'
970 my $sth3 = $dbh->prepare($guaquery);
971 $sth3->execute;
972 $sth3->finish;
975 =head2 GetPendingIssues
977 ($count, $issues) = &GetPendingIssues($borrowernumber);
979 Looks up what the patron with the given borrowernumber has borrowed.
981 C<&GetPendingIssues> returns a two-element array. C<$issues> is a
982 reference-to-array, where each element is a reference-to-hash; the
983 keys are the fields from the C<issues>, C<biblio>, and C<items> tables
984 in the Koha database. C<$count> is the number of elements in
985 C<$issues>.
987 =cut
990 sub GetPendingIssues {
991 my ($borrowernumber) = @_;
992 my $dbh = C4::Context->dbh;
994 my $sth = $dbh->prepare(
995 "SELECT * FROM issues
996 LEFT JOIN items ON issues.itemnumber=items.itemnumber
997 LEFT JOIN biblio ON items.biblionumber=biblio.biblionumber
998 LEFT JOIN biblioitems ON items.biblioitemnumber=biblioitems.biblioitemnumber
999 WHERE
1000 borrowernumber=?
1001 ORDER BY issues.issuedate"
1003 $sth->execute($borrowernumber);
1004 my $data = $sth->fetchall_arrayref({});
1005 my $today = POSIX::strftime("%Y%m%d", localtime);
1006 foreach( @$data ) {
1007 my $datedue = $_->{'date_due'};
1008 $datedue =~ s/-//g;
1009 if ( $datedue < $today ) {
1010 $_->{'overdue'} = 1;
1013 $sth->finish;
1014 return ( scalar(@$data), $data );
1017 =head2 GetAllIssues
1019 ($count, $issues) = &GetAllIssues($borrowernumber, $sortkey, $limit);
1021 Looks up what the patron with the given borrowernumber has borrowed,
1022 and sorts the results.
1024 C<$sortkey> is the name of a field on which to sort the results. This
1025 should be the name of a field in the C<issues>, C<biblio>,
1026 C<biblioitems>, or C<items> table in the Koha database.
1028 C<$limit> is the maximum number of results to return.
1030 C<&GetAllIssues> returns a two-element array. C<$issues> is a
1031 reference-to-array, where each element is a reference-to-hash; the
1032 keys are the fields from the C<issues>, C<biblio>, C<biblioitems>, and
1033 C<items> tables of the Koha database. C<$count> is the number of
1034 elements in C<$issues>
1036 =cut
1039 sub GetAllIssues {
1040 my ( $borrowernumber, $order, $limit ) = @_;
1042 #FIXME: sanity-check order and limit
1043 my $dbh = C4::Context->dbh;
1044 my $count = 0;
1045 my $query =
1046 "SELECT *,items.timestamp AS itemstimestamp
1047 FROM issues
1048 LEFT JOIN items on items.itemnumber=issues.itemnumber
1049 LEFT JOIN biblio ON items.biblionumber=biblio.biblionumber
1050 LEFT JOIN biblioitems ON items.biblioitemnumber=biblioitems.biblioitemnumber
1051 WHERE borrowernumber=?
1052 UNION ALL
1053 SELECT *,items.timestamp AS itemstimestamp
1054 FROM old_issues
1055 LEFT JOIN items on items.itemnumber=old_issues.itemnumber
1056 LEFT JOIN biblio ON items.biblionumber=biblio.biblionumber
1057 LEFT JOIN biblioitems ON items.biblioitemnumber=biblioitems.biblioitemnumber
1058 WHERE borrowernumber=?
1059 order by $order";
1060 if ( $limit != 0 ) {
1061 $query .= " limit $limit";
1064 #print $query;
1065 my $sth = $dbh->prepare($query);
1066 $sth->execute($borrowernumber, $borrowernumber);
1067 my @result;
1068 my $i = 0;
1069 while ( my $data = $sth->fetchrow_hashref ) {
1070 $result[$i] = $data;
1071 $i++;
1072 $count++;
1075 # get all issued items for borrowernumber from oldissues table
1076 # large chunk of older issues data put into table oldissues
1077 # to speed up db calls for issuing items
1078 if ( C4::Context->preference("ReadingHistory") ) {
1079 # FIXME oldissues (not to be confused with old_issues) is
1080 # apparently specific to HLT. Not sure if the ReadingHistory
1081 # syspref is still required, as old_issues by design
1082 # is no longer checked with each loan.
1083 my $query2 = "SELECT * FROM oldissues
1084 LEFT JOIN items ON items.itemnumber=oldissues.itemnumber
1085 LEFT JOIN biblio ON items.biblionumber=biblio.biblionumber
1086 LEFT JOIN biblioitems ON items.biblioitemnumber=biblioitems.biblioitemnumber
1087 WHERE borrowernumber=?
1088 ORDER BY $order";
1089 if ( $limit != 0 ) {
1090 $limit = $limit - $count;
1091 $query2 .= " limit $limit";
1094 my $sth2 = $dbh->prepare($query2);
1095 $sth2->execute($borrowernumber);
1097 while ( my $data2 = $sth2->fetchrow_hashref ) {
1098 $result[$i] = $data2;
1099 $i++;
1101 $sth2->finish;
1103 $sth->finish;
1105 return ( $i, \@result );
1109 =head2 GetMemberAccountRecords
1111 ($total, $acctlines, $count) = &GetMemberAccountRecords($borrowernumber);
1113 Looks up accounting data for the patron with the given borrowernumber.
1115 C<&GetMemberAccountRecords> returns a three-element array. C<$acctlines> is a
1116 reference-to-array, where each element is a reference-to-hash; the
1117 keys are the fields of the C<accountlines> table in the Koha database.
1118 C<$count> is the number of elements in C<$acctlines>. C<$total> is the
1119 total amount outstanding for all of the account lines.
1121 =cut
1124 sub GetMemberAccountRecords {
1125 my ($borrowernumber,$date) = @_;
1126 my $dbh = C4::Context->dbh;
1127 my @acctlines;
1128 my $numlines = 0;
1129 my $strsth = qq(
1130 SELECT *
1131 FROM accountlines
1132 WHERE borrowernumber=?);
1133 my @bind = ($borrowernumber);
1134 if ($date && $date ne ''){
1135 $strsth.=" AND date < ? ";
1136 push(@bind,$date);
1138 $strsth.=" ORDER BY date desc,timestamp DESC";
1139 my $sth= $dbh->prepare( $strsth );
1140 $sth->execute( @bind );
1141 my $total = 0;
1142 while ( my $data = $sth->fetchrow_hashref ) {
1143 $acctlines[$numlines] = $data;
1144 $numlines++;
1145 $total += $data->{'amountoutstanding'};
1147 $sth->finish;
1148 return ( $total, \@acctlines,$numlines);
1151 =head2 GetBorNotifyAcctRecord
1153 ($count, $acctlines, $total) = &GetBorNotifyAcctRecord($params,$notifyid);
1155 Looks up accounting data for the patron with the given borrowernumber per file number.
1157 (FIXME - I'm not at all sure what this is about.)
1159 C<&GetBorNotifyAcctRecord> returns a three-element array. C<$acctlines> is a
1160 reference-to-array, where each element is a reference-to-hash; the
1161 keys are the fields of the C<accountlines> table in the Koha database.
1162 C<$count> is the number of elements in C<$acctlines>. C<$total> is the
1163 total amount outstanding for all of the account lines.
1165 =cut
1167 sub GetBorNotifyAcctRecord {
1168 my ( $borrowernumber, $notifyid ) = @_;
1169 my $dbh = C4::Context->dbh;
1170 my @acctlines;
1171 my $numlines = 0;
1172 my $sth = $dbh->prepare(
1173 "SELECT *
1174 FROM accountlines
1175 WHERE borrowernumber=?
1176 AND notify_id=?
1177 AND amountoutstanding != '0'
1178 ORDER BY notify_id,accounttype
1180 # 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')
1182 $sth->execute( $borrowernumber, $notifyid );
1183 my $total = 0;
1184 while ( my $data = $sth->fetchrow_hashref ) {
1185 $acctlines[$numlines] = $data;
1186 $numlines++;
1187 $total += $data->{'amountoutstanding'};
1189 $sth->finish;
1190 return ( $total, \@acctlines, $numlines );
1193 =head2 checkuniquemember (OUEST-PROVENCE)
1195 ($result,$categorycode) = &checkuniquemember($collectivity,$surname,$firstname,$dateofbirth);
1197 Checks that a member exists or not in the database.
1199 C<&result> is nonzero (=exist) or 0 (=does not exist)
1200 C<&categorycode> is from categorycode table
1201 C<&collectivity> is 1 (= we add a collectivity) or 0 (= we add a physical member)
1202 C<&surname> is the surname
1203 C<&firstname> is the firstname (only if collectivity=0)
1204 C<&dateofbirth> is the date of birth in ISO format (only if collectivity=0)
1206 =cut
1208 # FIXME: This function is not legitimate. Multiple patrons might have the same first/last name and birthdate.
1209 # This is especially true since first name is not even a required field.
1211 sub checkuniquemember {
1212 my ( $collectivity, $surname, $firstname, $dateofbirth ) = @_;
1213 my $dbh = C4::Context->dbh;
1214 my $request = ($collectivity) ?
1215 "SELECT borrowernumber,categorycode FROM borrowers WHERE surname=? " :
1216 "SELECT borrowernumber,categorycode FROM borrowers WHERE surname=? and firstname=? and dateofbirth=? ";
1217 my $sth = $dbh->prepare($request);
1218 if ($collectivity) {
1219 $sth->execute( uc($surname) );
1220 } else {
1221 $sth->execute( uc($surname), ucfirst($firstname), $dateofbirth );
1223 my @data = $sth->fetchrow;
1224 $sth->finish;
1225 ( $data[0] ) and return $data[0], $data[1];
1226 return 0;
1229 sub checkcardnumber {
1230 my ($cardnumber,$borrowernumber) = @_;
1231 my $dbh = C4::Context->dbh;
1232 my $query = "SELECT * FROM borrowers WHERE cardnumber=?";
1233 $query .= " AND borrowernumber <> ?" if ($borrowernumber);
1234 my $sth = $dbh->prepare($query);
1235 if ($borrowernumber) {
1236 $sth->execute($cardnumber,$borrowernumber);
1237 } else {
1238 $sth->execute($cardnumber);
1240 if (my $data= $sth->fetchrow_hashref()){
1241 return 1;
1243 else {
1244 return 0;
1246 $sth->finish();
1250 =head2 getzipnamecity (OUEST-PROVENCE)
1252 take all info from table city for the fields city and zip
1253 check for the name and the zip code of the city selected
1255 =cut
1257 sub getzipnamecity {
1258 my ($cityid) = @_;
1259 my $dbh = C4::Context->dbh;
1260 my $sth =
1261 $dbh->prepare(
1262 "select city_name,city_zipcode from cities where cityid=? ");
1263 $sth->execute($cityid);
1264 my @data = $sth->fetchrow;
1265 return $data[0], $data[1];
1269 =head2 getdcity (OUEST-PROVENCE)
1271 recover cityid with city_name condition
1273 =cut
1275 sub getidcity {
1276 my ($city_name) = @_;
1277 my $dbh = C4::Context->dbh;
1278 my $sth = $dbh->prepare("select cityid from cities where city_name=? ");
1279 $sth->execute($city_name);
1280 my $data = $sth->fetchrow;
1281 return $data;
1285 =head2 GetExpiryDate
1287 $expirydate = GetExpiryDate($categorycode, $dateenrolled);
1289 Calculate expiry date given a categorycode and starting date. Date argument must be in ISO format.
1290 Return date is also in ISO format.
1292 =cut
1294 sub GetExpiryDate {
1295 my ( $categorycode, $dateenrolled ) = @_;
1296 my $enrolmentperiod = 12; # reasonable default
1297 if ($categorycode) {
1298 my $dbh = C4::Context->dbh;
1299 my $sth = $dbh->prepare("select enrolmentperiod from categories where categorycode=?");
1300 $sth->execute($categorycode);
1301 $enrolmentperiod = $sth->fetchrow;
1303 # die "GetExpiryDate: for enrollmentperiod $enrolmentperiod (category '$categorycode') starting $dateenrolled.\n";
1304 my @date = split /-/,$dateenrolled;
1305 return sprintf("%04d-%02d-%02d", Add_Delta_YM(@date,0,$enrolmentperiod));
1308 =head2 checkuserpassword (OUEST-PROVENCE)
1310 check for the password and login are not used
1311 return the number of record
1312 0=> NOT USED 1=> USED
1314 =cut
1316 sub checkuserpassword {
1317 my ( $borrowernumber, $userid, $password ) = @_;
1318 $password = md5_base64($password);
1319 my $dbh = C4::Context->dbh;
1320 my $sth =
1321 $dbh->prepare(
1322 "Select count(*) from borrowers where borrowernumber !=? and userid =? and password=? "
1324 $sth->execute( $borrowernumber, $userid, $password );
1325 my $number_rows = $sth->fetchrow;
1326 return $number_rows;
1330 =head2 GetborCatFromCatType
1332 ($codes_arrayref, $labels_hashref) = &GetborCatFromCatType();
1334 Looks up the different types of borrowers in the database. Returns two
1335 elements: a reference-to-array, which lists the borrower category
1336 codes, and a reference-to-hash, which maps the borrower category codes
1337 to category descriptions.
1339 =cut
1342 sub GetborCatFromCatType {
1343 my ( $category_type, $action ) = @_;
1344 # FIXME - This API seems both limited and dangerous.
1345 my $dbh = C4::Context->dbh;
1346 my $request = qq| SELECT categorycode,description
1347 FROM categories
1348 $action
1349 ORDER BY categorycode|;
1350 my $sth = $dbh->prepare($request);
1351 if ($action) {
1352 $sth->execute($category_type);
1354 else {
1355 $sth->execute();
1358 my %labels;
1359 my @codes;
1361 while ( my $data = $sth->fetchrow_hashref ) {
1362 push @codes, $data->{'categorycode'};
1363 $labels{ $data->{'categorycode'} } = $data->{'description'};
1365 $sth->finish;
1366 return ( \@codes, \%labels );
1369 =head2 GetBorrowercategory
1371 $hashref = &GetBorrowercategory($categorycode);
1373 Given the borrower's category code, the function returns the corresponding
1374 data hashref for a comprehensive information display.
1376 $arrayref_hashref = &GetBorrowercategory;
1377 If no category code provided, the function returns all the categories.
1379 =cut
1381 sub GetBorrowercategory {
1382 my ($catcode) = @_;
1383 my $dbh = C4::Context->dbh;
1384 if ($catcode){
1385 my $sth =
1386 $dbh->prepare(
1387 "SELECT description,dateofbirthrequired,upperagelimit,category_type
1388 FROM categories
1389 WHERE categorycode = ?"
1391 $sth->execute($catcode);
1392 my $data =
1393 $sth->fetchrow_hashref;
1394 $sth->finish();
1395 return $data;
1397 return;
1398 } # sub getborrowercategory
1400 =head2 GetBorrowercategoryList
1402 $arrayref_hashref = &GetBorrowercategoryList;
1403 If no category code provided, the function returns all the categories.
1405 =cut
1407 sub GetBorrowercategoryList {
1408 my $dbh = C4::Context->dbh;
1409 my $sth =
1410 $dbh->prepare(
1411 "SELECT *
1412 FROM categories
1413 ORDER BY description"
1415 $sth->execute;
1416 my $data =
1417 $sth->fetchall_arrayref({});
1418 $sth->finish();
1419 return $data;
1420 } # sub getborrowercategory
1422 =head2 ethnicitycategories
1424 ($codes_arrayref, $labels_hashref) = &ethnicitycategories();
1426 Looks up the different ethnic types in the database. Returns two
1427 elements: a reference-to-array, which lists the ethnicity codes, and a
1428 reference-to-hash, which maps the ethnicity codes to ethnicity
1429 descriptions.
1431 =cut
1435 sub ethnicitycategories {
1436 my $dbh = C4::Context->dbh;
1437 my $sth = $dbh->prepare("Select code,name from ethnicity order by name");
1438 $sth->execute;
1439 my %labels;
1440 my @codes;
1441 while ( my $data = $sth->fetchrow_hashref ) {
1442 push @codes, $data->{'code'};
1443 $labels{ $data->{'code'} } = $data->{'name'};
1445 $sth->finish;
1446 return ( \@codes, \%labels );
1449 =head2 fixEthnicity
1451 $ethn_name = &fixEthnicity($ethn_code);
1453 Takes an ethnicity code (e.g., "european" or "pi") and returns the
1454 corresponding descriptive name from the C<ethnicity> table in the
1455 Koha database ("European" or "Pacific Islander").
1457 =cut
1461 sub fixEthnicity {
1462 my $ethnicity = shift;
1463 return unless $ethnicity;
1464 my $dbh = C4::Context->dbh;
1465 my $sth = $dbh->prepare("Select name from ethnicity where code = ?");
1466 $sth->execute($ethnicity);
1467 my $data = $sth->fetchrow_hashref;
1468 $sth->finish;
1469 return $data->{'name'};
1470 } # sub fixEthnicity
1472 =head2 GetAge
1474 $dateofbirth,$date = &GetAge($date);
1476 this function return the borrowers age with the value of dateofbirth
1478 =cut
1481 sub GetAge{
1482 my ( $date, $date_ref ) = @_;
1484 if ( not defined $date_ref ) {
1485 $date_ref = sprintf( '%04d-%02d-%02d', Today() );
1488 my ( $year1, $month1, $day1 ) = split /-/, $date;
1489 my ( $year2, $month2, $day2 ) = split /-/, $date_ref;
1491 my $age = $year2 - $year1;
1492 if ( $month1 . $day1 > $month2 . $day2 ) {
1493 $age--;
1496 return $age;
1497 } # sub get_age
1499 =head2 get_institutions
1500 $insitutions = get_institutions();
1502 Just returns a list of all the borrowers of type I, borrownumber and name
1504 =cut
1507 sub get_institutions {
1508 my $dbh = C4::Context->dbh();
1509 my $sth =
1510 $dbh->prepare(
1511 "SELECT borrowernumber,surname FROM borrowers WHERE categorycode=? ORDER BY surname"
1513 $sth->execute('I');
1514 my %orgs;
1515 while ( my $data = $sth->fetchrow_hashref() ) {
1516 $orgs{ $data->{'borrowernumber'} } = $data;
1518 $sth->finish();
1519 return ( \%orgs );
1521 } # sub get_institutions
1523 =head2 add_member_orgs
1525 add_member_orgs($borrowernumber,$borrowernumbers);
1527 Takes a borrowernumber and a list of other borrowernumbers and inserts them into the borrowers_to_borrowers table
1529 =cut
1532 sub add_member_orgs {
1533 my ( $borrowernumber, $otherborrowers ) = @_;
1534 my $dbh = C4::Context->dbh();
1535 my $query =
1536 "INSERT INTO borrowers_to_borrowers (borrower1,borrower2) VALUES (?,?)";
1537 my $sth = $dbh->prepare($query);
1538 foreach my $otherborrowernumber (@$otherborrowers) {
1539 $sth->execute( $borrowernumber, $otherborrowernumber );
1541 $sth->finish();
1543 } # sub add_member_orgs
1545 =head2 GetCities (OUEST-PROVENCE)
1547 ($id_cityarrayref, $city_hashref) = &GetCities();
1549 Looks up the different city and zip in the database. Returns two
1550 elements: a reference-to-array, which lists the zip city
1551 codes, and a reference-to-hash, which maps the name of the city.
1552 WHERE =>OUEST PROVENCE OR EXTERIEUR
1554 =cut
1556 sub GetCities {
1558 #my ($type_city) = @_;
1559 my $dbh = C4::Context->dbh;
1560 my $query = qq|SELECT cityid,city_zipcode,city_name
1561 FROM cities
1562 ORDER BY city_name|;
1563 my $sth = $dbh->prepare($query);
1565 #$sth->execute($type_city);
1566 $sth->execute();
1567 my %city;
1568 my @id;
1569 # insert empty value to create a empty choice in cgi popup
1570 push @id, " ";
1571 $city{""} = "";
1572 while ( my $data = $sth->fetchrow_hashref ) {
1573 push @id, $data->{'city_zipcode'}."|".$data->{'city_name'};
1574 $city{ $data->{'city_zipcode'}."|".$data->{'city_name'} } = $data->{'city_name'};
1577 #test to know if the table contain some records if no the function return nothing
1578 my $id = @id;
1579 $sth->finish;
1580 if ( $id == 1 ) {
1581 # all we have is the one blank row
1582 return ();
1584 else {
1585 unshift( @id, "" );
1586 return ( \@id, \%city );
1590 =head2 GetSortDetails (OUEST-PROVENCE)
1592 ($lib) = &GetSortDetails($category,$sortvalue);
1594 Returns the authorized value details
1595 C<&$lib>return value of authorized value details
1596 C<&$sortvalue>this is the value of authorized value
1597 C<&$category>this is the value of authorized value category
1599 =cut
1601 sub GetSortDetails {
1602 my ( $category, $sortvalue ) = @_;
1603 my $dbh = C4::Context->dbh;
1604 my $query = qq|SELECT lib
1605 FROM authorised_values
1606 WHERE category=?
1607 AND authorised_value=? |;
1608 my $sth = $dbh->prepare($query);
1609 $sth->execute( $category, $sortvalue );
1610 my $lib = $sth->fetchrow;
1611 return ($lib) if ($lib);
1612 return ($sortvalue) unless ($lib);
1615 =head2 DeleteBorrower
1617 () = &DeleteBorrower($member);
1619 delete all data fo borrowers and add record to deletedborrowers table
1620 C<&$member>this is the borrowernumber
1622 =cut
1624 sub MoveMemberToDeleted {
1625 my ($member) = @_;
1626 my $dbh = C4::Context->dbh;
1627 my $query;
1628 $query = qq|SELECT *
1629 FROM borrowers
1630 WHERE borrowernumber=?|;
1631 my $sth = $dbh->prepare($query);
1632 $sth->execute($member);
1633 my @data = $sth->fetchrow_array;
1634 $sth->finish;
1635 $sth =
1636 $dbh->prepare( "INSERT INTO deletedborrowers VALUES ("
1637 . ( "?," x ( scalar(@data) - 1 ) )
1638 . "?)" );
1639 $sth->execute(@data);
1640 $sth->finish;
1643 =head2 DelMember
1645 DelMember($borrowernumber);
1647 This function remove directly a borrower whitout writing it on deleteborrower.
1648 + Deletes reserves for the borrower
1650 =cut
1652 sub DelMember {
1653 my $dbh = C4::Context->dbh;
1654 my $borrowernumber = shift;
1655 #warn "in delmember with $borrowernumber";
1656 return unless $borrowernumber; # borrowernumber is mandatory.
1658 my $query = qq|DELETE
1659 FROM reserves
1660 WHERE borrowernumber=?|;
1661 my $sth = $dbh->prepare($query);
1662 $sth->execute($borrowernumber);
1663 $sth->finish;
1664 $query = "
1665 DELETE
1666 FROM borrowers
1667 WHERE borrowernumber = ?
1669 $sth = $dbh->prepare($query);
1670 $sth->execute($borrowernumber);
1671 $sth->finish;
1672 logaction("MEMBERS", "DELETE", $borrowernumber, "") if C4::Context->preference("BorrowersLog");
1673 return $sth->rows;
1676 =head2 ExtendMemberSubscriptionTo (OUEST-PROVENCE)
1678 $date = ExtendMemberSubscriptionTo($borrowerid, $date);
1680 Extending the subscription to a given date or to the expiry date calculated on ISO date.
1681 Returns ISO date.
1683 =cut
1685 sub ExtendMemberSubscriptionTo {
1686 my ( $borrowerid,$date) = @_;
1687 my $dbh = C4::Context->dbh;
1688 my $borrower = GetMember($borrowerid,'borrowernumber');
1689 unless ($date){
1690 $date=POSIX::strftime("%Y-%m-%d",localtime());
1691 my $borrower = GetMember($borrowerid,'borrowernumber');
1692 $date = GetExpiryDate( $borrower->{'categorycode'}, $date );
1694 my $sth = $dbh->do(<<EOF);
1695 UPDATE borrowers
1696 SET dateexpiry='$date'
1697 WHERE borrowernumber='$borrowerid'
1699 # add enrolmentfee if needed
1700 $sth = $dbh->prepare("SELECT enrolmentfee FROM categories WHERE categorycode=?");
1701 $sth->execute($borrower->{'categorycode'});
1702 my ($enrolmentfee) = $sth->fetchrow;
1703 if ($enrolmentfee) {
1704 # insert fee in patron debts
1705 manualinvoice($borrower->{'borrowernumber'}, '', '', 'A', $enrolmentfee);
1707 return $date if ($sth);
1708 return 0;
1711 =head2 GetRoadTypes (OUEST-PROVENCE)
1713 ($idroadtypearrayref, $roadttype_hashref) = &GetRoadTypes();
1715 Looks up the different road type . Returns two
1716 elements: a reference-to-array, which lists the id_roadtype
1717 codes, and a reference-to-hash, which maps the road type of the road .
1719 =cut
1721 sub GetRoadTypes {
1722 my $dbh = C4::Context->dbh;
1723 my $query = qq|
1724 SELECT roadtypeid,road_type
1725 FROM roadtype
1726 ORDER BY road_type|;
1727 my $sth = $dbh->prepare($query);
1728 $sth->execute();
1729 my %roadtype;
1730 my @id;
1732 # insert empty value to create a empty choice in cgi popup
1734 while ( my $data = $sth->fetchrow_hashref ) {
1736 push @id, $data->{'roadtypeid'};
1737 $roadtype{ $data->{'roadtypeid'} } = $data->{'road_type'};
1740 #test to know if the table contain some records if no the function return nothing
1741 my $id = @id;
1742 $sth->finish;
1743 if ( $id eq 0 ) {
1744 return ();
1746 else {
1747 unshift( @id, "" );
1748 return ( \@id, \%roadtype );
1754 =head2 GetTitles (OUEST-PROVENCE)
1756 ($borrowertitle)= &GetTitles();
1758 Looks up the different title . Returns array with all borrowers title
1760 =cut
1762 sub GetTitles {
1763 my @borrowerTitle = split /,|\|/,C4::Context->preference('BorrowersTitles');
1764 unshift( @borrowerTitle, "" );
1765 my $count=@borrowerTitle;
1766 if ($count == 1){
1767 return ();
1769 else {
1770 return ( \@borrowerTitle);
1774 =head2 GetPatronImage
1776 my ($imagedata, $dberror) = GetPatronImage($cardnumber);
1778 Returns the mimetype and binary image data of the image for the patron with the supplied cardnumber.
1780 =cut
1782 sub GetPatronImage {
1783 my ($cardnumber) = @_;
1784 warn "Cardnumber passed to GetPatronImage is $cardnumber" if $debug;
1785 my $dbh = C4::Context->dbh;
1786 my $query = "SELECT mimetype, imagefile FROM patronimage WHERE cardnumber = ?;";
1787 my $sth = $dbh->prepare($query);
1788 $sth->execute($cardnumber);
1789 my $imagedata = $sth->fetchrow_hashref;
1790 my $dberror = $sth->errstr;
1791 warn "Database error!" if $sth->errstr;
1792 $sth->finish;
1793 return $imagedata, $dberror;
1796 =head2 PutPatronImage
1798 PutPatronImage($cardnumber, $mimetype, $imgfile);
1800 Stores patron binary image data and mimetype in database.
1801 NOTE: This function is good for updating images as well as inserting new images in the database.
1803 =cut
1805 sub PutPatronImage {
1806 my ($cardnumber, $mimetype, $imgfile) = @_;
1807 warn "Parameters passed in: Cardnumber=$cardnumber, Mimetype=$mimetype, " . ($imgfile ? "Imagefile" : "No Imagefile") if $debug;
1808 my $dbh = C4::Context->dbh;
1809 my $query = "INSERT INTO patronimage (cardnumber, mimetype, imagefile) VALUES (?,?,?) ON DUPLICATE KEY UPDATE imagefile = ?;";
1810 my $sth = $dbh->prepare($query);
1811 $sth->execute($cardnumber,$mimetype,$imgfile,$imgfile);
1812 warn "Error returned inserting $cardnumber.$mimetype." if $sth->errstr;
1813 my $dberror = $sth->errstr;
1814 $sth->finish;
1815 return $dberror;
1818 =head2 RmPatronImage
1820 my ($dberror) = RmPatronImage($cardnumber);
1822 Removes the image for the patron with the supplied cardnumber.
1824 =cut
1826 sub RmPatronImage {
1827 my ($cardnumber) = @_;
1828 warn "Cardnumber passed to GetPatronImage is $cardnumber" if $debug;
1829 my $dbh = C4::Context->dbh;
1830 my $query = "DELETE FROM patronimage WHERE cardnumber = ?;";
1831 my $sth = $dbh->prepare($query);
1832 $sth->execute($cardnumber);
1833 my $dberror = $sth->errstr;
1834 warn "Database error!" if $sth->errstr;
1835 $sth->finish;
1836 return $dberror;
1839 =head2 GetRoadTypeDetails (OUEST-PROVENCE)
1841 ($roadtype) = &GetRoadTypeDetails($roadtypeid);
1843 Returns the description of roadtype
1844 C<&$roadtype>return description of road type
1845 C<&$roadtypeid>this is the value of roadtype s
1847 =cut
1849 sub GetRoadTypeDetails {
1850 my ($roadtypeid) = @_;
1851 my $dbh = C4::Context->dbh;
1852 my $query = qq|
1853 SELECT road_type
1854 FROM roadtype
1855 WHERE roadtypeid=?|;
1856 my $sth = $dbh->prepare($query);
1857 $sth->execute($roadtypeid);
1858 my $roadtype = $sth->fetchrow;
1859 return ($roadtype);
1862 =head2 GetBorrowersWhoHaveNotBorrowedSince
1864 &GetBorrowersWhoHaveNotBorrowedSince($date)
1866 this function get all borrowers who haven't borrowed since the date given on input arg.
1868 =cut
1870 sub GetBorrowersWhoHaveNotBorrowedSince {
1871 ### TODO : It could be dangerous to delete Borrowers who have just been entered and who have not yet borrowed any book. May be good to add a dateexpiry or dateenrolled filter.
1873 my $filterdate = shift||POSIX::strftime("%Y-%m-%d",localtime());
1874 my $filterbranch = shift ||
1875 ((C4::Context->preference('IndependantBranches')
1876 && C4::Context->userenv
1877 && C4::Context->userenv->{flags}!=1
1878 && C4::Context->userenv->{branch})
1879 ? C4::Context->userenv->{branch}
1880 : "");
1881 my $dbh = C4::Context->dbh;
1882 my $query = "
1883 SELECT borrowers.borrowernumber,max(issues.timestamp) as latestissue
1884 FROM borrowers
1885 JOIN categories USING (categorycode)
1886 LEFT JOIN issues ON borrowers.borrowernumber = issues.borrowernumber
1887 WHERE category_type <> 'S'
1889 my @query_params;
1890 if ($filterbranch && $filterbranch ne ""){
1891 $query.=" AND borrowers.branchcode= ?";
1892 push @query_params,$filterbranch;
1894 $query.=" GROUP BY borrowers.borrowernumber";
1895 if ($filterdate){
1896 $query.=" HAVING latestissue <? OR latestissue IS NULL";
1897 push @query_params,$filterdate;
1899 warn $query if $debug;
1900 my $sth = $dbh->prepare($query);
1901 if (scalar(@query_params)>0){
1902 $sth->execute(@query_params);
1904 else {
1905 $sth->execute;
1908 my @results;
1909 while ( my $data = $sth->fetchrow_hashref ) {
1910 push @results, $data;
1912 return \@results;
1915 =head2 GetBorrowersWhoHaveNeverBorrowed
1917 $results = &GetBorrowersWhoHaveNeverBorrowed
1919 this function get all borrowers who have never borrowed.
1921 I<$result> is a ref to an array which all elements are a hasref.
1923 =cut
1925 sub GetBorrowersWhoHaveNeverBorrowed {
1926 my $filterbranch = shift ||
1927 ((C4::Context->preference('IndependantBranches')
1928 && C4::Context->userenv
1929 && C4::Context->userenv->{flags}!=1
1930 && C4::Context->userenv->{branch})
1931 ? C4::Context->userenv->{branch}
1932 : "");
1933 my $dbh = C4::Context->dbh;
1934 my $query = "
1935 SELECT borrowers.borrowernumber,max(timestamp) as latestissue
1936 FROM borrowers
1937 LEFT JOIN issues ON borrowers.borrowernumber = issues.borrowernumber
1938 WHERE issues.borrowernumber IS NULL
1940 my @query_params;
1941 if ($filterbranch && $filterbranch ne ""){
1942 $query.=" AND borrowers.branchcode= ?";
1943 push @query_params,$filterbranch;
1945 warn $query if $debug;
1947 my $sth = $dbh->prepare($query);
1948 if (scalar(@query_params)>0){
1949 $sth->execute(@query_params);
1951 else {
1952 $sth->execute;
1955 my @results;
1956 while ( my $data = $sth->fetchrow_hashref ) {
1957 push @results, $data;
1959 return \@results;
1962 =head2 GetBorrowersWithIssuesHistoryOlderThan
1964 $results = &GetBorrowersWithIssuesHistoryOlderThan($date)
1966 this function get all borrowers who has an issue history older than I<$date> given on input arg.
1968 I<$result> is a ref to an array which all elements are a hashref.
1969 This hashref is containt the number of time this borrowers has borrowed before I<$date> and the borrowernumber.
1971 =cut
1973 sub GetBorrowersWithIssuesHistoryOlderThan {
1974 my $dbh = C4::Context->dbh;
1975 my $date = shift ||POSIX::strftime("%Y-%m-%d",localtime());
1976 my $filterbranch = shift ||
1977 ((C4::Context->preference('IndependantBranches')
1978 && C4::Context->userenv
1979 && C4::Context->userenv->{flags}!=1
1980 && C4::Context->userenv->{branch})
1981 ? C4::Context->userenv->{branch}
1982 : "");
1983 my $query = "
1984 SELECT count(borrowernumber) as n,borrowernumber
1985 FROM old_issues
1986 WHERE returndate < ?
1987 AND borrowernumber IS NOT NULL
1989 my @query_params;
1990 push @query_params, $date;
1991 if ($filterbranch){
1992 $query.=" AND branchcode = ?";
1993 push @query_params, $filterbranch;
1995 $query.=" GROUP BY borrowernumber ";
1996 warn $query if $debug;
1997 my $sth = $dbh->prepare($query);
1998 $sth->execute(@query_params);
1999 my @results;
2001 while ( my $data = $sth->fetchrow_hashref ) {
2002 push @results, $data;
2004 return \@results;
2007 =head2 GetBorrowersNamesAndLatestIssue
2009 $results = &GetBorrowersNamesAndLatestIssueList(@borrowernumbers)
2011 this function get borrowers Names and surnames and Issue information.
2013 I<@borrowernumbers> is an array which all elements are borrowernumbers.
2014 This hashref is containt the number of time this borrowers has borrowed before I<$date> and the borrowernumber.
2016 =cut
2018 sub GetBorrowersNamesAndLatestIssue {
2019 my $dbh = C4::Context->dbh;
2020 my @borrowernumbers=@_;
2021 my $query = "
2022 SELECT surname,lastname, phone, email,max(timestamp)
2023 FROM borrowers
2024 LEFT JOIN issues ON borrowers.borrowernumber=issues.borrowernumber
2025 GROUP BY borrowernumber
2027 my $sth = $dbh->prepare($query);
2028 $sth->execute;
2029 my $results = $sth->fetchall_arrayref({});
2030 return $results;
2033 =head2 DebarMember
2035 =over 4
2037 my $success = DebarMember( $borrowernumber );
2039 marks a Member as debarred, and therefore unable to checkout any more
2040 items.
2042 return :
2043 true on success, false on failure
2045 =back
2047 =cut
2049 sub DebarMember {
2050 my $borrowernumber = shift;
2052 return unless defined $borrowernumber;
2053 return unless $borrowernumber =~ /^\d+$/;
2055 return ModMember( borrowernumber => $borrowernumber,
2056 debarred => 1 );
2060 END { } # module clean-up code here (global destructor)
2064 __END__
2066 =head1 AUTHOR
2068 Koha Team
2070 =cut