Bug 11856: Add confirm option to POD in advance_notices.pl
[koha.git] / C4 / Members.pm
blobf8324951edc0a7c617c24f276fe2a43614422a9c
1 package C4::Members;
3 # Copyright 2000-2003 Katipo Communications
4 # Copyright 2010 BibLibre
5 # Parts Copyright 2010 Catalyst IT
7 # This file is part of Koha.
9 # Koha is free software; you can redistribute it and/or modify it under the
10 # terms of the GNU General Public License as published by the Free Software
11 # Foundation; either version 2 of the License, or (at your option) any later
12 # version.
14 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
15 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
16 # A PARTICULAR PURPOSE. See the GNU General Public License for more details.
18 # You should have received a copy of the GNU General Public License along
19 # with Koha; if not, write to the Free Software Foundation, Inc.,
20 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
23 use strict;
24 #use warnings; FIXME - Bug 2505
25 use C4::Context;
26 use C4::Dates qw(format_date_in_iso format_date);
27 use String::Random qw( random_string );
28 use Date::Calc qw/Today Add_Delta_YM check_date Date_to_Days/;
29 use C4::Log; # logaction
30 use C4::Overdues;
31 use C4::Reserves;
32 use C4::Accounts;
33 use C4::Biblio;
34 use C4::Letters;
35 use C4::SQLHelper qw(InsertInTable UpdateInTable SearchInTable);
36 use C4::Members::Attributes qw(SearchIdMatchingAttribute);
37 use C4::NewsChannels; #get slip news
38 use DateTime;
39 use DateTime::Format::DateParse;
40 use Koha::DateUtils;
41 use Koha::Borrower::Debarments qw(IsDebarred);
42 use Text::Unaccent qw( unac_string );
43 use Koha::AuthUtils qw(hash_password);
45 our ($VERSION,@ISA,@EXPORT,@EXPORT_OK,$debug);
47 BEGIN {
48 $VERSION = 3.07.00.049;
49 $debug = $ENV{DEBUG} || 0;
50 require Exporter;
51 @ISA = qw(Exporter);
52 #Get data
53 push @EXPORT, qw(
54 &Search
55 &GetMemberDetails
56 &GetMemberRelatives
57 &GetMember
59 &GetGuarantees
61 &GetMemberIssuesAndFines
62 &GetPendingIssues
63 &GetAllIssues
65 &getzipnamecity
66 &getidcity
68 &GetFirstValidEmailAddress
69 &GetNoticeEmailAddress
71 &GetAge
72 &GetCities
73 &GetSortDetails
74 &GetTitles
76 &GetPatronImage
77 &PutPatronImage
78 &RmPatronImage
80 &GetHideLostItemsPreference
82 &IsMemberBlocked
83 &GetMemberAccountRecords
84 &GetBorNotifyAcctRecord
86 &GetborCatFromCatType
87 &GetBorrowercategory
88 GetBorrowerCategorycode
89 &GetBorrowercategoryList
91 &GetBorrowersToExpunge
92 &GetBorrowersWhoHaveNeverBorrowed
93 &GetBorrowersWithIssuesHistoryOlderThan
95 &GetExpiryDate
97 &AddMessage
98 &DeleteMessage
99 &GetMessages
100 &GetMessagesCount
102 &IssueSlip
103 GetBorrowersWithEmail
105 HasOverdues
108 #Modify data
109 push @EXPORT, qw(
110 &ModMember
111 &changepassword
112 &ModPrivacy
115 #Delete data
116 push @EXPORT, qw(
117 &DelMember
120 #Insert data
121 push @EXPORT, qw(
122 &AddMember
123 &AddMember_Opac
124 &MoveMemberToDeleted
125 &ExtendMemberSubscriptionTo
128 #Check data
129 push @EXPORT, qw(
130 &checkuniquemember
131 &checkuserpassword
132 &Check_Userid
133 &Generate_Userid
134 &fixEthnicity
135 &ethnicitycategories
136 &fixup_cardnumber
137 &checkcardnumber
141 =head1 NAME
143 C4::Members - Perl Module containing convenience functions for member handling
145 =head1 SYNOPSIS
147 use C4::Members;
149 =head1 DESCRIPTION
151 This module contains routines for adding, modifying and deleting members/patrons/borrowers
153 =head1 FUNCTIONS
155 =head2 Search
157 $borrowers_result_array_ref = &Search($filter,$orderby, $limit,
158 $columns_out, $search_on_fields,$searchtype);
160 Looks up patrons (borrowers) on filter. A wrapper for SearchInTable('borrowers').
162 For C<$filter>, C<$orderby>, C<$limit>, C<&columns_out>, C<&search_on_fields> and C<&searchtype>
163 refer to C4::SQLHelper:SearchInTable().
165 Special C<$filter> key '' is effectively expanded to search on surname firstname othernamescw
166 and cardnumber unless C<&search_on_fields> is defined
168 Examples:
170 $borrowers = Search('abcd', 'cardnumber');
172 $borrowers = Search({''=>'abcd', category_type=>'I'}, 'surname');
174 =cut
176 sub _express_member_find {
177 my ($filter) = @_;
179 # this is used by circulation everytime a new borrowers cardnumber is scanned
180 # so we can check an exact match first, if that works return, otherwise do the rest
181 my $dbh = C4::Context->dbh;
182 my $query = "SELECT borrowernumber FROM borrowers WHERE cardnumber = ?";
183 if ( my $borrowernumber = $dbh->selectrow_array($query, undef, $filter) ) {
184 return( {"borrowernumber"=>$borrowernumber} );
187 my ($search_on_fields, $searchtype);
188 if ( length($filter) == 1 ) {
189 $search_on_fields = [ qw(surname) ];
190 $searchtype = 'start_with';
191 } else {
192 $search_on_fields = [ qw(surname firstname othernames cardnumber) ];
193 $searchtype = 'contain';
196 return (undef, $search_on_fields, $searchtype);
199 sub Search {
200 my ( $filter, $orderby, $limit, $columns_out, $search_on_fields, $searchtype ) = @_;
202 my $search_string;
203 my $found_borrower;
205 if ( my $fr = ref $filter ) {
206 if ( $fr eq "HASH" ) {
207 if ( my $search_string = $filter->{''} ) {
208 my ($member_filter, $member_search_on_fields, $member_searchtype) = _express_member_find($search_string);
209 if ($member_filter) {
210 $filter = $member_filter;
211 $found_borrower = 1;
212 } else {
213 $search_on_fields ||= $member_search_on_fields;
214 $searchtype ||= $member_searchtype;
218 else {
219 $search_string = $filter;
222 else {
223 $search_string = $filter;
224 my ($member_filter, $member_search_on_fields, $member_searchtype) = _express_member_find($search_string);
225 if ($member_filter) {
226 $filter = $member_filter;
227 $found_borrower = 1;
228 } else {
229 $search_on_fields ||= $member_search_on_fields;
230 $searchtype ||= $member_searchtype;
234 if ( !$found_borrower && C4::Context->preference('ExtendedPatronAttributes') && $search_string ) {
235 my $matching_records = C4::Members::Attributes::SearchIdMatchingAttribute($search_string);
236 if(scalar(@$matching_records)>0) {
237 if ( my $fr = ref $filter ) {
238 if ( $fr eq "HASH" ) {
239 my %f = %$filter;
240 $filter = [ $filter ];
241 delete $f{''};
242 push @$filter, { %f, "borrowernumber"=>$$matching_records };
244 else {
245 push @$filter, {"borrowernumber"=>$matching_records};
248 else {
249 $filter = [ $filter ];
250 push @$filter, {"borrowernumber"=>$matching_records};
255 # $showallbranches was not used at the time SearchMember() was mainstreamed into Search().
256 # Mentioning for the reference
258 if ( C4::Context->preference("IndependentBranches") ) { # && !$showallbranches){
259 if ( my $userenv = C4::Context->userenv ) {
260 my $branch = $userenv->{'branch'};
261 if ( !C4::Context->IsSuperLibrarian() && $branch ){
262 if (my $fr = ref $filter) {
263 if ( $fr eq "HASH" ) {
264 $filter->{branchcode} = $branch;
266 else {
267 foreach (@$filter) {
268 $_ = { '' => $_ } unless ref $_;
269 $_->{branchcode} = $branch;
273 else {
274 $filter = { '' => $filter, branchcode => $branch };
280 if ($found_borrower) {
281 $searchtype = "exact";
283 $searchtype ||= "start_with";
285 return SearchInTable( "borrowers", $filter, $orderby, $limit, $columns_out, $search_on_fields, $searchtype );
288 =head2 GetMemberDetails
290 ($borrower) = &GetMemberDetails($borrowernumber, $cardnumber);
292 Looks up a patron and returns information about him or her. If
293 C<$borrowernumber> is true (nonzero), C<&GetMemberDetails> looks
294 up the borrower by number; otherwise, it looks up the borrower by card
295 number.
297 C<$borrower> is a reference-to-hash whose keys are the fields of the
298 borrowers table in the Koha database. In addition,
299 C<$borrower-E<gt>{flags}> is a hash giving more detailed information
300 about the patron. Its keys act as flags :
302 if $borrower->{flags}->{LOST} {
303 # Patron's card was reported lost
306 If the state of a flag means that the patron should not be
307 allowed to borrow any more books, then it will have a C<noissues> key
308 with a true value.
310 See patronflags for more details.
312 C<$borrower-E<gt>{authflags}> is a hash giving more detailed information
313 about the top-level permissions flags set for the borrower. For example,
314 if a user has the "editcatalogue" permission,
315 C<$borrower-E<gt>{authflags}-E<gt>{editcatalogue}> will exist and have
316 the value "1".
318 =cut
320 sub GetMemberDetails {
321 my ( $borrowernumber, $cardnumber ) = @_;
322 my $dbh = C4::Context->dbh;
323 my $query;
324 my $sth;
325 if ($borrowernumber) {
326 $sth = $dbh->prepare("
327 SELECT borrowers.*,
328 category_type,
329 categories.description,
330 categories.BlockExpiredPatronOpacActions,
331 reservefee,
332 enrolmentperiod
333 FROM borrowers
334 LEFT JOIN categories ON borrowers.categorycode=categories.categorycode
335 WHERE borrowernumber = ?
337 $sth->execute($borrowernumber);
339 elsif ($cardnumber) {
340 $sth = $dbh->prepare("
341 SELECT borrowers.*,
342 category_type,
343 categories.description,
344 categories.BlockExpiredPatronOpacActions,
345 reservefee,
346 enrolmentperiod
347 FROM borrowers
348 LEFT JOIN categories ON borrowers.categorycode = categories.categorycode
349 WHERE cardnumber = ?
351 $sth->execute($cardnumber);
353 else {
354 return;
356 my $borrower = $sth->fetchrow_hashref;
357 return unless $borrower;
358 my ($amount) = GetMemberAccountRecords( $borrowernumber);
359 $borrower->{'amountoutstanding'} = $amount;
360 # FIXME - patronflags calls GetMemberAccountRecords... just have patronflags return $amount
361 my $flags = patronflags( $borrower);
362 my $accessflagshash;
364 $sth = $dbh->prepare("select bit,flag from userflags");
365 $sth->execute;
366 while ( my ( $bit, $flag ) = $sth->fetchrow ) {
367 if ( $borrower->{'flags'} && $borrower->{'flags'} & 2**$bit ) {
368 $accessflagshash->{$flag} = 1;
371 $borrower->{'flags'} = $flags;
372 $borrower->{'authflags'} = $accessflagshash;
374 # For the purposes of making templates easier, we'll define a
375 # 'showname' which is the alternate form the user's first name if
376 # 'other name' is defined.
377 if ($borrower->{category_type} eq 'I') {
378 $borrower->{'showname'} = $borrower->{'othernames'};
379 $borrower->{'showname'} .= " $borrower->{'firstname'}" if $borrower->{'firstname'};
380 } else {
381 $borrower->{'showname'} = $borrower->{'firstname'};
384 # Handle setting the true behavior for BlockExpiredPatronOpacActions
385 $borrower->{'BlockExpiredPatronOpacActions'} =
386 C4::Context->preference('BlockExpiredPatronOpacActions')
387 if ( $borrower->{'BlockExpiredPatronOpacActions'} == -1 );
389 $borrower->{'is_expired'} = 0;
390 $borrower->{'is_expired'} = 1 if
391 defined($borrower->{dateexpiry}) &&
392 $borrower->{'dateexpiry'} ne '0000-00-00' &&
393 Date_to_Days( Today() ) >
394 Date_to_Days( split /-/, $borrower->{'dateexpiry'} );
396 return ($borrower); #, $flags, $accessflagshash);
399 =head2 patronflags
401 $flags = &patronflags($patron);
403 This function is not exported.
405 The following will be set where applicable:
406 $flags->{CHARGES}->{amount} Amount of debt
407 $flags->{CHARGES}->{noissues} Set if debt amount >$5.00 (or syspref noissuescharge)
408 $flags->{CHARGES}->{message} Message -- deprecated
410 $flags->{CREDITS}->{amount} Amount of credit
411 $flags->{CREDITS}->{message} Message -- deprecated
413 $flags->{ GNA } Patron has no valid address
414 $flags->{ GNA }->{noissues} Set for each GNA
415 $flags->{ GNA }->{message} "Borrower has no valid address" -- deprecated
417 $flags->{ LOST } Patron's card reported lost
418 $flags->{ LOST }->{noissues} Set for each LOST
419 $flags->{ LOST }->{message} Message -- deprecated
421 $flags->{DBARRED} Set if patron debarred, no access
422 $flags->{DBARRED}->{noissues} Set for each DBARRED
423 $flags->{DBARRED}->{message} Message -- deprecated
425 $flags->{ NOTES }
426 $flags->{ NOTES }->{message} The note itself. NOT deprecated
428 $flags->{ ODUES } Set if patron has overdue books.
429 $flags->{ ODUES }->{message} "Yes" -- deprecated
430 $flags->{ ODUES }->{itemlist} ref-to-array: list of overdue books
431 $flags->{ ODUES }->{itemlisttext} Text list of overdue items -- deprecated
433 $flags->{WAITING} Set if any of patron's reserves are available
434 $flags->{WAITING}->{message} Message -- deprecated
435 $flags->{WAITING}->{itemlist} ref-to-array: list of available items
437 =over
439 =item C<$flags-E<gt>{ODUES}-E<gt>{itemlist}> is a reference-to-array listing the
440 overdue items. Its elements are references-to-hash, each describing an
441 overdue item. The keys are selected fields from the issues, biblio,
442 biblioitems, and items tables of the Koha database.
444 =item C<$flags-E<gt>{ODUES}-E<gt>{itemlisttext}> is a string giving a text listing of
445 the overdue items, one per line. Deprecated.
447 =item C<$flags-E<gt>{WAITING}-E<gt>{itemlist}> is a reference-to-array listing the
448 available items. Each element is a reference-to-hash whose keys are
449 fields from the reserves table of the Koha database.
451 =back
453 All the "message" fields that include language generated in this function are deprecated,
454 because such strings belong properly in the display layer.
456 The "message" field that comes from the DB is OK.
458 =cut
460 # TODO: use {anonymous => hashes} instead of a dozen %flaginfo
461 # FIXME rename this function.
462 sub patronflags {
463 my %flags;
464 my ( $patroninformation) = @_;
465 my $dbh=C4::Context->dbh;
466 my ($balance, $owing) = GetMemberAccountBalance( $patroninformation->{'borrowernumber'});
467 if ( $owing > 0 ) {
468 my %flaginfo;
469 my $noissuescharge = C4::Context->preference("noissuescharge") || 5;
470 $flaginfo{'message'} = sprintf 'Patron owes %.02f', $owing;
471 $flaginfo{'amount'} = sprintf "%.02f", $owing;
472 if ( $owing > $noissuescharge && !C4::Context->preference("AllowFineOverride") ) {
473 $flaginfo{'noissues'} = 1;
475 $flags{'CHARGES'} = \%flaginfo;
477 elsif ( $balance < 0 ) {
478 my %flaginfo;
479 $flaginfo{'message'} = sprintf 'Patron has credit of %.02f', -$balance;
480 $flaginfo{'amount'} = sprintf "%.02f", $balance;
481 $flags{'CREDITS'} = \%flaginfo;
483 if ( $patroninformation->{'gonenoaddress'}
484 && $patroninformation->{'gonenoaddress'} == 1 )
486 my %flaginfo;
487 $flaginfo{'message'} = 'Borrower has no valid address.';
488 $flaginfo{'noissues'} = 1;
489 $flags{'GNA'} = \%flaginfo;
491 if ( $patroninformation->{'lost'} && $patroninformation->{'lost'} == 1 ) {
492 my %flaginfo;
493 $flaginfo{'message'} = 'Borrower\'s card reported lost.';
494 $flaginfo{'noissues'} = 1;
495 $flags{'LOST'} = \%flaginfo;
497 if ( $patroninformation->{'debarred'} && check_date( split( /-/, $patroninformation->{'debarred'} ) ) ) {
498 if ( Date_to_Days(Date::Calc::Today) < Date_to_Days( split( /-/, $patroninformation->{'debarred'} ) ) ) {
499 my %flaginfo;
500 $flaginfo{'debarredcomment'} = $patroninformation->{'debarredcomment'};
501 $flaginfo{'message'} = $patroninformation->{'debarredcomment'};
502 $flaginfo{'noissues'} = 1;
503 $flaginfo{'dateend'} = $patroninformation->{'debarred'};
504 $flags{'DBARRED'} = \%flaginfo;
507 if ( $patroninformation->{'borrowernotes'}
508 && $patroninformation->{'borrowernotes'} )
510 my %flaginfo;
511 $flaginfo{'message'} = $patroninformation->{'borrowernotes'};
512 $flags{'NOTES'} = \%flaginfo;
514 my ( $odues, $itemsoverdue ) = C4::Overdues::checkoverdues($patroninformation->{'borrowernumber'});
515 if ( $odues && $odues > 0 ) {
516 my %flaginfo;
517 $flaginfo{'message'} = "Yes";
518 $flaginfo{'itemlist'} = $itemsoverdue;
519 foreach ( sort { $a->{'date_due'} cmp $b->{'date_due'} }
520 @$itemsoverdue )
522 $flaginfo{'itemlisttext'} .=
523 "$_->{'date_due'} $_->{'barcode'} $_->{'title'} \n"; # newline is display layer
525 $flags{'ODUES'} = \%flaginfo;
527 my @itemswaiting = C4::Reserves::GetReservesFromBorrowernumber( $patroninformation->{'borrowernumber'},'W' );
528 my $nowaiting = scalar @itemswaiting;
529 if ( $nowaiting > 0 ) {
530 my %flaginfo;
531 $flaginfo{'message'} = "Reserved items available";
532 $flaginfo{'itemlist'} = \@itemswaiting;
533 $flags{'WAITING'} = \%flaginfo;
535 return ( \%flags );
539 =head2 GetMember
541 $borrower = &GetMember(%information);
543 Retrieve the first patron record meeting on criteria listed in the
544 C<%information> hash, which should contain one or more
545 pairs of borrowers column names and values, e.g.,
547 $borrower = GetMember(borrowernumber => id);
549 C<&GetBorrower> returns a reference-to-hash whose keys are the fields of
550 the C<borrowers> table in the Koha database.
552 FIXME: GetMember() is used throughout the code as a lookup
553 on a unique key such as the borrowernumber, but this meaning is not
554 enforced in the routine itself.
556 =cut
559 sub GetMember {
560 my ( %information ) = @_;
561 if (exists $information{borrowernumber} && !defined $information{borrowernumber}) {
562 #passing mysql's kohaadmin?? Makes no sense as a query
563 return;
565 my $dbh = C4::Context->dbh;
566 my $select =
567 q{SELECT borrowers.*, categories.category_type, categories.description
568 FROM borrowers
569 LEFT JOIN categories on borrowers.categorycode=categories.categorycode WHERE };
570 my $more_p = 0;
571 my @values = ();
572 for (keys %information ) {
573 if ($more_p) {
574 $select .= ' AND ';
576 else {
577 $more_p++;
580 if (defined $information{$_}) {
581 $select .= "$_ = ?";
582 push @values, $information{$_};
584 else {
585 $select .= "$_ IS NULL";
588 $debug && warn $select, " ",values %information;
589 my $sth = $dbh->prepare("$select");
590 $sth->execute(map{$information{$_}} keys %information);
591 my $data = $sth->fetchall_arrayref({});
592 #FIXME interface to this routine now allows generation of a result set
593 #so whole array should be returned but bowhere in the current code expects this
594 if (@{$data} ) {
595 return $data->[0];
598 return;
601 =head2 GetMemberRelatives
603 @borrowernumbers = GetMemberRelatives($borrowernumber);
605 C<GetMemberRelatives> returns a borrowersnumber's list of guarantor/guarantees of the member given in parameter
607 =cut
608 sub GetMemberRelatives {
609 my $borrowernumber = shift;
610 my $dbh = C4::Context->dbh;
611 my @glist;
613 # Getting guarantor
614 my $query = "SELECT guarantorid FROM borrowers WHERE borrowernumber=?";
615 my $sth = $dbh->prepare($query);
616 $sth->execute($borrowernumber);
617 my $data = $sth->fetchrow_arrayref();
618 push @glist, $data->[0] if $data->[0];
619 my $guarantor = $data->[0] ? $data->[0] : undef;
621 # Getting guarantees
622 $query = "SELECT borrowernumber FROM borrowers WHERE guarantorid=?";
623 $sth = $dbh->prepare($query);
624 $sth->execute($borrowernumber);
625 while ($data = $sth->fetchrow_arrayref()) {
626 push @glist, $data->[0];
629 # Getting sibling guarantees
630 if ($guarantor) {
631 $query = "SELECT borrowernumber FROM borrowers WHERE guarantorid=?";
632 $sth = $dbh->prepare($query);
633 $sth->execute($guarantor);
634 while ($data = $sth->fetchrow_arrayref()) {
635 push @glist, $data->[0] if ($data->[0] != $borrowernumber);
639 return @glist;
642 =head2 IsMemberBlocked
644 my ($block_status, $count) = IsMemberBlocked( $borrowernumber );
646 Returns whether a patron has overdue items that may result
647 in a block or whether the patron has active fine days
648 that would block circulation privileges.
650 C<$block_status> can have the following values:
652 1 if the patron has outstanding fine days, in which case C<$count> is the number of them
654 -1 if the patron has overdue items, in which case C<$count> is the number of them
656 0 if the patron has no overdue items or outstanding fine days, in which case C<$count> is 0
658 Outstanding fine days are checked before current overdue items
659 are.
661 FIXME: this needs to be split into two functions; a potential block
662 based on the number of current overdue items could be orthogonal
663 to a block based on whether the patron has any fine days accrued.
665 =cut
667 sub IsMemberBlocked {
668 my $borrowernumber = shift;
669 my $dbh = C4::Context->dbh;
671 my $blockeddate = Koha::Borrower::Debarments::IsDebarred($borrowernumber);
673 return ( 1, $blockeddate ) if $blockeddate;
675 # if he have late issues
676 my $sth = $dbh->prepare(
677 "SELECT COUNT(*) as latedocs
678 FROM issues
679 WHERE borrowernumber = ?
680 AND date_due < now()"
682 $sth->execute($borrowernumber);
683 my $latedocs = $sth->fetchrow_hashref->{'latedocs'};
685 return ( -1, $latedocs ) if $latedocs > 0;
687 return ( 0, 0 );
690 =head2 GetMemberIssuesAndFines
692 ($overdue_count, $issue_count, $total_fines) = &GetMemberIssuesAndFines($borrowernumber);
694 Returns aggregate data about items borrowed by the patron with the
695 given borrowernumber.
697 C<&GetMemberIssuesAndFines> returns a three-element array. C<$overdue_count> is the
698 number of overdue items the patron currently has borrowed. C<$issue_count> is the
699 number of books the patron currently has borrowed. C<$total_fines> is
700 the total fine currently due by the borrower.
702 =cut
705 sub GetMemberIssuesAndFines {
706 my ( $borrowernumber ) = @_;
707 my $dbh = C4::Context->dbh;
708 my $query = "SELECT COUNT(*) FROM issues WHERE borrowernumber = ?";
710 $debug and warn $query."\n";
711 my $sth = $dbh->prepare($query);
712 $sth->execute($borrowernumber);
713 my $issue_count = $sth->fetchrow_arrayref->[0];
715 $sth = $dbh->prepare(
716 "SELECT COUNT(*) FROM issues
717 WHERE borrowernumber = ?
718 AND date_due < now()"
720 $sth->execute($borrowernumber);
721 my $overdue_count = $sth->fetchrow_arrayref->[0];
723 $sth = $dbh->prepare("SELECT SUM(amountoutstanding) FROM accountlines WHERE borrowernumber = ?");
724 $sth->execute($borrowernumber);
725 my $total_fines = $sth->fetchrow_arrayref->[0];
727 return ($overdue_count, $issue_count, $total_fines);
731 =head2 columns
733 my @columns = C4::Member::columns();
735 Returns an array of borrowers' table columns on success,
736 and an empty array on failure.
738 =cut
740 sub columns {
742 # Pure ANSI SQL goodness.
743 my $sql = 'SELECT * FROM borrowers WHERE 1=0;';
745 # Get the database handle.
746 my $dbh = C4::Context->dbh;
748 # Run the SQL statement to load STH's readonly properties.
749 my $sth = $dbh->prepare($sql);
750 my $rv = $sth->execute();
752 # This only fails if the table doesn't exist.
753 # This will always be called AFTER an install or upgrade,
754 # so borrowers will exist!
755 my @data;
756 if ($sth->{NUM_OF_FIELDS}>0) {
757 @data = @{$sth->{NAME}};
759 else {
760 @data = ();
762 return @data;
766 =head2 ModMember
768 my $success = ModMember(borrowernumber => $borrowernumber,
769 [ field => value ]... );
771 Modify borrower's data. All date fields should ALREADY be in ISO format.
773 return :
774 true on success, or false on failure
776 =cut
778 sub ModMember {
779 my (%data) = @_;
780 # test to know if you must update or not the borrower password
781 if (exists $data{password}) {
782 if ($data{password} eq '****' or $data{password} eq '') {
783 delete $data{password};
784 } else {
785 $data{password} = hash_password($data{password});
788 my $old_categorycode = GetBorrowerCategorycode( $data{borrowernumber} );
789 my $execute_success=UpdateInTable("borrowers",\%data);
790 if ($execute_success) { # only proceed if the update was a success
791 # ok if its an adult (type) it may have borrowers that depend on it as a guarantor
792 # so when we update information for an adult we should check for guarantees and update the relevant part
793 # of their records, ie addresses and phone numbers
794 my $borrowercategory= GetBorrowercategory( $data{'category_type'} );
795 if ( exists $borrowercategory->{'category_type'} && $borrowercategory->{'category_type'} eq ('A' || 'S') ) {
796 # is adult check guarantees;
797 UpdateGuarantees(%data);
800 # If the patron changes to a category with enrollment fee, we add a fee
801 if ( $data{categorycode} and $data{categorycode} ne $old_categorycode ) {
802 AddEnrolmentFeeIfNeeded( $data{categorycode}, $data{borrowernumber} );
805 logaction("MEMBERS", "MODIFY", $data{'borrowernumber'}, "UPDATE (executed w/ arg: $data{'borrowernumber'})") if C4::Context->preference("BorrowersLog");
807 return $execute_success;
810 =head2 AddMember
812 $borrowernumber = &AddMember(%borrower);
814 insert new borrower into table
815 Returns the borrowernumber upon success
817 Returns as undef upon any db error without further processing
819 =cut
822 sub AddMember {
823 my (%data) = @_;
824 my $dbh = C4::Context->dbh;
826 # generate a proper login if none provided
827 $data{'userid'} = Generate_Userid($data{'borrowernumber'}, $data{'firstname'}, $data{'surname'}) if $data{'userid'} eq '';
829 # add expiration date if it isn't already there
830 unless ( $data{'dateexpiry'} ) {
831 $data{'dateexpiry'} = GetExpiryDate( $data{'categorycode'}, C4::Dates->new()->output("iso") );
834 # add enrollment date if it isn't already there
835 unless ( $data{'dateenrolled'} ) {
836 $data{'dateenrolled'} = C4::Dates->new()->output("iso");
839 # create a disabled account if no password provided
840 $data{'password'} = ($data{'password'})? hash_password($data{'password'}) : '!';
841 $data{'borrowernumber'}=InsertInTable("borrowers",\%data);
843 # mysql_insertid is probably bad. not necessarily accurate and mysql-specific at best.
844 logaction("MEMBERS", "CREATE", $data{'borrowernumber'}, "") if C4::Context->preference("BorrowersLog");
846 AddEnrolmentFeeIfNeeded( $data{categorycode}, $data{borrowernumber} );
848 return $data{'borrowernumber'};
851 =head2 Check_Userid
853 my $uniqueness = Check_Userid($userid,$borrowernumber);
855 $borrowernumber is optional (i.e. it can contain a blank value). If $userid is passed with a blank $borrowernumber variable, the database will be checked for all instances of that userid (i.e. userid=? AND borrowernumber != '').
857 If $borrowernumber is provided, the database will be checked for every instance of that userid coupled with a different borrower(number) than the one provided.
859 return :
860 0 for not unique (i.e. this $userid already exists)
861 1 for unique (i.e. this $userid does not exist, or this $userid/$borrowernumber combination already exists)
863 =cut
865 sub Check_Userid {
866 my ($uid,$member) = @_;
867 my $dbh = C4::Context->dbh;
868 my $sth =
869 $dbh->prepare(
870 "SELECT * FROM borrowers WHERE userid=? AND borrowernumber != ?");
871 $sth->execute( $uid, $member );
872 if ( ( $uid ne '' ) && ( my $row = $sth->fetchrow_hashref ) ) {
873 return 0;
875 else {
876 return 1;
880 =head2 Generate_Userid
882 my $newuid = Generate_Userid($borrowernumber, $firstname, $surname);
884 Generate a userid using the $surname and the $firstname (if there is a value in $firstname).
886 $borrowernumber is optional (i.e. it can contain a blank value). A value is passed when generating a new userid for an existing borrower. When a new userid is created for a new borrower, a blank value is passed to this sub.
888 return :
889 new userid ($firstname.$surname if there is a $firstname, or $surname if there is no value in $firstname) plus offset (0 if the $newuid is unique, or a higher numeric value if Check_Userid finds an existing match for the $newuid in the database).
891 =cut
893 sub Generate_Userid {
894 my ($borrowernumber, $firstname, $surname) = @_;
895 my $newuid;
896 my $offset = 0;
897 #The script will "do" the following code and increment the $offset until Check_Userid = 1 (i.e. until $newuid comes back as unique)
898 do {
899 $firstname =~ s/[[:digit:][:space:][:blank:][:punct:][:cntrl:]]//g;
900 $surname =~ s/[[:digit:][:space:][:blank:][:punct:][:cntrl:]]//g;
901 $newuid = lc(($firstname)? "$firstname.$surname" : $surname);
902 $newuid = unac_string('utf-8',$newuid);
903 $newuid .= $offset unless $offset == 0;
904 $offset++;
906 } while (!Check_Userid($newuid,$borrowernumber));
908 return $newuid;
911 sub changepassword {
912 my ( $uid, $member, $digest ) = @_;
913 my $dbh = C4::Context->dbh;
915 #Make sure the userid chosen is unique and not theirs if non-empty. If it is not,
916 #Then we need to tell the user and have them create a new one.
917 my $resultcode;
918 my $sth =
919 $dbh->prepare(
920 "SELECT * FROM borrowers WHERE userid=? AND borrowernumber != ?");
921 $sth->execute( $uid, $member );
922 if ( ( $uid ne '' ) && ( my $row = $sth->fetchrow_hashref ) ) {
923 $resultcode=0;
925 else {
926 #Everything is good so we can update the information.
927 $sth =
928 $dbh->prepare(
929 "update borrowers set userid=?, password=? where borrowernumber=?");
930 $sth->execute( $uid, $digest, $member );
931 $resultcode=1;
934 logaction("MEMBERS", "CHANGE PASS", $member, "") if C4::Context->preference("BorrowersLog");
935 return $resultcode;
940 =head2 fixup_cardnumber
942 Warning: The caller is responsible for locking the members table in write
943 mode, to avoid database corruption.
945 =cut
947 use vars qw( @weightings );
948 my @weightings = ( 8, 4, 6, 3, 5, 2, 1 );
950 sub fixup_cardnumber {
951 my ($cardnumber) = @_;
952 my $autonumber_members = C4::Context->boolean_preference('autoMemberNum') || 0;
954 # Find out whether member numbers should be generated
955 # automatically. Should be either "1" or something else.
956 # Defaults to "0", which is interpreted as "no".
958 # if ($cardnumber !~ /\S/ && $autonumber_members) {
959 ($autonumber_members) or return $cardnumber;
960 my $checkdigit = C4::Context->preference('checkdigit');
961 my $dbh = C4::Context->dbh;
962 if ( $checkdigit and $checkdigit eq 'katipo' ) {
964 # if checkdigit is selected, calculate katipo-style cardnumber.
965 # otherwise, just use the max()
966 # purpose: generate checksum'd member numbers.
967 # We'll assume we just got the max value of digits 2-8 of member #'s
968 # from the database and our job is to increment that by one,
969 # determine the 1st and 9th digits and return the full string.
970 my $sth = $dbh->prepare(
971 "select max(substring(borrowers.cardnumber,2,7)) as new_num from borrowers"
973 $sth->execute;
974 my $data = $sth->fetchrow_hashref;
975 $cardnumber = $data->{new_num};
976 if ( !$cardnumber ) { # If DB has no values,
977 $cardnumber = 1000000; # start at 1000000
978 } else {
979 $cardnumber += 1;
982 my $sum = 0;
983 for ( my $i = 0 ; $i < 8 ; $i += 1 ) {
984 # read weightings, left to right, 1 char at a time
985 my $temp1 = $weightings[$i];
987 # sequence left to right, 1 char at a time
988 my $temp2 = substr( $cardnumber, $i, 1 );
990 # mult each char 1-7 by its corresponding weighting
991 $sum += $temp1 * $temp2;
994 my $rem = ( $sum % 11 );
995 $rem = 'X' if $rem == 10;
997 return "V$cardnumber$rem";
998 } else {
1000 my $sth = $dbh->prepare(
1001 'SELECT MAX( CAST( cardnumber AS SIGNED ) ) FROM borrowers WHERE cardnumber REGEXP "^-?[0-9]+$"'
1003 $sth->execute;
1004 my ($result) = $sth->fetchrow;
1005 return $result + 1;
1007 return $cardnumber; # just here as a fallback/reminder
1010 =head2 GetGuarantees
1012 ($num_children, $children_arrayref) = &GetGuarantees($parent_borrno);
1013 $child0_cardno = $children_arrayref->[0]{"cardnumber"};
1014 $child0_borrno = $children_arrayref->[0]{"borrowernumber"};
1016 C<&GetGuarantees> takes a borrower number (e.g., that of a patron
1017 with children) and looks up the borrowers who are guaranteed by that
1018 borrower (i.e., the patron's children).
1020 C<&GetGuarantees> returns two values: an integer giving the number of
1021 borrowers guaranteed by C<$parent_borrno>, and a reference to an array
1022 of references to hash, which gives the actual results.
1024 =cut
1027 sub GetGuarantees {
1028 my ($borrowernumber) = @_;
1029 my $dbh = C4::Context->dbh;
1030 my $sth =
1031 $dbh->prepare(
1032 "select cardnumber,borrowernumber, firstname, surname from borrowers where guarantorid=?"
1034 $sth->execute($borrowernumber);
1036 my @dat;
1037 my $data = $sth->fetchall_arrayref({});
1038 return ( scalar(@$data), $data );
1041 =head2 UpdateGuarantees
1043 &UpdateGuarantees($parent_borrno);
1046 C<&UpdateGuarantees> borrower data for an adult and updates all the guarantees
1047 with the modified information
1049 =cut
1052 sub UpdateGuarantees {
1053 my %data = shift;
1054 my $dbh = C4::Context->dbh;
1055 my ( $count, $guarantees ) = GetGuarantees( $data{'borrowernumber'} );
1056 foreach my $guarantee (@$guarantees){
1057 my $guaquery = qq|UPDATE borrowers
1058 SET address=?,fax=?,B_city=?,mobile=?,city=?,phone=?
1059 WHERE borrowernumber=?
1061 my $sth = $dbh->prepare($guaquery);
1062 $sth->execute($data{'address'},$data{'fax'},$data{'B_city'},$data{'mobile'},$data{'city'},$data{'phone'},$guarantee->{'borrowernumber'});
1065 =head2 GetPendingIssues
1067 my $issues = &GetPendingIssues(@borrowernumber);
1069 Looks up what the patron with the given borrowernumber has borrowed.
1071 C<&GetPendingIssues> returns a
1072 reference-to-array where each element is a reference-to-hash; the
1073 keys are the fields from the C<issues>, C<biblio>, and C<items> tables.
1074 The keys include C<biblioitems> fields except marc and marcxml.
1076 =cut
1079 sub GetPendingIssues {
1080 my @borrowernumbers = @_;
1082 unless (@borrowernumbers ) { # return a ref_to_array
1083 return \@borrowernumbers; # to not cause surprise to caller
1086 # Borrowers part of the query
1087 my $bquery = '';
1088 for (my $i = 0; $i < @borrowernumbers; $i++) {
1089 $bquery .= ' issues.borrowernumber = ?';
1090 if ($i < $#borrowernumbers ) {
1091 $bquery .= ' OR';
1095 # must avoid biblioitems.* to prevent large marc and marcxml fields from killing performance
1096 # FIXME: namespace collision: each table has "timestamp" fields. Which one is "timestamp" ?
1097 # FIXME: circ/ciculation.pl tries to sort by timestamp!
1098 # FIXME: namespace collision: other collisions possible.
1099 # FIXME: most of this data isn't really being used by callers.
1100 my $query =
1101 "SELECT issues.*,
1102 items.*,
1103 biblio.*,
1104 biblioitems.volume,
1105 biblioitems.number,
1106 biblioitems.itemtype,
1107 biblioitems.isbn,
1108 biblioitems.issn,
1109 biblioitems.publicationyear,
1110 biblioitems.publishercode,
1111 biblioitems.volumedate,
1112 biblioitems.volumedesc,
1113 biblioitems.lccn,
1114 biblioitems.url,
1115 borrowers.firstname,
1116 borrowers.surname,
1117 borrowers.cardnumber,
1118 issues.timestamp AS timestamp,
1119 issues.renewals AS renewals,
1120 issues.borrowernumber AS borrowernumber,
1121 items.renewals AS totalrenewals
1122 FROM issues
1123 LEFT JOIN items ON items.itemnumber = issues.itemnumber
1124 LEFT JOIN biblio ON items.biblionumber = biblio.biblionumber
1125 LEFT JOIN biblioitems ON items.biblioitemnumber = biblioitems.biblioitemnumber
1126 LEFT JOIN borrowers ON issues.borrowernumber = borrowers.borrowernumber
1127 WHERE
1128 $bquery
1129 ORDER BY issues.issuedate"
1132 my $sth = C4::Context->dbh->prepare($query);
1133 $sth->execute(@borrowernumbers);
1134 my $data = $sth->fetchall_arrayref({});
1135 my $tz = C4::Context->tz();
1136 my $today = DateTime->now( time_zone => $tz);
1137 foreach (@{$data}) {
1138 if ($_->{issuedate}) {
1139 $_->{issuedate} = dt_from_string($_->{issuedate}, 'sql');
1141 $_->{date_due} or next;
1142 $_->{date_due} = DateTime::Format::DateParse->parse_datetime($_->{date_due}, $tz->name());
1143 if ( DateTime->compare($_->{date_due}, $today) == -1 ) {
1144 $_->{overdue} = 1;
1147 return $data;
1150 =head2 GetAllIssues
1152 $issues = &GetAllIssues($borrowernumber, $sortkey, $limit);
1154 Looks up what the patron with the given borrowernumber has borrowed,
1155 and sorts the results.
1157 C<$sortkey> is the name of a field on which to sort the results. This
1158 should be the name of a field in the C<issues>, C<biblio>,
1159 C<biblioitems>, or C<items> table in the Koha database.
1161 C<$limit> is the maximum number of results to return.
1163 C<&GetAllIssues> an arrayref, C<$issues>, of hashrefs, the keys of which
1164 are the fields from the C<issues>, C<biblio>, C<biblioitems>, and
1165 C<items> tables of the Koha database.
1167 =cut
1170 sub GetAllIssues {
1171 my ( $borrowernumber, $order, $limit ) = @_;
1173 my $dbh = C4::Context->dbh;
1174 my $query =
1175 'SELECT *, issues.timestamp as issuestimestamp, issues.renewals AS renewals,items.renewals AS totalrenewals,items.timestamp AS itemstimestamp
1176 FROM issues
1177 LEFT JOIN items on items.itemnumber=issues.itemnumber
1178 LEFT JOIN biblio ON items.biblionumber=biblio.biblionumber
1179 LEFT JOIN biblioitems ON items.biblioitemnumber=biblioitems.biblioitemnumber
1180 WHERE borrowernumber=?
1181 UNION ALL
1182 SELECT *, old_issues.timestamp as issuestimestamp, old_issues.renewals AS renewals,items.renewals AS totalrenewals,items.timestamp AS itemstimestamp
1183 FROM old_issues
1184 LEFT JOIN items on items.itemnumber=old_issues.itemnumber
1185 LEFT JOIN biblio ON items.biblionumber=biblio.biblionumber
1186 LEFT JOIN biblioitems ON items.biblioitemnumber=biblioitems.biblioitemnumber
1187 WHERE borrowernumber=? AND old_issues.itemnumber IS NOT NULL
1188 order by ' . $order;
1189 if ($limit) {
1190 $query .= " limit $limit";
1193 my $sth = $dbh->prepare($query);
1194 $sth->execute( $borrowernumber, $borrowernumber );
1195 return $sth->fetchall_arrayref( {} );
1199 =head2 GetMemberAccountRecords
1201 ($total, $acctlines, $count) = &GetMemberAccountRecords($borrowernumber);
1203 Looks up accounting data for the patron with the given borrowernumber.
1205 C<&GetMemberAccountRecords> returns a three-element array. C<$acctlines> is a
1206 reference-to-array, where each element is a reference-to-hash; the
1207 keys are the fields of the C<accountlines> table in the Koha database.
1208 C<$count> is the number of elements in C<$acctlines>. C<$total> is the
1209 total amount outstanding for all of the account lines.
1211 =cut
1213 sub GetMemberAccountRecords {
1214 my ($borrowernumber) = @_;
1215 my $dbh = C4::Context->dbh;
1216 my @acctlines;
1217 my $numlines = 0;
1218 my $strsth = qq(
1219 SELECT *
1220 FROM accountlines
1221 WHERE borrowernumber=?);
1222 $strsth.=" ORDER BY date desc,timestamp DESC";
1223 my $sth= $dbh->prepare( $strsth );
1224 $sth->execute( $borrowernumber );
1226 my $total = 0;
1227 while ( my $data = $sth->fetchrow_hashref ) {
1228 if ( $data->{itemnumber} ) {
1229 my $biblio = GetBiblioFromItemNumber( $data->{itemnumber} );
1230 $data->{biblionumber} = $biblio->{biblionumber};
1231 $data->{title} = $biblio->{title};
1233 $acctlines[$numlines] = $data;
1234 $numlines++;
1235 $total += int(1000 * $data->{'amountoutstanding'}); # convert float to integer to avoid round-off errors
1237 $total /= 1000;
1238 return ( $total, \@acctlines,$numlines);
1241 =head2 GetMemberAccountBalance
1243 ($total_balance, $non_issue_balance, $other_charges) = &GetMemberAccountBalance($borrowernumber);
1245 Calculates amount immediately owing by the patron - non-issue charges.
1246 Based on GetMemberAccountRecords.
1247 Charges exempt from non-issue are:
1248 * Res (reserves)
1249 * Rent (rental) if RentalsInNoissuesCharge syspref is set to false
1250 * Manual invoices if ManInvInNoissuesCharge syspref is set to false
1252 =cut
1254 sub GetMemberAccountBalance {
1255 my ($borrowernumber) = @_;
1257 my $ACCOUNT_TYPE_LENGTH = 5; # this is plain ridiculous...
1259 my @not_fines = ('Res');
1260 push @not_fines, 'Rent' unless C4::Context->preference('RentalsInNoissuesCharge');
1261 unless ( C4::Context->preference('ManInvInNoissuesCharge') ) {
1262 my $dbh = C4::Context->dbh;
1263 my $man_inv_types = $dbh->selectcol_arrayref(qq{SELECT authorised_value FROM authorised_values WHERE category = 'MANUAL_INV'});
1264 push @not_fines, map substr($_, 0, $ACCOUNT_TYPE_LENGTH), @$man_inv_types;
1266 my %not_fine = map {$_ => 1} @not_fines;
1268 my ($total, $acctlines) = GetMemberAccountRecords($borrowernumber);
1269 my $other_charges = 0;
1270 foreach (@$acctlines) {
1271 $other_charges += $_->{amountoutstanding} if $not_fine{ substr($_->{accounttype}, 0, $ACCOUNT_TYPE_LENGTH) };
1274 return ( $total, $total - $other_charges, $other_charges);
1277 =head2 GetBorNotifyAcctRecord
1279 ($total, $acctlines, $count) = &GetBorNotifyAcctRecord($params,$notifyid);
1281 Looks up accounting data for the patron with the given borrowernumber per file number.
1283 C<&GetBorNotifyAcctRecord> returns a three-element array. C<$acctlines> is a
1284 reference-to-array, where each element is a reference-to-hash; the
1285 keys are the fields of the C<accountlines> table in the Koha database.
1286 C<$count> is the number of elements in C<$acctlines>. C<$total> is the
1287 total amount outstanding for all of the account lines.
1289 =cut
1291 sub GetBorNotifyAcctRecord {
1292 my ( $borrowernumber, $notifyid ) = @_;
1293 my $dbh = C4::Context->dbh;
1294 my @acctlines;
1295 my $numlines = 0;
1296 my $sth = $dbh->prepare(
1297 "SELECT *
1298 FROM accountlines
1299 WHERE borrowernumber=?
1300 AND notify_id=?
1301 AND amountoutstanding != '0'
1302 ORDER BY notify_id,accounttype
1305 $sth->execute( $borrowernumber, $notifyid );
1306 my $total = 0;
1307 while ( my $data = $sth->fetchrow_hashref ) {
1308 if ( $data->{itemnumber} ) {
1309 my $biblio = GetBiblioFromItemNumber( $data->{itemnumber} );
1310 $data->{biblionumber} = $biblio->{biblionumber};
1311 $data->{title} = $biblio->{title};
1313 $acctlines[$numlines] = $data;
1314 $numlines++;
1315 $total += int(100 * $data->{'amountoutstanding'});
1317 $total /= 100;
1318 return ( $total, \@acctlines, $numlines );
1321 =head2 checkuniquemember (OUEST-PROVENCE)
1323 ($result,$categorycode) = &checkuniquemember($collectivity,$surname,$firstname,$dateofbirth);
1325 Checks that a member exists or not in the database.
1327 C<&result> is nonzero (=exist) or 0 (=does not exist)
1328 C<&categorycode> is from categorycode table
1329 C<&collectivity> is 1 (= we add a collectivity) or 0 (= we add a physical member)
1330 C<&surname> is the surname
1331 C<&firstname> is the firstname (only if collectivity=0)
1332 C<&dateofbirth> is the date of birth in ISO format (only if collectivity=0)
1334 =cut
1336 # FIXME: This function is not legitimate. Multiple patrons might have the same first/last name and birthdate.
1337 # This is especially true since first name is not even a required field.
1339 sub checkuniquemember {
1340 my ( $collectivity, $surname, $firstname, $dateofbirth ) = @_;
1341 my $dbh = C4::Context->dbh;
1342 my $request = ($collectivity) ?
1343 "SELECT borrowernumber,categorycode FROM borrowers WHERE surname=? " :
1344 ($dateofbirth) ?
1345 "SELECT borrowernumber,categorycode FROM borrowers WHERE surname=? and firstname=? and dateofbirth=?" :
1346 "SELECT borrowernumber,categorycode FROM borrowers WHERE surname=? and firstname=?";
1347 my $sth = $dbh->prepare($request);
1348 if ($collectivity) {
1349 $sth->execute( uc($surname) );
1350 } elsif($dateofbirth){
1351 $sth->execute( uc($surname), ucfirst($firstname), $dateofbirth );
1352 }else{
1353 $sth->execute( uc($surname), ucfirst($firstname));
1355 my @data = $sth->fetchrow;
1356 ( $data[0] ) and return $data[0], $data[1];
1357 return 0;
1360 sub checkcardnumber {
1361 my ( $cardnumber, $borrowernumber ) = @_;
1363 # If cardnumber is null, we assume they're allowed.
1364 return 0 unless defined $cardnumber;
1366 my $dbh = C4::Context->dbh;
1367 my $query = "SELECT * FROM borrowers WHERE cardnumber=?";
1368 $query .= " AND borrowernumber <> ?" if ($borrowernumber);
1369 my $sth = $dbh->prepare($query);
1370 $sth->execute(
1371 $cardnumber,
1372 ( $borrowernumber ? $borrowernumber : () )
1375 return 1 if $sth->fetchrow_hashref;
1377 my ( $min_length, $max_length ) = get_cardnumber_length();
1378 return 2
1379 if length $cardnumber > $max_length
1380 or length $cardnumber < $min_length;
1382 return 0;
1385 =head2 get_cardnumber_length
1387 my ($min, $max) = C4::Members::get_cardnumber_length()
1389 Returns the minimum and maximum length for patron cardnumbers as
1390 determined by the CardnumberLength system preference, the
1391 BorrowerMandatoryField system preference, and the width of the
1392 database column.
1394 =cut
1396 sub get_cardnumber_length {
1397 my ( $min, $max ) = ( 0, 16 ); # borrowers.cardnumber is a nullable varchar(16)
1398 $min = 1 if C4::Context->preference('BorrowerMandatoryField') =~ /cardnumber/;
1399 if ( my $cardnumber_length = C4::Context->preference('CardnumberLength') ) {
1400 # Is integer and length match
1401 if ( $cardnumber_length =~ m|^\d+$| ) {
1402 $min = $max = $cardnumber_length
1403 if $cardnumber_length >= $min
1404 and $cardnumber_length <= $max;
1406 # Else assuming it is a range
1407 elsif ( $cardnumber_length =~ m|(\d*),(\d*)| ) {
1408 $min = $1 if $1 and $min < $1;
1409 $max = $2 if $2 and $max > $2;
1413 return ( $min, $max );
1416 =head2 getzipnamecity (OUEST-PROVENCE)
1418 take all info from table city for the fields city and zip
1419 check for the name and the zip code of the city selected
1421 =cut
1423 sub getzipnamecity {
1424 my ($cityid) = @_;
1425 my $dbh = C4::Context->dbh;
1426 my $sth =
1427 $dbh->prepare(
1428 "select city_name,city_state,city_zipcode,city_country from cities where cityid=? ");
1429 $sth->execute($cityid);
1430 my @data = $sth->fetchrow;
1431 return $data[0], $data[1], $data[2], $data[3];
1435 =head2 getdcity (OUEST-PROVENCE)
1437 recover cityid with city_name condition
1439 =cut
1441 sub getidcity {
1442 my ($city_name) = @_;
1443 my $dbh = C4::Context->dbh;
1444 my $sth = $dbh->prepare("select cityid from cities where city_name=? ");
1445 $sth->execute($city_name);
1446 my $data = $sth->fetchrow;
1447 return $data;
1450 =head2 GetFirstValidEmailAddress
1452 $email = GetFirstValidEmailAddress($borrowernumber);
1454 Return the first valid email address for a borrower, given the borrowernumber. For now, the order
1455 is defined as email, emailpro, B_email. Returns the empty string if the borrower has no email
1456 addresses.
1458 =cut
1460 sub GetFirstValidEmailAddress {
1461 my $borrowernumber = shift;
1462 my $dbh = C4::Context->dbh;
1463 my $sth = $dbh->prepare( "SELECT email, emailpro, B_email FROM borrowers where borrowernumber = ? ");
1464 $sth->execute( $borrowernumber );
1465 my $data = $sth->fetchrow_hashref;
1467 if ($data->{'email'}) {
1468 return $data->{'email'};
1469 } elsif ($data->{'emailpro'}) {
1470 return $data->{'emailpro'};
1471 } elsif ($data->{'B_email'}) {
1472 return $data->{'B_email'};
1473 } else {
1474 return '';
1478 =head2 GetNoticeEmailAddress
1480 $email = GetNoticeEmailAddress($borrowernumber);
1482 Return the email address of borrower used for notices, given the borrowernumber.
1483 Returns the empty string if no email address.
1485 =cut
1487 sub GetNoticeEmailAddress {
1488 my $borrowernumber = shift;
1490 my $which_address = C4::Context->preference("AutoEmailPrimaryAddress");
1491 # if syspref is set to 'first valid' (value == OFF), look up email address
1492 if ( $which_address eq 'OFF' ) {
1493 return GetFirstValidEmailAddress($borrowernumber);
1495 # specified email address field
1496 my $dbh = C4::Context->dbh;
1497 my $sth = $dbh->prepare( qq{
1498 SELECT $which_address AS primaryemail
1499 FROM borrowers
1500 WHERE borrowernumber=?
1501 } );
1502 $sth->execute($borrowernumber);
1503 my $data = $sth->fetchrow_hashref;
1504 return $data->{'primaryemail'} || '';
1507 =head2 GetExpiryDate
1509 $expirydate = GetExpiryDate($categorycode, $dateenrolled);
1511 Calculate expiry date given a categorycode and starting date. Date argument must be in ISO format.
1512 Return date is also in ISO format.
1514 =cut
1516 sub GetExpiryDate {
1517 my ( $categorycode, $dateenrolled ) = @_;
1518 my $enrolments;
1519 if ($categorycode) {
1520 my $dbh = C4::Context->dbh;
1521 my $sth = $dbh->prepare("SELECT enrolmentperiod,enrolmentperioddate FROM categories WHERE categorycode=?");
1522 $sth->execute($categorycode);
1523 $enrolments = $sth->fetchrow_hashref;
1525 # die "GetExpiryDate: for enrollmentperiod $enrolmentperiod (category '$categorycode') starting $dateenrolled.\n";
1526 my @date = split (/-/,$dateenrolled);
1527 if($enrolments->{enrolmentperiod}){
1528 return sprintf("%04d-%02d-%02d", Add_Delta_YM(@date,0,$enrolments->{enrolmentperiod}));
1529 }else{
1530 return $enrolments->{enrolmentperioddate};
1534 =head2 GetborCatFromCatType
1536 ($codes_arrayref, $labels_hashref) = &GetborCatFromCatType();
1538 Looks up the different types of borrowers in the database. Returns two
1539 elements: a reference-to-array, which lists the borrower category
1540 codes, and a reference-to-hash, which maps the borrower category codes
1541 to category descriptions.
1543 =cut
1546 sub GetborCatFromCatType {
1547 my ( $category_type, $action, $no_branch_limit ) = @_;
1549 my $branch_limit = $no_branch_limit
1551 : C4::Context->userenv ? C4::Context->userenv->{"branch"} : "";
1553 # FIXME - This API seems both limited and dangerous.
1554 my $dbh = C4::Context->dbh;
1556 my $request = qq{
1557 SELECT categories.categorycode, categories.description
1558 FROM categories
1560 $request .= qq{
1561 LEFT JOIN categories_branches ON categories.categorycode = categories_branches.categorycode
1562 } if $branch_limit;
1563 if($action) {
1564 $request .= " $action ";
1565 $request .= " AND (branchcode = ? OR branchcode IS NULL) GROUP BY description" if $branch_limit;
1566 } else {
1567 $request .= " WHERE branchcode = ? OR branchcode IS NULL GROUP BY description" if $branch_limit;
1569 $request .= " ORDER BY categorycode";
1571 my $sth = $dbh->prepare($request);
1572 $sth->execute(
1573 $action ? $category_type : (),
1574 $branch_limit ? $branch_limit : ()
1577 my %labels;
1578 my @codes;
1580 while ( my $data = $sth->fetchrow_hashref ) {
1581 push @codes, $data->{'categorycode'};
1582 $labels{ $data->{'categorycode'} } = $data->{'description'};
1584 $sth->finish;
1585 return ( \@codes, \%labels );
1588 =head2 GetBorrowercategory
1590 $hashref = &GetBorrowercategory($categorycode);
1592 Given the borrower's category code, the function returns the corresponding
1593 data hashref for a comprehensive information display.
1595 =cut
1597 sub GetBorrowercategory {
1598 my ($catcode) = @_;
1599 my $dbh = C4::Context->dbh;
1600 if ($catcode){
1601 my $sth =
1602 $dbh->prepare(
1603 "SELECT description,dateofbirthrequired,upperagelimit,category_type
1604 FROM categories
1605 WHERE categorycode = ?"
1607 $sth->execute($catcode);
1608 my $data =
1609 $sth->fetchrow_hashref;
1610 return $data;
1612 return;
1613 } # sub getborrowercategory
1616 =head2 GetBorrowerCategorycode
1618 $categorycode = &GetBorrowerCategoryCode( $borrowernumber );
1620 Given the borrowernumber, the function returns the corresponding categorycode
1621 =cut
1623 sub GetBorrowerCategorycode {
1624 my ( $borrowernumber ) = @_;
1625 my $dbh = C4::Context->dbh;
1626 my $sth = $dbh->prepare( qq{
1627 SELECT categorycode
1628 FROM borrowers
1629 WHERE borrowernumber = ?
1630 } );
1631 $sth->execute( $borrowernumber );
1632 return $sth->fetchrow;
1635 =head2 GetBorrowercategoryList
1637 $arrayref_hashref = &GetBorrowercategoryList;
1638 If no category code provided, the function returns all the categories.
1640 =cut
1642 sub GetBorrowercategoryList {
1643 my $no_branch_limit = @_ ? shift : 0;
1644 my $branch_limit = $no_branch_limit
1646 : C4::Context->userenv ? C4::Context->userenv->{"branch"} : "";
1647 my $dbh = C4::Context->dbh;
1648 my $query = "SELECT categories.* FROM categories";
1649 $query .= qq{
1650 LEFT JOIN categories_branches ON categories.categorycode = categories_branches.categorycode
1651 WHERE branchcode = ? OR branchcode IS NULL GROUP BY description
1652 } if $branch_limit;
1653 $query .= " ORDER BY description";
1654 my $sth = $dbh->prepare( $query );
1655 $sth->execute( $branch_limit ? $branch_limit : () );
1656 my $data = $sth->fetchall_arrayref( {} );
1657 $sth->finish;
1658 return $data;
1659 } # sub getborrowercategory
1661 =head2 ethnicitycategories
1663 ($codes_arrayref, $labels_hashref) = &ethnicitycategories();
1665 Looks up the different ethnic types in the database. Returns two
1666 elements: a reference-to-array, which lists the ethnicity codes, and a
1667 reference-to-hash, which maps the ethnicity codes to ethnicity
1668 descriptions.
1670 =cut
1674 sub ethnicitycategories {
1675 my $dbh = C4::Context->dbh;
1676 my $sth = $dbh->prepare("Select code,name from ethnicity order by name");
1677 $sth->execute;
1678 my %labels;
1679 my @codes;
1680 while ( my $data = $sth->fetchrow_hashref ) {
1681 push @codes, $data->{'code'};
1682 $labels{ $data->{'code'} } = $data->{'name'};
1684 return ( \@codes, \%labels );
1687 =head2 fixEthnicity
1689 $ethn_name = &fixEthnicity($ethn_code);
1691 Takes an ethnicity code (e.g., "european" or "pi") and returns the
1692 corresponding descriptive name from the C<ethnicity> table in the
1693 Koha database ("European" or "Pacific Islander").
1695 =cut
1699 sub fixEthnicity {
1700 my $ethnicity = shift;
1701 return unless $ethnicity;
1702 my $dbh = C4::Context->dbh;
1703 my $sth = $dbh->prepare("Select name from ethnicity where code = ?");
1704 $sth->execute($ethnicity);
1705 my $data = $sth->fetchrow_hashref;
1706 return $data->{'name'};
1707 } # sub fixEthnicity
1709 =head2 GetAge
1711 $dateofbirth,$date = &GetAge($date);
1713 this function return the borrowers age with the value of dateofbirth
1715 =cut
1718 sub GetAge{
1719 my ( $date, $date_ref ) = @_;
1721 if ( not defined $date_ref ) {
1722 $date_ref = sprintf( '%04d-%02d-%02d', Today() );
1725 my ( $year1, $month1, $day1 ) = split /-/, $date;
1726 my ( $year2, $month2, $day2 ) = split /-/, $date_ref;
1728 my $age = $year2 - $year1;
1729 if ( $month1 . $day1 > $month2 . $day2 ) {
1730 $age--;
1733 return $age;
1734 } # sub get_age
1736 =head2 GetCities
1738 $cityarrayref = GetCities();
1740 Returns an array_ref of the entries in the cities table
1741 If there are entries in the table an empty row is returned
1742 This is currently only used to populate a popup in memberentry
1744 =cut
1746 sub GetCities {
1748 my $dbh = C4::Context->dbh;
1749 my $city_arr = $dbh->selectall_arrayref(
1750 q|SELECT cityid,city_zipcode,city_name,city_state,city_country FROM cities ORDER BY city_name|,
1751 { Slice => {} });
1752 if ( @{$city_arr} ) {
1753 unshift @{$city_arr}, {
1754 city_zipcode => q{},
1755 city_name => q{},
1756 cityid => q{},
1757 city_state => q{},
1758 city_country => q{},
1762 return $city_arr;
1765 =head2 GetSortDetails (OUEST-PROVENCE)
1767 ($lib) = &GetSortDetails($category,$sortvalue);
1769 Returns the authorized value details
1770 C<&$lib>return value of authorized value details
1771 C<&$sortvalue>this is the value of authorized value
1772 C<&$category>this is the value of authorized value category
1774 =cut
1776 sub GetSortDetails {
1777 my ( $category, $sortvalue ) = @_;
1778 my $dbh = C4::Context->dbh;
1779 my $query = qq|SELECT lib
1780 FROM authorised_values
1781 WHERE category=?
1782 AND authorised_value=? |;
1783 my $sth = $dbh->prepare($query);
1784 $sth->execute( $category, $sortvalue );
1785 my $lib = $sth->fetchrow;
1786 return ($lib) if ($lib);
1787 return ($sortvalue) unless ($lib);
1790 =head2 MoveMemberToDeleted
1792 $result = &MoveMemberToDeleted($borrowernumber);
1794 Copy the record from borrowers to deletedborrowers table.
1796 =cut
1798 # FIXME: should do it in one SQL statement w/ subquery
1799 # Otherwise, we should return the @data on success
1801 sub MoveMemberToDeleted {
1802 my ($member) = shift or return;
1803 my $dbh = C4::Context->dbh;
1804 my $query = qq|SELECT *
1805 FROM borrowers
1806 WHERE borrowernumber=?|;
1807 my $sth = $dbh->prepare($query);
1808 $sth->execute($member);
1809 my @data = $sth->fetchrow_array;
1810 (@data) or return; # if we got a bad borrowernumber, there's nothing to insert
1811 $sth =
1812 $dbh->prepare( "INSERT INTO deletedborrowers VALUES ("
1813 . ( "?," x ( scalar(@data) - 1 ) )
1814 . "?)" );
1815 $sth->execute(@data);
1818 =head2 DelMember
1820 DelMember($borrowernumber);
1822 This function remove directly a borrower whitout writing it on deleteborrower.
1823 + Deletes reserves for the borrower
1825 =cut
1827 sub DelMember {
1828 my $dbh = C4::Context->dbh;
1829 my $borrowernumber = shift;
1830 #warn "in delmember with $borrowernumber";
1831 return unless $borrowernumber; # borrowernumber is mandatory.
1833 my $query = qq|DELETE
1834 FROM reserves
1835 WHERE borrowernumber=?|;
1836 my $sth = $dbh->prepare($query);
1837 $sth->execute($borrowernumber);
1838 $query = "
1839 DELETE
1840 FROM borrowers
1841 WHERE borrowernumber = ?
1843 $sth = $dbh->prepare($query);
1844 $sth->execute($borrowernumber);
1845 logaction("MEMBERS", "DELETE", $borrowernumber, "") if C4::Context->preference("BorrowersLog");
1846 return $sth->rows;
1849 =head2 ExtendMemberSubscriptionTo (OUEST-PROVENCE)
1851 $date = ExtendMemberSubscriptionTo($borrowerid, $date);
1853 Extending the subscription to a given date or to the expiry date calculated on ISO date.
1854 Returns ISO date.
1856 =cut
1858 sub ExtendMemberSubscriptionTo {
1859 my ( $borrowerid,$date) = @_;
1860 my $dbh = C4::Context->dbh;
1861 my $borrower = GetMember('borrowernumber'=>$borrowerid);
1862 unless ($date){
1863 $date = (C4::Context->preference('BorrowerRenewalPeriodBase') eq 'dateexpiry') ?
1864 C4::Dates->new($borrower->{'dateexpiry'}, 'iso')->output("iso") :
1865 C4::Dates->new()->output("iso");
1866 $date = GetExpiryDate( $borrower->{'categorycode'}, $date );
1868 my $sth = $dbh->do(<<EOF);
1869 UPDATE borrowers
1870 SET dateexpiry='$date'
1871 WHERE borrowernumber='$borrowerid'
1874 AddEnrolmentFeeIfNeeded( $borrower->{categorycode}, $borrower->{borrowernumber} );
1876 logaction("MEMBERS", "RENEW", $borrower->{'borrowernumber'}, "Membership renewed")if C4::Context->preference("BorrowersLog");
1877 return $date if ($sth);
1878 return 0;
1881 =head2 GetTitles (OUEST-PROVENCE)
1883 ($borrowertitle)= &GetTitles();
1885 Looks up the different title . Returns array with all borrowers title
1887 =cut
1889 sub GetTitles {
1890 my @borrowerTitle = split (/,|\|/,C4::Context->preference('BorrowersTitles'));
1891 unshift( @borrowerTitle, "" );
1892 my $count=@borrowerTitle;
1893 if ($count == 1){
1894 return ();
1896 else {
1897 return ( \@borrowerTitle);
1901 =head2 GetPatronImage
1903 my ($imagedata, $dberror) = GetPatronImage($borrowernumber);
1905 Returns the mimetype and binary image data of the image for the patron with the supplied borrowernumber.
1907 =cut
1909 sub GetPatronImage {
1910 my ($borrowernumber) = @_;
1911 warn "Borrowernumber passed to GetPatronImage is $borrowernumber" if $debug;
1912 my $dbh = C4::Context->dbh;
1913 my $query = 'SELECT mimetype, imagefile FROM patronimage WHERE borrowernumber = ?';
1914 my $sth = $dbh->prepare($query);
1915 $sth->execute($borrowernumber);
1916 my $imagedata = $sth->fetchrow_hashref;
1917 warn "Database error!" if $sth->errstr;
1918 return $imagedata, $sth->errstr;
1921 =head2 PutPatronImage
1923 PutPatronImage($cardnumber, $mimetype, $imgfile);
1925 Stores patron binary image data and mimetype in database.
1926 NOTE: This function is good for updating images as well as inserting new images in the database.
1928 =cut
1930 sub PutPatronImage {
1931 my ($cardnumber, $mimetype, $imgfile) = @_;
1932 warn "Parameters passed in: Cardnumber=$cardnumber, Mimetype=$mimetype, " . ($imgfile ? "Imagefile" : "No Imagefile") if $debug;
1933 my $dbh = C4::Context->dbh;
1934 my $query = "INSERT INTO patronimage (borrowernumber, mimetype, imagefile) VALUES ( ( SELECT borrowernumber from borrowers WHERE cardnumber = ? ),?,?) ON DUPLICATE KEY UPDATE imagefile = ?;";
1935 my $sth = $dbh->prepare($query);
1936 $sth->execute($cardnumber,$mimetype,$imgfile,$imgfile);
1937 warn "Error returned inserting $cardnumber.$mimetype." if $sth->errstr;
1938 return $sth->errstr;
1941 =head2 RmPatronImage
1943 my ($dberror) = RmPatronImage($borrowernumber);
1945 Removes the image for the patron with the supplied borrowernumber.
1947 =cut
1949 sub RmPatronImage {
1950 my ($borrowernumber) = @_;
1951 warn "Borrowernumber passed to GetPatronImage is $borrowernumber" if $debug;
1952 my $dbh = C4::Context->dbh;
1953 my $query = "DELETE FROM patronimage WHERE borrowernumber = ?;";
1954 my $sth = $dbh->prepare($query);
1955 $sth->execute($borrowernumber);
1956 my $dberror = $sth->errstr;
1957 warn "Database error!" if $sth->errstr;
1958 return $dberror;
1961 =head2 GetHideLostItemsPreference
1963 $hidelostitemspref = &GetHideLostItemsPreference($borrowernumber);
1965 Returns the HideLostItems preference for the patron category of the supplied borrowernumber
1966 C<&$hidelostitemspref>return value of function, 0 or 1
1968 =cut
1970 sub GetHideLostItemsPreference {
1971 my ($borrowernumber) = @_;
1972 my $dbh = C4::Context->dbh;
1973 my $query = "SELECT hidelostitems FROM borrowers,categories WHERE borrowers.categorycode = categories.categorycode AND borrowernumber = ?";
1974 my $sth = $dbh->prepare($query);
1975 $sth->execute($borrowernumber);
1976 my $hidelostitems = $sth->fetchrow;
1977 return $hidelostitems;
1980 =head2 GetBorrowersToExpunge
1982 $borrowers = &GetBorrowersToExpunge(
1983 not_borrowered_since => $not_borrowered_since,
1984 expired_before => $expired_before,
1985 category_code => $category_code,
1986 branchcode => $branchcode
1989 This function get all borrowers based on the given criteria.
1991 =cut
1993 sub GetBorrowersToExpunge {
1994 my $params = shift;
1996 my $filterdate = $params->{'not_borrowered_since'};
1997 my $filterexpiry = $params->{'expired_before'};
1998 my $filtercategory = $params->{'category_code'};
1999 my $filterbranch = $params->{'branchcode'} ||
2000 ((C4::Context->preference('IndependentBranches')
2001 && C4::Context->userenv
2002 && !C4::Context->IsSuperLibrarian()
2003 && C4::Context->userenv->{branch})
2004 ? C4::Context->userenv->{branch}
2005 : "");
2007 my $dbh = C4::Context->dbh;
2008 my $query = "
2009 SELECT borrowers.borrowernumber,
2010 MAX(old_issues.timestamp) AS latestissue,
2011 MAX(issues.timestamp) AS currentissue
2012 FROM borrowers
2013 JOIN categories USING (categorycode)
2014 LEFT JOIN old_issues USING (borrowernumber)
2015 LEFT JOIN issues USING (borrowernumber)
2016 WHERE category_type <> 'S'
2017 AND borrowernumber NOT IN (SELECT guarantorid FROM borrowers WHERE guarantorid IS NOT NULL AND guarantorid <> 0)
2019 my @query_params;
2020 if ( $filterbranch && $filterbranch ne "" ) {
2021 $query.= " AND borrowers.branchcode = ? ";
2022 push( @query_params, $filterbranch );
2024 if ( $filterexpiry ) {
2025 $query .= " AND dateexpiry < ? ";
2026 push( @query_params, $filterexpiry );
2028 if ( $filtercategory ) {
2029 $query .= " AND categorycode = ? ";
2030 push( @query_params, $filtercategory );
2032 $query.=" GROUP BY borrowers.borrowernumber HAVING currentissue IS NULL ";
2033 if ( $filterdate ) {
2034 $query.=" AND ( latestissue < ? OR latestissue IS NULL ) ";
2035 push @query_params,$filterdate;
2037 warn $query if $debug;
2039 my $sth = $dbh->prepare($query);
2040 if (scalar(@query_params)>0){
2041 $sth->execute(@query_params);
2043 else {
2044 $sth->execute;
2047 my @results;
2048 while ( my $data = $sth->fetchrow_hashref ) {
2049 push @results, $data;
2051 return \@results;
2054 =head2 GetBorrowersWhoHaveNeverBorrowed
2056 $results = &GetBorrowersWhoHaveNeverBorrowed
2058 This function get all borrowers who have never borrowed.
2060 I<$result> is a ref to an array which all elements are a hasref.
2062 =cut
2064 sub GetBorrowersWhoHaveNeverBorrowed {
2065 my $filterbranch = shift ||
2066 ((C4::Context->preference('IndependentBranches')
2067 && C4::Context->userenv
2068 && !C4::Context->IsSuperLibrarian()
2069 && C4::Context->userenv->{branch})
2070 ? C4::Context->userenv->{branch}
2071 : "");
2072 my $dbh = C4::Context->dbh;
2073 my $query = "
2074 SELECT borrowers.borrowernumber,max(timestamp) as latestissue
2075 FROM borrowers
2076 LEFT JOIN issues ON borrowers.borrowernumber = issues.borrowernumber
2077 WHERE issues.borrowernumber IS NULL
2079 my @query_params;
2080 if ($filterbranch && $filterbranch ne ""){
2081 $query.=" AND borrowers.branchcode= ?";
2082 push @query_params,$filterbranch;
2084 warn $query if $debug;
2086 my $sth = $dbh->prepare($query);
2087 if (scalar(@query_params)>0){
2088 $sth->execute(@query_params);
2090 else {
2091 $sth->execute;
2094 my @results;
2095 while ( my $data = $sth->fetchrow_hashref ) {
2096 push @results, $data;
2098 return \@results;
2101 =head2 GetBorrowersWithIssuesHistoryOlderThan
2103 $results = &GetBorrowersWithIssuesHistoryOlderThan($date)
2105 this function get all borrowers who has an issue history older than I<$date> given on input arg.
2107 I<$result> is a ref to an array which all elements are a hashref.
2108 This hashref is containt the number of time this borrowers has borrowed before I<$date> and the borrowernumber.
2110 =cut
2112 sub GetBorrowersWithIssuesHistoryOlderThan {
2113 my $dbh = C4::Context->dbh;
2114 my $date = shift ||POSIX::strftime("%Y-%m-%d",localtime());
2115 my $filterbranch = shift ||
2116 ((C4::Context->preference('IndependentBranches')
2117 && C4::Context->userenv
2118 && !C4::Context->IsSuperLibrarian()
2119 && C4::Context->userenv->{branch})
2120 ? C4::Context->userenv->{branch}
2121 : "");
2122 my $query = "
2123 SELECT count(borrowernumber) as n,borrowernumber
2124 FROM old_issues
2125 WHERE returndate < ?
2126 AND borrowernumber IS NOT NULL
2128 my @query_params;
2129 push @query_params, $date;
2130 if ($filterbranch){
2131 $query.=" AND branchcode = ?";
2132 push @query_params, $filterbranch;
2134 $query.=" GROUP BY borrowernumber ";
2135 warn $query if $debug;
2136 my $sth = $dbh->prepare($query);
2137 $sth->execute(@query_params);
2138 my @results;
2140 while ( my $data = $sth->fetchrow_hashref ) {
2141 push @results, $data;
2143 return \@results;
2146 =head2 GetBorrowersNamesAndLatestIssue
2148 $results = &GetBorrowersNamesAndLatestIssueList(@borrowernumbers)
2150 this function get borrowers Names and surnames and Issue information.
2152 I<@borrowernumbers> is an array which all elements are borrowernumbers.
2153 This hashref is containt the number of time this borrowers has borrowed before I<$date> and the borrowernumber.
2155 =cut
2157 sub GetBorrowersNamesAndLatestIssue {
2158 my $dbh = C4::Context->dbh;
2159 my @borrowernumbers=@_;
2160 my $query = "
2161 SELECT surname,lastname, phone, email,max(timestamp)
2162 FROM borrowers
2163 LEFT JOIN issues ON borrowers.borrowernumber=issues.borrowernumber
2164 GROUP BY borrowernumber
2166 my $sth = $dbh->prepare($query);
2167 $sth->execute;
2168 my $results = $sth->fetchall_arrayref({});
2169 return $results;
2172 =head2 ModPrivacy
2174 =over 4
2176 my $success = ModPrivacy( $borrowernumber, $privacy );
2178 Update the privacy of a patron.
2180 return :
2181 true on success, false on failure
2183 =back
2185 =cut
2187 sub ModPrivacy {
2188 my $borrowernumber = shift;
2189 my $privacy = shift;
2190 return unless defined $borrowernumber;
2191 return unless $borrowernumber =~ /^\d+$/;
2193 return ModMember( borrowernumber => $borrowernumber,
2194 privacy => $privacy );
2197 =head2 AddMessage
2199 AddMessage( $borrowernumber, $message_type, $message, $branchcode );
2201 Adds a message to the messages table for the given borrower.
2203 Returns:
2204 True on success
2205 False on failure
2207 =cut
2209 sub AddMessage {
2210 my ( $borrowernumber, $message_type, $message, $branchcode ) = @_;
2212 my $dbh = C4::Context->dbh;
2214 if ( ! ( $borrowernumber && $message_type && $message && $branchcode ) ) {
2215 return;
2218 my $query = "INSERT INTO messages ( borrowernumber, branchcode, message_type, message ) VALUES ( ?, ?, ?, ? )";
2219 my $sth = $dbh->prepare($query);
2220 $sth->execute( $borrowernumber, $branchcode, $message_type, $message );
2221 logaction("MEMBERS", "ADDCIRCMESSAGE", $borrowernumber, $message) if C4::Context->preference("BorrowersLog");
2222 return 1;
2225 =head2 GetMessages
2227 GetMessages( $borrowernumber, $type );
2229 $type is message type, B for borrower, or L for Librarian.
2230 Empty type returns all messages of any type.
2232 Returns all messages for the given borrowernumber
2234 =cut
2236 sub GetMessages {
2237 my ( $borrowernumber, $type, $branchcode ) = @_;
2239 if ( ! $type ) {
2240 $type = '%';
2243 my $dbh = C4::Context->dbh;
2245 my $query = "SELECT
2246 branches.branchname,
2247 messages.*,
2248 message_date,
2249 messages.branchcode LIKE '$branchcode' AS can_delete
2250 FROM messages, branches
2251 WHERE borrowernumber = ?
2252 AND message_type LIKE ?
2253 AND messages.branchcode = branches.branchcode
2254 ORDER BY message_date DESC";
2255 my $sth = $dbh->prepare($query);
2256 $sth->execute( $borrowernumber, $type ) ;
2257 my @results;
2259 while ( my $data = $sth->fetchrow_hashref ) {
2260 my $d = C4::Dates->new( $data->{message_date}, 'iso' );
2261 $data->{message_date_formatted} = $d->output;
2262 push @results, $data;
2264 return \@results;
2268 =head2 GetMessages
2270 GetMessagesCount( $borrowernumber, $type );
2272 $type is message type, B for borrower, or L for Librarian.
2273 Empty type returns all messages of any type.
2275 Returns the number of messages for the given borrowernumber
2277 =cut
2279 sub GetMessagesCount {
2280 my ( $borrowernumber, $type, $branchcode ) = @_;
2282 if ( ! $type ) {
2283 $type = '%';
2286 my $dbh = C4::Context->dbh;
2288 my $query = "SELECT COUNT(*) as MsgCount FROM messages WHERE borrowernumber = ? AND message_type LIKE ?";
2289 my $sth = $dbh->prepare($query);
2290 $sth->execute( $borrowernumber, $type ) ;
2291 my @results;
2293 my $data = $sth->fetchrow_hashref;
2294 my $count = $data->{'MsgCount'};
2296 return $count;
2301 =head2 DeleteMessage
2303 DeleteMessage( $message_id );
2305 =cut
2307 sub DeleteMessage {
2308 my ( $message_id ) = @_;
2310 my $dbh = C4::Context->dbh;
2311 my $query = "SELECT * FROM messages WHERE message_id = ?";
2312 my $sth = $dbh->prepare($query);
2313 $sth->execute( $message_id );
2314 my $message = $sth->fetchrow_hashref();
2316 $query = "DELETE FROM messages WHERE message_id = ?";
2317 $sth = $dbh->prepare($query);
2318 $sth->execute( $message_id );
2319 logaction("MEMBERS", "DELCIRCMESSAGE", $message->{'borrowernumber'}, $message->{'message'}) if C4::Context->preference("BorrowersLog");
2322 =head2 IssueSlip
2324 IssueSlip($branchcode, $borrowernumber, $quickslip)
2326 Returns letter hash ( see C4::Letters::GetPreparedLetter )
2328 $quickslip is boolean, to indicate whether we want a quick slip
2330 =cut
2332 sub IssueSlip {
2333 my ($branch, $borrowernumber, $quickslip) = @_;
2335 # return unless ( C4::Context->boolean_preference('printcirculationslips') );
2337 my $now = POSIX::strftime("%Y-%m-%d", localtime);
2339 my $issueslist = GetPendingIssues($borrowernumber);
2340 foreach my $it (@$issueslist){
2341 if ((substr $it->{'issuedate'}, 0, 10) eq $now || (substr $it->{'lastreneweddate'}, 0, 10) eq $now) {
2342 $it->{'now'} = 1;
2344 elsif ((substr $it->{'date_due'}, 0, 10) le $now) {
2345 $it->{'overdue'} = 1;
2347 my $dt = dt_from_string( $it->{'date_due'} );
2348 $it->{'date_due'} = output_pref( $dt );;
2350 my @issues = sort { $b->{'timestamp'} <=> $a->{'timestamp'} } @$issueslist;
2352 my ($letter_code, %repeat);
2353 if ( $quickslip ) {
2354 $letter_code = 'ISSUEQSLIP';
2355 %repeat = (
2356 'checkedout' => [ map {
2357 'biblio' => $_,
2358 'items' => $_,
2359 'issues' => $_,
2360 }, grep { $_->{'now'} } @issues ],
2363 else {
2364 $letter_code = 'ISSUESLIP';
2365 %repeat = (
2366 'checkedout' => [ map {
2367 'biblio' => $_,
2368 'items' => $_,
2369 'issues' => $_,
2370 }, grep { !$_->{'overdue'} } @issues ],
2372 'overdue' => [ map {
2373 'biblio' => $_,
2374 'items' => $_,
2375 'issues' => $_,
2376 }, grep { $_->{'overdue'} } @issues ],
2378 'news' => [ map {
2379 $_->{'timestamp'} = $_->{'newdate'};
2380 { opac_news => $_ }
2381 } @{ GetNewsToDisplay("slip",$branch) } ],
2385 return C4::Letters::GetPreparedLetter (
2386 module => 'circulation',
2387 letter_code => $letter_code,
2388 branchcode => $branch,
2389 tables => {
2390 'branches' => $branch,
2391 'borrowers' => $borrowernumber,
2393 repeat => \%repeat,
2397 =head2 GetBorrowersWithEmail
2399 ([$borrnum,$userid], ...) = GetBorrowersWithEmail('me@example.com');
2401 This gets a list of users and their basic details from their email address.
2402 As it's possible for multiple user to have the same email address, it provides
2403 you with all of them. If there is no userid for the user, there will be an
2404 C<undef> there. An empty list will be returned if there are no matches.
2406 =cut
2408 sub GetBorrowersWithEmail {
2409 my $email = shift;
2411 my $dbh = C4::Context->dbh;
2413 my $query = "SELECT borrowernumber, userid FROM borrowers WHERE email=?";
2414 my $sth=$dbh->prepare($query);
2415 $sth->execute($email);
2416 my @result = ();
2417 while (my $ref = $sth->fetch) {
2418 push @result, $ref;
2420 die "Failure searching for borrowers by email address: $sth->errstr" if $sth->err;
2421 return @result;
2424 sub AddMember_Opac {
2425 my ( %borrower ) = @_;
2427 $borrower{'categorycode'} = C4::Context->preference('PatronSelfRegistrationDefaultCategory');
2429 my $sr = new String::Random;
2430 $sr->{'A'} = [ 'A'..'Z', 'a'..'z' ];
2431 my $password = $sr->randpattern("AAAAAAAAAA");
2432 $borrower{'password'} = $password;
2434 $borrower{'cardnumber'} = fixup_cardnumber();
2436 my $borrowernumber = AddMember(%borrower);
2438 return ( $borrowernumber, $password );
2441 =head2 AddEnrolmentFeeIfNeeded
2443 AddEnrolmentFeeIfNeeded( $borrower->{categorycode}, $borrower->{borrowernumber} );
2445 Add enrolment fee for a patron if needed.
2447 =cut
2449 sub AddEnrolmentFeeIfNeeded {
2450 my ( $categorycode, $borrowernumber ) = @_;
2451 # check for enrollment fee & add it if needed
2452 my $dbh = C4::Context->dbh;
2453 my $sth = $dbh->prepare(q{
2454 SELECT enrolmentfee
2455 FROM categories
2456 WHERE categorycode=?
2458 $sth->execute( $categorycode );
2459 if ( $sth->err ) {
2460 warn sprintf('Database returned the following error: %s', $sth->errstr);
2461 return;
2463 my ($enrolmentfee) = $sth->fetchrow;
2464 if ($enrolmentfee && $enrolmentfee > 0) {
2465 # insert fee in patron debts
2466 C4::Accounts::manualinvoice( $borrowernumber, '', '', 'A', $enrolmentfee );
2470 sub HasOverdues {
2471 my ( $borrowernumber ) = @_;
2473 my $sql = "SELECT COUNT(*) FROM issues WHERE date_due < NOW() AND borrowernumber = ?";
2474 my $sth = C4::Context->dbh->prepare( $sql );
2475 $sth->execute( $borrowernumber );
2476 my ( $count ) = $sth->fetchrow_array();
2478 return $count;
2481 END { } # module clean-up code here (global destructor)
2485 __END__
2487 =head1 AUTHOR
2489 Koha Team
2491 =cut