Bug 14252: (followup) fix lang chooser for sublanguages
[koha.git] / C4 / Members.pm
blob1a172dbffd91fc6e441678659179eec7bcea41f8
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 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::Members::Attributes qw(SearchIdMatchingAttribute UpdateBorrowerAttribute);
36 use C4::NewsChannels; #get slip news
37 use DateTime;
38 use Koha::Database;
39 use Koha::DateUtils;
40 use Koha::Borrower::Debarments qw(IsDebarred);
41 use Text::Unaccent qw( unac_string );
42 use Koha::AuthUtils qw(hash_password);
43 use Koha::Database;
44 use Module::Load;
45 if ( C4::Context->preference('NorwegianPatronDBEnable') && C4::Context->preference('NorwegianPatronDBEnable') == 1 ) {
46 load Koha::NorwegianPatronDB, qw( NLUpdateHashedPIN NLEncryptPIN NLSync );
49 our ($VERSION,@ISA,@EXPORT,@EXPORT_OK,$debug);
51 BEGIN {
52 $VERSION = 3.07.00.049;
53 $debug = $ENV{DEBUG} || 0;
54 require Exporter;
55 @ISA = qw(Exporter);
56 #Get data
57 push @EXPORT, qw(
58 &Search
59 &GetMemberDetails
60 &GetMemberRelatives
61 &GetMember
63 &GetGuarantees
65 &GetMemberIssuesAndFines
66 &GetPendingIssues
67 &GetAllIssues
69 &getzipnamecity
70 &getidcity
72 &GetFirstValidEmailAddress
73 &GetNoticeEmailAddress
75 &GetAge
76 &GetCities
77 &GetSortDetails
78 &GetTitles
80 &GetPatronImage
81 &PutPatronImage
82 &RmPatronImage
84 &GetHideLostItemsPreference
86 &IsMemberBlocked
87 &GetMemberAccountRecords
88 &GetBorNotifyAcctRecord
90 &GetborCatFromCatType
91 &GetBorrowercategory
92 GetBorrowerCategorycode
93 &GetBorrowercategoryList
95 &GetBorrowersToExpunge
96 &GetBorrowersWhoHaveNeverBorrowed
97 &GetBorrowersWithIssuesHistoryOlderThan
99 &GetExpiryDate
101 &AddMessage
102 &DeleteMessage
103 &GetMessages
104 &GetMessagesCount
106 &IssueSlip
107 GetBorrowersWithEmail
109 HasOverdues
112 #Modify data
113 push @EXPORT, qw(
114 &ModMember
115 &changepassword
116 &ModPrivacy
119 #Delete data
120 push @EXPORT, qw(
121 &DelMember
124 #Insert data
125 push @EXPORT, qw(
126 &AddMember
127 &AddMember_Opac
128 &MoveMemberToDeleted
129 &ExtendMemberSubscriptionTo
132 #Check data
133 push @EXPORT, qw(
134 &checkuniquemember
135 &checkuserpassword
136 &Check_Userid
137 &Generate_Userid
138 &fixEthnicity
139 &ethnicitycategories
140 &fixup_cardnumber
141 &checkcardnumber
145 =head1 NAME
147 C4::Members - Perl Module containing convenience functions for member handling
149 =head1 SYNOPSIS
151 use C4::Members;
153 =head1 DESCRIPTION
155 This module contains routines for adding, modifying and deleting members/patrons/borrowers
157 =head1 FUNCTIONS
159 =head2 GetMemberDetails
161 ($borrower) = &GetMemberDetails($borrowernumber, $cardnumber);
163 Looks up a patron and returns information about him or her. If
164 C<$borrowernumber> is true (nonzero), C<&GetMemberDetails> looks
165 up the borrower by number; otherwise, it looks up the borrower by card
166 number.
168 C<$borrower> is a reference-to-hash whose keys are the fields of the
169 borrowers table in the Koha database. In addition,
170 C<$borrower-E<gt>{flags}> is a hash giving more detailed information
171 about the patron. Its keys act as flags :
173 if $borrower->{flags}->{LOST} {
174 # Patron's card was reported lost
177 If the state of a flag means that the patron should not be
178 allowed to borrow any more books, then it will have a C<noissues> key
179 with a true value.
181 See patronflags for more details.
183 C<$borrower-E<gt>{authflags}> is a hash giving more detailed information
184 about the top-level permissions flags set for the borrower. For example,
185 if a user has the "editcatalogue" permission,
186 C<$borrower-E<gt>{authflags}-E<gt>{editcatalogue}> will exist and have
187 the value "1".
189 =cut
191 sub GetMemberDetails {
192 my ( $borrowernumber, $cardnumber ) = @_;
193 my $dbh = C4::Context->dbh;
194 my $query;
195 my $sth;
196 if ($borrowernumber) {
197 $sth = $dbh->prepare("
198 SELECT borrowers.*,
199 category_type,
200 categories.description,
201 categories.BlockExpiredPatronOpacActions,
202 reservefee,
203 enrolmentperiod
204 FROM borrowers
205 LEFT JOIN categories ON borrowers.categorycode=categories.categorycode
206 WHERE borrowernumber = ?
208 $sth->execute($borrowernumber);
210 elsif ($cardnumber) {
211 $sth = $dbh->prepare("
212 SELECT borrowers.*,
213 category_type,
214 categories.description,
215 categories.BlockExpiredPatronOpacActions,
216 reservefee,
217 enrolmentperiod
218 FROM borrowers
219 LEFT JOIN categories ON borrowers.categorycode = categories.categorycode
220 WHERE cardnumber = ?
222 $sth->execute($cardnumber);
224 else {
225 return;
227 my $borrower = $sth->fetchrow_hashref;
228 return unless $borrower;
229 my ($amount) = GetMemberAccountRecords($borrower->{borrowernumber});
230 $borrower->{'amountoutstanding'} = $amount;
231 # FIXME - patronflags calls GetMemberAccountRecords... just have patronflags return $amount
232 my $flags = patronflags( $borrower);
233 my $accessflagshash;
235 $sth = $dbh->prepare("select bit,flag from userflags");
236 $sth->execute;
237 while ( my ( $bit, $flag ) = $sth->fetchrow ) {
238 if ( $borrower->{'flags'} && $borrower->{'flags'} & 2**$bit ) {
239 $accessflagshash->{$flag} = 1;
242 $borrower->{'flags'} = $flags;
243 $borrower->{'authflags'} = $accessflagshash;
245 # For the purposes of making templates easier, we'll define a
246 # 'showname' which is the alternate form the user's first name if
247 # 'other name' is defined.
248 if ($borrower->{category_type} eq 'I') {
249 $borrower->{'showname'} = $borrower->{'othernames'};
250 $borrower->{'showname'} .= " $borrower->{'firstname'}" if $borrower->{'firstname'};
251 } else {
252 $borrower->{'showname'} = $borrower->{'firstname'};
255 # Handle setting the true behavior for BlockExpiredPatronOpacActions
256 $borrower->{'BlockExpiredPatronOpacActions'} =
257 C4::Context->preference('BlockExpiredPatronOpacActions')
258 if ( $borrower->{'BlockExpiredPatronOpacActions'} == -1 );
260 $borrower->{'is_expired'} = 0;
261 $borrower->{'is_expired'} = 1 if
262 defined($borrower->{dateexpiry}) &&
263 $borrower->{'dateexpiry'} ne '0000-00-00' &&
264 Date_to_Days( Today() ) >
265 Date_to_Days( split /-/, $borrower->{'dateexpiry'} );
267 return ($borrower); #, $flags, $accessflagshash);
270 =head2 patronflags
272 $flags = &patronflags($patron);
274 This function is not exported.
276 The following will be set where applicable:
277 $flags->{CHARGES}->{amount} Amount of debt
278 $flags->{CHARGES}->{noissues} Set if debt amount >$5.00 (or syspref noissuescharge)
279 $flags->{CHARGES}->{message} Message -- deprecated
281 $flags->{CREDITS}->{amount} Amount of credit
282 $flags->{CREDITS}->{message} Message -- deprecated
284 $flags->{ GNA } Patron has no valid address
285 $flags->{ GNA }->{noissues} Set for each GNA
286 $flags->{ GNA }->{message} "Borrower has no valid address" -- deprecated
288 $flags->{ LOST } Patron's card reported lost
289 $flags->{ LOST }->{noissues} Set for each LOST
290 $flags->{ LOST }->{message} Message -- deprecated
292 $flags->{DBARRED} Set if patron debarred, no access
293 $flags->{DBARRED}->{noissues} Set for each DBARRED
294 $flags->{DBARRED}->{message} Message -- deprecated
296 $flags->{ NOTES }
297 $flags->{ NOTES }->{message} The note itself. NOT deprecated
299 $flags->{ ODUES } Set if patron has overdue books.
300 $flags->{ ODUES }->{message} "Yes" -- deprecated
301 $flags->{ ODUES }->{itemlist} ref-to-array: list of overdue books
302 $flags->{ ODUES }->{itemlisttext} Text list of overdue items -- deprecated
304 $flags->{WAITING} Set if any of patron's reserves are available
305 $flags->{WAITING}->{message} Message -- deprecated
306 $flags->{WAITING}->{itemlist} ref-to-array: list of available items
308 =over
310 =item C<$flags-E<gt>{ODUES}-E<gt>{itemlist}> is a reference-to-array listing the
311 overdue items. Its elements are references-to-hash, each describing an
312 overdue item. The keys are selected fields from the issues, biblio,
313 biblioitems, and items tables of the Koha database.
315 =item C<$flags-E<gt>{ODUES}-E<gt>{itemlisttext}> is a string giving a text listing of
316 the overdue items, one per line. Deprecated.
318 =item C<$flags-E<gt>{WAITING}-E<gt>{itemlist}> is a reference-to-array listing the
319 available items. Each element is a reference-to-hash whose keys are
320 fields from the reserves table of the Koha database.
322 =back
324 All the "message" fields that include language generated in this function are deprecated,
325 because such strings belong properly in the display layer.
327 The "message" field that comes from the DB is OK.
329 =cut
331 # TODO: use {anonymous => hashes} instead of a dozen %flaginfo
332 # FIXME rename this function.
333 sub patronflags {
334 my %flags;
335 my ( $patroninformation) = @_;
336 my $dbh=C4::Context->dbh;
337 my ($balance, $owing) = GetMemberAccountBalance( $patroninformation->{'borrowernumber'});
338 if ( $owing > 0 ) {
339 my %flaginfo;
340 my $noissuescharge = C4::Context->preference("noissuescharge") || 5;
341 $flaginfo{'message'} = sprintf 'Patron owes %.02f', $owing;
342 $flaginfo{'amount'} = sprintf "%.02f", $owing;
343 if ( $owing > $noissuescharge && !C4::Context->preference("AllowFineOverride") ) {
344 $flaginfo{'noissues'} = 1;
346 $flags{'CHARGES'} = \%flaginfo;
348 elsif ( $balance < 0 ) {
349 my %flaginfo;
350 $flaginfo{'message'} = sprintf 'Patron has credit of %.02f', -$balance;
351 $flaginfo{'amount'} = sprintf "%.02f", $balance;
352 $flags{'CREDITS'} = \%flaginfo;
354 if ( $patroninformation->{'gonenoaddress'}
355 && $patroninformation->{'gonenoaddress'} == 1 )
357 my %flaginfo;
358 $flaginfo{'message'} = 'Borrower has no valid address.';
359 $flaginfo{'noissues'} = 1;
360 $flags{'GNA'} = \%flaginfo;
362 if ( $patroninformation->{'lost'} && $patroninformation->{'lost'} == 1 ) {
363 my %flaginfo;
364 $flaginfo{'message'} = 'Borrower\'s card reported lost.';
365 $flaginfo{'noissues'} = 1;
366 $flags{'LOST'} = \%flaginfo;
368 if ( $patroninformation->{'debarred'} && check_date( split( /-/, $patroninformation->{'debarred'} ) ) ) {
369 if ( Date_to_Days(Date::Calc::Today) < Date_to_Days( split( /-/, $patroninformation->{'debarred'} ) ) ) {
370 my %flaginfo;
371 $flaginfo{'debarredcomment'} = $patroninformation->{'debarredcomment'};
372 $flaginfo{'message'} = $patroninformation->{'debarredcomment'};
373 $flaginfo{'noissues'} = 1;
374 $flaginfo{'dateend'} = $patroninformation->{'debarred'};
375 $flags{'DBARRED'} = \%flaginfo;
378 if ( $patroninformation->{'borrowernotes'}
379 && $patroninformation->{'borrowernotes'} )
381 my %flaginfo;
382 $flaginfo{'message'} = $patroninformation->{'borrowernotes'};
383 $flags{'NOTES'} = \%flaginfo;
385 my ( $odues, $itemsoverdue ) = C4::Overdues::checkoverdues($patroninformation->{'borrowernumber'});
386 if ( $odues && $odues > 0 ) {
387 my %flaginfo;
388 $flaginfo{'message'} = "Yes";
389 $flaginfo{'itemlist'} = $itemsoverdue;
390 foreach ( sort { $a->{'date_due'} cmp $b->{'date_due'} }
391 @$itemsoverdue )
393 $flaginfo{'itemlisttext'} .=
394 "$_->{'date_due'} $_->{'barcode'} $_->{'title'} \n"; # newline is display layer
396 $flags{'ODUES'} = \%flaginfo;
398 my @itemswaiting = C4::Reserves::GetReservesFromBorrowernumber( $patroninformation->{'borrowernumber'},'W' );
399 my $nowaiting = scalar @itemswaiting;
400 if ( $nowaiting > 0 ) {
401 my %flaginfo;
402 $flaginfo{'message'} = "Reserved items available";
403 $flaginfo{'itemlist'} = \@itemswaiting;
404 $flags{'WAITING'} = \%flaginfo;
406 return ( \%flags );
410 =head2 GetMember
412 $borrower = &GetMember(%information);
414 Retrieve the first patron record meeting on criteria listed in the
415 C<%information> hash, which should contain one or more
416 pairs of borrowers column names and values, e.g.,
418 $borrower = GetMember(borrowernumber => id);
420 C<&GetBorrower> returns a reference-to-hash whose keys are the fields of
421 the C<borrowers> table in the Koha database.
423 FIXME: GetMember() is used throughout the code as a lookup
424 on a unique key such as the borrowernumber, but this meaning is not
425 enforced in the routine itself.
427 =cut
430 sub GetMember {
431 my ( %information ) = @_;
432 if (exists $information{borrowernumber} && !defined $information{borrowernumber}) {
433 #passing mysql's kohaadmin?? Makes no sense as a query
434 return;
436 my $dbh = C4::Context->dbh;
437 my $select =
438 q{SELECT borrowers.*, categories.category_type, categories.description
439 FROM borrowers
440 LEFT JOIN categories on borrowers.categorycode=categories.categorycode WHERE };
441 my $more_p = 0;
442 my @values = ();
443 for (keys %information ) {
444 if ($more_p) {
445 $select .= ' AND ';
447 else {
448 $more_p++;
451 if (defined $information{$_}) {
452 $select .= "$_ = ?";
453 push @values, $information{$_};
455 else {
456 $select .= "$_ IS NULL";
459 $debug && warn $select, " ",values %information;
460 my $sth = $dbh->prepare("$select");
461 $sth->execute(map{$information{$_}} keys %information);
462 my $data = $sth->fetchall_arrayref({});
463 #FIXME interface to this routine now allows generation of a result set
464 #so whole array should be returned but bowhere in the current code expects this
465 if (@{$data} ) {
466 return $data->[0];
469 return;
472 =head2 GetMemberRelatives
474 @borrowernumbers = GetMemberRelatives($borrowernumber);
476 C<GetMemberRelatives> returns a borrowersnumber's list of guarantor/guarantees of the member given in parameter
478 =cut
480 sub GetMemberRelatives {
481 my $borrowernumber = shift;
482 my $dbh = C4::Context->dbh;
483 my @glist;
485 # Getting guarantor
486 my $query = "SELECT guarantorid FROM borrowers WHERE borrowernumber=?";
487 my $sth = $dbh->prepare($query);
488 $sth->execute($borrowernumber);
489 my $data = $sth->fetchrow_arrayref();
490 push @glist, $data->[0] if $data->[0];
491 my $guarantor = $data->[0] ? $data->[0] : undef;
493 # Getting guarantees
494 $query = "SELECT borrowernumber FROM borrowers WHERE guarantorid=?";
495 $sth = $dbh->prepare($query);
496 $sth->execute($borrowernumber);
497 while ($data = $sth->fetchrow_arrayref()) {
498 push @glist, $data->[0];
501 # Getting sibling guarantees
502 if ($guarantor) {
503 $query = "SELECT borrowernumber FROM borrowers WHERE guarantorid=?";
504 $sth = $dbh->prepare($query);
505 $sth->execute($guarantor);
506 while ($data = $sth->fetchrow_arrayref()) {
507 push @glist, $data->[0] if ($data->[0] != $borrowernumber);
511 return @glist;
514 =head2 IsMemberBlocked
516 my ($block_status, $count) = IsMemberBlocked( $borrowernumber );
518 Returns whether a patron is restricted or has overdue items that may result
519 in a block of circulation privileges.
521 C<$block_status> can have the following values:
523 1 if the patron is currently restricted, in which case
524 C<$count> is the expiration date (9999-12-31 for indefinite)
526 -1 if the patron has overdue items, in which case C<$count> is the number of them
528 0 if the patron has no overdue items or outstanding fine days, in which case C<$count> is 0
530 Existing active restrictions are checked before current overdue items.
532 =cut
534 sub IsMemberBlocked {
535 my $borrowernumber = shift;
536 my $dbh = C4::Context->dbh;
538 my $blockeddate = Koha::Borrower::Debarments::IsDebarred($borrowernumber);
540 return ( 1, $blockeddate ) if $blockeddate;
542 # if he have late issues
543 my $sth = $dbh->prepare(
544 "SELECT COUNT(*) as latedocs
545 FROM issues
546 WHERE borrowernumber = ?
547 AND date_due < now()"
549 $sth->execute($borrowernumber);
550 my $latedocs = $sth->fetchrow_hashref->{'latedocs'};
552 return ( -1, $latedocs ) if $latedocs > 0;
554 return ( 0, 0 );
557 =head2 GetMemberIssuesAndFines
559 ($overdue_count, $issue_count, $total_fines) = &GetMemberIssuesAndFines($borrowernumber);
561 Returns aggregate data about items borrowed by the patron with the
562 given borrowernumber.
564 C<&GetMemberIssuesAndFines> returns a three-element array. C<$overdue_count> is the
565 number of overdue items the patron currently has borrowed. C<$issue_count> is the
566 number of books the patron currently has borrowed. C<$total_fines> is
567 the total fine currently due by the borrower.
569 =cut
572 sub GetMemberIssuesAndFines {
573 my ( $borrowernumber ) = @_;
574 my $dbh = C4::Context->dbh;
575 my $query = "SELECT COUNT(*) FROM issues WHERE borrowernumber = ?";
577 $debug and warn $query."\n";
578 my $sth = $dbh->prepare($query);
579 $sth->execute($borrowernumber);
580 my $issue_count = $sth->fetchrow_arrayref->[0];
582 $sth = $dbh->prepare(
583 "SELECT COUNT(*) FROM issues
584 WHERE borrowernumber = ?
585 AND date_due < now()"
587 $sth->execute($borrowernumber);
588 my $overdue_count = $sth->fetchrow_arrayref->[0];
590 $sth = $dbh->prepare("SELECT SUM(amountoutstanding) FROM accountlines WHERE borrowernumber = ?");
591 $sth->execute($borrowernumber);
592 my $total_fines = $sth->fetchrow_arrayref->[0];
594 return ($overdue_count, $issue_count, $total_fines);
598 =head2 columns
600 my @columns = C4::Member::columns();
602 Returns an array of borrowers' table columns on success,
603 and an empty array on failure.
605 =cut
607 sub columns {
609 # Pure ANSI SQL goodness.
610 my $sql = 'SELECT * FROM borrowers WHERE 1=0;';
612 # Get the database handle.
613 my $dbh = C4::Context->dbh;
615 # Run the SQL statement to load STH's readonly properties.
616 my $sth = $dbh->prepare($sql);
617 my $rv = $sth->execute();
619 # This only fails if the table doesn't exist.
620 # This will always be called AFTER an install or upgrade,
621 # so borrowers will exist!
622 my @data;
623 if ($sth->{NUM_OF_FIELDS}>0) {
624 @data = @{$sth->{NAME}};
626 else {
627 @data = ();
629 return @data;
633 =head2 ModMember
635 my $success = ModMember(borrowernumber => $borrowernumber,
636 [ field => value ]... );
638 Modify borrower's data. All date fields should ALREADY be in ISO format.
640 return :
641 true on success, or false on failure
643 =cut
645 sub ModMember {
646 my (%data) = @_;
647 # test to know if you must update or not the borrower password
648 if (exists $data{password}) {
649 if ($data{password} eq '****' or $data{password} eq '') {
650 delete $data{password};
651 } else {
652 if ( C4::Context->preference('NorwegianPatronDBEnable') && C4::Context->preference('NorwegianPatronDBEnable') == 1 ) {
653 # Update the hashed PIN in borrower_sync.hashed_pin, before Koha hashes it
654 NLUpdateHashedPIN( $data{'borrowernumber'}, $data{password} );
656 $data{password} = hash_password($data{password});
659 my $old_categorycode = GetBorrowerCategorycode( $data{borrowernumber} );
661 # get only the columns of a borrower
662 my $schema = Koha::Database->new()->schema;
663 my @columns = $schema->source('Borrower')->columns;
664 my $new_borrower = { map { join(' ', @columns) =~ /$_/ ? ( $_ => $data{$_} ) : () } keys(%data) };
665 delete $new_borrower->{flags};
667 $new_borrower->{dateofbirth} ||= undef if exists $new_borrower->{dateofbirth};
668 $new_borrower->{dateenrolled} ||= undef if exists $new_borrower->{dateenrolled};
669 $new_borrower->{dateexpiry} ||= undef if exists $new_borrower->{dateexpiry};
670 my $rs = $schema->resultset('Borrower')->search({
671 borrowernumber => $new_borrower->{borrowernumber},
673 my $execute_success = $rs->update($new_borrower);
674 if ($execute_success ne '0E0') { # only proceed if the update was a success
675 # ok if its an adult (type) it may have borrowers that depend on it as a guarantor
676 # so when we update information for an adult we should check for guarantees and update the relevant part
677 # of their records, ie addresses and phone numbers
678 my $borrowercategory= GetBorrowercategory( $data{'category_type'} );
679 if ( exists $borrowercategory->{'category_type'} && $borrowercategory->{'category_type'} eq ('A' || 'S') ) {
680 # is adult check guarantees;
681 UpdateGuarantees(%data);
684 # If the patron changes to a category with enrollment fee, we add a fee
685 if ( $data{categorycode} and $data{categorycode} ne $old_categorycode ) {
686 AddEnrolmentFeeIfNeeded( $data{categorycode}, $data{borrowernumber} );
689 # If NorwegianPatronDBEnable is enabled, we set syncstatus to something that a
690 # cronjob will use for syncing with NL
691 if ( C4::Context->preference('NorwegianPatronDBEnable') && C4::Context->preference('NorwegianPatronDBEnable') == 1 ) {
692 my $borrowersync = Koha::Database->new->schema->resultset('BorrowerSync')->find({
693 'synctype' => 'norwegianpatrondb',
694 'borrowernumber' => $data{'borrowernumber'}
696 # Do not set to "edited" if syncstatus is "new". We need to sync as new before
697 # we can sync as changed. And the "new sync" will pick up all changes since
698 # the patron was created anyway.
699 if ( $borrowersync->syncstatus ne 'new' && $borrowersync->syncstatus ne 'delete' ) {
700 $borrowersync->update( { 'syncstatus' => 'edited' } );
702 # Set the value of 'sync'
703 $borrowersync->update( { 'sync' => $data{'sync'} } );
704 # Try to do the live sync
705 NLSync({ 'borrowernumber' => $data{'borrowernumber'} });
708 logaction("MEMBERS", "MODIFY", $data{'borrowernumber'}, "UPDATE (executed w/ arg: $data{'borrowernumber'})") if C4::Context->preference("BorrowersLog");
710 return $execute_success;
713 =head2 AddMember
715 $borrowernumber = &AddMember(%borrower);
717 insert new borrower into table
719 (%borrower keys are database columns. Database columns could be
720 different in different versions. Please look into database for correct
721 column names.)
723 Returns the borrowernumber upon success
725 Returns as undef upon any db error without further processing
727 =cut
730 sub AddMember {
731 my (%data) = @_;
732 my $dbh = C4::Context->dbh;
733 my $schema = Koha::Database->new()->schema;
735 # generate a proper login if none provided
736 $data{'userid'} = Generate_Userid( $data{'borrowernumber'}, $data{'firstname'}, $data{'surname'} )
737 if ( $data{'userid'} eq '' || !Check_Userid( $data{'userid'} ) );
739 # add expiration date if it isn't already there
740 unless ( $data{'dateexpiry'} ) {
741 $data{'dateexpiry'} = GetExpiryDate( $data{'categorycode'}, C4::Dates->new()->output("iso") );
744 # add enrollment date if it isn't already there
745 unless ( $data{'dateenrolled'} ) {
746 $data{'dateenrolled'} = C4::Dates->new()->output("iso");
749 my $patron_category = $schema->resultset('Category')->find( $data{'categorycode'} );
750 $data{'privacy'} =
751 $patron_category->default_privacy() eq 'default' ? 1
752 : $patron_category->default_privacy() eq 'never' ? 2
753 : $patron_category->default_privacy() eq 'forever' ? 0
754 : undef;
755 # Make a copy of the plain text password for later use
756 my $plain_text_password = $data{'password'};
758 # create a disabled account if no password provided
759 $data{'password'} = ($data{'password'})? hash_password($data{'password'}) : '!';
760 $data{'dateofbirth'} = undef if( not $data{'dateofbirth'} );
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' => 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 date desc,timestamp 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 += int(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 GetborCatFromCatType
1485 ($codes_arrayref, $labels_hashref) = &GetborCatFromCatType();
1487 Looks up the different types of borrowers in the database. Returns two
1488 elements: a reference-to-array, which lists the borrower category
1489 codes, and a reference-to-hash, which maps the borrower category codes
1490 to category descriptions.
1492 =cut
1495 sub GetborCatFromCatType {
1496 my ( $category_type, $action, $no_branch_limit ) = @_;
1498 my $branch_limit = $no_branch_limit
1500 : C4::Context->userenv ? C4::Context->userenv->{"branch"} : "";
1502 # FIXME - This API seems both limited and dangerous.
1503 my $dbh = C4::Context->dbh;
1505 my $request = qq{
1506 SELECT categories.categorycode, categories.description
1507 FROM categories
1509 $request .= qq{
1510 LEFT JOIN categories_branches ON categories.categorycode = categories_branches.categorycode
1511 } if $branch_limit;
1512 if($action) {
1513 $request .= " $action ";
1514 $request .= " AND (branchcode = ? OR branchcode IS NULL) GROUP BY description" if $branch_limit;
1515 } else {
1516 $request .= " WHERE branchcode = ? OR branchcode IS NULL GROUP BY description" if $branch_limit;
1518 $request .= " ORDER BY categorycode";
1520 my $sth = $dbh->prepare($request);
1521 $sth->execute(
1522 $action ? $category_type : (),
1523 $branch_limit ? $branch_limit : ()
1526 my %labels;
1527 my @codes;
1529 while ( my $data = $sth->fetchrow_hashref ) {
1530 push @codes, $data->{'categorycode'};
1531 $labels{ $data->{'categorycode'} } = $data->{'description'};
1533 $sth->finish;
1534 return ( \@codes, \%labels );
1537 =head2 GetBorrowercategory
1539 $hashref = &GetBorrowercategory($categorycode);
1541 Given the borrower's category code, the function returns the corresponding
1542 data hashref for a comprehensive information display.
1544 =cut
1546 sub GetBorrowercategory {
1547 my ($catcode) = @_;
1548 my $dbh = C4::Context->dbh;
1549 if ($catcode){
1550 my $sth =
1551 $dbh->prepare(
1552 "SELECT description,dateofbirthrequired,upperagelimit,category_type
1553 FROM categories
1554 WHERE categorycode = ?"
1556 $sth->execute($catcode);
1557 my $data =
1558 $sth->fetchrow_hashref;
1559 return $data;
1561 return;
1562 } # sub getborrowercategory
1565 =head2 GetBorrowerCategorycode
1567 $categorycode = &GetBorrowerCategoryCode( $borrowernumber );
1569 Given the borrowernumber, the function returns the corresponding categorycode
1571 =cut
1573 sub GetBorrowerCategorycode {
1574 my ( $borrowernumber ) = @_;
1575 my $dbh = C4::Context->dbh;
1576 my $sth = $dbh->prepare( qq{
1577 SELECT categorycode
1578 FROM borrowers
1579 WHERE borrowernumber = ?
1580 } );
1581 $sth->execute( $borrowernumber );
1582 return $sth->fetchrow;
1585 =head2 GetBorrowercategoryList
1587 $arrayref_hashref = &GetBorrowercategoryList;
1588 If no category code provided, the function returns all the categories.
1590 =cut
1592 sub GetBorrowercategoryList {
1593 my $no_branch_limit = @_ ? shift : 0;
1594 my $branch_limit = $no_branch_limit
1596 : C4::Context->userenv ? C4::Context->userenv->{"branch"} : "";
1597 my $dbh = C4::Context->dbh;
1598 my $query = "SELECT categories.* FROM categories";
1599 $query .= qq{
1600 LEFT JOIN categories_branches ON categories.categorycode = categories_branches.categorycode
1601 WHERE branchcode = ? OR branchcode IS NULL GROUP BY description
1602 } if $branch_limit;
1603 $query .= " ORDER BY description";
1604 my $sth = $dbh->prepare( $query );
1605 $sth->execute( $branch_limit ? $branch_limit : () );
1606 my $data = $sth->fetchall_arrayref( {} );
1607 $sth->finish;
1608 return $data;
1609 } # sub getborrowercategory
1611 =head2 ethnicitycategories
1613 ($codes_arrayref, $labels_hashref) = &ethnicitycategories();
1615 Looks up the different ethnic types in the database. Returns two
1616 elements: a reference-to-array, which lists the ethnicity codes, and a
1617 reference-to-hash, which maps the ethnicity codes to ethnicity
1618 descriptions.
1620 =cut
1624 sub ethnicitycategories {
1625 my $dbh = C4::Context->dbh;
1626 my $sth = $dbh->prepare("Select code,name from ethnicity order by name");
1627 $sth->execute;
1628 my %labels;
1629 my @codes;
1630 while ( my $data = $sth->fetchrow_hashref ) {
1631 push @codes, $data->{'code'};
1632 $labels{ $data->{'code'} } = $data->{'name'};
1634 return ( \@codes, \%labels );
1637 =head2 fixEthnicity
1639 $ethn_name = &fixEthnicity($ethn_code);
1641 Takes an ethnicity code (e.g., "european" or "pi") and returns the
1642 corresponding descriptive name from the C<ethnicity> table in the
1643 Koha database ("European" or "Pacific Islander").
1645 =cut
1649 sub fixEthnicity {
1650 my $ethnicity = shift;
1651 return unless $ethnicity;
1652 my $dbh = C4::Context->dbh;
1653 my $sth = $dbh->prepare("Select name from ethnicity where code = ?");
1654 $sth->execute($ethnicity);
1655 my $data = $sth->fetchrow_hashref;
1656 return $data->{'name'};
1657 } # sub fixEthnicity
1659 =head2 GetAge
1661 $dateofbirth,$date = &GetAge($date);
1663 this function return the borrowers age with the value of dateofbirth
1665 =cut
1668 sub GetAge{
1669 my ( $date, $date_ref ) = @_;
1671 if ( not defined $date_ref ) {
1672 $date_ref = sprintf( '%04d-%02d-%02d', Today() );
1675 my ( $year1, $month1, $day1 ) = split /-/, $date;
1676 my ( $year2, $month2, $day2 ) = split /-/, $date_ref;
1678 my $age = $year2 - $year1;
1679 if ( $month1 . $day1 > $month2 . $day2 ) {
1680 $age--;
1683 return $age;
1684 } # sub get_age
1686 =head2 SetAge
1688 $borrower = C4::Members::SetAge($borrower, $datetimeduration);
1689 $borrower = C4::Members::SetAge($borrower, '0015-12-10');
1690 $borrower = C4::Members::SetAge($borrower, $datetimeduration, $datetime_reference);
1692 eval { $borrower = C4::Members::SetAge($borrower, '015-1-10'); };
1693 if ($@) {print $@;} #Catch a bad ISO Date or kill your script!
1695 This function sets the borrower's dateofbirth to match the given age.
1696 Optionally relative to the given $datetime_reference.
1698 @PARAM1 koha.borrowers-object
1699 @PARAM2 DateTime::Duration-object as the desired age
1700 OR a ISO 8601 Date. (To make the API more pleasant)
1701 @PARAM3 DateTime-object as the relative date, defaults to now().
1702 RETURNS The given borrower reference @PARAM1.
1703 DIES If there was an error with the ISO Date handling.
1705 =cut
1708 sub SetAge{
1709 my ( $borrower, $datetimeduration, $datetime_ref ) = @_;
1710 $datetime_ref = DateTime->now() unless $datetime_ref;
1712 if ($datetimeduration && ref $datetimeduration ne 'DateTime::Duration') {
1713 if ($datetimeduration =~ /^(\d{4})-(\d{2})-(\d{2})/) {
1714 $datetimeduration = DateTime::Duration->new(years => $1, months => $2, days => $3);
1716 else {
1717 die "C4::Members::SetAge($borrower, $datetimeduration), datetimeduration not a valid ISO 8601 Date!\n";
1721 my $new_datetime_ref = $datetime_ref->clone();
1722 $new_datetime_ref->subtract_duration( $datetimeduration );
1724 $borrower->{dateofbirth} = $new_datetime_ref->ymd();
1726 return $borrower;
1727 } # sub SetAge
1729 =head2 GetCities
1731 $cityarrayref = GetCities();
1733 Returns an array_ref of the entries in the cities table
1734 If there are entries in the table an empty row is returned
1735 This is currently only used to populate a popup in memberentry
1737 =cut
1739 sub GetCities {
1741 my $dbh = C4::Context->dbh;
1742 my $city_arr = $dbh->selectall_arrayref(
1743 q|SELECT cityid,city_zipcode,city_name,city_state,city_country FROM cities ORDER BY city_name|,
1744 { Slice => {} });
1745 if ( @{$city_arr} ) {
1746 unshift @{$city_arr}, {
1747 city_zipcode => q{},
1748 city_name => q{},
1749 cityid => q{},
1750 city_state => q{},
1751 city_country => q{},
1755 return $city_arr;
1758 =head2 GetSortDetails (OUEST-PROVENCE)
1760 ($lib) = &GetSortDetails($category,$sortvalue);
1762 Returns the authorized value details
1763 C<&$lib>return value of authorized value details
1764 C<&$sortvalue>this is the value of authorized value
1765 C<&$category>this is the value of authorized value category
1767 =cut
1769 sub GetSortDetails {
1770 my ( $category, $sortvalue ) = @_;
1771 my $dbh = C4::Context->dbh;
1772 my $query = qq|SELECT lib
1773 FROM authorised_values
1774 WHERE category=?
1775 AND authorised_value=? |;
1776 my $sth = $dbh->prepare($query);
1777 $sth->execute( $category, $sortvalue );
1778 my $lib = $sth->fetchrow;
1779 return ($lib) if ($lib);
1780 return ($sortvalue) unless ($lib);
1783 =head2 MoveMemberToDeleted
1785 $result = &MoveMemberToDeleted($borrowernumber);
1787 Copy the record from borrowers to deletedborrowers table.
1788 The routine returns 1 for success, undef for failure.
1790 =cut
1792 sub MoveMemberToDeleted {
1793 my ($member) = shift or return;
1795 my $schema = Koha::Database->new()->schema();
1796 my $borrowers_rs = $schema->resultset('Borrower');
1797 $borrowers_rs->result_class('DBIx::Class::ResultClass::HashRefInflator');
1798 my $borrower = $borrowers_rs->find($member);
1799 return unless $borrower;
1801 my $deleted = $schema->resultset('Deletedborrower')->create($borrower);
1803 return $deleted ? 1 : undef;
1806 =head2 DelMember
1808 DelMember($borrowernumber);
1810 This function remove directly a borrower whitout writing it on deleteborrower.
1811 + Deletes reserves for the borrower
1813 =cut
1815 sub DelMember {
1816 my $dbh = C4::Context->dbh;
1817 my $borrowernumber = shift;
1818 #warn "in delmember with $borrowernumber";
1819 return unless $borrowernumber; # borrowernumber is mandatory.
1821 my $query = qq|DELETE
1822 FROM reserves
1823 WHERE borrowernumber=?|;
1824 my $sth = $dbh->prepare($query);
1825 $sth->execute($borrowernumber);
1826 $query = "
1827 DELETE
1828 FROM borrowers
1829 WHERE borrowernumber = ?
1831 $sth = $dbh->prepare($query);
1832 $sth->execute($borrowernumber);
1833 logaction("MEMBERS", "DELETE", $borrowernumber, "") if C4::Context->preference("BorrowersLog");
1834 return $sth->rows;
1837 =head2 ExtendMemberSubscriptionTo (OUEST-PROVENCE)
1839 $date = ExtendMemberSubscriptionTo($borrowerid, $date);
1841 Extending the subscription to a given date or to the expiry date calculated on ISO date.
1842 Returns ISO date.
1844 =cut
1846 sub ExtendMemberSubscriptionTo {
1847 my ( $borrowerid,$date) = @_;
1848 my $dbh = C4::Context->dbh;
1849 my $borrower = GetMember('borrowernumber'=>$borrowerid);
1850 unless ($date){
1851 $date = (C4::Context->preference('BorrowerRenewalPeriodBase') eq 'dateexpiry') ?
1852 C4::Dates->new($borrower->{'dateexpiry'}, 'iso')->output("iso") :
1853 C4::Dates->new()->output("iso");
1854 $date = GetExpiryDate( $borrower->{'categorycode'}, $date );
1856 my $sth = $dbh->do(<<EOF);
1857 UPDATE borrowers
1858 SET dateexpiry='$date'
1859 WHERE borrowernumber='$borrowerid'
1862 AddEnrolmentFeeIfNeeded( $borrower->{categorycode}, $borrower->{borrowernumber} );
1864 logaction("MEMBERS", "RENEW", $borrower->{'borrowernumber'}, "Membership renewed")if C4::Context->preference("BorrowersLog");
1865 return $date if ($sth);
1866 return 0;
1869 =head2 GetTitles (OUEST-PROVENCE)
1871 ($borrowertitle)= &GetTitles();
1873 Looks up the different title . Returns array with all borrowers title
1875 =cut
1877 sub GetTitles {
1878 my @borrowerTitle = split (/,|\|/,C4::Context->preference('BorrowersTitles'));
1879 unshift( @borrowerTitle, "" );
1880 my $count=@borrowerTitle;
1881 if ($count == 1){
1882 return ();
1884 else {
1885 return ( \@borrowerTitle);
1889 =head2 GetPatronImage
1891 my ($imagedata, $dberror) = GetPatronImage($borrowernumber);
1893 Returns the mimetype and binary image data of the image for the patron with the supplied borrowernumber.
1895 =cut
1897 sub GetPatronImage {
1898 my ($borrowernumber) = @_;
1899 warn "Borrowernumber passed to GetPatronImage is $borrowernumber" if $debug;
1900 my $dbh = C4::Context->dbh;
1901 my $query = 'SELECT mimetype, imagefile FROM patronimage WHERE borrowernumber = ?';
1902 my $sth = $dbh->prepare($query);
1903 $sth->execute($borrowernumber);
1904 my $imagedata = $sth->fetchrow_hashref;
1905 warn "Database error!" if $sth->errstr;
1906 return $imagedata, $sth->errstr;
1909 =head2 PutPatronImage
1911 PutPatronImage($cardnumber, $mimetype, $imgfile);
1913 Stores patron binary image data and mimetype in database.
1914 NOTE: This function is good for updating images as well as inserting new images in the database.
1916 =cut
1918 sub PutPatronImage {
1919 my ($cardnumber, $mimetype, $imgfile) = @_;
1920 warn "Parameters passed in: Cardnumber=$cardnumber, Mimetype=$mimetype, " . ($imgfile ? "Imagefile" : "No Imagefile") if $debug;
1921 my $dbh = C4::Context->dbh;
1922 my $query = "INSERT INTO patronimage (borrowernumber, mimetype, imagefile) VALUES ( ( SELECT borrowernumber from borrowers WHERE cardnumber = ? ),?,?) ON DUPLICATE KEY UPDATE imagefile = ?;";
1923 my $sth = $dbh->prepare($query);
1924 $sth->execute($cardnumber,$mimetype,$imgfile,$imgfile);
1925 warn "Error returned inserting $cardnumber.$mimetype." if $sth->errstr;
1926 return $sth->errstr;
1929 =head2 RmPatronImage
1931 my ($dberror) = RmPatronImage($borrowernumber);
1933 Removes the image for the patron with the supplied borrowernumber.
1935 =cut
1937 sub RmPatronImage {
1938 my ($borrowernumber) = @_;
1939 warn "Borrowernumber passed to GetPatronImage is $borrowernumber" if $debug;
1940 my $dbh = C4::Context->dbh;
1941 my $query = "DELETE FROM patronimage WHERE borrowernumber = ?;";
1942 my $sth = $dbh->prepare($query);
1943 $sth->execute($borrowernumber);
1944 my $dberror = $sth->errstr;
1945 warn "Database error!" if $sth->errstr;
1946 return $dberror;
1949 =head2 GetHideLostItemsPreference
1951 $hidelostitemspref = &GetHideLostItemsPreference($borrowernumber);
1953 Returns the HideLostItems preference for the patron category of the supplied borrowernumber
1954 C<&$hidelostitemspref>return value of function, 0 or 1
1956 =cut
1958 sub GetHideLostItemsPreference {
1959 my ($borrowernumber) = @_;
1960 my $dbh = C4::Context->dbh;
1961 my $query = "SELECT hidelostitems FROM borrowers,categories WHERE borrowers.categorycode = categories.categorycode AND borrowernumber = ?";
1962 my $sth = $dbh->prepare($query);
1963 $sth->execute($borrowernumber);
1964 my $hidelostitems = $sth->fetchrow;
1965 return $hidelostitems;
1968 =head2 GetBorrowersToExpunge
1970 $borrowers = &GetBorrowersToExpunge(
1971 not_borrowered_since => $not_borrowered_since,
1972 expired_before => $expired_before,
1973 category_code => $category_code,
1974 branchcode => $branchcode
1977 This function get all borrowers based on the given criteria.
1979 =cut
1981 sub GetBorrowersToExpunge {
1982 my $params = shift;
1984 my $filterdate = $params->{'not_borrowered_since'};
1985 my $filterexpiry = $params->{'expired_before'};
1986 my $filtercategory = $params->{'category_code'};
1987 my $filterbranch = $params->{'branchcode'} ||
1988 ((C4::Context->preference('IndependentBranches')
1989 && C4::Context->userenv
1990 && !C4::Context->IsSuperLibrarian()
1991 && C4::Context->userenv->{branch})
1992 ? C4::Context->userenv->{branch}
1993 : "");
1995 my $dbh = C4::Context->dbh;
1996 my $query = q|
1997 SELECT borrowers.borrowernumber,
1998 MAX(old_issues.timestamp) AS latestissue,
1999 MAX(issues.timestamp) AS currentissue
2000 FROM borrowers
2001 JOIN categories USING (categorycode)
2002 LEFT JOIN (
2003 SELECT guarantorid
2004 FROM borrowers
2005 WHERE guarantorid IS NOT NULL
2006 AND guarantorid <> 0
2007 ) as tmp ON borrowers.borrowernumber=tmp.guarantorid
2008 LEFT JOIN old_issues USING (borrowernumber)
2009 LEFT JOIN issues USING (borrowernumber)
2010 WHERE category_type <> 'S'
2011 AND tmp.guarantorid IS NULL
2014 my @query_params;
2015 if ( $filterbranch && $filterbranch ne "" ) {
2016 $query.= " AND borrowers.branchcode = ? ";
2017 push( @query_params, $filterbranch );
2019 if ( $filterexpiry ) {
2020 $query .= " AND dateexpiry < ? ";
2021 push( @query_params, $filterexpiry );
2023 if ( $filtercategory ) {
2024 $query .= " AND categorycode = ? ";
2025 push( @query_params, $filtercategory );
2027 $query.=" GROUP BY borrowers.borrowernumber HAVING currentissue IS NULL ";
2028 if ( $filterdate ) {
2029 $query.=" AND ( latestissue < ? OR latestissue IS NULL ) ";
2030 push @query_params,$filterdate;
2032 warn $query if $debug;
2034 my $sth = $dbh->prepare($query);
2035 if (scalar(@query_params)>0){
2036 $sth->execute(@query_params);
2038 else {
2039 $sth->execute;
2042 my @results;
2043 while ( my $data = $sth->fetchrow_hashref ) {
2044 push @results, $data;
2046 return \@results;
2049 =head2 GetBorrowersWhoHaveNeverBorrowed
2051 $results = &GetBorrowersWhoHaveNeverBorrowed
2053 This function get all borrowers who have never borrowed.
2055 I<$result> is a ref to an array which all elements are a hasref.
2057 =cut
2059 sub GetBorrowersWhoHaveNeverBorrowed {
2060 my $filterbranch = shift ||
2061 ((C4::Context->preference('IndependentBranches')
2062 && C4::Context->userenv
2063 && !C4::Context->IsSuperLibrarian()
2064 && C4::Context->userenv->{branch})
2065 ? C4::Context->userenv->{branch}
2066 : "");
2067 my $dbh = C4::Context->dbh;
2068 my $query = "
2069 SELECT borrowers.borrowernumber,max(timestamp) as latestissue
2070 FROM borrowers
2071 LEFT JOIN issues ON borrowers.borrowernumber = issues.borrowernumber
2072 WHERE issues.borrowernumber IS NULL
2074 my @query_params;
2075 if ($filterbranch && $filterbranch ne ""){
2076 $query.=" AND borrowers.branchcode= ?";
2077 push @query_params,$filterbranch;
2079 warn $query if $debug;
2081 my $sth = $dbh->prepare($query);
2082 if (scalar(@query_params)>0){
2083 $sth->execute(@query_params);
2085 else {
2086 $sth->execute;
2089 my @results;
2090 while ( my $data = $sth->fetchrow_hashref ) {
2091 push @results, $data;
2093 return \@results;
2096 =head2 GetBorrowersWithIssuesHistoryOlderThan
2098 $results = &GetBorrowersWithIssuesHistoryOlderThan($date)
2100 this function get all borrowers who has an issue history older than I<$date> given on input arg.
2102 I<$result> is a ref to an array which all elements are a hashref.
2103 This hashref is containt the number of time this borrowers has borrowed before I<$date> and the borrowernumber.
2105 =cut
2107 sub GetBorrowersWithIssuesHistoryOlderThan {
2108 my $dbh = C4::Context->dbh;
2109 my $date = shift ||POSIX::strftime("%Y-%m-%d",localtime());
2110 my $filterbranch = shift ||
2111 ((C4::Context->preference('IndependentBranches')
2112 && C4::Context->userenv
2113 && !C4::Context->IsSuperLibrarian()
2114 && C4::Context->userenv->{branch})
2115 ? C4::Context->userenv->{branch}
2116 : "");
2117 my $query = "
2118 SELECT count(borrowernumber) as n,borrowernumber
2119 FROM old_issues
2120 WHERE returndate < ?
2121 AND borrowernumber IS NOT NULL
2123 my @query_params;
2124 push @query_params, $date;
2125 if ($filterbranch){
2126 $query.=" AND branchcode = ?";
2127 push @query_params, $filterbranch;
2129 $query.=" GROUP BY borrowernumber ";
2130 warn $query if $debug;
2131 my $sth = $dbh->prepare($query);
2132 $sth->execute(@query_params);
2133 my @results;
2135 while ( my $data = $sth->fetchrow_hashref ) {
2136 push @results, $data;
2138 return \@results;
2141 =head2 GetBorrowersNamesAndLatestIssue
2143 $results = &GetBorrowersNamesAndLatestIssueList(@borrowernumbers)
2145 this function get borrowers Names and surnames and Issue information.
2147 I<@borrowernumbers> is an array which all elements are borrowernumbers.
2148 This hashref is containt the number of time this borrowers has borrowed before I<$date> and the borrowernumber.
2150 =cut
2152 sub GetBorrowersNamesAndLatestIssue {
2153 my $dbh = C4::Context->dbh;
2154 my @borrowernumbers=@_;
2155 my $query = "
2156 SELECT surname,lastname, phone, email,max(timestamp)
2157 FROM borrowers
2158 LEFT JOIN issues ON borrowers.borrowernumber=issues.borrowernumber
2159 GROUP BY borrowernumber
2161 my $sth = $dbh->prepare($query);
2162 $sth->execute;
2163 my $results = $sth->fetchall_arrayref({});
2164 return $results;
2167 =head2 ModPrivacy
2169 my $success = ModPrivacy( $borrowernumber, $privacy );
2171 Update the privacy of a patron.
2173 return :
2174 true on success, false on failure
2176 =cut
2178 sub ModPrivacy {
2179 my $borrowernumber = shift;
2180 my $privacy = shift;
2181 return unless defined $borrowernumber;
2182 return unless $borrowernumber =~ /^\d+$/;
2184 return ModMember( borrowernumber => $borrowernumber,
2185 privacy => $privacy );
2188 =head2 AddMessage
2190 AddMessage( $borrowernumber, $message_type, $message, $branchcode );
2192 Adds a message to the messages table for the given borrower.
2194 Returns:
2195 True on success
2196 False on failure
2198 =cut
2200 sub AddMessage {
2201 my ( $borrowernumber, $message_type, $message, $branchcode ) = @_;
2203 my $dbh = C4::Context->dbh;
2205 if ( ! ( $borrowernumber && $message_type && $message && $branchcode ) ) {
2206 return;
2209 my $query = "INSERT INTO messages ( borrowernumber, branchcode, message_type, message ) VALUES ( ?, ?, ?, ? )";
2210 my $sth = $dbh->prepare($query);
2211 $sth->execute( $borrowernumber, $branchcode, $message_type, $message );
2212 logaction("MEMBERS", "ADDCIRCMESSAGE", $borrowernumber, $message) if C4::Context->preference("BorrowersLog");
2213 return 1;
2216 =head2 GetMessages
2218 GetMessages( $borrowernumber, $type );
2220 $type is message type, B for borrower, or L for Librarian.
2221 Empty type returns all messages of any type.
2223 Returns all messages for the given borrowernumber
2225 =cut
2227 sub GetMessages {
2228 my ( $borrowernumber, $type, $branchcode ) = @_;
2230 if ( ! $type ) {
2231 $type = '%';
2234 my $dbh = C4::Context->dbh;
2236 my $query = "SELECT
2237 branches.branchname,
2238 messages.*,
2239 message_date,
2240 messages.branchcode LIKE '$branchcode' AS can_delete
2241 FROM messages, branches
2242 WHERE borrowernumber = ?
2243 AND message_type LIKE ?
2244 AND messages.branchcode = branches.branchcode
2245 ORDER BY message_date DESC";
2246 my $sth = $dbh->prepare($query);
2247 $sth->execute( $borrowernumber, $type ) ;
2248 my @results;
2250 while ( my $data = $sth->fetchrow_hashref ) {
2251 my $d = C4::Dates->new( $data->{message_date}, 'iso' );
2252 $data->{message_date_formatted} = $d->output;
2253 push @results, $data;
2255 return \@results;
2259 =head2 GetMessages
2261 GetMessagesCount( $borrowernumber, $type );
2263 $type is message type, B for borrower, or L for Librarian.
2264 Empty type returns all messages of any type.
2266 Returns the number of messages for the given borrowernumber
2268 =cut
2270 sub GetMessagesCount {
2271 my ( $borrowernumber, $type, $branchcode ) = @_;
2273 if ( ! $type ) {
2274 $type = '%';
2277 my $dbh = C4::Context->dbh;
2279 my $query = "SELECT COUNT(*) as MsgCount FROM messages WHERE borrowernumber = ? AND message_type LIKE ?";
2280 my $sth = $dbh->prepare($query);
2281 $sth->execute( $borrowernumber, $type ) ;
2282 my @results;
2284 my $data = $sth->fetchrow_hashref;
2285 my $count = $data->{'MsgCount'};
2287 return $count;
2292 =head2 DeleteMessage
2294 DeleteMessage( $message_id );
2296 =cut
2298 sub DeleteMessage {
2299 my ( $message_id ) = @_;
2301 my $dbh = C4::Context->dbh;
2302 my $query = "SELECT * FROM messages WHERE message_id = ?";
2303 my $sth = $dbh->prepare($query);
2304 $sth->execute( $message_id );
2305 my $message = $sth->fetchrow_hashref();
2307 $query = "DELETE FROM messages WHERE message_id = ?";
2308 $sth = $dbh->prepare($query);
2309 $sth->execute( $message_id );
2310 logaction("MEMBERS", "DELCIRCMESSAGE", $message->{'borrowernumber'}, $message->{'message'}) if C4::Context->preference("BorrowersLog");
2313 =head2 IssueSlip
2315 IssueSlip($branchcode, $borrowernumber, $quickslip)
2317 Returns letter hash ( see C4::Letters::GetPreparedLetter )
2319 $quickslip is boolean, to indicate whether we want a quick slip
2321 IssueSlip populates ISSUESLIP and ISSUEQSLIP, and will make the following expansions:
2323 Both slips:
2325 <<branches.*>>
2326 <<borrowers.*>>
2328 ISSUESLIP:
2330 <checkedout>
2331 <<biblio.*>>
2332 <<items.*>>
2333 <<biblioitems.*>>
2334 <<issues.*>>
2335 </checkedout>
2337 <overdue>
2338 <<biblio.*>>
2339 <<items.*>>
2340 <<biblioitems.*>>
2341 <<issues.*>>
2342 </overdue>
2344 <news>
2345 <<opac_news.*>>
2346 </news>
2348 ISSUEQSLIP:
2350 <checkedout>
2351 <<biblio.*>>
2352 <<items.*>>
2353 <<biblioitems.*>>
2354 <<issues.*>>
2355 </checkedout>
2357 NOTE: Not all table fields are available, pleasee see GetPendingIssues for a list of available fields.
2359 =cut
2361 sub IssueSlip {
2362 my ($branch, $borrowernumber, $quickslip) = @_;
2364 # FIXME Check callers before removing this statement
2365 #return unless $borrowernumber;
2367 my @issues = @{ GetPendingIssues($borrowernumber) };
2369 for my $issue (@issues) {
2370 $issue->{date_due} = $issue->{date_due_sql};
2371 if ($quickslip) {
2372 my $today = output_pref({ dt => dt_from_string, dateformat => 'iso', dateonly => 1 });
2373 if ( substr( $issue->{issuedate}, 0, 10 ) eq $today
2374 or substr( $issue->{lastreneweddate}, 0, 10 ) eq $today ) {
2375 $issue->{now} = 1;
2380 # Sort on timestamp then on issuedate (useful for tests and could be if modified in a batch
2381 @issues = sort {
2382 my $s = $b->{timestamp} <=> $a->{timestamp};
2383 $s == 0 ?
2384 $b->{issuedate} <=> $a->{issuedate} : $s;
2385 } @issues;
2387 my ($letter_code, %repeat);
2388 if ( $quickslip ) {
2389 $letter_code = 'ISSUEQSLIP';
2390 %repeat = (
2391 'checkedout' => [ map {
2392 'biblio' => $_,
2393 'items' => $_,
2394 'biblioitems' => $_,
2395 'issues' => $_,
2396 }, grep { $_->{'now'} } @issues ],
2399 else {
2400 $letter_code = 'ISSUESLIP';
2401 %repeat = (
2402 'checkedout' => [ map {
2403 'biblio' => $_,
2404 'items' => $_,
2405 'biblioitems' => $_,
2406 'issues' => $_,
2407 }, grep { !$_->{'overdue'} } @issues ],
2409 'overdue' => [ map {
2410 'biblio' => $_,
2411 'items' => $_,
2412 'biblioitems' => $_,
2413 'issues' => $_,
2414 }, grep { $_->{'overdue'} } @issues ],
2416 'news' => [ map {
2417 $_->{'timestamp'} = $_->{'newdate'};
2418 { opac_news => $_ }
2419 } @{ GetNewsToDisplay("slip",$branch) } ],
2423 return C4::Letters::GetPreparedLetter (
2424 module => 'circulation',
2425 letter_code => $letter_code,
2426 branchcode => $branch,
2427 tables => {
2428 'branches' => $branch,
2429 'borrowers' => $borrowernumber,
2431 repeat => \%repeat,
2435 =head2 GetBorrowersWithEmail
2437 ([$borrnum,$userid], ...) = GetBorrowersWithEmail('me@example.com');
2439 This gets a list of users and their basic details from their email address.
2440 As it's possible for multiple user to have the same email address, it provides
2441 you with all of them. If there is no userid for the user, there will be an
2442 C<undef> there. An empty list will be returned if there are no matches.
2444 =cut
2446 sub GetBorrowersWithEmail {
2447 my $email = shift;
2449 my $dbh = C4::Context->dbh;
2451 my $query = "SELECT borrowernumber, userid FROM borrowers WHERE email=?";
2452 my $sth=$dbh->prepare($query);
2453 $sth->execute($email);
2454 my @result = ();
2455 while (my $ref = $sth->fetch) {
2456 push @result, $ref;
2458 die "Failure searching for borrowers by email address: $sth->errstr" if $sth->err;
2459 return @result;
2462 sub AddMember_Opac {
2463 my ( %borrower ) = @_;
2465 $borrower{'categorycode'} = C4::Context->preference('PatronSelfRegistrationDefaultCategory');
2467 my $sr = new String::Random;
2468 $sr->{'A'} = [ 'A'..'Z', 'a'..'z' ];
2469 my $password = $sr->randpattern("AAAAAAAAAA");
2470 $borrower{'password'} = $password;
2472 $borrower{'cardnumber'} = fixup_cardnumber();
2474 my $borrowernumber = AddMember(%borrower);
2476 return ( $borrowernumber, $password );
2479 =head2 AddEnrolmentFeeIfNeeded
2481 AddEnrolmentFeeIfNeeded( $borrower->{categorycode}, $borrower->{borrowernumber} );
2483 Add enrolment fee for a patron if needed.
2485 =cut
2487 sub AddEnrolmentFeeIfNeeded {
2488 my ( $categorycode, $borrowernumber ) = @_;
2489 # check for enrollment fee & add it if needed
2490 my $dbh = C4::Context->dbh;
2491 my $sth = $dbh->prepare(q{
2492 SELECT enrolmentfee
2493 FROM categories
2494 WHERE categorycode=?
2496 $sth->execute( $categorycode );
2497 if ( $sth->err ) {
2498 warn sprintf('Database returned the following error: %s', $sth->errstr);
2499 return;
2501 my ($enrolmentfee) = $sth->fetchrow;
2502 if ($enrolmentfee && $enrolmentfee > 0) {
2503 # insert fee in patron debts
2504 C4::Accounts::manualinvoice( $borrowernumber, '', '', 'A', $enrolmentfee );
2508 sub HasOverdues {
2509 my ( $borrowernumber ) = @_;
2511 my $sql = "SELECT COUNT(*) FROM issues WHERE date_due < NOW() AND borrowernumber = ?";
2512 my $sth = C4::Context->dbh->prepare( $sql );
2513 $sth->execute( $borrowernumber );
2514 my ( $count ) = $sth->fetchrow_array();
2516 return $count;
2519 END { } # module clean-up code here (global destructor)
2523 __END__
2525 =head1 AUTHOR
2527 Koha Team
2529 =cut