Bug 16412: Make sure Koha::Cache->set_in_cache will not warn anymore
[koha.git] / C4 / Members.pm
blobca1b02fb0e5617439f2dc4adaf5379bc808a1498
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
10 # under the terms of the GNU General Public License as published by
11 # the Free Software Foundation; either version 3 of the License, or
12 # (at your option) any later version.
14 # Koha is distributed in the hope that it will be useful, but
15 # WITHOUT ANY WARRANTY; without even the implied warranty of
16 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 # GNU General Public License for more details.
19 # You should have received a copy of the GNU General Public License
20 # along with Koha; if not, see <http://www.gnu.org/licenses>.
23 use strict;
24 #use warnings; FIXME - Bug 2505
25 use C4::Context;
26 use String::Random qw( random_string );
27 use Date::Calc qw/Today Add_Delta_YM check_date Date_to_Days/;
28 use C4::Log; # logaction
29 use C4::Overdues;
30 use C4::Reserves;
31 use C4::Accounts;
32 use C4::Biblio;
33 use C4::Letters;
34 use C4::Members::Attributes qw(SearchIdMatchingAttribute UpdateBorrowerAttribute);
35 use C4::NewsChannels; #get slip news
36 use DateTime;
37 use Koha::Database;
38 use Koha::DateUtils;
39 use Koha::Borrower::Debarments qw(IsDebarred);
40 use Text::Unaccent qw( unac_string );
41 use Koha::AuthUtils qw(hash_password);
42 use Koha::Database;
44 our ($VERSION,@ISA,@EXPORT,@EXPORT_OK,$debug);
46 use Module::Load::Conditional qw( can_load );
47 if ( ! can_load( modules => { 'Koha::NorwegianPatronDB' => undef } ) ) {
48 $debug && warn "Unable to load Koha::NorwegianPatronDB";
52 BEGIN {
53 $VERSION = 3.07.00.049;
54 $debug = $ENV{DEBUG} || 0;
55 require Exporter;
56 @ISA = qw(Exporter);
57 #Get data
58 push @EXPORT, qw(
59 &Search
60 &GetMemberDetails
61 &GetMemberRelatives
62 &GetMember
64 &GetGuarantees
66 &GetMemberIssuesAndFines
67 &GetPendingIssues
68 &GetAllIssues
70 &getzipnamecity
71 &getidcity
73 &GetFirstValidEmailAddress
74 &GetNoticeEmailAddress
76 &GetAge
77 &GetCities
78 &GetSortDetails
79 &GetTitles
81 &GetPatronImage
82 &PutPatronImage
83 &RmPatronImage
85 &GetHideLostItemsPreference
87 &IsMemberBlocked
88 &GetMemberAccountRecords
89 &GetBorNotifyAcctRecord
91 &GetborCatFromCatType
92 &GetBorrowercategory
93 GetBorrowerCategorycode
94 &GetBorrowercategoryList
96 &GetBorrowersToExpunge
97 &GetBorrowersWhoHaveNeverBorrowed
98 &GetBorrowersWithIssuesHistoryOlderThan
100 &GetExpiryDate
101 &GetUpcomingMembershipExpires
103 &AddMessage
104 &DeleteMessage
105 &GetMessages
106 &GetMessagesCount
108 &IssueSlip
109 GetBorrowersWithEmail
111 HasOverdues
112 GetOverduesForPatron
115 #Modify data
116 push @EXPORT, qw(
117 &ModMember
118 &changepassword
119 &ModPrivacy
122 #Delete data
123 push @EXPORT, qw(
124 &DelMember
127 #Insert data
128 push @EXPORT, qw(
129 &AddMember
130 &AddMember_Opac
131 &MoveMemberToDeleted
132 &ExtendMemberSubscriptionTo
135 #Check data
136 push @EXPORT, qw(
137 &checkuniquemember
138 &checkuserpassword
139 &Check_Userid
140 &Generate_Userid
141 &fixup_cardnumber
142 &checkcardnumber
146 =head1 NAME
148 C4::Members - Perl Module containing convenience functions for member handling
150 =head1 SYNOPSIS
152 use C4::Members;
154 =head1 DESCRIPTION
156 This module contains routines for adding, modifying and deleting members/patrons/borrowers
158 =head1 FUNCTIONS
160 =head2 GetMemberDetails
162 ($borrower) = &GetMemberDetails($borrowernumber, $cardnumber);
164 Looks up a patron and returns information about him or her. If
165 C<$borrowernumber> is true (nonzero), C<&GetMemberDetails> looks
166 up the borrower by number; otherwise, it looks up the borrower by card
167 number.
169 C<$borrower> is a reference-to-hash whose keys are the fields of the
170 borrowers table in the Koha database. In addition,
171 C<$borrower-E<gt>{flags}> is a hash giving more detailed information
172 about the patron. Its keys act as flags :
174 if $borrower->{flags}->{LOST} {
175 # Patron's card was reported lost
178 If the state of a flag means that the patron should not be
179 allowed to borrow any more books, then it will have a C<noissues> key
180 with a true value.
182 See patronflags for more details.
184 C<$borrower-E<gt>{authflags}> is a hash giving more detailed information
185 about the top-level permissions flags set for the borrower. For example,
186 if a user has the "editcatalogue" permission,
187 C<$borrower-E<gt>{authflags}-E<gt>{editcatalogue}> will exist and have
188 the value "1".
190 =cut
192 sub GetMemberDetails {
193 my ( $borrowernumber, $cardnumber ) = @_;
194 my $dbh = C4::Context->dbh;
195 my $query;
196 my $sth;
197 if ($borrowernumber) {
198 $sth = $dbh->prepare("
199 SELECT borrowers.*,
200 category_type,
201 categories.description,
202 categories.BlockExpiredPatronOpacActions,
203 reservefee,
204 enrolmentperiod
205 FROM borrowers
206 LEFT JOIN categories ON borrowers.categorycode=categories.categorycode
207 WHERE borrowernumber = ?
209 $sth->execute($borrowernumber);
211 elsif ($cardnumber) {
212 $sth = $dbh->prepare("
213 SELECT borrowers.*,
214 category_type,
215 categories.description,
216 categories.BlockExpiredPatronOpacActions,
217 reservefee,
218 enrolmentperiod
219 FROM borrowers
220 LEFT JOIN categories ON borrowers.categorycode = categories.categorycode
221 WHERE cardnumber = ?
223 $sth->execute($cardnumber);
225 else {
226 return;
228 my $borrower = $sth->fetchrow_hashref;
229 return unless $borrower;
230 my ($amount) = GetMemberAccountRecords($borrower->{borrowernumber});
231 $borrower->{'amountoutstanding'} = $amount;
232 # FIXME - patronflags calls GetMemberAccountRecords... just have patronflags return $amount
233 my $flags = patronflags( $borrower);
234 my $accessflagshash;
236 $sth = $dbh->prepare("select bit,flag from userflags");
237 $sth->execute;
238 while ( my ( $bit, $flag ) = $sth->fetchrow ) {
239 if ( $borrower->{'flags'} && $borrower->{'flags'} & 2**$bit ) {
240 $accessflagshash->{$flag} = 1;
243 $borrower->{'flags'} = $flags;
244 $borrower->{'authflags'} = $accessflagshash;
246 # Handle setting the true behavior for BlockExpiredPatronOpacActions
247 $borrower->{'BlockExpiredPatronOpacActions'} =
248 C4::Context->preference('BlockExpiredPatronOpacActions')
249 if ( $borrower->{'BlockExpiredPatronOpacActions'} == -1 );
251 $borrower->{'is_expired'} = 0;
252 $borrower->{'is_expired'} = 1 if
253 defined($borrower->{dateexpiry}) &&
254 $borrower->{'dateexpiry'} ne '0000-00-00' &&
255 Date_to_Days( Today() ) >
256 Date_to_Days( split /-/, $borrower->{'dateexpiry'} );
258 return ($borrower); #, $flags, $accessflagshash);
261 =head2 patronflags
263 $flags = &patronflags($patron);
265 This function is not exported.
267 The following will be set where applicable:
268 $flags->{CHARGES}->{amount} Amount of debt
269 $flags->{CHARGES}->{noissues} Set if debt amount >$5.00 (or syspref noissuescharge)
270 $flags->{CHARGES}->{message} Message -- deprecated
272 $flags->{CREDITS}->{amount} Amount of credit
273 $flags->{CREDITS}->{message} Message -- deprecated
275 $flags->{ GNA } Patron has no valid address
276 $flags->{ GNA }->{noissues} Set for each GNA
277 $flags->{ GNA }->{message} "Borrower has no valid address" -- deprecated
279 $flags->{ LOST } Patron's card reported lost
280 $flags->{ LOST }->{noissues} Set for each LOST
281 $flags->{ LOST }->{message} Message -- deprecated
283 $flags->{DBARRED} Set if patron debarred, no access
284 $flags->{DBARRED}->{noissues} Set for each DBARRED
285 $flags->{DBARRED}->{message} Message -- deprecated
287 $flags->{ NOTES }
288 $flags->{ NOTES }->{message} The note itself. NOT deprecated
290 $flags->{ ODUES } Set if patron has overdue books.
291 $flags->{ ODUES }->{message} "Yes" -- deprecated
292 $flags->{ ODUES }->{itemlist} ref-to-array: list of overdue books
293 $flags->{ ODUES }->{itemlisttext} Text list of overdue items -- deprecated
295 $flags->{WAITING} Set if any of patron's reserves are available
296 $flags->{WAITING}->{message} Message -- deprecated
297 $flags->{WAITING}->{itemlist} ref-to-array: list of available items
299 =over
301 =item C<$flags-E<gt>{ODUES}-E<gt>{itemlist}> is a reference-to-array listing the
302 overdue items. Its elements are references-to-hash, each describing an
303 overdue item. The keys are selected fields from the issues, biblio,
304 biblioitems, and items tables of the Koha database.
306 =item C<$flags-E<gt>{ODUES}-E<gt>{itemlisttext}> is a string giving a text listing of
307 the overdue items, one per line. Deprecated.
309 =item C<$flags-E<gt>{WAITING}-E<gt>{itemlist}> is a reference-to-array listing the
310 available items. Each element is a reference-to-hash whose keys are
311 fields from the reserves table of the Koha database.
313 =back
315 All the "message" fields that include language generated in this function are deprecated,
316 because such strings belong properly in the display layer.
318 The "message" field that comes from the DB is OK.
320 =cut
322 # TODO: use {anonymous => hashes} instead of a dozen %flaginfo
323 # FIXME rename this function.
324 sub patronflags {
325 my %flags;
326 my ( $patroninformation) = @_;
327 my $dbh=C4::Context->dbh;
328 my ($balance, $owing) = GetMemberAccountBalance( $patroninformation->{'borrowernumber'});
329 if ( $owing > 0 ) {
330 my %flaginfo;
331 my $noissuescharge = C4::Context->preference("noissuescharge") || 5;
332 $flaginfo{'message'} = sprintf 'Patron owes %.02f', $owing;
333 $flaginfo{'amount'} = sprintf "%.02f", $owing;
334 if ( $owing > $noissuescharge && !C4::Context->preference("AllowFineOverride") ) {
335 $flaginfo{'noissues'} = 1;
337 $flags{'CHARGES'} = \%flaginfo;
339 elsif ( $balance < 0 ) {
340 my %flaginfo;
341 $flaginfo{'message'} = sprintf 'Patron has credit of %.02f', -$balance;
342 $flaginfo{'amount'} = sprintf "%.02f", $balance;
343 $flags{'CREDITS'} = \%flaginfo;
345 if ( $patroninformation->{'gonenoaddress'}
346 && $patroninformation->{'gonenoaddress'} == 1 )
348 my %flaginfo;
349 $flaginfo{'message'} = 'Borrower has no valid address.';
350 $flaginfo{'noissues'} = 1;
351 $flags{'GNA'} = \%flaginfo;
353 if ( $patroninformation->{'lost'} && $patroninformation->{'lost'} == 1 ) {
354 my %flaginfo;
355 $flaginfo{'message'} = 'Borrower\'s card reported lost.';
356 $flaginfo{'noissues'} = 1;
357 $flags{'LOST'} = \%flaginfo;
359 if ( $patroninformation->{'debarred'} && check_date( split( /-/, $patroninformation->{'debarred'} ) ) ) {
360 if ( Date_to_Days(Date::Calc::Today) < Date_to_Days( split( /-/, $patroninformation->{'debarred'} ) ) ) {
361 my %flaginfo;
362 $flaginfo{'debarredcomment'} = $patroninformation->{'debarredcomment'};
363 $flaginfo{'message'} = $patroninformation->{'debarredcomment'};
364 $flaginfo{'noissues'} = 1;
365 $flaginfo{'dateend'} = $patroninformation->{'debarred'};
366 $flags{'DBARRED'} = \%flaginfo;
369 if ( $patroninformation->{'borrowernotes'}
370 && $patroninformation->{'borrowernotes'} )
372 my %flaginfo;
373 $flaginfo{'message'} = $patroninformation->{'borrowernotes'};
374 $flags{'NOTES'} = \%flaginfo;
376 my ( $odues, $itemsoverdue ) = C4::Overdues::checkoverdues($patroninformation->{'borrowernumber'});
377 if ( $odues && $odues > 0 ) {
378 my %flaginfo;
379 $flaginfo{'message'} = "Yes";
380 $flaginfo{'itemlist'} = $itemsoverdue;
381 foreach ( sort { $a->{'date_due'} cmp $b->{'date_due'} }
382 @$itemsoverdue )
384 $flaginfo{'itemlisttext'} .=
385 "$_->{'date_due'} $_->{'barcode'} $_->{'title'} \n"; # newline is display layer
387 $flags{'ODUES'} = \%flaginfo;
389 my @itemswaiting = C4::Reserves::GetReservesFromBorrowernumber( $patroninformation->{'borrowernumber'},'W' );
390 my $nowaiting = scalar @itemswaiting;
391 if ( $nowaiting > 0 ) {
392 my %flaginfo;
393 $flaginfo{'message'} = "Reserved items available";
394 $flaginfo{'itemlist'} = \@itemswaiting;
395 $flags{'WAITING'} = \%flaginfo;
397 return ( \%flags );
401 =head2 GetMember
403 $borrower = &GetMember(%information);
405 Retrieve the first patron record meeting on criteria listed in the
406 C<%information> hash, which should contain one or more
407 pairs of borrowers column names and values, e.g.,
409 $borrower = GetMember(borrowernumber => id);
411 C<&GetBorrower> returns a reference-to-hash whose keys are the fields of
412 the C<borrowers> table in the Koha database.
414 FIXME: GetMember() is used throughout the code as a lookup
415 on a unique key such as the borrowernumber, but this meaning is not
416 enforced in the routine itself.
418 =cut
421 sub GetMember {
422 my ( %information ) = @_;
423 if (exists $information{borrowernumber} && !defined $information{borrowernumber}) {
424 #passing mysql's kohaadmin?? Makes no sense as a query
425 return;
427 my $dbh = C4::Context->dbh;
428 my $select =
429 q{SELECT borrowers.*, categories.category_type, categories.description
430 FROM borrowers
431 LEFT JOIN categories on borrowers.categorycode=categories.categorycode WHERE };
432 my $more_p = 0;
433 my @values = ();
434 for (keys %information ) {
435 if ($more_p) {
436 $select .= ' AND ';
438 else {
439 $more_p++;
442 if (defined $information{$_}) {
443 $select .= "$_ = ?";
444 push @values, $information{$_};
446 else {
447 $select .= "$_ IS NULL";
450 $debug && warn $select, " ",values %information;
451 my $sth = $dbh->prepare("$select");
452 $sth->execute(@values);
453 my $data = $sth->fetchall_arrayref({});
454 #FIXME interface to this routine now allows generation of a result set
455 #so whole array should be returned but bowhere in the current code expects this
456 if (@{$data} ) {
457 return $data->[0];
460 return;
463 =head2 GetMemberRelatives
465 @borrowernumbers = GetMemberRelatives($borrowernumber);
467 C<GetMemberRelatives> returns a borrowersnumber's list of guarantor/guarantees of the member given in parameter
469 =cut
471 sub GetMemberRelatives {
472 my $borrowernumber = shift;
473 my $dbh = C4::Context->dbh;
474 my @glist;
476 # Getting guarantor
477 my $query = "SELECT guarantorid FROM borrowers WHERE borrowernumber=?";
478 my $sth = $dbh->prepare($query);
479 $sth->execute($borrowernumber);
480 my $data = $sth->fetchrow_arrayref();
481 push @glist, $data->[0] if $data->[0];
482 my $guarantor = $data->[0] ? $data->[0] : undef;
484 # Getting guarantees
485 $query = "SELECT borrowernumber FROM borrowers WHERE guarantorid=?";
486 $sth = $dbh->prepare($query);
487 $sth->execute($borrowernumber);
488 while ($data = $sth->fetchrow_arrayref()) {
489 push @glist, $data->[0];
492 # Getting sibling guarantees
493 if ($guarantor) {
494 $query = "SELECT borrowernumber FROM borrowers WHERE guarantorid=?";
495 $sth = $dbh->prepare($query);
496 $sth->execute($guarantor);
497 while ($data = $sth->fetchrow_arrayref()) {
498 push @glist, $data->[0] if ($data->[0] != $borrowernumber);
502 return @glist;
505 =head2 IsMemberBlocked
507 my ($block_status, $count) = IsMemberBlocked( $borrowernumber );
509 Returns whether a patron is restricted or has overdue items that may result
510 in a block of circulation privileges.
512 C<$block_status> can have the following values:
514 1 if the patron is currently restricted, in which case
515 C<$count> is the expiration date (9999-12-31 for indefinite)
517 -1 if the patron has overdue items, in which case C<$count> is the number of them
519 0 if the patron has no overdue items or outstanding fine days, in which case C<$count> is 0
521 Existing active restrictions are checked before current overdue items.
523 =cut
525 sub IsMemberBlocked {
526 my $borrowernumber = shift;
527 my $dbh = C4::Context->dbh;
529 my $blockeddate = Koha::Borrower::Debarments::IsDebarred($borrowernumber);
531 return ( 1, $blockeddate ) if $blockeddate;
533 # if he have late issues
534 my $sth = $dbh->prepare(
535 "SELECT COUNT(*) as latedocs
536 FROM issues
537 WHERE borrowernumber = ?
538 AND date_due < now()"
540 $sth->execute($borrowernumber);
541 my $latedocs = $sth->fetchrow_hashref->{'latedocs'};
543 return ( -1, $latedocs ) if $latedocs > 0;
545 return ( 0, 0 );
548 =head2 GetMemberIssuesAndFines
550 ($overdue_count, $issue_count, $total_fines) = &GetMemberIssuesAndFines($borrowernumber);
552 Returns aggregate data about items borrowed by the patron with the
553 given borrowernumber.
555 C<&GetMemberIssuesAndFines> returns a three-element array. C<$overdue_count> is the
556 number of overdue items the patron currently has borrowed. C<$issue_count> is the
557 number of books the patron currently has borrowed. C<$total_fines> is
558 the total fine currently due by the borrower.
560 =cut
563 sub GetMemberIssuesAndFines {
564 my ( $borrowernumber ) = @_;
565 my $dbh = C4::Context->dbh;
566 my $query = "SELECT COUNT(*) FROM issues WHERE borrowernumber = ?";
568 $debug and warn $query."\n";
569 my $sth = $dbh->prepare($query);
570 $sth->execute($borrowernumber);
571 my $issue_count = $sth->fetchrow_arrayref->[0];
573 $sth = $dbh->prepare(
574 "SELECT COUNT(*) FROM issues
575 WHERE borrowernumber = ?
576 AND date_due < now()"
578 $sth->execute($borrowernumber);
579 my $overdue_count = $sth->fetchrow_arrayref->[0];
581 $sth = $dbh->prepare("SELECT SUM(amountoutstanding) FROM accountlines WHERE borrowernumber = ?");
582 $sth->execute($borrowernumber);
583 my $total_fines = $sth->fetchrow_arrayref->[0];
585 return ($overdue_count, $issue_count, $total_fines);
589 =head2 columns
591 my @columns = C4::Member::columns();
593 Returns an array of borrowers' table columns on success,
594 and an empty array on failure.
596 =cut
598 sub columns {
600 # Pure ANSI SQL goodness.
601 my $sql = 'SELECT * FROM borrowers WHERE 1=0;';
603 # Get the database handle.
604 my $dbh = C4::Context->dbh;
606 # Run the SQL statement to load STH's readonly properties.
607 my $sth = $dbh->prepare($sql);
608 my $rv = $sth->execute();
610 # This only fails if the table doesn't exist.
611 # This will always be called AFTER an install or upgrade,
612 # so borrowers will exist!
613 my @data;
614 if ($sth->{NUM_OF_FIELDS}>0) {
615 @data = @{$sth->{NAME}};
617 else {
618 @data = ();
620 return @data;
624 =head2 ModMember
626 my $success = ModMember(borrowernumber => $borrowernumber,
627 [ field => value ]... );
629 Modify borrower's data. All date fields should ALREADY be in ISO format.
631 return :
632 true on success, or false on failure
634 =cut
636 sub ModMember {
637 my (%data) = @_;
638 # test to know if you must update or not the borrower password
639 if (exists $data{password}) {
640 if ($data{password} eq '****' or $data{password} eq '') {
641 delete $data{password};
642 } else {
643 if ( C4::Context->preference('NorwegianPatronDBEnable') && C4::Context->preference('NorwegianPatronDBEnable') == 1 ) {
644 # Update the hashed PIN in borrower_sync.hashed_pin, before Koha hashes it
645 Koha::NorwegianPatronDB::NLUpdateHashedPIN( $data{'borrowernumber'}, $data{password} );
647 $data{password} = hash_password($data{password});
650 my $old_categorycode = GetBorrowerCategorycode( $data{borrowernumber} );
652 # get only the columns of a borrower
653 my $schema = Koha::Database->new()->schema;
654 my @columns = $schema->source('Borrower')->columns;
655 my $new_borrower = { map { join(' ', @columns) =~ /$_/ ? ( $_ => $data{$_} ) : () } keys(%data) };
656 delete $new_borrower->{flags};
658 $new_borrower->{dateofbirth} ||= undef if exists $new_borrower->{dateofbirth};
659 $new_borrower->{dateenrolled} ||= undef if exists $new_borrower->{dateenrolled};
660 $new_borrower->{dateexpiry} ||= undef if exists $new_borrower->{dateexpiry};
661 $new_borrower->{debarred} ||= undef if exists $new_borrower->{debarred};
662 my $rs = $schema->resultset('Borrower')->search({
663 borrowernumber => $new_borrower->{borrowernumber},
666 delete $new_borrower->{userid} if exists $new_borrower->{userid} and not $new_borrower->{userid};
668 my $execute_success = $rs->update($new_borrower);
669 if ($execute_success ne '0E0') { # only proceed if the update was a success
670 # ok if its an adult (type) it may have borrowers that depend on it as a guarantor
671 # so when we update information for an adult we should check for guarantees and update the relevant part
672 # of their records, ie addresses and phone numbers
673 my $borrowercategory= GetBorrowercategory( $data{'category_type'} );
674 if ( exists $borrowercategory->{'category_type'} && $borrowercategory->{'category_type'} eq ('A' || 'S') ) {
675 # is adult check guarantees;
676 UpdateGuarantees(%data);
679 # If the patron changes to a category with enrollment fee, we add a fee
680 if ( $data{categorycode} and $data{categorycode} ne $old_categorycode ) {
681 if ( C4::Context->preference('FeeOnChangePatronCategory') ) {
682 AddEnrolmentFeeIfNeeded( $data{categorycode}, $data{borrowernumber} );
686 # If NorwegianPatronDBEnable is enabled, we set syncstatus to something that a
687 # cronjob will use for syncing with NL
688 if ( C4::Context->preference('NorwegianPatronDBEnable') && C4::Context->preference('NorwegianPatronDBEnable') == 1 ) {
689 my $borrowersync = Koha::Database->new->schema->resultset('BorrowerSync')->find({
690 'synctype' => 'norwegianpatrondb',
691 'borrowernumber' => $data{'borrowernumber'}
693 # Do not set to "edited" if syncstatus is "new". We need to sync as new before
694 # we can sync as changed. And the "new sync" will pick up all changes since
695 # the patron was created anyway.
696 if ( $borrowersync->syncstatus ne 'new' && $borrowersync->syncstatus ne 'delete' ) {
697 $borrowersync->update( { 'syncstatus' => 'edited' } );
699 # Set the value of 'sync'
700 $borrowersync->update( { 'sync' => $data{'sync'} } );
701 # Try to do the live sync
702 Koha::NorwegianPatronDB::NLSync({ 'borrowernumber' => $data{'borrowernumber'} });
705 logaction("MEMBERS", "MODIFY", $data{'borrowernumber'}, "UPDATE (executed w/ arg: $data{'borrowernumber'})") if C4::Context->preference("BorrowersLog");
707 return $execute_success;
710 =head2 AddMember
712 $borrowernumber = &AddMember(%borrower);
714 insert new borrower into table
716 (%borrower keys are database columns. Database columns could be
717 different in different versions. Please look into database for correct
718 column names.)
720 Returns the borrowernumber upon success
722 Returns as undef upon any db error without further processing
724 =cut
727 sub AddMember {
728 my (%data) = @_;
729 my $dbh = C4::Context->dbh;
730 my $schema = Koha::Database->new()->schema;
732 # generate a proper login if none provided
733 $data{'userid'} = Generate_Userid( $data{'borrowernumber'}, $data{'firstname'}, $data{'surname'} )
734 if ( $data{'userid'} eq '' || !Check_Userid( $data{'userid'} ) );
736 # add expiration date if it isn't already there
737 unless ( $data{'dateexpiry'} ) {
738 $data{'dateexpiry'} = GetExpiryDate( $data{'categorycode'}, output_pref( { dt => dt_from_string, dateonly => 1, dateformat => 'iso' } ) );
741 # add enrollment date if it isn't already there
742 unless ( $data{'dateenrolled'} ) {
743 $data{'dateenrolled'} = output_pref( { dt => dt_from_string, dateonly => 1, dateformat => 'iso' } );
746 my $patron_category = $schema->resultset('Category')->find( $data{'categorycode'} );
747 $data{'privacy'} =
748 $patron_category->default_privacy() eq 'default' ? 1
749 : $patron_category->default_privacy() eq 'never' ? 2
750 : $patron_category->default_privacy() eq 'forever' ? 0
751 : undef;
752 # Make a copy of the plain text password for later use
753 my $plain_text_password = $data{'password'};
755 # create a disabled account if no password provided
756 $data{'password'} = ($data{'password'})? hash_password($data{'password'}) : '!';
758 # we don't want invalid dates in the db (mysql has a bad habit of inserting 0000-00-00
759 $data{'dateofbirth'} = undef if( not $data{'dateofbirth'} );
760 $data{'debarred'} = undef if ( not $data{'debarred'} );
762 # get only the columns of Borrower
763 my @columns = $schema->source('Borrower')->columns;
764 my $new_member = { map { join(' ',@columns) =~ /$_/ ? ( $_ => $data{$_} ) : () } keys(%data) } ;
765 delete $new_member->{borrowernumber};
767 my $rs = $schema->resultset('Borrower');
768 $data{borrowernumber} = $rs->create($new_member)->id;
770 # If NorwegianPatronDBEnable is enabled, we set syncstatus to something that a
771 # cronjob will use for syncing with NL
772 if ( exists $data{'borrowernumber'} && C4::Context->preference('NorwegianPatronDBEnable') && C4::Context->preference('NorwegianPatronDBEnable') == 1 ) {
773 Koha::Database->new->schema->resultset('BorrowerSync')->create({
774 'borrowernumber' => $data{'borrowernumber'},
775 'synctype' => 'norwegianpatrondb',
776 'sync' => 1,
777 'syncstatus' => 'new',
778 'hashed_pin' => Koha::NorwegianPatronDB::NLEncryptPIN( $plain_text_password ),
782 # mysql_insertid is probably bad. not necessarily accurate and mysql-specific at best.
783 logaction("MEMBERS", "CREATE", $data{'borrowernumber'}, "") if C4::Context->preference("BorrowersLog");
785 AddEnrolmentFeeIfNeeded( $data{categorycode}, $data{borrowernumber} );
787 return $data{borrowernumber};
790 =head2 Check_Userid
792 my $uniqueness = Check_Userid($userid,$borrowernumber);
794 $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 != '').
796 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.
798 return :
799 0 for not unique (i.e. this $userid already exists)
800 1 for unique (i.e. this $userid does not exist, or this $userid/$borrowernumber combination already exists)
802 =cut
804 sub Check_Userid {
805 my ( $uid, $borrowernumber ) = @_;
807 return 0 unless ($uid); # userid is a unique column, we should assume NULL is not unique
809 return 0 if ( $uid eq C4::Context->config('user') );
811 my $rs = Koha::Database->new()->schema()->resultset('Borrower');
813 my $params;
814 $params->{userid} = $uid;
815 $params->{borrowernumber} = { '!=' => $borrowernumber } if ($borrowernumber);
817 my $count = $rs->count( $params );
819 return $count ? 0 : 1;
822 =head2 Generate_Userid
824 my $newuid = Generate_Userid($borrowernumber, $firstname, $surname);
826 Generate a userid using the $surname and the $firstname (if there is a value in $firstname).
828 $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.
830 return :
831 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).
833 =cut
835 sub Generate_Userid {
836 my ($borrowernumber, $firstname, $surname) = @_;
837 my $newuid;
838 my $offset = 0;
839 #The script will "do" the following code and increment the $offset until Check_Userid = 1 (i.e. until $newuid comes back as unique)
840 do {
841 $firstname =~ s/[[:digit:][:space:][:blank:][:punct:][:cntrl:]]//g;
842 $surname =~ s/[[:digit:][:space:][:blank:][:punct:][:cntrl:]]//g;
843 $newuid = lc(($firstname)? "$firstname.$surname" : $surname);
844 $newuid = unac_string('utf-8',$newuid);
845 $newuid .= $offset unless $offset == 0;
846 $offset++;
848 } while (!Check_Userid($newuid,$borrowernumber));
850 return $newuid;
853 sub changepassword {
854 my ( $uid, $member, $digest ) = @_;
855 my $dbh = C4::Context->dbh;
857 #Make sure the userid chosen is unique and not theirs if non-empty. If it is not,
858 #Then we need to tell the user and have them create a new one.
859 my $resultcode;
860 my $sth =
861 $dbh->prepare(
862 "SELECT * FROM borrowers WHERE userid=? AND borrowernumber != ?");
863 $sth->execute( $uid, $member );
864 if ( ( $uid ne '' ) && ( my $row = $sth->fetchrow_hashref ) ) {
865 $resultcode=0;
867 else {
868 #Everything is good so we can update the information.
869 $sth =
870 $dbh->prepare(
871 "update borrowers set userid=?, password=? where borrowernumber=?");
872 $sth->execute( $uid, $digest, $member );
873 $resultcode=1;
876 logaction("MEMBERS", "CHANGE PASS", $member, "") if C4::Context->preference("BorrowersLog");
877 return $resultcode;
882 =head2 fixup_cardnumber
884 Warning: The caller is responsible for locking the members table in write
885 mode, to avoid database corruption.
887 =cut
889 use vars qw( @weightings );
890 my @weightings = ( 8, 4, 6, 3, 5, 2, 1 );
892 sub fixup_cardnumber {
893 my ($cardnumber) = @_;
894 my $autonumber_members = C4::Context->boolean_preference('autoMemberNum') || 0;
896 # Find out whether member numbers should be generated
897 # automatically. Should be either "1" or something else.
898 # Defaults to "0", which is interpreted as "no".
900 # if ($cardnumber !~ /\S/ && $autonumber_members) {
901 ($autonumber_members) or return $cardnumber;
902 my $checkdigit = C4::Context->preference('checkdigit');
903 my $dbh = C4::Context->dbh;
904 if ( $checkdigit and $checkdigit eq 'katipo' ) {
906 # if checkdigit is selected, calculate katipo-style cardnumber.
907 # otherwise, just use the max()
908 # purpose: generate checksum'd member numbers.
909 # We'll assume we just got the max value of digits 2-8 of member #'s
910 # from the database and our job is to increment that by one,
911 # determine the 1st and 9th digits and return the full string.
912 my $sth = $dbh->prepare(
913 "select max(substring(borrowers.cardnumber,2,7)) as new_num from borrowers"
915 $sth->execute;
916 my $data = $sth->fetchrow_hashref;
917 $cardnumber = $data->{new_num};
918 if ( !$cardnumber ) { # If DB has no values,
919 $cardnumber = 1000000; # start at 1000000
920 } else {
921 $cardnumber += 1;
924 my $sum = 0;
925 for ( my $i = 0 ; $i < 8 ; $i += 1 ) {
926 # read weightings, left to right, 1 char at a time
927 my $temp1 = $weightings[$i];
929 # sequence left to right, 1 char at a time
930 my $temp2 = substr( $cardnumber, $i, 1 );
932 # mult each char 1-7 by its corresponding weighting
933 $sum += $temp1 * $temp2;
936 my $rem = ( $sum % 11 );
937 $rem = 'X' if $rem == 10;
939 return "V$cardnumber$rem";
940 } else {
942 my $sth = $dbh->prepare(
943 'SELECT MAX( CAST( cardnumber AS SIGNED ) ) FROM borrowers WHERE cardnumber REGEXP "^-?[0-9]+$"'
945 $sth->execute;
946 my ($result) = $sth->fetchrow;
947 return $result + 1;
949 return $cardnumber; # just here as a fallback/reminder
952 =head2 GetGuarantees
954 ($num_children, $children_arrayref) = &GetGuarantees($parent_borrno);
955 $child0_cardno = $children_arrayref->[0]{"cardnumber"};
956 $child0_borrno = $children_arrayref->[0]{"borrowernumber"};
958 C<&GetGuarantees> takes a borrower number (e.g., that of a patron
959 with children) and looks up the borrowers who are guaranteed by that
960 borrower (i.e., the patron's children).
962 C<&GetGuarantees> returns two values: an integer giving the number of
963 borrowers guaranteed by C<$parent_borrno>, and a reference to an array
964 of references to hash, which gives the actual results.
966 =cut
969 sub GetGuarantees {
970 my ($borrowernumber) = @_;
971 my $dbh = C4::Context->dbh;
972 my $sth =
973 $dbh->prepare(
974 "select cardnumber,borrowernumber, firstname, surname from borrowers where guarantorid=?"
976 $sth->execute($borrowernumber);
978 my @dat;
979 my $data = $sth->fetchall_arrayref({});
980 return ( scalar(@$data), $data );
983 =head2 UpdateGuarantees
985 &UpdateGuarantees($parent_borrno);
988 C<&UpdateGuarantees> borrower data for an adult and updates all the guarantees
989 with the modified information
991 =cut
994 sub UpdateGuarantees {
995 my %data = shift;
996 my $dbh = C4::Context->dbh;
997 my ( $count, $guarantees ) = GetGuarantees( $data{'borrowernumber'} );
998 foreach my $guarantee (@$guarantees){
999 my $guaquery = qq|UPDATE borrowers
1000 SET address=?,fax=?,B_city=?,mobile=?,city=?,phone=?
1001 WHERE borrowernumber=?
1003 my $sth = $dbh->prepare($guaquery);
1004 $sth->execute($data{'address'},$data{'fax'},$data{'B_city'},$data{'mobile'},$data{'city'},$data{'phone'},$guarantee->{'borrowernumber'});
1007 =head2 GetPendingIssues
1009 my $issues = &GetPendingIssues(@borrowernumber);
1011 Looks up what the patron with the given borrowernumber has borrowed.
1013 C<&GetPendingIssues> returns a
1014 reference-to-array where each element is a reference-to-hash; the
1015 keys are the fields from the C<issues>, C<biblio>, and C<items> tables.
1016 The keys include C<biblioitems> fields except marc and marcxml.
1018 =cut
1021 sub GetPendingIssues {
1022 my @borrowernumbers = @_;
1024 unless (@borrowernumbers ) { # return a ref_to_array
1025 return \@borrowernumbers; # to not cause surprise to caller
1028 # Borrowers part of the query
1029 my $bquery = '';
1030 for (my $i = 0; $i < @borrowernumbers; $i++) {
1031 $bquery .= ' issues.borrowernumber = ?';
1032 if ($i < $#borrowernumbers ) {
1033 $bquery .= ' OR';
1037 # must avoid biblioitems.* to prevent large marc and marcxml fields from killing performance
1038 # FIXME: namespace collision: each table has "timestamp" fields. Which one is "timestamp" ?
1039 # FIXME: circ/ciculation.pl tries to sort by timestamp!
1040 # FIXME: namespace collision: other collisions possible.
1041 # FIXME: most of this data isn't really being used by callers.
1042 my $query =
1043 "SELECT issues.*,
1044 items.*,
1045 biblio.*,
1046 biblioitems.volume,
1047 biblioitems.number,
1048 biblioitems.itemtype,
1049 biblioitems.isbn,
1050 biblioitems.issn,
1051 biblioitems.publicationyear,
1052 biblioitems.publishercode,
1053 biblioitems.volumedate,
1054 biblioitems.volumedesc,
1055 biblioitems.lccn,
1056 biblioitems.url,
1057 borrowers.firstname,
1058 borrowers.surname,
1059 borrowers.cardnumber,
1060 issues.timestamp AS timestamp,
1061 issues.renewals AS renewals,
1062 issues.borrowernumber AS borrowernumber,
1063 items.renewals AS totalrenewals
1064 FROM issues
1065 LEFT JOIN items ON items.itemnumber = issues.itemnumber
1066 LEFT JOIN biblio ON items.biblionumber = biblio.biblionumber
1067 LEFT JOIN biblioitems ON items.biblioitemnumber = biblioitems.biblioitemnumber
1068 LEFT JOIN borrowers ON issues.borrowernumber = borrowers.borrowernumber
1069 WHERE
1070 $bquery
1071 ORDER BY issues.issuedate"
1074 my $sth = C4::Context->dbh->prepare($query);
1075 $sth->execute(@borrowernumbers);
1076 my $data = $sth->fetchall_arrayref({});
1077 my $today = dt_from_string;
1078 foreach (@{$data}) {
1079 if ($_->{issuedate}) {
1080 $_->{issuedate} = dt_from_string($_->{issuedate}, 'sql');
1082 $_->{date_due_sql} = $_->{date_due};
1083 # FIXME no need to have this value
1084 $_->{date_due} or next;
1085 $_->{date_due_sql} = $_->{date_due};
1086 # FIXME no need to have this value
1087 $_->{date_due} = dt_from_string($_->{date_due}, 'sql');
1088 if ( DateTime->compare($_->{date_due}, $today) == -1 ) {
1089 $_->{overdue} = 1;
1092 return $data;
1095 =head2 GetAllIssues
1097 $issues = &GetAllIssues($borrowernumber, $sortkey, $limit);
1099 Looks up what the patron with the given borrowernumber has borrowed,
1100 and sorts the results.
1102 C<$sortkey> is the name of a field on which to sort the results. This
1103 should be the name of a field in the C<issues>, C<biblio>,
1104 C<biblioitems>, or C<items> table in the Koha database.
1106 C<$limit> is the maximum number of results to return.
1108 C<&GetAllIssues> an arrayref, C<$issues>, of hashrefs, the keys of which
1109 are the fields from the C<issues>, C<biblio>, C<biblioitems>, and
1110 C<items> tables of the Koha database.
1112 =cut
1115 sub GetAllIssues {
1116 my ( $borrowernumber, $order, $limit ) = @_;
1118 return unless $borrowernumber;
1119 $order = 'date_due desc' unless $order;
1121 my $dbh = C4::Context->dbh;
1122 my $query =
1123 'SELECT *, issues.timestamp as issuestimestamp, issues.renewals AS renewals,items.renewals AS totalrenewals,items.timestamp AS itemstimestamp
1124 FROM issues
1125 LEFT JOIN items on items.itemnumber=issues.itemnumber
1126 LEFT JOIN biblio ON items.biblionumber=biblio.biblionumber
1127 LEFT JOIN biblioitems ON items.biblioitemnumber=biblioitems.biblioitemnumber
1128 WHERE borrowernumber=?
1129 UNION ALL
1130 SELECT *, old_issues.timestamp as issuestimestamp, old_issues.renewals AS renewals,items.renewals AS totalrenewals,items.timestamp AS itemstimestamp
1131 FROM old_issues
1132 LEFT JOIN items on items.itemnumber=old_issues.itemnumber
1133 LEFT JOIN biblio ON items.biblionumber=biblio.biblionumber
1134 LEFT JOIN biblioitems ON items.biblioitemnumber=biblioitems.biblioitemnumber
1135 WHERE borrowernumber=? AND old_issues.itemnumber IS NOT NULL
1136 order by ' . $order;
1137 if ($limit) {
1138 $query .= " limit $limit";
1141 my $sth = $dbh->prepare($query);
1142 $sth->execute( $borrowernumber, $borrowernumber );
1143 return $sth->fetchall_arrayref( {} );
1147 =head2 GetMemberAccountRecords
1149 ($total, $acctlines, $count) = &GetMemberAccountRecords($borrowernumber);
1151 Looks up accounting data for the patron with the given borrowernumber.
1153 C<&GetMemberAccountRecords> returns a three-element array. C<$acctlines> is a
1154 reference-to-array, where each element is a reference-to-hash; the
1155 keys are the fields of the C<accountlines> table in the Koha database.
1156 C<$count> is the number of elements in C<$acctlines>. C<$total> is the
1157 total amount outstanding for all of the account lines.
1159 =cut
1161 sub GetMemberAccountRecords {
1162 my ($borrowernumber) = @_;
1163 my $dbh = C4::Context->dbh;
1164 my @acctlines;
1165 my $numlines = 0;
1166 my $strsth = qq(
1167 SELECT *
1168 FROM accountlines
1169 WHERE borrowernumber=?);
1170 $strsth.=" ORDER BY accountlines_id desc";
1171 my $sth= $dbh->prepare( $strsth );
1172 $sth->execute( $borrowernumber );
1174 my $total = 0;
1175 while ( my $data = $sth->fetchrow_hashref ) {
1176 if ( $data->{itemnumber} ) {
1177 my $biblio = GetBiblioFromItemNumber( $data->{itemnumber} );
1178 $data->{biblionumber} = $biblio->{biblionumber};
1179 $data->{title} = $biblio->{title};
1181 $acctlines[$numlines] = $data;
1182 $numlines++;
1183 $total += sprintf "%.0f", 1000*$data->{amountoutstanding}; # convert float to integer to avoid round-off errors
1185 $total /= 1000;
1186 return ( $total, \@acctlines,$numlines);
1189 =head2 GetMemberAccountBalance
1191 ($total_balance, $non_issue_balance, $other_charges) = &GetMemberAccountBalance($borrowernumber);
1193 Calculates amount immediately owing by the patron - non-issue charges.
1194 Based on GetMemberAccountRecords.
1195 Charges exempt from non-issue are:
1196 * Res (reserves)
1197 * Rent (rental) if RentalsInNoissuesCharge syspref is set to false
1198 * Manual invoices if ManInvInNoissuesCharge syspref is set to false
1200 =cut
1202 sub GetMemberAccountBalance {
1203 my ($borrowernumber) = @_;
1205 my $ACCOUNT_TYPE_LENGTH = 5; # this is plain ridiculous...
1207 my @not_fines;
1208 push @not_fines, 'Res' unless C4::Context->preference('HoldsInNoissuesCharge');
1209 push @not_fines, 'Rent' unless C4::Context->preference('RentalsInNoissuesCharge');
1210 unless ( C4::Context->preference('ManInvInNoissuesCharge') ) {
1211 my $dbh = C4::Context->dbh;
1212 my $man_inv_types = $dbh->selectcol_arrayref(qq{SELECT authorised_value FROM authorised_values WHERE category = 'MANUAL_INV'});
1213 push @not_fines, map substr($_, 0, $ACCOUNT_TYPE_LENGTH), @$man_inv_types;
1215 my %not_fine = map {$_ => 1} @not_fines;
1217 my ($total, $acctlines) = GetMemberAccountRecords($borrowernumber);
1218 my $other_charges = 0;
1219 foreach (@$acctlines) {
1220 $other_charges += $_->{amountoutstanding} if $not_fine{ substr($_->{accounttype}, 0, $ACCOUNT_TYPE_LENGTH) };
1223 return ( $total, $total - $other_charges, $other_charges);
1226 =head2 GetBorNotifyAcctRecord
1228 ($total, $acctlines, $count) = &GetBorNotifyAcctRecord($params,$notifyid);
1230 Looks up accounting data for the patron with the given borrowernumber per file number.
1232 C<&GetBorNotifyAcctRecord> returns a three-element array. C<$acctlines> is a
1233 reference-to-array, where each element is a reference-to-hash; the
1234 keys are the fields of the C<accountlines> table in the Koha database.
1235 C<$count> is the number of elements in C<$acctlines>. C<$total> is the
1236 total amount outstanding for all of the account lines.
1238 =cut
1240 sub GetBorNotifyAcctRecord {
1241 my ( $borrowernumber, $notifyid ) = @_;
1242 my $dbh = C4::Context->dbh;
1243 my @acctlines;
1244 my $numlines = 0;
1245 my $sth = $dbh->prepare(
1246 "SELECT *
1247 FROM accountlines
1248 WHERE borrowernumber=?
1249 AND notify_id=?
1250 AND amountoutstanding != '0'
1251 ORDER BY notify_id,accounttype
1254 $sth->execute( $borrowernumber, $notifyid );
1255 my $total = 0;
1256 while ( my $data = $sth->fetchrow_hashref ) {
1257 if ( $data->{itemnumber} ) {
1258 my $biblio = GetBiblioFromItemNumber( $data->{itemnumber} );
1259 $data->{biblionumber} = $biblio->{biblionumber};
1260 $data->{title} = $biblio->{title};
1262 $acctlines[$numlines] = $data;
1263 $numlines++;
1264 $total += int(100 * $data->{'amountoutstanding'});
1266 $total /= 100;
1267 return ( $total, \@acctlines, $numlines );
1270 =head2 checkuniquemember (OUEST-PROVENCE)
1272 ($result,$categorycode) = &checkuniquemember($collectivity,$surname,$firstname,$dateofbirth);
1274 Checks that a member exists or not in the database.
1276 C<&result> is nonzero (=exist) or 0 (=does not exist)
1277 C<&categorycode> is from categorycode table
1278 C<&collectivity> is 1 (= we add a collectivity) or 0 (= we add a physical member)
1279 C<&surname> is the surname
1280 C<&firstname> is the firstname (only if collectivity=0)
1281 C<&dateofbirth> is the date of birth in ISO format (only if collectivity=0)
1283 =cut
1285 # FIXME: This function is not legitimate. Multiple patrons might have the same first/last name and birthdate.
1286 # This is especially true since first name is not even a required field.
1288 sub checkuniquemember {
1289 my ( $collectivity, $surname, $firstname, $dateofbirth ) = @_;
1290 my $dbh = C4::Context->dbh;
1291 my $request = ($collectivity) ?
1292 "SELECT borrowernumber,categorycode FROM borrowers WHERE surname=? " :
1293 ($dateofbirth) ?
1294 "SELECT borrowernumber,categorycode FROM borrowers WHERE surname=? and firstname=? and dateofbirth=?" :
1295 "SELECT borrowernumber,categorycode FROM borrowers WHERE surname=? and firstname=?";
1296 my $sth = $dbh->prepare($request);
1297 if ($collectivity) {
1298 $sth->execute( uc($surname) );
1299 } elsif($dateofbirth){
1300 $sth->execute( uc($surname), ucfirst($firstname), $dateofbirth );
1301 }else{
1302 $sth->execute( uc($surname), ucfirst($firstname));
1304 my @data = $sth->fetchrow;
1305 ( $data[0] ) and return $data[0], $data[1];
1306 return 0;
1309 sub checkcardnumber {
1310 my ( $cardnumber, $borrowernumber ) = @_;
1312 # If cardnumber is null, we assume they're allowed.
1313 return 0 unless defined $cardnumber;
1315 my $dbh = C4::Context->dbh;
1316 my $query = "SELECT * FROM borrowers WHERE cardnumber=?";
1317 $query .= " AND borrowernumber <> ?" if ($borrowernumber);
1318 my $sth = $dbh->prepare($query);
1319 $sth->execute(
1320 $cardnumber,
1321 ( $borrowernumber ? $borrowernumber : () )
1324 return 1 if $sth->fetchrow_hashref;
1326 my ( $min_length, $max_length ) = get_cardnumber_length();
1327 return 2
1328 if length $cardnumber > $max_length
1329 or length $cardnumber < $min_length;
1331 return 0;
1334 =head2 get_cardnumber_length
1336 my ($min, $max) = C4::Members::get_cardnumber_length()
1338 Returns the minimum and maximum length for patron cardnumbers as
1339 determined by the CardnumberLength system preference, the
1340 BorrowerMandatoryField system preference, and the width of the
1341 database column.
1343 =cut
1345 sub get_cardnumber_length {
1346 my ( $min, $max ) = ( 0, 16 ); # borrowers.cardnumber is a nullable varchar(16)
1347 $min = 1 if C4::Context->preference('BorrowerMandatoryField') =~ /cardnumber/;
1348 if ( my $cardnumber_length = C4::Context->preference('CardnumberLength') ) {
1349 # Is integer and length match
1350 if ( $cardnumber_length =~ m|^\d+$| ) {
1351 $min = $max = $cardnumber_length
1352 if $cardnumber_length >= $min
1353 and $cardnumber_length <= $max;
1355 # Else assuming it is a range
1356 elsif ( $cardnumber_length =~ m|(\d*),(\d*)| ) {
1357 $min = $1 if $1 and $min < $1;
1358 $max = $2 if $2 and $max > $2;
1362 return ( $min, $max );
1365 =head2 getzipnamecity (OUEST-PROVENCE)
1367 take all info from table city for the fields city and zip
1368 check for the name and the zip code of the city selected
1370 =cut
1372 sub getzipnamecity {
1373 my ($cityid) = @_;
1374 my $dbh = C4::Context->dbh;
1375 my $sth =
1376 $dbh->prepare(
1377 "select city_name,city_state,city_zipcode,city_country from cities where cityid=? ");
1378 $sth->execute($cityid);
1379 my @data = $sth->fetchrow;
1380 return $data[0], $data[1], $data[2], $data[3];
1384 =head2 getdcity (OUEST-PROVENCE)
1386 recover cityid with city_name condition
1388 =cut
1390 sub getidcity {
1391 my ($city_name) = @_;
1392 my $dbh = C4::Context->dbh;
1393 my $sth = $dbh->prepare("select cityid from cities where city_name=? ");
1394 $sth->execute($city_name);
1395 my $data = $sth->fetchrow;
1396 return $data;
1399 =head2 GetFirstValidEmailAddress
1401 $email = GetFirstValidEmailAddress($borrowernumber);
1403 Return the first valid email address for a borrower, given the borrowernumber. For now, the order
1404 is defined as email, emailpro, B_email. Returns the empty string if the borrower has no email
1405 addresses.
1407 =cut
1409 sub GetFirstValidEmailAddress {
1410 my $borrowernumber = shift;
1411 my $dbh = C4::Context->dbh;
1412 my $sth = $dbh->prepare( "SELECT email, emailpro, B_email FROM borrowers where borrowernumber = ? ");
1413 $sth->execute( $borrowernumber );
1414 my $data = $sth->fetchrow_hashref;
1416 if ($data->{'email'}) {
1417 return $data->{'email'};
1418 } elsif ($data->{'emailpro'}) {
1419 return $data->{'emailpro'};
1420 } elsif ($data->{'B_email'}) {
1421 return $data->{'B_email'};
1422 } else {
1423 return '';
1427 =head2 GetNoticeEmailAddress
1429 $email = GetNoticeEmailAddress($borrowernumber);
1431 Return the email address of borrower used for notices, given the borrowernumber.
1432 Returns the empty string if no email address.
1434 =cut
1436 sub GetNoticeEmailAddress {
1437 my $borrowernumber = shift;
1439 my $which_address = C4::Context->preference("AutoEmailPrimaryAddress");
1440 # if syspref is set to 'first valid' (value == OFF), look up email address
1441 if ( $which_address eq 'OFF' ) {
1442 return GetFirstValidEmailAddress($borrowernumber);
1444 # specified email address field
1445 my $dbh = C4::Context->dbh;
1446 my $sth = $dbh->prepare( qq{
1447 SELECT $which_address AS primaryemail
1448 FROM borrowers
1449 WHERE borrowernumber=?
1450 } );
1451 $sth->execute($borrowernumber);
1452 my $data = $sth->fetchrow_hashref;
1453 return $data->{'primaryemail'} || '';
1456 =head2 GetExpiryDate
1458 $expirydate = GetExpiryDate($categorycode, $dateenrolled);
1460 Calculate expiry date given a categorycode and starting date. Date argument must be in ISO format.
1461 Return date is also in ISO format.
1463 =cut
1465 sub GetExpiryDate {
1466 my ( $categorycode, $dateenrolled ) = @_;
1467 my $enrolments;
1468 if ($categorycode) {
1469 my $dbh = C4::Context->dbh;
1470 my $sth = $dbh->prepare("SELECT enrolmentperiod,enrolmentperioddate FROM categories WHERE categorycode=?");
1471 $sth->execute($categorycode);
1472 $enrolments = $sth->fetchrow_hashref;
1474 # die "GetExpiryDate: for enrollmentperiod $enrolmentperiod (category '$categorycode') starting $dateenrolled.\n";
1475 my @date = split (/-/,$dateenrolled);
1476 if($enrolments->{enrolmentperiod}){
1477 return sprintf("%04d-%02d-%02d", Add_Delta_YM(@date,0,$enrolments->{enrolmentperiod}));
1478 }else{
1479 return $enrolments->{enrolmentperioddate};
1483 =head2 GetUpcomingMembershipExpires
1485 my $upcoming_mem_expires = GetUpcomingMembershipExpires();
1487 =cut
1489 sub GetUpcomingMembershipExpires {
1490 my $dbh = C4::Context->dbh;
1491 my $days = C4::Context->preference("MembershipExpiryDaysNotice") || 0;
1492 my $dateexpiry = output_pref({ dt => (dt_from_string()->add( days => $days)), dateformat => 'iso', dateonly => 1 });
1494 my $query = "
1495 SELECT borrowers.*, categories.description,
1496 branches.branchname, branches.branchemail FROM borrowers
1497 LEFT JOIN branches on borrowers.branchcode = branches.branchcode
1498 LEFT JOIN categories on borrowers.categorycode = categories.categorycode
1499 WHERE dateexpiry = ?;
1501 my $sth = $dbh->prepare($query);
1502 $sth->execute($dateexpiry);
1503 my $results = $sth->fetchall_arrayref({});
1504 return $results;
1507 =head2 GetborCatFromCatType
1509 ($codes_arrayref, $labels_hashref) = &GetborCatFromCatType();
1511 Looks up the different types of borrowers in the database. Returns two
1512 elements: a reference-to-array, which lists the borrower category
1513 codes, and a reference-to-hash, which maps the borrower category codes
1514 to category descriptions.
1516 =cut
1519 sub GetborCatFromCatType {
1520 my ( $category_type, $action, $no_branch_limit ) = @_;
1522 my $branch_limit = $no_branch_limit
1524 : C4::Context->userenv ? C4::Context->userenv->{"branch"} : "";
1526 # FIXME - This API seems both limited and dangerous.
1527 my $dbh = C4::Context->dbh;
1529 my $request = qq{
1530 SELECT categories.categorycode, categories.description
1531 FROM categories
1533 $request .= qq{
1534 LEFT JOIN categories_branches ON categories.categorycode = categories_branches.categorycode
1535 } if $branch_limit;
1536 if($action) {
1537 $request .= " $action ";
1538 $request .= " AND (branchcode = ? OR branchcode IS NULL) GROUP BY description" if $branch_limit;
1539 } else {
1540 $request .= " WHERE branchcode = ? OR branchcode IS NULL GROUP BY description" if $branch_limit;
1542 $request .= " ORDER BY categorycode";
1544 my $sth = $dbh->prepare($request);
1545 $sth->execute(
1546 $action ? $category_type : (),
1547 $branch_limit ? $branch_limit : ()
1550 my %labels;
1551 my @codes;
1553 while ( my $data = $sth->fetchrow_hashref ) {
1554 push @codes, $data->{'categorycode'};
1555 $labels{ $data->{'categorycode'} } = $data->{'description'};
1557 $sth->finish;
1558 return ( \@codes, \%labels );
1561 =head2 GetBorrowercategory
1563 $hashref = &GetBorrowercategory($categorycode);
1565 Given the borrower's category code, the function returns the corresponding
1566 data hashref for a comprehensive information display.
1568 =cut
1570 sub GetBorrowercategory {
1571 my ($catcode) = @_;
1572 my $dbh = C4::Context->dbh;
1573 if ($catcode){
1574 my $sth =
1575 $dbh->prepare(
1576 "SELECT description,dateofbirthrequired,upperagelimit,category_type
1577 FROM categories
1578 WHERE categorycode = ?"
1580 $sth->execute($catcode);
1581 my $data =
1582 $sth->fetchrow_hashref;
1583 return $data;
1585 return;
1586 } # sub getborrowercategory
1589 =head2 GetBorrowerCategorycode
1591 $categorycode = &GetBorrowerCategoryCode( $borrowernumber );
1593 Given the borrowernumber, the function returns the corresponding categorycode
1595 =cut
1597 sub GetBorrowerCategorycode {
1598 my ( $borrowernumber ) = @_;
1599 my $dbh = C4::Context->dbh;
1600 my $sth = $dbh->prepare( qq{
1601 SELECT categorycode
1602 FROM borrowers
1603 WHERE borrowernumber = ?
1604 } );
1605 $sth->execute( $borrowernumber );
1606 return $sth->fetchrow;
1609 =head2 GetBorrowercategoryList
1611 $arrayref_hashref = &GetBorrowercategoryList;
1612 If no category code provided, the function returns all the categories.
1614 =cut
1616 sub GetBorrowercategoryList {
1617 my $no_branch_limit = @_ ? shift : 0;
1618 my $branch_limit = $no_branch_limit
1620 : C4::Context->userenv ? C4::Context->userenv->{"branch"} : "";
1621 my $dbh = C4::Context->dbh;
1622 my $query = "SELECT categories.* FROM categories";
1623 $query .= qq{
1624 LEFT JOIN categories_branches ON categories.categorycode = categories_branches.categorycode
1625 WHERE branchcode = ? OR branchcode IS NULL GROUP BY description
1626 } if $branch_limit;
1627 $query .= " ORDER BY description";
1628 my $sth = $dbh->prepare( $query );
1629 $sth->execute( $branch_limit ? $branch_limit : () );
1630 my $data = $sth->fetchall_arrayref( {} );
1631 $sth->finish;
1632 return $data;
1633 } # sub getborrowercategory
1635 =head2 GetAge
1637 $dateofbirth,$date = &GetAge($date);
1639 this function return the borrowers age with the value of dateofbirth
1641 =cut
1644 sub GetAge{
1645 my ( $date, $date_ref ) = @_;
1647 if ( not defined $date_ref ) {
1648 $date_ref = sprintf( '%04d-%02d-%02d', Today() );
1651 my ( $year1, $month1, $day1 ) = split /-/, $date;
1652 my ( $year2, $month2, $day2 ) = split /-/, $date_ref;
1654 my $age = $year2 - $year1;
1655 if ( $month1 . $day1 > $month2 . $day2 ) {
1656 $age--;
1659 return $age;
1660 } # sub get_age
1662 =head2 SetAge
1664 $borrower = C4::Members::SetAge($borrower, $datetimeduration);
1665 $borrower = C4::Members::SetAge($borrower, '0015-12-10');
1666 $borrower = C4::Members::SetAge($borrower, $datetimeduration, $datetime_reference);
1668 eval { $borrower = C4::Members::SetAge($borrower, '015-1-10'); };
1669 if ($@) {print $@;} #Catch a bad ISO Date or kill your script!
1671 This function sets the borrower's dateofbirth to match the given age.
1672 Optionally relative to the given $datetime_reference.
1674 @PARAM1 koha.borrowers-object
1675 @PARAM2 DateTime::Duration-object as the desired age
1676 OR a ISO 8601 Date. (To make the API more pleasant)
1677 @PARAM3 DateTime-object as the relative date, defaults to now().
1678 RETURNS The given borrower reference @PARAM1.
1679 DIES If there was an error with the ISO Date handling.
1681 =cut
1684 sub SetAge{
1685 my ( $borrower, $datetimeduration, $datetime_ref ) = @_;
1686 $datetime_ref = DateTime->now() unless $datetime_ref;
1688 if ($datetimeduration && ref $datetimeduration ne 'DateTime::Duration') {
1689 if ($datetimeduration =~ /^(\d{4})-(\d{2})-(\d{2})/) {
1690 $datetimeduration = DateTime::Duration->new(years => $1, months => $2, days => $3);
1692 else {
1693 die "C4::Members::SetAge($borrower, $datetimeduration), datetimeduration not a valid ISO 8601 Date!\n";
1697 my $new_datetime_ref = $datetime_ref->clone();
1698 $new_datetime_ref->subtract_duration( $datetimeduration );
1700 $borrower->{dateofbirth} = $new_datetime_ref->ymd();
1702 return $borrower;
1703 } # sub SetAge
1705 =head2 GetCities
1707 $cityarrayref = GetCities();
1709 Returns an array_ref of the entries in the cities table
1710 If there are entries in the table an empty row is returned
1711 This is currently only used to populate a popup in memberentry
1713 =cut
1715 sub GetCities {
1717 my $dbh = C4::Context->dbh;
1718 my $city_arr = $dbh->selectall_arrayref(
1719 q|SELECT cityid,city_zipcode,city_name,city_state,city_country FROM cities ORDER BY city_name|,
1720 { Slice => {} });
1721 if ( @{$city_arr} ) {
1722 unshift @{$city_arr}, {
1723 city_zipcode => q{},
1724 city_name => q{},
1725 cityid => q{},
1726 city_state => q{},
1727 city_country => q{},
1731 return $city_arr;
1734 =head2 GetSortDetails (OUEST-PROVENCE)
1736 ($lib) = &GetSortDetails($category,$sortvalue);
1738 Returns the authorized value details
1739 C<&$lib>return value of authorized value details
1740 C<&$sortvalue>this is the value of authorized value
1741 C<&$category>this is the value of authorized value category
1743 =cut
1745 sub GetSortDetails {
1746 my ( $category, $sortvalue ) = @_;
1747 my $dbh = C4::Context->dbh;
1748 my $query = qq|SELECT lib
1749 FROM authorised_values
1750 WHERE category=?
1751 AND authorised_value=? |;
1752 my $sth = $dbh->prepare($query);
1753 $sth->execute( $category, $sortvalue );
1754 my $lib = $sth->fetchrow;
1755 return ($lib) if ($lib);
1756 return ($sortvalue) unless ($lib);
1759 =head2 MoveMemberToDeleted
1761 $result = &MoveMemberToDeleted($borrowernumber);
1763 Copy the record from borrowers to deletedborrowers table.
1764 The routine returns 1 for success, undef for failure.
1766 =cut
1768 sub MoveMemberToDeleted {
1769 my ($member) = shift or return;
1771 my $schema = Koha::Database->new()->schema();
1772 my $borrowers_rs = $schema->resultset('Borrower');
1773 $borrowers_rs->result_class('DBIx::Class::ResultClass::HashRefInflator');
1774 my $borrower = $borrowers_rs->find($member);
1775 return unless $borrower;
1777 my $deleted = $schema->resultset('Deletedborrower')->create($borrower);
1779 return $deleted ? 1 : undef;
1782 =head2 DelMember
1784 DelMember($borrowernumber);
1786 This function remove directly a borrower whitout writing it on deleteborrower.
1787 + Deletes reserves for the borrower
1789 =cut
1791 sub DelMember {
1792 my $dbh = C4::Context->dbh;
1793 my $borrowernumber = shift;
1794 #warn "in delmember with $borrowernumber";
1795 return unless $borrowernumber; # borrowernumber is mandatory.
1797 my $query = qq|DELETE
1798 FROM reserves
1799 WHERE borrowernumber=?|;
1800 my $sth = $dbh->prepare($query);
1801 $sth->execute($borrowernumber);
1802 $query = "
1803 DELETE
1804 FROM borrowers
1805 WHERE borrowernumber = ?
1807 $sth = $dbh->prepare($query);
1808 $sth->execute($borrowernumber);
1809 logaction("MEMBERS", "DELETE", $borrowernumber, "") if C4::Context->preference("BorrowersLog");
1810 return $sth->rows;
1813 =head2 HandleDelBorrower
1815 HandleDelBorrower($borrower);
1817 When a member is deleted (DelMember in Members.pm), you should call me first.
1818 This routine deletes/moves lists and entries for the deleted member/borrower.
1819 Lists owned by the borrower are deleted, but entries from the borrower to
1820 other lists are kept.
1822 =cut
1824 sub HandleDelBorrower {
1825 my ($borrower)= @_;
1826 my $query;
1827 my $dbh = C4::Context->dbh;
1829 #Delete all lists and all shares of this borrower
1830 #Consistent with the approach Koha uses on deleting individual lists
1831 #Note that entries in virtualshelfcontents added by this borrower to
1832 #lists of others will be handled by a table constraint: the borrower
1833 #is set to NULL in those entries.
1834 $query="DELETE FROM virtualshelves WHERE owner=?";
1835 $dbh->do($query,undef,($borrower));
1837 #NOTE:
1838 #We could handle the above deletes via a constraint too.
1839 #But a new BZ report 11889 has been opened to discuss another approach.
1840 #Instead of deleting we could also disown lists (based on a pref).
1841 #In that way we could save shared and public lists.
1842 #The current table constraints support that idea now.
1843 #This pref should then govern the results of other routines/methods such as
1844 #Koha::Virtualshelf->new->delete too.
1847 =head2 ExtendMemberSubscriptionTo (OUEST-PROVENCE)
1849 $date = ExtendMemberSubscriptionTo($borrowerid, $date);
1851 Extending the subscription to a given date or to the expiry date calculated on ISO date.
1852 Returns ISO date.
1854 =cut
1856 sub ExtendMemberSubscriptionTo {
1857 my ( $borrowerid,$date) = @_;
1858 my $dbh = C4::Context->dbh;
1859 my $borrower = GetMember('borrowernumber'=>$borrowerid);
1860 unless ($date){
1861 $date = (C4::Context->preference('BorrowerRenewalPeriodBase') eq 'dateexpiry') ?
1862 eval { output_pref( { dt => dt_from_string( $borrower->{'dateexpiry'} ), dateonly => 1, dateformat => 'iso' } ); }
1864 output_pref( { dt => dt_from_string, dateonly => 1, dateformat => 'iso' } );
1865 $date = GetExpiryDate( $borrower->{'categorycode'}, $date );
1867 my $sth = $dbh->do(<<EOF);
1868 UPDATE borrowers
1869 SET dateexpiry='$date'
1870 WHERE borrowernumber='$borrowerid'
1873 AddEnrolmentFeeIfNeeded( $borrower->{categorycode}, $borrower->{borrowernumber} );
1875 logaction("MEMBERS", "RENEW", $borrower->{'borrowernumber'}, "Membership renewed")if C4::Context->preference("BorrowersLog");
1876 return $date if ($sth);
1877 return 0;
1880 =head2 GetTitles (OUEST-PROVENCE)
1882 ($borrowertitle)= &GetTitles();
1884 Looks up the different title . Returns array with all borrowers title
1886 =cut
1888 sub GetTitles {
1889 my @borrowerTitle = split (/,|\|/,C4::Context->preference('BorrowersTitles'));
1890 unshift( @borrowerTitle, "" );
1891 my $count=@borrowerTitle;
1892 if ($count == 1){
1893 return ();
1895 else {
1896 return ( \@borrowerTitle);
1900 =head2 GetPatronImage
1902 my ($imagedata, $dberror) = GetPatronImage($borrowernumber);
1904 Returns the mimetype and binary image data of the image for the patron with the supplied borrowernumber.
1906 =cut
1908 sub GetPatronImage {
1909 my ($borrowernumber) = @_;
1910 warn "Borrowernumber passed to GetPatronImage is $borrowernumber" if $debug;
1911 my $dbh = C4::Context->dbh;
1912 my $query = 'SELECT mimetype, imagefile FROM patronimage WHERE borrowernumber = ?';
1913 my $sth = $dbh->prepare($query);
1914 $sth->execute($borrowernumber);
1915 my $imagedata = $sth->fetchrow_hashref;
1916 warn "Database error!" if $sth->errstr;
1917 return $imagedata, $sth->errstr;
1920 =head2 PutPatronImage
1922 PutPatronImage($cardnumber, $mimetype, $imgfile);
1924 Stores patron binary image data and mimetype in database.
1925 NOTE: This function is good for updating images as well as inserting new images in the database.
1927 =cut
1929 sub PutPatronImage {
1930 my ($cardnumber, $mimetype, $imgfile) = @_;
1931 warn "Parameters passed in: Cardnumber=$cardnumber, Mimetype=$mimetype, " . ($imgfile ? "Imagefile" : "No Imagefile") if $debug;
1932 my $dbh = C4::Context->dbh;
1933 my $query = "INSERT INTO patronimage (borrowernumber, mimetype, imagefile) VALUES ( ( SELECT borrowernumber from borrowers WHERE cardnumber = ? ),?,?) ON DUPLICATE KEY UPDATE imagefile = ?;";
1934 my $sth = $dbh->prepare($query);
1935 $sth->execute($cardnumber,$mimetype,$imgfile,$imgfile);
1936 warn "Error returned inserting $cardnumber.$mimetype." if $sth->errstr;
1937 return $sth->errstr;
1940 =head2 RmPatronImage
1942 my ($dberror) = RmPatronImage($borrowernumber);
1944 Removes the image for the patron with the supplied borrowernumber.
1946 =cut
1948 sub RmPatronImage {
1949 my ($borrowernumber) = @_;
1950 warn "Borrowernumber passed to GetPatronImage is $borrowernumber" if $debug;
1951 my $dbh = C4::Context->dbh;
1952 my $query = "DELETE FROM patronimage WHERE borrowernumber = ?;";
1953 my $sth = $dbh->prepare($query);
1954 $sth->execute($borrowernumber);
1955 my $dberror = $sth->errstr;
1956 warn "Database error!" if $sth->errstr;
1957 return $dberror;
1960 =head2 GetHideLostItemsPreference
1962 $hidelostitemspref = &GetHideLostItemsPreference($borrowernumber);
1964 Returns the HideLostItems preference for the patron category of the supplied borrowernumber
1965 C<&$hidelostitemspref>return value of function, 0 or 1
1967 =cut
1969 sub GetHideLostItemsPreference {
1970 my ($borrowernumber) = @_;
1971 my $dbh = C4::Context->dbh;
1972 my $query = "SELECT hidelostitems FROM borrowers,categories WHERE borrowers.categorycode = categories.categorycode AND borrowernumber = ?";
1973 my $sth = $dbh->prepare($query);
1974 $sth->execute($borrowernumber);
1975 my $hidelostitems = $sth->fetchrow;
1976 return $hidelostitems;
1979 =head2 GetBorrowersToExpunge
1981 $borrowers = &GetBorrowersToExpunge(
1982 not_borrowered_since => $not_borrowered_since,
1983 expired_before => $expired_before,
1984 category_code => $category_code,
1985 branchcode => $branchcode
1988 This function get all borrowers based on the given criteria.
1990 =cut
1992 sub GetBorrowersToExpunge {
1993 my $params = shift;
1995 my $filterdate = $params->{'not_borrowered_since'};
1996 my $filterexpiry = $params->{'expired_before'};
1997 my $filtercategory = $params->{'category_code'};
1998 my $filterbranch = $params->{'branchcode'} ||
1999 ((C4::Context->preference('IndependentBranches')
2000 && C4::Context->userenv
2001 && !C4::Context->IsSuperLibrarian()
2002 && C4::Context->userenv->{branch})
2003 ? C4::Context->userenv->{branch}
2004 : "");
2006 my $dbh = C4::Context->dbh;
2007 my $query = q|
2008 SELECT borrowers.borrowernumber,
2009 MAX(old_issues.timestamp) AS latestissue,
2010 MAX(issues.timestamp) AS currentissue
2011 FROM borrowers
2012 JOIN categories USING (categorycode)
2013 LEFT JOIN (
2014 SELECT guarantorid
2015 FROM borrowers
2016 WHERE guarantorid IS NOT NULL
2017 AND guarantorid <> 0
2018 ) as tmp ON borrowers.borrowernumber=tmp.guarantorid
2019 LEFT JOIN old_issues USING (borrowernumber)
2020 LEFT JOIN issues USING (borrowernumber)
2021 WHERE category_type <> 'S'
2022 AND tmp.guarantorid IS NULL
2025 my @query_params;
2026 if ( $filterbranch && $filterbranch ne "" ) {
2027 $query.= " AND borrowers.branchcode = ? ";
2028 push( @query_params, $filterbranch );
2030 if ( $filterexpiry ) {
2031 $query .= " AND dateexpiry < ? ";
2032 push( @query_params, $filterexpiry );
2034 if ( $filtercategory ) {
2035 $query .= " AND categorycode = ? ";
2036 push( @query_params, $filtercategory );
2038 $query.=" GROUP BY borrowers.borrowernumber HAVING currentissue IS NULL ";
2039 if ( $filterdate ) {
2040 $query.=" AND ( latestissue < ? OR latestissue IS NULL ) ";
2041 push @query_params,$filterdate;
2043 warn $query if $debug;
2045 my $sth = $dbh->prepare($query);
2046 if (scalar(@query_params)>0){
2047 $sth->execute(@query_params);
2049 else {
2050 $sth->execute;
2053 my @results;
2054 while ( my $data = $sth->fetchrow_hashref ) {
2055 push @results, $data;
2057 return \@results;
2060 =head2 GetBorrowersWhoHaveNeverBorrowed
2062 $results = &GetBorrowersWhoHaveNeverBorrowed
2064 This function get all borrowers who have never borrowed.
2066 I<$result> is a ref to an array which all elements are a hasref.
2068 =cut
2070 sub GetBorrowersWhoHaveNeverBorrowed {
2071 my $filterbranch = shift ||
2072 ((C4::Context->preference('IndependentBranches')
2073 && C4::Context->userenv
2074 && !C4::Context->IsSuperLibrarian()
2075 && C4::Context->userenv->{branch})
2076 ? C4::Context->userenv->{branch}
2077 : "");
2078 my $dbh = C4::Context->dbh;
2079 my $query = "
2080 SELECT borrowers.borrowernumber,max(timestamp) as latestissue
2081 FROM borrowers
2082 LEFT JOIN issues ON borrowers.borrowernumber = issues.borrowernumber
2083 WHERE issues.borrowernumber IS NULL
2085 my @query_params;
2086 if ($filterbranch && $filterbranch ne ""){
2087 $query.=" AND borrowers.branchcode= ?";
2088 push @query_params,$filterbranch;
2090 warn $query if $debug;
2092 my $sth = $dbh->prepare($query);
2093 if (scalar(@query_params)>0){
2094 $sth->execute(@query_params);
2096 else {
2097 $sth->execute;
2100 my @results;
2101 while ( my $data = $sth->fetchrow_hashref ) {
2102 push @results, $data;
2104 return \@results;
2107 =head2 GetBorrowersWithIssuesHistoryOlderThan
2109 $results = &GetBorrowersWithIssuesHistoryOlderThan($date)
2111 this function get all borrowers who has an issue history older than I<$date> given on input arg.
2113 I<$result> is a ref to an array which all elements are a hashref.
2114 This hashref is containt the number of time this borrowers has borrowed before I<$date> and the borrowernumber.
2116 =cut
2118 sub GetBorrowersWithIssuesHistoryOlderThan {
2119 my $dbh = C4::Context->dbh;
2120 my $date = shift ||POSIX::strftime("%Y-%m-%d",localtime());
2121 my $filterbranch = shift ||
2122 ((C4::Context->preference('IndependentBranches')
2123 && C4::Context->userenv
2124 && !C4::Context->IsSuperLibrarian()
2125 && C4::Context->userenv->{branch})
2126 ? C4::Context->userenv->{branch}
2127 : "");
2128 my $query = "
2129 SELECT count(borrowernumber) as n,borrowernumber
2130 FROM old_issues
2131 WHERE returndate < ?
2132 AND borrowernumber IS NOT NULL
2134 my @query_params;
2135 push @query_params, $date;
2136 if ($filterbranch){
2137 $query.=" AND branchcode = ?";
2138 push @query_params, $filterbranch;
2140 $query.=" GROUP BY borrowernumber ";
2141 warn $query if $debug;
2142 my $sth = $dbh->prepare($query);
2143 $sth->execute(@query_params);
2144 my @results;
2146 while ( my $data = $sth->fetchrow_hashref ) {
2147 push @results, $data;
2149 return \@results;
2152 =head2 GetBorrowersNamesAndLatestIssue
2154 $results = &GetBorrowersNamesAndLatestIssueList(@borrowernumbers)
2156 this function get borrowers Names and surnames and Issue information.
2158 I<@borrowernumbers> is an array which all elements are borrowernumbers.
2159 This hashref is containt the number of time this borrowers has borrowed before I<$date> and the borrowernumber.
2161 =cut
2163 sub GetBorrowersNamesAndLatestIssue {
2164 my $dbh = C4::Context->dbh;
2165 my @borrowernumbers=@_;
2166 my $query = "
2167 SELECT surname,lastname, phone, email,max(timestamp)
2168 FROM borrowers
2169 LEFT JOIN issues ON borrowers.borrowernumber=issues.borrowernumber
2170 GROUP BY borrowernumber
2172 my $sth = $dbh->prepare($query);
2173 $sth->execute;
2174 my $results = $sth->fetchall_arrayref({});
2175 return $results;
2178 =head2 ModPrivacy
2180 my $success = ModPrivacy( $borrowernumber, $privacy );
2182 Update the privacy of a patron.
2184 return :
2185 true on success, false on failure
2187 =cut
2189 sub ModPrivacy {
2190 my $borrowernumber = shift;
2191 my $privacy = shift;
2192 return unless defined $borrowernumber;
2193 return unless $borrowernumber =~ /^\d+$/;
2195 return ModMember( borrowernumber => $borrowernumber,
2196 privacy => $privacy );
2199 =head2 AddMessage
2201 AddMessage( $borrowernumber, $message_type, $message, $branchcode );
2203 Adds a message to the messages table for the given borrower.
2205 Returns:
2206 True on success
2207 False on failure
2209 =cut
2211 sub AddMessage {
2212 my ( $borrowernumber, $message_type, $message, $branchcode ) = @_;
2214 my $dbh = C4::Context->dbh;
2216 if ( ! ( $borrowernumber && $message_type && $message && $branchcode ) ) {
2217 return;
2220 my $query = "INSERT INTO messages ( borrowernumber, branchcode, message_type, message ) VALUES ( ?, ?, ?, ? )";
2221 my $sth = $dbh->prepare($query);
2222 $sth->execute( $borrowernumber, $branchcode, $message_type, $message );
2223 logaction("MEMBERS", "ADDCIRCMESSAGE", $borrowernumber, $message) if C4::Context->preference("BorrowersLog");
2224 return 1;
2227 =head2 GetMessages
2229 GetMessages( $borrowernumber, $type );
2231 $type is message type, B for borrower, or L for Librarian.
2232 Empty type returns all messages of any type.
2234 Returns all messages for the given borrowernumber
2236 =cut
2238 sub GetMessages {
2239 my ( $borrowernumber, $type, $branchcode ) = @_;
2241 if ( ! $type ) {
2242 $type = '%';
2245 my $dbh = C4::Context->dbh;
2247 my $query = "SELECT
2248 branches.branchname,
2249 messages.*,
2250 message_date,
2251 messages.branchcode LIKE '$branchcode' AS can_delete
2252 FROM messages, branches
2253 WHERE borrowernumber = ?
2254 AND message_type LIKE ?
2255 AND messages.branchcode = branches.branchcode
2256 ORDER BY message_date DESC";
2257 my $sth = $dbh->prepare($query);
2258 $sth->execute( $borrowernumber, $type ) ;
2259 my @results;
2261 while ( my $data = $sth->fetchrow_hashref ) {
2262 $data->{message_date_formatted} = output_pref( { dt => dt_from_string( $data->{message_date} ), dateonly => 1, dateformat => 'iso' } );
2263 push @results, $data;
2265 return \@results;
2269 =head2 GetMessages
2271 GetMessagesCount( $borrowernumber, $type );
2273 $type is message type, B for borrower, or L for Librarian.
2274 Empty type returns all messages of any type.
2276 Returns the number of messages for the given borrowernumber
2278 =cut
2280 sub GetMessagesCount {
2281 my ( $borrowernumber, $type, $branchcode ) = @_;
2283 if ( ! $type ) {
2284 $type = '%';
2287 my $dbh = C4::Context->dbh;
2289 my $query = "SELECT COUNT(*) as MsgCount FROM messages WHERE borrowernumber = ? AND message_type LIKE ?";
2290 my $sth = $dbh->prepare($query);
2291 $sth->execute( $borrowernumber, $type ) ;
2292 my @results;
2294 my $data = $sth->fetchrow_hashref;
2295 my $count = $data->{'MsgCount'};
2297 return $count;
2302 =head2 DeleteMessage
2304 DeleteMessage( $message_id );
2306 =cut
2308 sub DeleteMessage {
2309 my ( $message_id ) = @_;
2311 my $dbh = C4::Context->dbh;
2312 my $query = "SELECT * FROM messages WHERE message_id = ?";
2313 my $sth = $dbh->prepare($query);
2314 $sth->execute( $message_id );
2315 my $message = $sth->fetchrow_hashref();
2317 $query = "DELETE FROM messages WHERE message_id = ?";
2318 $sth = $dbh->prepare($query);
2319 $sth->execute( $message_id );
2320 logaction("MEMBERS", "DELCIRCMESSAGE", $message->{'borrowernumber'}, $message->{'message'}) if C4::Context->preference("BorrowersLog");
2323 =head2 IssueSlip
2325 IssueSlip($branchcode, $borrowernumber, $quickslip)
2327 Returns letter hash ( see C4::Letters::GetPreparedLetter )
2329 $quickslip is boolean, to indicate whether we want a quick slip
2331 IssueSlip populates ISSUESLIP and ISSUEQSLIP, and will make the following expansions:
2333 Both slips:
2335 <<branches.*>>
2336 <<borrowers.*>>
2338 ISSUESLIP:
2340 <checkedout>
2341 <<biblio.*>>
2342 <<items.*>>
2343 <<biblioitems.*>>
2344 <<issues.*>>
2345 </checkedout>
2347 <overdue>
2348 <<biblio.*>>
2349 <<items.*>>
2350 <<biblioitems.*>>
2351 <<issues.*>>
2352 </overdue>
2354 <news>
2355 <<opac_news.*>>
2356 </news>
2358 ISSUEQSLIP:
2360 <checkedout>
2361 <<biblio.*>>
2362 <<items.*>>
2363 <<biblioitems.*>>
2364 <<issues.*>>
2365 </checkedout>
2367 NOTE: Not all table fields are available, pleasee see GetPendingIssues for a list of available fields.
2369 =cut
2371 sub IssueSlip {
2372 my ($branch, $borrowernumber, $quickslip) = @_;
2374 # FIXME Check callers before removing this statement
2375 #return unless $borrowernumber;
2377 my @issues = @{ GetPendingIssues($borrowernumber) };
2379 for my $issue (@issues) {
2380 $issue->{date_due} = $issue->{date_due_sql};
2381 if ($quickslip) {
2382 my $today = output_pref({ dt => dt_from_string, dateformat => 'iso', dateonly => 1 });
2383 if ( substr( $issue->{issuedate}, 0, 10 ) eq $today
2384 or substr( $issue->{lastreneweddate}, 0, 10 ) eq $today ) {
2385 $issue->{now} = 1;
2390 # Sort on timestamp then on issuedate (useful for tests and could be if modified in a batch
2391 @issues = sort {
2392 my $s = $b->{timestamp} <=> $a->{timestamp};
2393 $s == 0 ?
2394 $b->{issuedate} <=> $a->{issuedate} : $s;
2395 } @issues;
2397 my ($letter_code, %repeat);
2398 if ( $quickslip ) {
2399 $letter_code = 'ISSUEQSLIP';
2400 %repeat = (
2401 'checkedout' => [ map {
2402 'biblio' => $_,
2403 'items' => $_,
2404 'biblioitems' => $_,
2405 'issues' => $_,
2406 }, grep { $_->{'now'} } @issues ],
2409 else {
2410 $letter_code = 'ISSUESLIP';
2411 %repeat = (
2412 'checkedout' => [ map {
2413 'biblio' => $_,
2414 'items' => $_,
2415 'biblioitems' => $_,
2416 'issues' => $_,
2417 }, grep { !$_->{'overdue'} } @issues ],
2419 'overdue' => [ map {
2420 'biblio' => $_,
2421 'items' => $_,
2422 'biblioitems' => $_,
2423 'issues' => $_,
2424 }, grep { $_->{'overdue'} } @issues ],
2426 'news' => [ map {
2427 $_->{'timestamp'} = $_->{'newdate'};
2428 { opac_news => $_ }
2429 } @{ GetNewsToDisplay("slip",$branch) } ],
2433 return C4::Letters::GetPreparedLetter (
2434 module => 'circulation',
2435 letter_code => $letter_code,
2436 branchcode => $branch,
2437 tables => {
2438 'branches' => $branch,
2439 'borrowers' => $borrowernumber,
2441 repeat => \%repeat,
2445 =head2 GetBorrowersWithEmail
2447 ([$borrnum,$userid], ...) = GetBorrowersWithEmail('me@example.com');
2449 This gets a list of users and their basic details from their email address.
2450 As it's possible for multiple user to have the same email address, it provides
2451 you with all of them. If there is no userid for the user, there will be an
2452 C<undef> there. An empty list will be returned if there are no matches.
2454 =cut
2456 sub GetBorrowersWithEmail {
2457 my $email = shift;
2459 my $dbh = C4::Context->dbh;
2461 my $query = "SELECT borrowernumber, userid FROM borrowers WHERE email=?";
2462 my $sth=$dbh->prepare($query);
2463 $sth->execute($email);
2464 my @result = ();
2465 while (my $ref = $sth->fetch) {
2466 push @result, $ref;
2468 die "Failure searching for borrowers by email address: $sth->errstr" if $sth->err;
2469 return @result;
2472 =head2 AddMember_Opac
2474 =cut
2476 sub AddMember_Opac {
2477 my ( %borrower ) = @_;
2479 $borrower{'categorycode'} = C4::Context->preference('PatronSelfRegistrationDefaultCategory');
2481 my $sr = new String::Random;
2482 $sr->{'A'} = [ 'A'..'Z', 'a'..'z' ];
2483 my $password = $sr->randpattern("AAAAAAAAAA");
2484 $borrower{'password'} = $password;
2486 $borrower{'cardnumber'} = fixup_cardnumber();
2488 my $borrowernumber = AddMember(%borrower);
2490 return ( $borrowernumber, $password );
2493 =head2 AddEnrolmentFeeIfNeeded
2495 AddEnrolmentFeeIfNeeded( $borrower->{categorycode}, $borrower->{borrowernumber} );
2497 Add enrolment fee for a patron if needed.
2499 =cut
2501 sub AddEnrolmentFeeIfNeeded {
2502 my ( $categorycode, $borrowernumber ) = @_;
2503 # check for enrollment fee & add it if needed
2504 my $dbh = C4::Context->dbh;
2505 my $sth = $dbh->prepare(q{
2506 SELECT enrolmentfee
2507 FROM categories
2508 WHERE categorycode=?
2510 $sth->execute( $categorycode );
2511 if ( $sth->err ) {
2512 warn sprintf('Database returned the following error: %s', $sth->errstr);
2513 return;
2515 my ($enrolmentfee) = $sth->fetchrow;
2516 if ($enrolmentfee && $enrolmentfee > 0) {
2517 # insert fee in patron debts
2518 C4::Accounts::manualinvoice( $borrowernumber, '', '', 'A', $enrolmentfee );
2522 =head2 HasOverdues
2524 =cut
2526 sub HasOverdues {
2527 my ( $borrowernumber ) = @_;
2529 my $sql = "SELECT COUNT(*) FROM issues WHERE date_due < NOW() AND borrowernumber = ?";
2530 my $sth = C4::Context->dbh->prepare( $sql );
2531 $sth->execute( $borrowernumber );
2532 my ( $count ) = $sth->fetchrow_array();
2534 return $count;
2537 =head2 DeleteExpiredOpacRegistrations
2539 Delete accounts that haven't been upgraded from the 'temporary' category
2540 Returns the number of removed patrons
2542 =cut
2544 sub DeleteExpiredOpacRegistrations {
2546 my $delay = C4::Context->preference('PatronSelfRegistrationExpireTemporaryAccountsDelay');
2547 my $category_code = C4::Context->preference('PatronSelfRegistrationDefaultCategory');
2549 return 0 if not $category_code or not defined $delay or $delay eq q||;
2551 my $query = qq|
2552 SELECT borrowernumber
2553 FROM borrowers
2554 WHERE categorycode = ? AND DATEDIFF( NOW(), dateenrolled ) > ? |;
2556 my $dbh = C4::Context->dbh;
2557 my $sth = $dbh->prepare($query);
2558 $sth->execute( $category_code, $delay );
2559 my $cnt=0;
2560 while ( my ($borrowernumber) = $sth->fetchrow_array() ) {
2561 DelMember($borrowernumber);
2562 $cnt++;
2564 return $cnt;
2567 =head2 DeleteUnverifiedOpacRegistrations
2569 Delete all unverified self registrations in borrower_modifications,
2570 older than the specified number of days.
2572 =cut
2574 sub DeleteUnverifiedOpacRegistrations {
2575 my ( $days ) = @_;
2576 my $dbh = C4::Context->dbh;
2577 my $sql=qq|
2578 DELETE FROM borrower_modifications
2579 WHERE borrowernumber = 0 AND DATEDIFF( NOW(), timestamp ) > ?|;
2580 my $cnt=$dbh->do($sql, undef, ($days) );
2581 return $cnt eq '0E0'? 0: $cnt;
2584 sub GetOverduesForPatron {
2585 my ( $borrowernumber ) = @_;
2587 my $sql = "
2588 SELECT *
2589 FROM issues, items, biblio, biblioitems
2590 WHERE items.itemnumber=issues.itemnumber
2591 AND biblio.biblionumber = items.biblionumber
2592 AND biblio.biblionumber = biblioitems.biblionumber
2593 AND issues.borrowernumber = ?
2594 AND date_due < NOW()
2597 my $sth = C4::Context->dbh->prepare( $sql );
2598 $sth->execute( $borrowernumber );
2600 return $sth->fetchall_arrayref({});
2603 END { } # module clean-up code here (global destructor)
2607 __END__
2609 =head1 AUTHOR
2611 Koha Team
2613 =cut