Bug 12567: Make catalog statistics wizard publication year work for MARC21
[koha.git] / C4 / Members.pm
blobd88ea45e73b2d655cfe32dcb9e825f8fe4306805
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 UpdateBorrowerAttribute);
37 use C4::NewsChannels; #get slip news
38 use DateTime;
39 use DateTime::Format::DateParse;
40 use Koha::Database;
41 use Koha::DateUtils;
42 use Koha::Borrower::Debarments qw(IsDebarred);
43 use Text::Unaccent qw( unac_string );
44 use Koha::AuthUtils qw(hash_password);
45 use Koha::Database;
46 use Module::Load;
47 if ( C4::Context->preference('NorwegianPatronDBEnable') && C4::Context->preference('NorwegianPatronDBEnable') == 1 ) {
48 load Koha::NorwegianPatronDB, qw( NLUpdateHashedPIN NLEncryptPIN NLSync );
51 our ($VERSION,@ISA,@EXPORT,@EXPORT_OK,$debug);
53 BEGIN {
54 $VERSION = 3.07.00.049;
55 $debug = $ENV{DEBUG} || 0;
56 require Exporter;
57 @ISA = qw(Exporter);
58 #Get data
59 push @EXPORT, qw(
60 &Search
61 &GetMemberDetails
62 &GetMemberRelatives
63 &GetMember
65 &GetGuarantees
67 &GetMemberIssuesAndFines
68 &GetPendingIssues
69 &GetAllIssues
71 &getzipnamecity
72 &getidcity
74 &GetFirstValidEmailAddress
75 &GetNoticeEmailAddress
77 &GetAge
78 &GetCities
79 &GetSortDetails
80 &GetTitles
82 &GetPatronImage
83 &PutPatronImage
84 &RmPatronImage
86 &GetHideLostItemsPreference
88 &IsMemberBlocked
89 &GetMemberAccountRecords
90 &GetBorNotifyAcctRecord
92 &GetborCatFromCatType
93 &GetBorrowercategory
94 GetBorrowerCategorycode
95 &GetBorrowercategoryList
97 &GetBorrowersToExpunge
98 &GetBorrowersWhoHaveNeverBorrowed
99 &GetBorrowersWithIssuesHistoryOlderThan
101 &GetExpiryDate
103 &AddMessage
104 &DeleteMessage
105 &GetMessages
106 &GetMessagesCount
108 &IssueSlip
109 GetBorrowersWithEmail
111 HasOverdues
114 #Modify data
115 push @EXPORT, qw(
116 &ModMember
117 &changepassword
118 &ModPrivacy
121 #Delete data
122 push @EXPORT, qw(
123 &DelMember
126 #Insert data
127 push @EXPORT, qw(
128 &AddMember
129 &AddMember_Opac
130 &MoveMemberToDeleted
131 &ExtendMemberSubscriptionTo
134 #Check data
135 push @EXPORT, qw(
136 &checkuniquemember
137 &checkuserpassword
138 &Check_Userid
139 &Generate_Userid
140 &fixEthnicity
141 &ethnicitycategories
142 &fixup_cardnumber
143 &checkcardnumber
147 =head1 NAME
149 C4::Members - Perl Module containing convenience functions for member handling
151 =head1 SYNOPSIS
153 use C4::Members;
155 =head1 DESCRIPTION
157 This module contains routines for adding, modifying and deleting members/patrons/borrowers
159 =head1 FUNCTIONS
161 =head2 Search
163 $borrowers_result_array_ref = &Search($filter,$orderby, $limit,
164 $columns_out, $search_on_fields,$searchtype);
166 Looks up patrons (borrowers) on filter. A wrapper for SearchInTable('borrowers').
168 For C<$filter>, C<$orderby>, C<$limit>, C<&columns_out>, C<&search_on_fields> and C<&searchtype>
169 refer to C4::SQLHelper:SearchInTable().
171 Special C<$filter> key '' is effectively expanded to search on surname firstname othernamescw
172 and cardnumber unless C<&search_on_fields> is defined
174 Examples:
176 $borrowers = Search('abcd', 'cardnumber');
178 $borrowers = Search({''=>'abcd', category_type=>'I'}, 'surname');
180 =cut
182 sub _express_member_find {
183 my ($filter) = @_;
185 # this is used by circulation everytime a new borrowers cardnumber is scanned
186 # so we can check an exact match first, if that works return, otherwise do the rest
187 my $dbh = C4::Context->dbh;
188 my $query = "SELECT borrowernumber FROM borrowers WHERE cardnumber = ?";
189 if ( my $borrowernumber = $dbh->selectrow_array($query, undef, $filter) ) {
190 return( {"borrowernumber"=>$borrowernumber} );
193 my ($search_on_fields, $searchtype);
194 if ( length($filter) == 1 ) {
195 $search_on_fields = [ qw(surname) ];
196 $searchtype = 'start_with';
197 } else {
198 $search_on_fields = [ qw(surname firstname othernames cardnumber) ];
199 $searchtype = 'contain';
202 return (undef, $search_on_fields, $searchtype);
205 sub Search {
206 my ( $filter, $orderby, $limit, $columns_out, $search_on_fields, $searchtype ) = @_;
208 my $search_string;
209 my $found_borrower;
211 if ( my $fr = ref $filter ) {
212 if ( $fr eq "HASH" ) {
213 if ( my $search_string = $filter->{''} ) {
214 my ($member_filter, $member_search_on_fields, $member_searchtype) = _express_member_find($search_string);
215 if ($member_filter) {
216 $filter = $member_filter;
217 $found_borrower = 1;
218 } else {
219 $search_on_fields ||= $member_search_on_fields;
220 $searchtype ||= $member_searchtype;
224 else {
225 $search_string = $filter;
228 else {
229 $search_string = $filter;
230 my ($member_filter, $member_search_on_fields, $member_searchtype) = _express_member_find($search_string);
231 if ($member_filter) {
232 $filter = $member_filter;
233 $found_borrower = 1;
234 } else {
235 $search_on_fields ||= $member_search_on_fields;
236 $searchtype ||= $member_searchtype;
240 if ( !$found_borrower && C4::Context->preference('ExtendedPatronAttributes') && $search_string ) {
241 my $matching_records = C4::Members::Attributes::SearchIdMatchingAttribute($search_string);
242 if(scalar(@$matching_records)>0) {
243 if ( my $fr = ref $filter ) {
244 if ( $fr eq "HASH" ) {
245 my %f = %$filter;
246 $filter = [ $filter ];
247 delete $f{''};
248 push @$filter, { %f, "borrowernumber"=>$$matching_records };
250 else {
251 push @$filter, {"borrowernumber"=>$matching_records};
254 else {
255 $filter = [ $filter ];
256 push @$filter, {"borrowernumber"=>$matching_records};
261 # $showallbranches was not used at the time SearchMember() was mainstreamed into Search().
262 # Mentioning for the reference
264 if ( C4::Context->preference("IndependentBranches") ) { # && !$showallbranches){
265 if ( my $userenv = C4::Context->userenv ) {
266 my $branch = $userenv->{'branch'};
267 if ( !C4::Context->IsSuperLibrarian() && $branch ){
268 if (my $fr = ref $filter) {
269 if ( $fr eq "HASH" ) {
270 $filter->{branchcode} = $branch;
272 else {
273 foreach (@$filter) {
274 $_ = { '' => $_ } unless ref $_;
275 $_->{branchcode} = $branch;
279 else {
280 $filter = { '' => $filter, branchcode => $branch };
286 if ($found_borrower) {
287 $searchtype = "exact";
289 $searchtype ||= "start_with";
291 return SearchInTable( "borrowers", $filter, $orderby, $limit, $columns_out, $search_on_fields, $searchtype );
294 =head2 GetMemberDetails
296 ($borrower) = &GetMemberDetails($borrowernumber, $cardnumber);
298 Looks up a patron and returns information about him or her. If
299 C<$borrowernumber> is true (nonzero), C<&GetMemberDetails> looks
300 up the borrower by number; otherwise, it looks up the borrower by card
301 number.
303 C<$borrower> is a reference-to-hash whose keys are the fields of the
304 borrowers table in the Koha database. In addition,
305 C<$borrower-E<gt>{flags}> is a hash giving more detailed information
306 about the patron. Its keys act as flags :
308 if $borrower->{flags}->{LOST} {
309 # Patron's card was reported lost
312 If the state of a flag means that the patron should not be
313 allowed to borrow any more books, then it will have a C<noissues> key
314 with a true value.
316 See patronflags for more details.
318 C<$borrower-E<gt>{authflags}> is a hash giving more detailed information
319 about the top-level permissions flags set for the borrower. For example,
320 if a user has the "editcatalogue" permission,
321 C<$borrower-E<gt>{authflags}-E<gt>{editcatalogue}> will exist and have
322 the value "1".
324 =cut
326 sub GetMemberDetails {
327 my ( $borrowernumber, $cardnumber ) = @_;
328 my $dbh = C4::Context->dbh;
329 my $query;
330 my $sth;
331 if ($borrowernumber) {
332 $sth = $dbh->prepare("
333 SELECT borrowers.*,
334 category_type,
335 categories.description,
336 categories.BlockExpiredPatronOpacActions,
337 reservefee,
338 enrolmentperiod
339 FROM borrowers
340 LEFT JOIN categories ON borrowers.categorycode=categories.categorycode
341 WHERE borrowernumber = ?
343 $sth->execute($borrowernumber);
345 elsif ($cardnumber) {
346 $sth = $dbh->prepare("
347 SELECT borrowers.*,
348 category_type,
349 categories.description,
350 categories.BlockExpiredPatronOpacActions,
351 reservefee,
352 enrolmentperiod
353 FROM borrowers
354 LEFT JOIN categories ON borrowers.categorycode = categories.categorycode
355 WHERE cardnumber = ?
357 $sth->execute($cardnumber);
359 else {
360 return;
362 my $borrower = $sth->fetchrow_hashref;
363 return unless $borrower;
364 my ($amount) = GetMemberAccountRecords( $borrowernumber);
365 $borrower->{'amountoutstanding'} = $amount;
366 # FIXME - patronflags calls GetMemberAccountRecords... just have patronflags return $amount
367 my $flags = patronflags( $borrower);
368 my $accessflagshash;
370 $sth = $dbh->prepare("select bit,flag from userflags");
371 $sth->execute;
372 while ( my ( $bit, $flag ) = $sth->fetchrow ) {
373 if ( $borrower->{'flags'} && $borrower->{'flags'} & 2**$bit ) {
374 $accessflagshash->{$flag} = 1;
377 $borrower->{'flags'} = $flags;
378 $borrower->{'authflags'} = $accessflagshash;
380 # For the purposes of making templates easier, we'll define a
381 # 'showname' which is the alternate form the user's first name if
382 # 'other name' is defined.
383 if ($borrower->{category_type} eq 'I') {
384 $borrower->{'showname'} = $borrower->{'othernames'};
385 $borrower->{'showname'} .= " $borrower->{'firstname'}" if $borrower->{'firstname'};
386 } else {
387 $borrower->{'showname'} = $borrower->{'firstname'};
390 # Handle setting the true behavior for BlockExpiredPatronOpacActions
391 $borrower->{'BlockExpiredPatronOpacActions'} =
392 C4::Context->preference('BlockExpiredPatronOpacActions')
393 if ( $borrower->{'BlockExpiredPatronOpacActions'} == -1 );
395 $borrower->{'is_expired'} = 0;
396 $borrower->{'is_expired'} = 1 if
397 defined($borrower->{dateexpiry}) &&
398 $borrower->{'dateexpiry'} ne '0000-00-00' &&
399 Date_to_Days( Today() ) >
400 Date_to_Days( split /-/, $borrower->{'dateexpiry'} );
402 return ($borrower); #, $flags, $accessflagshash);
405 =head2 patronflags
407 $flags = &patronflags($patron);
409 This function is not exported.
411 The following will be set where applicable:
412 $flags->{CHARGES}->{amount} Amount of debt
413 $flags->{CHARGES}->{noissues} Set if debt amount >$5.00 (or syspref noissuescharge)
414 $flags->{CHARGES}->{message} Message -- deprecated
416 $flags->{CREDITS}->{amount} Amount of credit
417 $flags->{CREDITS}->{message} Message -- deprecated
419 $flags->{ GNA } Patron has no valid address
420 $flags->{ GNA }->{noissues} Set for each GNA
421 $flags->{ GNA }->{message} "Borrower has no valid address" -- deprecated
423 $flags->{ LOST } Patron's card reported lost
424 $flags->{ LOST }->{noissues} Set for each LOST
425 $flags->{ LOST }->{message} Message -- deprecated
427 $flags->{DBARRED} Set if patron debarred, no access
428 $flags->{DBARRED}->{noissues} Set for each DBARRED
429 $flags->{DBARRED}->{message} Message -- deprecated
431 $flags->{ NOTES }
432 $flags->{ NOTES }->{message} The note itself. NOT deprecated
434 $flags->{ ODUES } Set if patron has overdue books.
435 $flags->{ ODUES }->{message} "Yes" -- deprecated
436 $flags->{ ODUES }->{itemlist} ref-to-array: list of overdue books
437 $flags->{ ODUES }->{itemlisttext} Text list of overdue items -- deprecated
439 $flags->{WAITING} Set if any of patron's reserves are available
440 $flags->{WAITING}->{message} Message -- deprecated
441 $flags->{WAITING}->{itemlist} ref-to-array: list of available items
443 =over
445 =item C<$flags-E<gt>{ODUES}-E<gt>{itemlist}> is a reference-to-array listing the
446 overdue items. Its elements are references-to-hash, each describing an
447 overdue item. The keys are selected fields from the issues, biblio,
448 biblioitems, and items tables of the Koha database.
450 =item C<$flags-E<gt>{ODUES}-E<gt>{itemlisttext}> is a string giving a text listing of
451 the overdue items, one per line. Deprecated.
453 =item C<$flags-E<gt>{WAITING}-E<gt>{itemlist}> is a reference-to-array listing the
454 available items. Each element is a reference-to-hash whose keys are
455 fields from the reserves table of the Koha database.
457 =back
459 All the "message" fields that include language generated in this function are deprecated,
460 because such strings belong properly in the display layer.
462 The "message" field that comes from the DB is OK.
464 =cut
466 # TODO: use {anonymous => hashes} instead of a dozen %flaginfo
467 # FIXME rename this function.
468 sub patronflags {
469 my %flags;
470 my ( $patroninformation) = @_;
471 my $dbh=C4::Context->dbh;
472 my ($balance, $owing) = GetMemberAccountBalance( $patroninformation->{'borrowernumber'});
473 if ( $owing > 0 ) {
474 my %flaginfo;
475 my $noissuescharge = C4::Context->preference("noissuescharge") || 5;
476 $flaginfo{'message'} = sprintf 'Patron owes %.02f', $owing;
477 $flaginfo{'amount'} = sprintf "%.02f", $owing;
478 if ( $owing > $noissuescharge && !C4::Context->preference("AllowFineOverride") ) {
479 $flaginfo{'noissues'} = 1;
481 $flags{'CHARGES'} = \%flaginfo;
483 elsif ( $balance < 0 ) {
484 my %flaginfo;
485 $flaginfo{'message'} = sprintf 'Patron has credit of %.02f', -$balance;
486 $flaginfo{'amount'} = sprintf "%.02f", $balance;
487 $flags{'CREDITS'} = \%flaginfo;
489 if ( $patroninformation->{'gonenoaddress'}
490 && $patroninformation->{'gonenoaddress'} == 1 )
492 my %flaginfo;
493 $flaginfo{'message'} = 'Borrower has no valid address.';
494 $flaginfo{'noissues'} = 1;
495 $flags{'GNA'} = \%flaginfo;
497 if ( $patroninformation->{'lost'} && $patroninformation->{'lost'} == 1 ) {
498 my %flaginfo;
499 $flaginfo{'message'} = 'Borrower\'s card reported lost.';
500 $flaginfo{'noissues'} = 1;
501 $flags{'LOST'} = \%flaginfo;
503 if ( $patroninformation->{'debarred'} && check_date( split( /-/, $patroninformation->{'debarred'} ) ) ) {
504 if ( Date_to_Days(Date::Calc::Today) < Date_to_Days( split( /-/, $patroninformation->{'debarred'} ) ) ) {
505 my %flaginfo;
506 $flaginfo{'debarredcomment'} = $patroninformation->{'debarredcomment'};
507 $flaginfo{'message'} = $patroninformation->{'debarredcomment'};
508 $flaginfo{'noissues'} = 1;
509 $flaginfo{'dateend'} = $patroninformation->{'debarred'};
510 $flags{'DBARRED'} = \%flaginfo;
513 if ( $patroninformation->{'borrowernotes'}
514 && $patroninformation->{'borrowernotes'} )
516 my %flaginfo;
517 $flaginfo{'message'} = $patroninformation->{'borrowernotes'};
518 $flags{'NOTES'} = \%flaginfo;
520 my ( $odues, $itemsoverdue ) = C4::Overdues::checkoverdues($patroninformation->{'borrowernumber'});
521 if ( $odues && $odues > 0 ) {
522 my %flaginfo;
523 $flaginfo{'message'} = "Yes";
524 $flaginfo{'itemlist'} = $itemsoverdue;
525 foreach ( sort { $a->{'date_due'} cmp $b->{'date_due'} }
526 @$itemsoverdue )
528 $flaginfo{'itemlisttext'} .=
529 "$_->{'date_due'} $_->{'barcode'} $_->{'title'} \n"; # newline is display layer
531 $flags{'ODUES'} = \%flaginfo;
533 my @itemswaiting = C4::Reserves::GetReservesFromBorrowernumber( $patroninformation->{'borrowernumber'},'W' );
534 my $nowaiting = scalar @itemswaiting;
535 if ( $nowaiting > 0 ) {
536 my %flaginfo;
537 $flaginfo{'message'} = "Reserved items available";
538 $flaginfo{'itemlist'} = \@itemswaiting;
539 $flags{'WAITING'} = \%flaginfo;
541 return ( \%flags );
545 =head2 GetMember
547 $borrower = &GetMember(%information);
549 Retrieve the first patron record meeting on criteria listed in the
550 C<%information> hash, which should contain one or more
551 pairs of borrowers column names and values, e.g.,
553 $borrower = GetMember(borrowernumber => id);
555 C<&GetBorrower> returns a reference-to-hash whose keys are the fields of
556 the C<borrowers> table in the Koha database.
558 FIXME: GetMember() is used throughout the code as a lookup
559 on a unique key such as the borrowernumber, but this meaning is not
560 enforced in the routine itself.
562 =cut
565 sub GetMember {
566 my ( %information ) = @_;
567 if (exists $information{borrowernumber} && !defined $information{borrowernumber}) {
568 #passing mysql's kohaadmin?? Makes no sense as a query
569 return;
571 my $dbh = C4::Context->dbh;
572 my $select =
573 q{SELECT borrowers.*, categories.category_type, categories.description
574 FROM borrowers
575 LEFT JOIN categories on borrowers.categorycode=categories.categorycode WHERE };
576 my $more_p = 0;
577 my @values = ();
578 for (keys %information ) {
579 if ($more_p) {
580 $select .= ' AND ';
582 else {
583 $more_p++;
586 if (defined $information{$_}) {
587 $select .= "$_ = ?";
588 push @values, $information{$_};
590 else {
591 $select .= "$_ IS NULL";
594 $debug && warn $select, " ",values %information;
595 my $sth = $dbh->prepare("$select");
596 $sth->execute(map{$information{$_}} keys %information);
597 my $data = $sth->fetchall_arrayref({});
598 #FIXME interface to this routine now allows generation of a result set
599 #so whole array should be returned but bowhere in the current code expects this
600 if (@{$data} ) {
601 return $data->[0];
604 return;
607 =head2 GetMemberRelatives
609 @borrowernumbers = GetMemberRelatives($borrowernumber);
611 C<GetMemberRelatives> returns a borrowersnumber's list of guarantor/guarantees of the member given in parameter
613 =cut
615 sub GetMemberRelatives {
616 my $borrowernumber = shift;
617 my $dbh = C4::Context->dbh;
618 my @glist;
620 # Getting guarantor
621 my $query = "SELECT guarantorid FROM borrowers WHERE borrowernumber=?";
622 my $sth = $dbh->prepare($query);
623 $sth->execute($borrowernumber);
624 my $data = $sth->fetchrow_arrayref();
625 push @glist, $data->[0] if $data->[0];
626 my $guarantor = $data->[0] ? $data->[0] : undef;
628 # Getting guarantees
629 $query = "SELECT borrowernumber FROM borrowers WHERE guarantorid=?";
630 $sth = $dbh->prepare($query);
631 $sth->execute($borrowernumber);
632 while ($data = $sth->fetchrow_arrayref()) {
633 push @glist, $data->[0];
636 # Getting sibling guarantees
637 if ($guarantor) {
638 $query = "SELECT borrowernumber FROM borrowers WHERE guarantorid=?";
639 $sth = $dbh->prepare($query);
640 $sth->execute($guarantor);
641 while ($data = $sth->fetchrow_arrayref()) {
642 push @glist, $data->[0] if ($data->[0] != $borrowernumber);
646 return @glist;
649 =head2 IsMemberBlocked
651 my ($block_status, $count) = IsMemberBlocked( $borrowernumber );
653 Returns whether a patron has overdue items that may result
654 in a block or whether the patron has active fine days
655 that would block circulation privileges.
657 C<$block_status> can have the following values:
659 1 if the patron has outstanding fine days or a manual debarment, in which case
660 C<$count> is the expiration date (9999-12-31 for indefinite)
662 -1 if the patron has overdue items, in which case C<$count> is the number of them
664 0 if the patron has no overdue items or outstanding fine days, in which case C<$count> is 0
666 Outstanding fine days are checked before current overdue items
667 are.
669 FIXME: this needs to be split into two functions; a potential block
670 based on the number of current overdue items could be orthogonal
671 to a block based on whether the patron has any fine days accrued.
673 =cut
675 sub IsMemberBlocked {
676 my $borrowernumber = shift;
677 my $dbh = C4::Context->dbh;
679 my $blockeddate = Koha::Borrower::Debarments::IsDebarred($borrowernumber);
681 return ( 1, $blockeddate ) if $blockeddate;
683 # if he have late issues
684 my $sth = $dbh->prepare(
685 "SELECT COUNT(*) as latedocs
686 FROM issues
687 WHERE borrowernumber = ?
688 AND date_due < now()"
690 $sth->execute($borrowernumber);
691 my $latedocs = $sth->fetchrow_hashref->{'latedocs'};
693 return ( -1, $latedocs ) if $latedocs > 0;
695 return ( 0, 0 );
698 =head2 GetMemberIssuesAndFines
700 ($overdue_count, $issue_count, $total_fines) = &GetMemberIssuesAndFines($borrowernumber);
702 Returns aggregate data about items borrowed by the patron with the
703 given borrowernumber.
705 C<&GetMemberIssuesAndFines> returns a three-element array. C<$overdue_count> is the
706 number of overdue items the patron currently has borrowed. C<$issue_count> is the
707 number of books the patron currently has borrowed. C<$total_fines> is
708 the total fine currently due by the borrower.
710 =cut
713 sub GetMemberIssuesAndFines {
714 my ( $borrowernumber ) = @_;
715 my $dbh = C4::Context->dbh;
716 my $query = "SELECT COUNT(*) FROM issues WHERE borrowernumber = ?";
718 $debug and warn $query."\n";
719 my $sth = $dbh->prepare($query);
720 $sth->execute($borrowernumber);
721 my $issue_count = $sth->fetchrow_arrayref->[0];
723 $sth = $dbh->prepare(
724 "SELECT COUNT(*) FROM issues
725 WHERE borrowernumber = ?
726 AND date_due < now()"
728 $sth->execute($borrowernumber);
729 my $overdue_count = $sth->fetchrow_arrayref->[0];
731 $sth = $dbh->prepare("SELECT SUM(amountoutstanding) FROM accountlines WHERE borrowernumber = ?");
732 $sth->execute($borrowernumber);
733 my $total_fines = $sth->fetchrow_arrayref->[0];
735 return ($overdue_count, $issue_count, $total_fines);
739 =head2 columns
741 my @columns = C4::Member::columns();
743 Returns an array of borrowers' table columns on success,
744 and an empty array on failure.
746 =cut
748 sub columns {
750 # Pure ANSI SQL goodness.
751 my $sql = 'SELECT * FROM borrowers WHERE 1=0;';
753 # Get the database handle.
754 my $dbh = C4::Context->dbh;
756 # Run the SQL statement to load STH's readonly properties.
757 my $sth = $dbh->prepare($sql);
758 my $rv = $sth->execute();
760 # This only fails if the table doesn't exist.
761 # This will always be called AFTER an install or upgrade,
762 # so borrowers will exist!
763 my @data;
764 if ($sth->{NUM_OF_FIELDS}>0) {
765 @data = @{$sth->{NAME}};
767 else {
768 @data = ();
770 return @data;
774 =head2 ModMember
776 my $success = ModMember(borrowernumber => $borrowernumber,
777 [ field => value ]... );
779 Modify borrower's data. All date fields should ALREADY be in ISO format.
781 return :
782 true on success, or false on failure
784 =cut
786 sub ModMember {
787 my (%data) = @_;
788 # test to know if you must update or not the borrower password
789 if (exists $data{password}) {
790 if ($data{password} eq '****' or $data{password} eq '') {
791 delete $data{password};
792 } else {
793 if ( C4::Context->preference('NorwegianPatronDBEnable') && C4::Context->preference('NorwegianPatronDBEnable') == 1 ) {
794 # Update the hashed PIN in borrower_sync.hashed_pin, before Koha hashes it
795 NLUpdateHashedPIN( $data{'borrowernumber'}, $data{password} );
797 $data{password} = hash_password($data{password});
800 my $old_categorycode = GetBorrowerCategorycode( $data{borrowernumber} );
801 my $execute_success=UpdateInTable("borrowers",\%data);
802 if ($execute_success) { # only proceed if the update was a success
803 # ok if its an adult (type) it may have borrowers that depend on it as a guarantor
804 # so when we update information for an adult we should check for guarantees and update the relevant part
805 # of their records, ie addresses and phone numbers
806 my $borrowercategory= GetBorrowercategory( $data{'category_type'} );
807 if ( exists $borrowercategory->{'category_type'} && $borrowercategory->{'category_type'} eq ('A' || 'S') ) {
808 # is adult check guarantees;
809 UpdateGuarantees(%data);
812 # If the patron changes to a category with enrollment fee, we add a fee
813 if ( $data{categorycode} and $data{categorycode} ne $old_categorycode ) {
814 AddEnrolmentFeeIfNeeded( $data{categorycode}, $data{borrowernumber} );
817 # If NorwegianPatronDBEnable is enabled, we set syncstatus to something that a
818 # cronjob will use for syncing with NL
819 if ( C4::Context->preference('NorwegianPatronDBEnable') && C4::Context->preference('NorwegianPatronDBEnable') == 1 ) {
820 my $borrowersync = Koha::Database->new->schema->resultset('BorrowerSync')->find({
821 'synctype' => 'norwegianpatrondb',
822 'borrowernumber' => $data{'borrowernumber'}
824 # Do not set to "edited" if syncstatus is "new". We need to sync as new before
825 # we can sync as changed. And the "new sync" will pick up all changes since
826 # the patron was created anyway.
827 if ( $borrowersync->syncstatus ne 'new' && $borrowersync->syncstatus ne 'delete' ) {
828 $borrowersync->update( { 'syncstatus' => 'edited' } );
830 # Set the value of 'sync'
831 $borrowersync->update( { 'sync' => $data{'sync'} } );
832 # Try to do the live sync
833 NLSync({ 'borrowernumber' => $data{'borrowernumber'} });
836 logaction("MEMBERS", "MODIFY", $data{'borrowernumber'}, "UPDATE (executed w/ arg: $data{'borrowernumber'})") if C4::Context->preference("BorrowersLog");
838 return $execute_success;
841 =head2 AddMember
843 $borrowernumber = &AddMember(%borrower);
845 insert new borrower into table
846 Returns the borrowernumber upon success
848 Returns as undef upon any db error without further processing
850 =cut
853 sub AddMember {
854 my (%data) = @_;
855 my $dbh = C4::Context->dbh;
857 # generate a proper login if none provided
858 $data{'userid'} = Generate_Userid($data{'borrowernumber'}, $data{'firstname'}, $data{'surname'}) if $data{'userid'} eq '';
860 # add expiration date if it isn't already there
861 unless ( $data{'dateexpiry'} ) {
862 $data{'dateexpiry'} = GetExpiryDate( $data{'categorycode'}, C4::Dates->new()->output("iso") );
865 # add enrollment date if it isn't already there
866 unless ( $data{'dateenrolled'} ) {
867 $data{'dateenrolled'} = C4::Dates->new()->output("iso");
870 my $patron_category =
871 Koha::Database->new()->schema()->resultset('Category')
872 ->find( $data{'categorycode'} );
873 $data{'privacy'} =
874 $patron_category->default_privacy() eq 'default' ? 1
875 : $patron_category->default_privacy() eq 'never' ? 2
876 : $patron_category->default_privacy() eq 'forever' ? 0
877 : undef;
878 # Make a copy of the plain text password for later use
879 my $plain_text_password = $data{'password'};
881 # create a disabled account if no password provided
882 $data{'password'} = ($data{'password'})? hash_password($data{'password'}) : '!';
883 $data{'borrowernumber'}=InsertInTable("borrowers",\%data);
885 # If NorwegianPatronDBEnable is enabled, we set syncstatus to something that a
886 # cronjob will use for syncing with NL
887 if ( exists $data{'borrowernumber'} && C4::Context->preference('NorwegianPatronDBEnable') && C4::Context->preference('NorwegianPatronDBEnable') == 1 ) {
888 Koha::Database->new->schema->resultset('BorrowerSync')->create({
889 'borrowernumber' => $data{'borrowernumber'},
890 'synctype' => 'norwegianpatrondb',
891 'sync' => 1,
892 'syncstatus' => 'new',
893 'hashed_pin' => NLEncryptPIN( $plain_text_password ),
897 # mysql_insertid is probably bad. not necessarily accurate and mysql-specific at best.
898 logaction("MEMBERS", "CREATE", $data{'borrowernumber'}, "") if C4::Context->preference("BorrowersLog");
900 AddEnrolmentFeeIfNeeded( $data{categorycode}, $data{borrowernumber} );
902 return $data{'borrowernumber'};
905 =head2 Check_Userid
907 my $uniqueness = Check_Userid($userid,$borrowernumber);
909 $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 != '').
911 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.
913 return :
914 0 for not unique (i.e. this $userid already exists)
915 1 for unique (i.e. this $userid does not exist, or this $userid/$borrowernumber combination already exists)
917 =cut
919 sub Check_Userid {
920 my ($uid,$member) = @_;
921 my $dbh = C4::Context->dbh;
922 my $sth =
923 $dbh->prepare(
924 "SELECT * FROM borrowers WHERE userid=? AND borrowernumber != ?");
925 $sth->execute( $uid, $member );
926 if ( (( $uid ne '' ) && ( my $row = $sth->fetchrow_hashref )) or
927 (( $uid ne '' ) && ( $uid eq C4::Context->config('user') )) ) {
928 return 0;
930 else {
931 return 1;
935 =head2 Generate_Userid
937 my $newuid = Generate_Userid($borrowernumber, $firstname, $surname);
939 Generate a userid using the $surname and the $firstname (if there is a value in $firstname).
941 $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.
943 return :
944 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).
946 =cut
948 sub Generate_Userid {
949 my ($borrowernumber, $firstname, $surname) = @_;
950 my $newuid;
951 my $offset = 0;
952 #The script will "do" the following code and increment the $offset until Check_Userid = 1 (i.e. until $newuid comes back as unique)
953 do {
954 $firstname =~ s/[[:digit:][:space:][:blank:][:punct:][:cntrl:]]//g;
955 $surname =~ s/[[:digit:][:space:][:blank:][:punct:][:cntrl:]]//g;
956 $newuid = lc(($firstname)? "$firstname.$surname" : $surname);
957 $newuid = unac_string('utf-8',$newuid);
958 $newuid .= $offset unless $offset == 0;
959 $offset++;
961 } while (!Check_Userid($newuid,$borrowernumber));
963 return $newuid;
966 sub changepassword {
967 my ( $uid, $member, $digest ) = @_;
968 my $dbh = C4::Context->dbh;
970 #Make sure the userid chosen is unique and not theirs if non-empty. If it is not,
971 #Then we need to tell the user and have them create a new one.
972 my $resultcode;
973 my $sth =
974 $dbh->prepare(
975 "SELECT * FROM borrowers WHERE userid=? AND borrowernumber != ?");
976 $sth->execute( $uid, $member );
977 if ( ( $uid ne '' ) && ( my $row = $sth->fetchrow_hashref ) ) {
978 $resultcode=0;
980 else {
981 #Everything is good so we can update the information.
982 $sth =
983 $dbh->prepare(
984 "update borrowers set userid=?, password=? where borrowernumber=?");
985 $sth->execute( $uid, $digest, $member );
986 $resultcode=1;
989 logaction("MEMBERS", "CHANGE PASS", $member, "") if C4::Context->preference("BorrowersLog");
990 return $resultcode;
995 =head2 fixup_cardnumber
997 Warning: The caller is responsible for locking the members table in write
998 mode, to avoid database corruption.
1000 =cut
1002 use vars qw( @weightings );
1003 my @weightings = ( 8, 4, 6, 3, 5, 2, 1 );
1005 sub fixup_cardnumber {
1006 my ($cardnumber) = @_;
1007 my $autonumber_members = C4::Context->boolean_preference('autoMemberNum') || 0;
1009 # Find out whether member numbers should be generated
1010 # automatically. Should be either "1" or something else.
1011 # Defaults to "0", which is interpreted as "no".
1013 # if ($cardnumber !~ /\S/ && $autonumber_members) {
1014 ($autonumber_members) or return $cardnumber;
1015 my $checkdigit = C4::Context->preference('checkdigit');
1016 my $dbh = C4::Context->dbh;
1017 if ( $checkdigit and $checkdigit eq 'katipo' ) {
1019 # if checkdigit is selected, calculate katipo-style cardnumber.
1020 # otherwise, just use the max()
1021 # purpose: generate checksum'd member numbers.
1022 # We'll assume we just got the max value of digits 2-8 of member #'s
1023 # from the database and our job is to increment that by one,
1024 # determine the 1st and 9th digits and return the full string.
1025 my $sth = $dbh->prepare(
1026 "select max(substring(borrowers.cardnumber,2,7)) as new_num from borrowers"
1028 $sth->execute;
1029 my $data = $sth->fetchrow_hashref;
1030 $cardnumber = $data->{new_num};
1031 if ( !$cardnumber ) { # If DB has no values,
1032 $cardnumber = 1000000; # start at 1000000
1033 } else {
1034 $cardnumber += 1;
1037 my $sum = 0;
1038 for ( my $i = 0 ; $i < 8 ; $i += 1 ) {
1039 # read weightings, left to right, 1 char at a time
1040 my $temp1 = $weightings[$i];
1042 # sequence left to right, 1 char at a time
1043 my $temp2 = substr( $cardnumber, $i, 1 );
1045 # mult each char 1-7 by its corresponding weighting
1046 $sum += $temp1 * $temp2;
1049 my $rem = ( $sum % 11 );
1050 $rem = 'X' if $rem == 10;
1052 return "V$cardnumber$rem";
1053 } else {
1055 my $sth = $dbh->prepare(
1056 'SELECT MAX( CAST( cardnumber AS SIGNED ) ) FROM borrowers WHERE cardnumber REGEXP "^-?[0-9]+$"'
1058 $sth->execute;
1059 my ($result) = $sth->fetchrow;
1060 return $result + 1;
1062 return $cardnumber; # just here as a fallback/reminder
1065 =head2 GetGuarantees
1067 ($num_children, $children_arrayref) = &GetGuarantees($parent_borrno);
1068 $child0_cardno = $children_arrayref->[0]{"cardnumber"};
1069 $child0_borrno = $children_arrayref->[0]{"borrowernumber"};
1071 C<&GetGuarantees> takes a borrower number (e.g., that of a patron
1072 with children) and looks up the borrowers who are guaranteed by that
1073 borrower (i.e., the patron's children).
1075 C<&GetGuarantees> returns two values: an integer giving the number of
1076 borrowers guaranteed by C<$parent_borrno>, and a reference to an array
1077 of references to hash, which gives the actual results.
1079 =cut
1082 sub GetGuarantees {
1083 my ($borrowernumber) = @_;
1084 my $dbh = C4::Context->dbh;
1085 my $sth =
1086 $dbh->prepare(
1087 "select cardnumber,borrowernumber, firstname, surname from borrowers where guarantorid=?"
1089 $sth->execute($borrowernumber);
1091 my @dat;
1092 my $data = $sth->fetchall_arrayref({});
1093 return ( scalar(@$data), $data );
1096 =head2 UpdateGuarantees
1098 &UpdateGuarantees($parent_borrno);
1101 C<&UpdateGuarantees> borrower data for an adult and updates all the guarantees
1102 with the modified information
1104 =cut
1107 sub UpdateGuarantees {
1108 my %data = shift;
1109 my $dbh = C4::Context->dbh;
1110 my ( $count, $guarantees ) = GetGuarantees( $data{'borrowernumber'} );
1111 foreach my $guarantee (@$guarantees){
1112 my $guaquery = qq|UPDATE borrowers
1113 SET address=?,fax=?,B_city=?,mobile=?,city=?,phone=?
1114 WHERE borrowernumber=?
1116 my $sth = $dbh->prepare($guaquery);
1117 $sth->execute($data{'address'},$data{'fax'},$data{'B_city'},$data{'mobile'},$data{'city'},$data{'phone'},$guarantee->{'borrowernumber'});
1120 =head2 GetPendingIssues
1122 my $issues = &GetPendingIssues(@borrowernumber);
1124 Looks up what the patron with the given borrowernumber has borrowed.
1126 C<&GetPendingIssues> returns a
1127 reference-to-array where each element is a reference-to-hash; the
1128 keys are the fields from the C<issues>, C<biblio>, and C<items> tables.
1129 The keys include C<biblioitems> fields except marc and marcxml.
1131 =cut
1134 sub GetPendingIssues {
1135 my @borrowernumbers = @_;
1137 unless (@borrowernumbers ) { # return a ref_to_array
1138 return \@borrowernumbers; # to not cause surprise to caller
1141 # Borrowers part of the query
1142 my $bquery = '';
1143 for (my $i = 0; $i < @borrowernumbers; $i++) {
1144 $bquery .= ' issues.borrowernumber = ?';
1145 if ($i < $#borrowernumbers ) {
1146 $bquery .= ' OR';
1150 # must avoid biblioitems.* to prevent large marc and marcxml fields from killing performance
1151 # FIXME: namespace collision: each table has "timestamp" fields. Which one is "timestamp" ?
1152 # FIXME: circ/ciculation.pl tries to sort by timestamp!
1153 # FIXME: namespace collision: other collisions possible.
1154 # FIXME: most of this data isn't really being used by callers.
1155 my $query =
1156 "SELECT issues.*,
1157 items.*,
1158 biblio.*,
1159 biblioitems.volume,
1160 biblioitems.number,
1161 biblioitems.itemtype,
1162 biblioitems.isbn,
1163 biblioitems.issn,
1164 biblioitems.publicationyear,
1165 biblioitems.publishercode,
1166 biblioitems.volumedate,
1167 biblioitems.volumedesc,
1168 biblioitems.lccn,
1169 biblioitems.url,
1170 borrowers.firstname,
1171 borrowers.surname,
1172 borrowers.cardnumber,
1173 issues.timestamp AS timestamp,
1174 issues.renewals AS renewals,
1175 issues.borrowernumber AS borrowernumber,
1176 items.renewals AS totalrenewals
1177 FROM issues
1178 LEFT JOIN items ON items.itemnumber = issues.itemnumber
1179 LEFT JOIN biblio ON items.biblionumber = biblio.biblionumber
1180 LEFT JOIN biblioitems ON items.biblioitemnumber = biblioitems.biblioitemnumber
1181 LEFT JOIN borrowers ON issues.borrowernumber = borrowers.borrowernumber
1182 WHERE
1183 $bquery
1184 ORDER BY issues.issuedate"
1187 my $sth = C4::Context->dbh->prepare($query);
1188 $sth->execute(@borrowernumbers);
1189 my $data = $sth->fetchall_arrayref({});
1190 my $tz = C4::Context->tz();
1191 my $today = DateTime->now( time_zone => $tz);
1192 foreach (@{$data}) {
1193 if ($_->{issuedate}) {
1194 $_->{issuedate} = dt_from_string($_->{issuedate}, 'sql');
1196 $_->{date_due} or next;
1197 $_->{date_due} = DateTime::Format::DateParse->parse_datetime($_->{date_due}, $tz->name());
1198 if ( DateTime->compare($_->{date_due}, $today) == -1 ) {
1199 $_->{overdue} = 1;
1202 return $data;
1205 =head2 GetAllIssues
1207 $issues = &GetAllIssues($borrowernumber, $sortkey, $limit);
1209 Looks up what the patron with the given borrowernumber has borrowed,
1210 and sorts the results.
1212 C<$sortkey> is the name of a field on which to sort the results. This
1213 should be the name of a field in the C<issues>, C<biblio>,
1214 C<biblioitems>, or C<items> table in the Koha database.
1216 C<$limit> is the maximum number of results to return.
1218 C<&GetAllIssues> an arrayref, C<$issues>, of hashrefs, the keys of which
1219 are the fields from the C<issues>, C<biblio>, C<biblioitems>, and
1220 C<items> tables of the Koha database.
1222 =cut
1225 sub GetAllIssues {
1226 my ( $borrowernumber, $order, $limit ) = @_;
1228 return unless $borrowernumber;
1229 $order = 'date_due desc' unless $order;
1231 my $dbh = C4::Context->dbh;
1232 my $query =
1233 'SELECT *, issues.timestamp as issuestimestamp, issues.renewals AS renewals,items.renewals AS totalrenewals,items.timestamp AS itemstimestamp
1234 FROM issues
1235 LEFT JOIN items on items.itemnumber=issues.itemnumber
1236 LEFT JOIN biblio ON items.biblionumber=biblio.biblionumber
1237 LEFT JOIN biblioitems ON items.biblioitemnumber=biblioitems.biblioitemnumber
1238 WHERE borrowernumber=?
1239 UNION ALL
1240 SELECT *, old_issues.timestamp as issuestimestamp, old_issues.renewals AS renewals,items.renewals AS totalrenewals,items.timestamp AS itemstimestamp
1241 FROM old_issues
1242 LEFT JOIN items on items.itemnumber=old_issues.itemnumber
1243 LEFT JOIN biblio ON items.biblionumber=biblio.biblionumber
1244 LEFT JOIN biblioitems ON items.biblioitemnumber=biblioitems.biblioitemnumber
1245 WHERE borrowernumber=? AND old_issues.itemnumber IS NOT NULL
1246 order by ' . $order;
1247 if ($limit) {
1248 $query .= " limit $limit";
1251 my $sth = $dbh->prepare($query);
1252 $sth->execute( $borrowernumber, $borrowernumber );
1253 return $sth->fetchall_arrayref( {} );
1257 =head2 GetMemberAccountRecords
1259 ($total, $acctlines, $count) = &GetMemberAccountRecords($borrowernumber);
1261 Looks up accounting data for the patron with the given borrowernumber.
1263 C<&GetMemberAccountRecords> returns a three-element array. C<$acctlines> is a
1264 reference-to-array, where each element is a reference-to-hash; the
1265 keys are the fields of the C<accountlines> table in the Koha database.
1266 C<$count> is the number of elements in C<$acctlines>. C<$total> is the
1267 total amount outstanding for all of the account lines.
1269 =cut
1271 sub GetMemberAccountRecords {
1272 my ($borrowernumber) = @_;
1273 my $dbh = C4::Context->dbh;
1274 my @acctlines;
1275 my $numlines = 0;
1276 my $strsth = qq(
1277 SELECT *
1278 FROM accountlines
1279 WHERE borrowernumber=?);
1280 $strsth.=" ORDER BY date desc,timestamp DESC";
1281 my $sth= $dbh->prepare( $strsth );
1282 $sth->execute( $borrowernumber );
1284 my $total = 0;
1285 while ( my $data = $sth->fetchrow_hashref ) {
1286 if ( $data->{itemnumber} ) {
1287 my $biblio = GetBiblioFromItemNumber( $data->{itemnumber} );
1288 $data->{biblionumber} = $biblio->{biblionumber};
1289 $data->{title} = $biblio->{title};
1291 $acctlines[$numlines] = $data;
1292 $numlines++;
1293 $total += int(1000 * $data->{'amountoutstanding'}); # convert float to integer to avoid round-off errors
1295 $total /= 1000;
1296 return ( $total, \@acctlines,$numlines);
1299 =head2 GetMemberAccountBalance
1301 ($total_balance, $non_issue_balance, $other_charges) = &GetMemberAccountBalance($borrowernumber);
1303 Calculates amount immediately owing by the patron - non-issue charges.
1304 Based on GetMemberAccountRecords.
1305 Charges exempt from non-issue are:
1306 * Res (reserves)
1307 * Rent (rental) if RentalsInNoissuesCharge syspref is set to false
1308 * Manual invoices if ManInvInNoissuesCharge syspref is set to false
1310 =cut
1312 sub GetMemberAccountBalance {
1313 my ($borrowernumber) = @_;
1315 my $ACCOUNT_TYPE_LENGTH = 5; # this is plain ridiculous...
1317 my @not_fines;
1318 push @not_fines, 'Res' unless C4::Context->preference('HoldsInNoissuesCharge');
1319 push @not_fines, 'Rent' unless C4::Context->preference('RentalsInNoissuesCharge');
1320 unless ( C4::Context->preference('ManInvInNoissuesCharge') ) {
1321 my $dbh = C4::Context->dbh;
1322 my $man_inv_types = $dbh->selectcol_arrayref(qq{SELECT authorised_value FROM authorised_values WHERE category = 'MANUAL_INV'});
1323 push @not_fines, map substr($_, 0, $ACCOUNT_TYPE_LENGTH), @$man_inv_types;
1325 my %not_fine = map {$_ => 1} @not_fines;
1327 my ($total, $acctlines) = GetMemberAccountRecords($borrowernumber);
1328 my $other_charges = 0;
1329 foreach (@$acctlines) {
1330 $other_charges += $_->{amountoutstanding} if $not_fine{ substr($_->{accounttype}, 0, $ACCOUNT_TYPE_LENGTH) };
1333 return ( $total, $total - $other_charges, $other_charges);
1336 =head2 GetBorNotifyAcctRecord
1338 ($total, $acctlines, $count) = &GetBorNotifyAcctRecord($params,$notifyid);
1340 Looks up accounting data for the patron with the given borrowernumber per file number.
1342 C<&GetBorNotifyAcctRecord> returns a three-element array. C<$acctlines> is a
1343 reference-to-array, where each element is a reference-to-hash; the
1344 keys are the fields of the C<accountlines> table in the Koha database.
1345 C<$count> is the number of elements in C<$acctlines>. C<$total> is the
1346 total amount outstanding for all of the account lines.
1348 =cut
1350 sub GetBorNotifyAcctRecord {
1351 my ( $borrowernumber, $notifyid ) = @_;
1352 my $dbh = C4::Context->dbh;
1353 my @acctlines;
1354 my $numlines = 0;
1355 my $sth = $dbh->prepare(
1356 "SELECT *
1357 FROM accountlines
1358 WHERE borrowernumber=?
1359 AND notify_id=?
1360 AND amountoutstanding != '0'
1361 ORDER BY notify_id,accounttype
1364 $sth->execute( $borrowernumber, $notifyid );
1365 my $total = 0;
1366 while ( my $data = $sth->fetchrow_hashref ) {
1367 if ( $data->{itemnumber} ) {
1368 my $biblio = GetBiblioFromItemNumber( $data->{itemnumber} );
1369 $data->{biblionumber} = $biblio->{biblionumber};
1370 $data->{title} = $biblio->{title};
1372 $acctlines[$numlines] = $data;
1373 $numlines++;
1374 $total += int(100 * $data->{'amountoutstanding'});
1376 $total /= 100;
1377 return ( $total, \@acctlines, $numlines );
1380 =head2 checkuniquemember (OUEST-PROVENCE)
1382 ($result,$categorycode) = &checkuniquemember($collectivity,$surname,$firstname,$dateofbirth);
1384 Checks that a member exists or not in the database.
1386 C<&result> is nonzero (=exist) or 0 (=does not exist)
1387 C<&categorycode> is from categorycode table
1388 C<&collectivity> is 1 (= we add a collectivity) or 0 (= we add a physical member)
1389 C<&surname> is the surname
1390 C<&firstname> is the firstname (only if collectivity=0)
1391 C<&dateofbirth> is the date of birth in ISO format (only if collectivity=0)
1393 =cut
1395 # FIXME: This function is not legitimate. Multiple patrons might have the same first/last name and birthdate.
1396 # This is especially true since first name is not even a required field.
1398 sub checkuniquemember {
1399 my ( $collectivity, $surname, $firstname, $dateofbirth ) = @_;
1400 my $dbh = C4::Context->dbh;
1401 my $request = ($collectivity) ?
1402 "SELECT borrowernumber,categorycode FROM borrowers WHERE surname=? " :
1403 ($dateofbirth) ?
1404 "SELECT borrowernumber,categorycode FROM borrowers WHERE surname=? and firstname=? and dateofbirth=?" :
1405 "SELECT borrowernumber,categorycode FROM borrowers WHERE surname=? and firstname=?";
1406 my $sth = $dbh->prepare($request);
1407 if ($collectivity) {
1408 $sth->execute( uc($surname) );
1409 } elsif($dateofbirth){
1410 $sth->execute( uc($surname), ucfirst($firstname), $dateofbirth );
1411 }else{
1412 $sth->execute( uc($surname), ucfirst($firstname));
1414 my @data = $sth->fetchrow;
1415 ( $data[0] ) and return $data[0], $data[1];
1416 return 0;
1419 sub checkcardnumber {
1420 my ( $cardnumber, $borrowernumber ) = @_;
1422 # If cardnumber is null, we assume they're allowed.
1423 return 0 unless defined $cardnumber;
1425 my $dbh = C4::Context->dbh;
1426 my $query = "SELECT * FROM borrowers WHERE cardnumber=?";
1427 $query .= " AND borrowernumber <> ?" if ($borrowernumber);
1428 my $sth = $dbh->prepare($query);
1429 $sth->execute(
1430 $cardnumber,
1431 ( $borrowernumber ? $borrowernumber : () )
1434 return 1 if $sth->fetchrow_hashref;
1436 my ( $min_length, $max_length ) = get_cardnumber_length();
1437 return 2
1438 if length $cardnumber > $max_length
1439 or length $cardnumber < $min_length;
1441 return 0;
1444 =head2 get_cardnumber_length
1446 my ($min, $max) = C4::Members::get_cardnumber_length()
1448 Returns the minimum and maximum length for patron cardnumbers as
1449 determined by the CardnumberLength system preference, the
1450 BorrowerMandatoryField system preference, and the width of the
1451 database column.
1453 =cut
1455 sub get_cardnumber_length {
1456 my ( $min, $max ) = ( 0, 16 ); # borrowers.cardnumber is a nullable varchar(16)
1457 $min = 1 if C4::Context->preference('BorrowerMandatoryField') =~ /cardnumber/;
1458 if ( my $cardnumber_length = C4::Context->preference('CardnumberLength') ) {
1459 # Is integer and length match
1460 if ( $cardnumber_length =~ m|^\d+$| ) {
1461 $min = $max = $cardnumber_length
1462 if $cardnumber_length >= $min
1463 and $cardnumber_length <= $max;
1465 # Else assuming it is a range
1466 elsif ( $cardnumber_length =~ m|(\d*),(\d*)| ) {
1467 $min = $1 if $1 and $min < $1;
1468 $max = $2 if $2 and $max > $2;
1472 return ( $min, $max );
1475 =head2 getzipnamecity (OUEST-PROVENCE)
1477 take all info from table city for the fields city and zip
1478 check for the name and the zip code of the city selected
1480 =cut
1482 sub getzipnamecity {
1483 my ($cityid) = @_;
1484 my $dbh = C4::Context->dbh;
1485 my $sth =
1486 $dbh->prepare(
1487 "select city_name,city_state,city_zipcode,city_country from cities where cityid=? ");
1488 $sth->execute($cityid);
1489 my @data = $sth->fetchrow;
1490 return $data[0], $data[1], $data[2], $data[3];
1494 =head2 getdcity (OUEST-PROVENCE)
1496 recover cityid with city_name condition
1498 =cut
1500 sub getidcity {
1501 my ($city_name) = @_;
1502 my $dbh = C4::Context->dbh;
1503 my $sth = $dbh->prepare("select cityid from cities where city_name=? ");
1504 $sth->execute($city_name);
1505 my $data = $sth->fetchrow;
1506 return $data;
1509 =head2 GetFirstValidEmailAddress
1511 $email = GetFirstValidEmailAddress($borrowernumber);
1513 Return the first valid email address for a borrower, given the borrowernumber. For now, the order
1514 is defined as email, emailpro, B_email. Returns the empty string if the borrower has no email
1515 addresses.
1517 =cut
1519 sub GetFirstValidEmailAddress {
1520 my $borrowernumber = shift;
1521 my $dbh = C4::Context->dbh;
1522 my $sth = $dbh->prepare( "SELECT email, emailpro, B_email FROM borrowers where borrowernumber = ? ");
1523 $sth->execute( $borrowernumber );
1524 my $data = $sth->fetchrow_hashref;
1526 if ($data->{'email'}) {
1527 return $data->{'email'};
1528 } elsif ($data->{'emailpro'}) {
1529 return $data->{'emailpro'};
1530 } elsif ($data->{'B_email'}) {
1531 return $data->{'B_email'};
1532 } else {
1533 return '';
1537 =head2 GetNoticeEmailAddress
1539 $email = GetNoticeEmailAddress($borrowernumber);
1541 Return the email address of borrower used for notices, given the borrowernumber.
1542 Returns the empty string if no email address.
1544 =cut
1546 sub GetNoticeEmailAddress {
1547 my $borrowernumber = shift;
1549 my $which_address = C4::Context->preference("AutoEmailPrimaryAddress");
1550 # if syspref is set to 'first valid' (value == OFF), look up email address
1551 if ( $which_address eq 'OFF' ) {
1552 return GetFirstValidEmailAddress($borrowernumber);
1554 # specified email address field
1555 my $dbh = C4::Context->dbh;
1556 my $sth = $dbh->prepare( qq{
1557 SELECT $which_address AS primaryemail
1558 FROM borrowers
1559 WHERE borrowernumber=?
1560 } );
1561 $sth->execute($borrowernumber);
1562 my $data = $sth->fetchrow_hashref;
1563 return $data->{'primaryemail'} || '';
1566 =head2 GetExpiryDate
1568 $expirydate = GetExpiryDate($categorycode, $dateenrolled);
1570 Calculate expiry date given a categorycode and starting date. Date argument must be in ISO format.
1571 Return date is also in ISO format.
1573 =cut
1575 sub GetExpiryDate {
1576 my ( $categorycode, $dateenrolled ) = @_;
1577 my $enrolments;
1578 if ($categorycode) {
1579 my $dbh = C4::Context->dbh;
1580 my $sth = $dbh->prepare("SELECT enrolmentperiod,enrolmentperioddate FROM categories WHERE categorycode=?");
1581 $sth->execute($categorycode);
1582 $enrolments = $sth->fetchrow_hashref;
1584 # die "GetExpiryDate: for enrollmentperiod $enrolmentperiod (category '$categorycode') starting $dateenrolled.\n";
1585 my @date = split (/-/,$dateenrolled);
1586 if($enrolments->{enrolmentperiod}){
1587 return sprintf("%04d-%02d-%02d", Add_Delta_YM(@date,0,$enrolments->{enrolmentperiod}));
1588 }else{
1589 return $enrolments->{enrolmentperioddate};
1593 =head2 GetborCatFromCatType
1595 ($codes_arrayref, $labels_hashref) = &GetborCatFromCatType();
1597 Looks up the different types of borrowers in the database. Returns two
1598 elements: a reference-to-array, which lists the borrower category
1599 codes, and a reference-to-hash, which maps the borrower category codes
1600 to category descriptions.
1602 =cut
1605 sub GetborCatFromCatType {
1606 my ( $category_type, $action, $no_branch_limit ) = @_;
1608 my $branch_limit = $no_branch_limit
1610 : C4::Context->userenv ? C4::Context->userenv->{"branch"} : "";
1612 # FIXME - This API seems both limited and dangerous.
1613 my $dbh = C4::Context->dbh;
1615 my $request = qq{
1616 SELECT categories.categorycode, categories.description
1617 FROM categories
1619 $request .= qq{
1620 LEFT JOIN categories_branches ON categories.categorycode = categories_branches.categorycode
1621 } if $branch_limit;
1622 if($action) {
1623 $request .= " $action ";
1624 $request .= " AND (branchcode = ? OR branchcode IS NULL) GROUP BY description" if $branch_limit;
1625 } else {
1626 $request .= " WHERE branchcode = ? OR branchcode IS NULL GROUP BY description" if $branch_limit;
1628 $request .= " ORDER BY categorycode";
1630 my $sth = $dbh->prepare($request);
1631 $sth->execute(
1632 $action ? $category_type : (),
1633 $branch_limit ? $branch_limit : ()
1636 my %labels;
1637 my @codes;
1639 while ( my $data = $sth->fetchrow_hashref ) {
1640 push @codes, $data->{'categorycode'};
1641 $labels{ $data->{'categorycode'} } = $data->{'description'};
1643 $sth->finish;
1644 return ( \@codes, \%labels );
1647 =head2 GetBorrowercategory
1649 $hashref = &GetBorrowercategory($categorycode);
1651 Given the borrower's category code, the function returns the corresponding
1652 data hashref for a comprehensive information display.
1654 =cut
1656 sub GetBorrowercategory {
1657 my ($catcode) = @_;
1658 my $dbh = C4::Context->dbh;
1659 if ($catcode){
1660 my $sth =
1661 $dbh->prepare(
1662 "SELECT description,dateofbirthrequired,upperagelimit,category_type
1663 FROM categories
1664 WHERE categorycode = ?"
1666 $sth->execute($catcode);
1667 my $data =
1668 $sth->fetchrow_hashref;
1669 return $data;
1671 return;
1672 } # sub getborrowercategory
1675 =head2 GetBorrowerCategorycode
1677 $categorycode = &GetBorrowerCategoryCode( $borrowernumber );
1679 Given the borrowernumber, the function returns the corresponding categorycode
1681 =cut
1683 sub GetBorrowerCategorycode {
1684 my ( $borrowernumber ) = @_;
1685 my $dbh = C4::Context->dbh;
1686 my $sth = $dbh->prepare( qq{
1687 SELECT categorycode
1688 FROM borrowers
1689 WHERE borrowernumber = ?
1690 } );
1691 $sth->execute( $borrowernumber );
1692 return $sth->fetchrow;
1695 =head2 GetBorrowercategoryList
1697 $arrayref_hashref = &GetBorrowercategoryList;
1698 If no category code provided, the function returns all the categories.
1700 =cut
1702 sub GetBorrowercategoryList {
1703 my $no_branch_limit = @_ ? shift : 0;
1704 my $branch_limit = $no_branch_limit
1706 : C4::Context->userenv ? C4::Context->userenv->{"branch"} : "";
1707 my $dbh = C4::Context->dbh;
1708 my $query = "SELECT categories.* FROM categories";
1709 $query .= qq{
1710 LEFT JOIN categories_branches ON categories.categorycode = categories_branches.categorycode
1711 WHERE branchcode = ? OR branchcode IS NULL GROUP BY description
1712 } if $branch_limit;
1713 $query .= " ORDER BY description";
1714 my $sth = $dbh->prepare( $query );
1715 $sth->execute( $branch_limit ? $branch_limit : () );
1716 my $data = $sth->fetchall_arrayref( {} );
1717 $sth->finish;
1718 return $data;
1719 } # sub getborrowercategory
1721 =head2 ethnicitycategories
1723 ($codes_arrayref, $labels_hashref) = &ethnicitycategories();
1725 Looks up the different ethnic types in the database. Returns two
1726 elements: a reference-to-array, which lists the ethnicity codes, and a
1727 reference-to-hash, which maps the ethnicity codes to ethnicity
1728 descriptions.
1730 =cut
1734 sub ethnicitycategories {
1735 my $dbh = C4::Context->dbh;
1736 my $sth = $dbh->prepare("Select code,name from ethnicity order by name");
1737 $sth->execute;
1738 my %labels;
1739 my @codes;
1740 while ( my $data = $sth->fetchrow_hashref ) {
1741 push @codes, $data->{'code'};
1742 $labels{ $data->{'code'} } = $data->{'name'};
1744 return ( \@codes, \%labels );
1747 =head2 fixEthnicity
1749 $ethn_name = &fixEthnicity($ethn_code);
1751 Takes an ethnicity code (e.g., "european" or "pi") and returns the
1752 corresponding descriptive name from the C<ethnicity> table in the
1753 Koha database ("European" or "Pacific Islander").
1755 =cut
1759 sub fixEthnicity {
1760 my $ethnicity = shift;
1761 return unless $ethnicity;
1762 my $dbh = C4::Context->dbh;
1763 my $sth = $dbh->prepare("Select name from ethnicity where code = ?");
1764 $sth->execute($ethnicity);
1765 my $data = $sth->fetchrow_hashref;
1766 return $data->{'name'};
1767 } # sub fixEthnicity
1769 =head2 GetAge
1771 $dateofbirth,$date = &GetAge($date);
1773 this function return the borrowers age with the value of dateofbirth
1775 =cut
1778 sub GetAge{
1779 my ( $date, $date_ref ) = @_;
1781 if ( not defined $date_ref ) {
1782 $date_ref = sprintf( '%04d-%02d-%02d', Today() );
1785 my ( $year1, $month1, $day1 ) = split /-/, $date;
1786 my ( $year2, $month2, $day2 ) = split /-/, $date_ref;
1788 my $age = $year2 - $year1;
1789 if ( $month1 . $day1 > $month2 . $day2 ) {
1790 $age--;
1793 return $age;
1794 } # sub get_age
1796 =head2 SetAge
1798 $borrower = C4::Members::SetAge($borrower, $datetimeduration);
1799 $borrower = C4::Members::SetAge($borrower, '0015-12-10');
1800 $borrower = C4::Members::SetAge($borrower, $datetimeduration, $datetime_reference);
1802 eval { $borrower = C4::Members::SetAge($borrower, '015-1-10'); };
1803 if ($@) {print $@;} #Catch a bad ISO Date or kill your script!
1805 This function sets the borrower's dateofbirth to match the given age.
1806 Optionally relative to the given $datetime_reference.
1808 @PARAM1 koha.borrowers-object
1809 @PARAM2 DateTime::Duration-object as the desired age
1810 OR a ISO 8601 Date. (To make the API more pleasant)
1811 @PARAM3 DateTime-object as the relative date, defaults to now().
1812 RETURNS The given borrower reference @PARAM1.
1813 DIES If there was an error with the ISO Date handling.
1815 =cut
1818 sub SetAge{
1819 my ( $borrower, $datetimeduration, $datetime_ref ) = @_;
1820 $datetime_ref = DateTime->now() unless $datetime_ref;
1822 if ($datetimeduration && ref $datetimeduration ne 'DateTime::Duration') {
1823 if ($datetimeduration =~ /^(\d{4})-(\d{2})-(\d{2})/) {
1824 $datetimeduration = DateTime::Duration->new(years => $1, months => $2, days => $3);
1826 else {
1827 die "C4::Members::SetAge($borrower, $datetimeduration), datetimeduration not a valid ISO 8601 Date!\n";
1831 my $new_datetime_ref = $datetime_ref->clone();
1832 $new_datetime_ref->subtract_duration( $datetimeduration );
1834 $borrower->{dateofbirth} = $new_datetime_ref->ymd();
1836 return $borrower;
1837 } # sub SetAge
1839 =head2 GetCities
1841 $cityarrayref = GetCities();
1843 Returns an array_ref of the entries in the cities table
1844 If there are entries in the table an empty row is returned
1845 This is currently only used to populate a popup in memberentry
1847 =cut
1849 sub GetCities {
1851 my $dbh = C4::Context->dbh;
1852 my $city_arr = $dbh->selectall_arrayref(
1853 q|SELECT cityid,city_zipcode,city_name,city_state,city_country FROM cities ORDER BY city_name|,
1854 { Slice => {} });
1855 if ( @{$city_arr} ) {
1856 unshift @{$city_arr}, {
1857 city_zipcode => q{},
1858 city_name => q{},
1859 cityid => q{},
1860 city_state => q{},
1861 city_country => q{},
1865 return $city_arr;
1868 =head2 GetSortDetails (OUEST-PROVENCE)
1870 ($lib) = &GetSortDetails($category,$sortvalue);
1872 Returns the authorized value details
1873 C<&$lib>return value of authorized value details
1874 C<&$sortvalue>this is the value of authorized value
1875 C<&$category>this is the value of authorized value category
1877 =cut
1879 sub GetSortDetails {
1880 my ( $category, $sortvalue ) = @_;
1881 my $dbh = C4::Context->dbh;
1882 my $query = qq|SELECT lib
1883 FROM authorised_values
1884 WHERE category=?
1885 AND authorised_value=? |;
1886 my $sth = $dbh->prepare($query);
1887 $sth->execute( $category, $sortvalue );
1888 my $lib = $sth->fetchrow;
1889 return ($lib) if ($lib);
1890 return ($sortvalue) unless ($lib);
1893 =head2 MoveMemberToDeleted
1895 $result = &MoveMemberToDeleted($borrowernumber);
1897 Copy the record from borrowers to deletedborrowers table.
1898 The routine returns 1 for success, undef for failure.
1900 =cut
1902 sub MoveMemberToDeleted {
1903 my ($member) = shift or return;
1905 my $schema = Koha::Database->new()->schema();
1906 my $borrowers_rs = $schema->resultset('Borrower');
1907 $borrowers_rs->result_class('DBIx::Class::ResultClass::HashRefInflator');
1908 my $borrower = $borrowers_rs->find($member);
1909 return unless $borrower;
1911 my $deleted = $schema->resultset('Deletedborrower')->create($borrower);
1913 return $deleted ? 1 : undef;
1916 =head2 DelMember
1918 DelMember($borrowernumber);
1920 This function remove directly a borrower whitout writing it on deleteborrower.
1921 + Deletes reserves for the borrower
1923 =cut
1925 sub DelMember {
1926 my $dbh = C4::Context->dbh;
1927 my $borrowernumber = shift;
1928 #warn "in delmember with $borrowernumber";
1929 return unless $borrowernumber; # borrowernumber is mandatory.
1931 my $query = qq|DELETE
1932 FROM reserves
1933 WHERE borrowernumber=?|;
1934 my $sth = $dbh->prepare($query);
1935 $sth->execute($borrowernumber);
1936 $query = "
1937 DELETE
1938 FROM borrowers
1939 WHERE borrowernumber = ?
1941 $sth = $dbh->prepare($query);
1942 $sth->execute($borrowernumber);
1943 logaction("MEMBERS", "DELETE", $borrowernumber, "") if C4::Context->preference("BorrowersLog");
1944 return $sth->rows;
1947 =head2 ExtendMemberSubscriptionTo (OUEST-PROVENCE)
1949 $date = ExtendMemberSubscriptionTo($borrowerid, $date);
1951 Extending the subscription to a given date or to the expiry date calculated on ISO date.
1952 Returns ISO date.
1954 =cut
1956 sub ExtendMemberSubscriptionTo {
1957 my ( $borrowerid,$date) = @_;
1958 my $dbh = C4::Context->dbh;
1959 my $borrower = GetMember('borrowernumber'=>$borrowerid);
1960 unless ($date){
1961 $date = (C4::Context->preference('BorrowerRenewalPeriodBase') eq 'dateexpiry') ?
1962 C4::Dates->new($borrower->{'dateexpiry'}, 'iso')->output("iso") :
1963 C4::Dates->new()->output("iso");
1964 $date = GetExpiryDate( $borrower->{'categorycode'}, $date );
1966 my $sth = $dbh->do(<<EOF);
1967 UPDATE borrowers
1968 SET dateexpiry='$date'
1969 WHERE borrowernumber='$borrowerid'
1972 AddEnrolmentFeeIfNeeded( $borrower->{categorycode}, $borrower->{borrowernumber} );
1974 logaction("MEMBERS", "RENEW", $borrower->{'borrowernumber'}, "Membership renewed")if C4::Context->preference("BorrowersLog");
1975 return $date if ($sth);
1976 return 0;
1979 =head2 GetTitles (OUEST-PROVENCE)
1981 ($borrowertitle)= &GetTitles();
1983 Looks up the different title . Returns array with all borrowers title
1985 =cut
1987 sub GetTitles {
1988 my @borrowerTitle = split (/,|\|/,C4::Context->preference('BorrowersTitles'));
1989 unshift( @borrowerTitle, "" );
1990 my $count=@borrowerTitle;
1991 if ($count == 1){
1992 return ();
1994 else {
1995 return ( \@borrowerTitle);
1999 =head2 GetPatronImage
2001 my ($imagedata, $dberror) = GetPatronImage($borrowernumber);
2003 Returns the mimetype and binary image data of the image for the patron with the supplied borrowernumber.
2005 =cut
2007 sub GetPatronImage {
2008 my ($borrowernumber) = @_;
2009 warn "Borrowernumber passed to GetPatronImage is $borrowernumber" if $debug;
2010 my $dbh = C4::Context->dbh;
2011 my $query = 'SELECT mimetype, imagefile FROM patronimage WHERE borrowernumber = ?';
2012 my $sth = $dbh->prepare($query);
2013 $sth->execute($borrowernumber);
2014 my $imagedata = $sth->fetchrow_hashref;
2015 warn "Database error!" if $sth->errstr;
2016 return $imagedata, $sth->errstr;
2019 =head2 PutPatronImage
2021 PutPatronImage($cardnumber, $mimetype, $imgfile);
2023 Stores patron binary image data and mimetype in database.
2024 NOTE: This function is good for updating images as well as inserting new images in the database.
2026 =cut
2028 sub PutPatronImage {
2029 my ($cardnumber, $mimetype, $imgfile) = @_;
2030 warn "Parameters passed in: Cardnumber=$cardnumber, Mimetype=$mimetype, " . ($imgfile ? "Imagefile" : "No Imagefile") if $debug;
2031 my $dbh = C4::Context->dbh;
2032 my $query = "INSERT INTO patronimage (borrowernumber, mimetype, imagefile) VALUES ( ( SELECT borrowernumber from borrowers WHERE cardnumber = ? ),?,?) ON DUPLICATE KEY UPDATE imagefile = ?;";
2033 my $sth = $dbh->prepare($query);
2034 $sth->execute($cardnumber,$mimetype,$imgfile,$imgfile);
2035 warn "Error returned inserting $cardnumber.$mimetype." if $sth->errstr;
2036 return $sth->errstr;
2039 =head2 RmPatronImage
2041 my ($dberror) = RmPatronImage($borrowernumber);
2043 Removes the image for the patron with the supplied borrowernumber.
2045 =cut
2047 sub RmPatronImage {
2048 my ($borrowernumber) = @_;
2049 warn "Borrowernumber passed to GetPatronImage is $borrowernumber" if $debug;
2050 my $dbh = C4::Context->dbh;
2051 my $query = "DELETE FROM patronimage WHERE borrowernumber = ?;";
2052 my $sth = $dbh->prepare($query);
2053 $sth->execute($borrowernumber);
2054 my $dberror = $sth->errstr;
2055 warn "Database error!" if $sth->errstr;
2056 return $dberror;
2059 =head2 GetHideLostItemsPreference
2061 $hidelostitemspref = &GetHideLostItemsPreference($borrowernumber);
2063 Returns the HideLostItems preference for the patron category of the supplied borrowernumber
2064 C<&$hidelostitemspref>return value of function, 0 or 1
2066 =cut
2068 sub GetHideLostItemsPreference {
2069 my ($borrowernumber) = @_;
2070 my $dbh = C4::Context->dbh;
2071 my $query = "SELECT hidelostitems FROM borrowers,categories WHERE borrowers.categorycode = categories.categorycode AND borrowernumber = ?";
2072 my $sth = $dbh->prepare($query);
2073 $sth->execute($borrowernumber);
2074 my $hidelostitems = $sth->fetchrow;
2075 return $hidelostitems;
2078 =head2 GetBorrowersToExpunge
2080 $borrowers = &GetBorrowersToExpunge(
2081 not_borrowered_since => $not_borrowered_since,
2082 expired_before => $expired_before,
2083 category_code => $category_code,
2084 branchcode => $branchcode
2087 This function get all borrowers based on the given criteria.
2089 =cut
2091 sub GetBorrowersToExpunge {
2092 my $params = shift;
2094 my $filterdate = $params->{'not_borrowered_since'};
2095 my $filterexpiry = $params->{'expired_before'};
2096 my $filtercategory = $params->{'category_code'};
2097 my $filterbranch = $params->{'branchcode'} ||
2098 ((C4::Context->preference('IndependentBranches')
2099 && C4::Context->userenv
2100 && !C4::Context->IsSuperLibrarian()
2101 && C4::Context->userenv->{branch})
2102 ? C4::Context->userenv->{branch}
2103 : "");
2105 my $dbh = C4::Context->dbh;
2106 my $query = "
2107 SELECT borrowers.borrowernumber,
2108 MAX(old_issues.timestamp) AS latestissue,
2109 MAX(issues.timestamp) AS currentissue
2110 FROM borrowers
2111 JOIN categories USING (categorycode)
2112 LEFT JOIN old_issues USING (borrowernumber)
2113 LEFT JOIN issues USING (borrowernumber)
2114 WHERE category_type <> 'S'
2115 AND borrowernumber NOT IN (SELECT guarantorid FROM borrowers WHERE guarantorid IS NOT NULL AND guarantorid <> 0)
2117 my @query_params;
2118 if ( $filterbranch && $filterbranch ne "" ) {
2119 $query.= " AND borrowers.branchcode = ? ";
2120 push( @query_params, $filterbranch );
2122 if ( $filterexpiry ) {
2123 $query .= " AND dateexpiry < ? ";
2124 push( @query_params, $filterexpiry );
2126 if ( $filtercategory ) {
2127 $query .= " AND categorycode = ? ";
2128 push( @query_params, $filtercategory );
2130 $query.=" GROUP BY borrowers.borrowernumber HAVING currentissue IS NULL ";
2131 if ( $filterdate ) {
2132 $query.=" AND ( latestissue < ? OR latestissue IS NULL ) ";
2133 push @query_params,$filterdate;
2135 warn $query if $debug;
2137 my $sth = $dbh->prepare($query);
2138 if (scalar(@query_params)>0){
2139 $sth->execute(@query_params);
2141 else {
2142 $sth->execute;
2145 my @results;
2146 while ( my $data = $sth->fetchrow_hashref ) {
2147 push @results, $data;
2149 return \@results;
2152 =head2 GetBorrowersWhoHaveNeverBorrowed
2154 $results = &GetBorrowersWhoHaveNeverBorrowed
2156 This function get all borrowers who have never borrowed.
2158 I<$result> is a ref to an array which all elements are a hasref.
2160 =cut
2162 sub GetBorrowersWhoHaveNeverBorrowed {
2163 my $filterbranch = shift ||
2164 ((C4::Context->preference('IndependentBranches')
2165 && C4::Context->userenv
2166 && !C4::Context->IsSuperLibrarian()
2167 && C4::Context->userenv->{branch})
2168 ? C4::Context->userenv->{branch}
2169 : "");
2170 my $dbh = C4::Context->dbh;
2171 my $query = "
2172 SELECT borrowers.borrowernumber,max(timestamp) as latestissue
2173 FROM borrowers
2174 LEFT JOIN issues ON borrowers.borrowernumber = issues.borrowernumber
2175 WHERE issues.borrowernumber IS NULL
2177 my @query_params;
2178 if ($filterbranch && $filterbranch ne ""){
2179 $query.=" AND borrowers.branchcode= ?";
2180 push @query_params,$filterbranch;
2182 warn $query if $debug;
2184 my $sth = $dbh->prepare($query);
2185 if (scalar(@query_params)>0){
2186 $sth->execute(@query_params);
2188 else {
2189 $sth->execute;
2192 my @results;
2193 while ( my $data = $sth->fetchrow_hashref ) {
2194 push @results, $data;
2196 return \@results;
2199 =head2 GetBorrowersWithIssuesHistoryOlderThan
2201 $results = &GetBorrowersWithIssuesHistoryOlderThan($date)
2203 this function get all borrowers who has an issue history older than I<$date> given on input arg.
2205 I<$result> is a ref to an array which all elements are a hashref.
2206 This hashref is containt the number of time this borrowers has borrowed before I<$date> and the borrowernumber.
2208 =cut
2210 sub GetBorrowersWithIssuesHistoryOlderThan {
2211 my $dbh = C4::Context->dbh;
2212 my $date = shift ||POSIX::strftime("%Y-%m-%d",localtime());
2213 my $filterbranch = shift ||
2214 ((C4::Context->preference('IndependentBranches')
2215 && C4::Context->userenv
2216 && !C4::Context->IsSuperLibrarian()
2217 && C4::Context->userenv->{branch})
2218 ? C4::Context->userenv->{branch}
2219 : "");
2220 my $query = "
2221 SELECT count(borrowernumber) as n,borrowernumber
2222 FROM old_issues
2223 WHERE returndate < ?
2224 AND borrowernumber IS NOT NULL
2226 my @query_params;
2227 push @query_params, $date;
2228 if ($filterbranch){
2229 $query.=" AND branchcode = ?";
2230 push @query_params, $filterbranch;
2232 $query.=" GROUP BY borrowernumber ";
2233 warn $query if $debug;
2234 my $sth = $dbh->prepare($query);
2235 $sth->execute(@query_params);
2236 my @results;
2238 while ( my $data = $sth->fetchrow_hashref ) {
2239 push @results, $data;
2241 return \@results;
2244 =head2 GetBorrowersNamesAndLatestIssue
2246 $results = &GetBorrowersNamesAndLatestIssueList(@borrowernumbers)
2248 this function get borrowers Names and surnames and Issue information.
2250 I<@borrowernumbers> is an array which all elements are borrowernumbers.
2251 This hashref is containt the number of time this borrowers has borrowed before I<$date> and the borrowernumber.
2253 =cut
2255 sub GetBorrowersNamesAndLatestIssue {
2256 my $dbh = C4::Context->dbh;
2257 my @borrowernumbers=@_;
2258 my $query = "
2259 SELECT surname,lastname, phone, email,max(timestamp)
2260 FROM borrowers
2261 LEFT JOIN issues ON borrowers.borrowernumber=issues.borrowernumber
2262 GROUP BY borrowernumber
2264 my $sth = $dbh->prepare($query);
2265 $sth->execute;
2266 my $results = $sth->fetchall_arrayref({});
2267 return $results;
2270 =head2 ModPrivacy
2272 my $success = ModPrivacy( $borrowernumber, $privacy );
2274 Update the privacy of a patron.
2276 return :
2277 true on success, false on failure
2279 =cut
2281 sub ModPrivacy {
2282 my $borrowernumber = shift;
2283 my $privacy = shift;
2284 return unless defined $borrowernumber;
2285 return unless $borrowernumber =~ /^\d+$/;
2287 return ModMember( borrowernumber => $borrowernumber,
2288 privacy => $privacy );
2291 =head2 AddMessage
2293 AddMessage( $borrowernumber, $message_type, $message, $branchcode );
2295 Adds a message to the messages table for the given borrower.
2297 Returns:
2298 True on success
2299 False on failure
2301 =cut
2303 sub AddMessage {
2304 my ( $borrowernumber, $message_type, $message, $branchcode ) = @_;
2306 my $dbh = C4::Context->dbh;
2308 if ( ! ( $borrowernumber && $message_type && $message && $branchcode ) ) {
2309 return;
2312 my $query = "INSERT INTO messages ( borrowernumber, branchcode, message_type, message ) VALUES ( ?, ?, ?, ? )";
2313 my $sth = $dbh->prepare($query);
2314 $sth->execute( $borrowernumber, $branchcode, $message_type, $message );
2315 logaction("MEMBERS", "ADDCIRCMESSAGE", $borrowernumber, $message) if C4::Context->preference("BorrowersLog");
2316 return 1;
2319 =head2 GetMessages
2321 GetMessages( $borrowernumber, $type );
2323 $type is message type, B for borrower, or L for Librarian.
2324 Empty type returns all messages of any type.
2326 Returns all messages for the given borrowernumber
2328 =cut
2330 sub GetMessages {
2331 my ( $borrowernumber, $type, $branchcode ) = @_;
2333 if ( ! $type ) {
2334 $type = '%';
2337 my $dbh = C4::Context->dbh;
2339 my $query = "SELECT
2340 branches.branchname,
2341 messages.*,
2342 message_date,
2343 messages.branchcode LIKE '$branchcode' AS can_delete
2344 FROM messages, branches
2345 WHERE borrowernumber = ?
2346 AND message_type LIKE ?
2347 AND messages.branchcode = branches.branchcode
2348 ORDER BY message_date DESC";
2349 my $sth = $dbh->prepare($query);
2350 $sth->execute( $borrowernumber, $type ) ;
2351 my @results;
2353 while ( my $data = $sth->fetchrow_hashref ) {
2354 my $d = C4::Dates->new( $data->{message_date}, 'iso' );
2355 $data->{message_date_formatted} = $d->output;
2356 push @results, $data;
2358 return \@results;
2362 =head2 GetMessages
2364 GetMessagesCount( $borrowernumber, $type );
2366 $type is message type, B for borrower, or L for Librarian.
2367 Empty type returns all messages of any type.
2369 Returns the number of messages for the given borrowernumber
2371 =cut
2373 sub GetMessagesCount {
2374 my ( $borrowernumber, $type, $branchcode ) = @_;
2376 if ( ! $type ) {
2377 $type = '%';
2380 my $dbh = C4::Context->dbh;
2382 my $query = "SELECT COUNT(*) as MsgCount FROM messages WHERE borrowernumber = ? AND message_type LIKE ?";
2383 my $sth = $dbh->prepare($query);
2384 $sth->execute( $borrowernumber, $type ) ;
2385 my @results;
2387 my $data = $sth->fetchrow_hashref;
2388 my $count = $data->{'MsgCount'};
2390 return $count;
2395 =head2 DeleteMessage
2397 DeleteMessage( $message_id );
2399 =cut
2401 sub DeleteMessage {
2402 my ( $message_id ) = @_;
2404 my $dbh = C4::Context->dbh;
2405 my $query = "SELECT * FROM messages WHERE message_id = ?";
2406 my $sth = $dbh->prepare($query);
2407 $sth->execute( $message_id );
2408 my $message = $sth->fetchrow_hashref();
2410 $query = "DELETE FROM messages WHERE message_id = ?";
2411 $sth = $dbh->prepare($query);
2412 $sth->execute( $message_id );
2413 logaction("MEMBERS", "DELCIRCMESSAGE", $message->{'borrowernumber'}, $message->{'message'}) if C4::Context->preference("BorrowersLog");
2416 =head2 IssueSlip
2418 IssueSlip($branchcode, $borrowernumber, $quickslip)
2420 Returns letter hash ( see C4::Letters::GetPreparedLetter )
2422 $quickslip is boolean, to indicate whether we want a quick slip
2424 =cut
2426 sub IssueSlip {
2427 my ($branch, $borrowernumber, $quickslip) = @_;
2429 # return unless ( C4::Context->boolean_preference('printcirculationslips') );
2431 my $now = POSIX::strftime("%Y-%m-%d", localtime);
2433 my $issueslist = GetPendingIssues($borrowernumber);
2434 foreach my $it (@$issueslist){
2435 if ((substr $it->{'issuedate'}, 0, 10) eq $now || (substr $it->{'lastreneweddate'}, 0, 10) eq $now) {
2436 $it->{'now'} = 1;
2438 elsif ((substr $it->{'date_due'}, 0, 10) le $now) {
2439 $it->{'overdue'} = 1;
2441 my $dt = dt_from_string( $it->{'date_due'} );
2442 $it->{'date_due'} = output_pref( $dt );;
2444 my @issues = sort { $b->{'timestamp'} <=> $a->{'timestamp'} } @$issueslist;
2446 my ($letter_code, %repeat);
2447 if ( $quickslip ) {
2448 $letter_code = 'ISSUEQSLIP';
2449 %repeat = (
2450 'checkedout' => [ map {
2451 'biblio' => $_,
2452 'items' => $_,
2453 'issues' => $_,
2454 }, grep { $_->{'now'} } @issues ],
2457 else {
2458 $letter_code = 'ISSUESLIP';
2459 %repeat = (
2460 'checkedout' => [ map {
2461 'biblio' => $_,
2462 'items' => $_,
2463 'issues' => $_,
2464 }, grep { !$_->{'overdue'} } @issues ],
2466 'overdue' => [ map {
2467 'biblio' => $_,
2468 'items' => $_,
2469 'issues' => $_,
2470 }, grep { $_->{'overdue'} } @issues ],
2472 'news' => [ map {
2473 $_->{'timestamp'} = $_->{'newdate'};
2474 { opac_news => $_ }
2475 } @{ GetNewsToDisplay("slip",$branch) } ],
2479 return C4::Letters::GetPreparedLetter (
2480 module => 'circulation',
2481 letter_code => $letter_code,
2482 branchcode => $branch,
2483 tables => {
2484 'branches' => $branch,
2485 'borrowers' => $borrowernumber,
2487 repeat => \%repeat,
2491 =head2 GetBorrowersWithEmail
2493 ([$borrnum,$userid], ...) = GetBorrowersWithEmail('me@example.com');
2495 This gets a list of users and their basic details from their email address.
2496 As it's possible for multiple user to have the same email address, it provides
2497 you with all of them. If there is no userid for the user, there will be an
2498 C<undef> there. An empty list will be returned if there are no matches.
2500 =cut
2502 sub GetBorrowersWithEmail {
2503 my $email = shift;
2505 my $dbh = C4::Context->dbh;
2507 my $query = "SELECT borrowernumber, userid FROM borrowers WHERE email=?";
2508 my $sth=$dbh->prepare($query);
2509 $sth->execute($email);
2510 my @result = ();
2511 while (my $ref = $sth->fetch) {
2512 push @result, $ref;
2514 die "Failure searching for borrowers by email address: $sth->errstr" if $sth->err;
2515 return @result;
2518 sub AddMember_Opac {
2519 my ( %borrower ) = @_;
2521 $borrower{'categorycode'} = C4::Context->preference('PatronSelfRegistrationDefaultCategory');
2523 my $sr = new String::Random;
2524 $sr->{'A'} = [ 'A'..'Z', 'a'..'z' ];
2525 my $password = $sr->randpattern("AAAAAAAAAA");
2526 $borrower{'password'} = $password;
2528 $borrower{'cardnumber'} = fixup_cardnumber();
2530 my $borrowernumber = AddMember(%borrower);
2532 return ( $borrowernumber, $password );
2535 =head2 AddEnrolmentFeeIfNeeded
2537 AddEnrolmentFeeIfNeeded( $borrower->{categorycode}, $borrower->{borrowernumber} );
2539 Add enrolment fee for a patron if needed.
2541 =cut
2543 sub AddEnrolmentFeeIfNeeded {
2544 my ( $categorycode, $borrowernumber ) = @_;
2545 # check for enrollment fee & add it if needed
2546 my $dbh = C4::Context->dbh;
2547 my $sth = $dbh->prepare(q{
2548 SELECT enrolmentfee
2549 FROM categories
2550 WHERE categorycode=?
2552 $sth->execute( $categorycode );
2553 if ( $sth->err ) {
2554 warn sprintf('Database returned the following error: %s', $sth->errstr);
2555 return;
2557 my ($enrolmentfee) = $sth->fetchrow;
2558 if ($enrolmentfee && $enrolmentfee > 0) {
2559 # insert fee in patron debts
2560 C4::Accounts::manualinvoice( $borrowernumber, '', '', 'A', $enrolmentfee );
2564 sub HasOverdues {
2565 my ( $borrowernumber ) = @_;
2567 my $sql = "SELECT COUNT(*) FROM issues WHERE date_due < NOW() AND borrowernumber = ?";
2568 my $sth = C4::Context->dbh->prepare( $sql );
2569 $sth->execute( $borrowernumber );
2570 my ( $count ) = $sth->fetchrow_array();
2572 return $count;
2575 END { } # module clean-up code here (global destructor)
2579 __END__
2581 =head1 AUTHOR
2583 Koha Team
2585 =cut