Bug 6679 - [SIGNED-OFF] fix 2 perlcritic violations in C4/Installer/PerlModules.pm
[koha.git] / C4 / Members.pm
blobb2f45b955bf3ff3ba57457ca6ec2130fb38021ec
1 package C4::Members;
3 # Copyright 2000-2003 Katipo Communications
4 # Copyright 2010 BibLibre
5 # Parts Copyright 2010 Catalyst IT
7 # This file is part of Koha.
9 # Koha is free software; you can redistribute it and/or modify it under the
10 # terms of the GNU General Public License as published by the Free Software
11 # Foundation; either version 2 of the License, or (at your option) any later
12 # version.
14 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
15 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
16 # A PARTICULAR PURPOSE. See the GNU General Public License for more details.
18 # You should have received a copy of the GNU General Public License along
19 # with Koha; if not, write to the Free Software Foundation, Inc.,
20 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
23 use strict;
24 #use warnings; FIXME - Bug 2505
25 use C4::Context;
26 use C4::Dates qw(format_date_in_iso format_date);
27 use Digest::MD5 qw(md5_base64);
28 use Date::Calc qw/Today Add_Delta_YM check_date Date_to_Days/;
29 use C4::Log; # logaction
30 use C4::Overdues;
31 use C4::Reserves;
32 use C4::Accounts;
33 use C4::Biblio;
34 use C4::Letters;
35 use C4::SQLHelper qw(InsertInTable UpdateInTable SearchInTable);
36 use C4::Members::Attributes qw(SearchIdMatchingAttribute);
37 use C4::NewsChannels; #get slip news
38 use DateTime;
39 use DateTime::Format::DateParse;
40 use Koha::DateUtils;
41 use Text::Unaccent qw( unac_string );
43 our ($VERSION,@ISA,@EXPORT,@EXPORT_OK,$debug);
45 BEGIN {
46 $VERSION = 3.07.00.049;
47 $debug = $ENV{DEBUG} || 0;
48 require Exporter;
49 @ISA = qw(Exporter);
50 #Get data
51 push @EXPORT, qw(
52 &Search
53 &GetMemberDetails
54 &GetMemberRelatives
55 &GetMember
57 &GetGuarantees
59 &GetMemberIssuesAndFines
60 &GetPendingIssues
61 &GetAllIssues
63 &get_institutions
64 &getzipnamecity
65 &getidcity
67 &GetFirstValidEmailAddress
69 &GetAge
70 &GetCities
71 &GetRoadTypes
72 &GetRoadTypeDetails
73 &GetSortDetails
74 &GetTitles
76 &GetPatronImage
77 &PutPatronImage
78 &RmPatronImage
80 &GetHideLostItemsPreference
82 &IsMemberBlocked
83 &GetMemberAccountRecords
84 &GetBorNotifyAcctRecord
86 &GetborCatFromCatType
87 &GetBorrowercategory
88 GetBorrowerCategorycode
89 &GetBorrowercategoryList
91 &GetBorrowersWhoHaveNotBorrowedSince
92 &GetBorrowersWhoHaveNeverBorrowed
93 &GetBorrowersWithIssuesHistoryOlderThan
95 &GetExpiryDate
97 &AddMessage
98 &DeleteMessage
99 &GetMessages
100 &GetMessagesCount
102 &IssueSlip
103 GetBorrowersWithEmail
106 #Modify data
107 push @EXPORT, qw(
108 &ModMember
109 &changepassword
110 &ModPrivacy
113 #Delete data
114 push @EXPORT, qw(
115 &DelMember
118 #Insert data
119 push @EXPORT, qw(
120 &AddMember
121 &add_member_orgs
122 &MoveMemberToDeleted
123 &ExtendMemberSubscriptionTo
126 #Check data
127 push @EXPORT, qw(
128 &checkuniquemember
129 &checkuserpassword
130 &Check_Userid
131 &Generate_Userid
132 &fixEthnicity
133 &ethnicitycategories
134 &fixup_cardnumber
135 &checkcardnumber
139 =head1 NAME
141 C4::Members - Perl Module containing convenience functions for member handling
143 =head1 SYNOPSIS
145 use C4::Members;
147 =head1 DESCRIPTION
149 This module contains routines for adding, modifying and deleting members/patrons/borrowers
151 =head1 FUNCTIONS
153 =head2 Search
155 $borrowers_result_array_ref = &Search($filter,$orderby, $limit,
156 $columns_out, $search_on_fields,$searchtype);
158 Looks up patrons (borrowers) on filter. A wrapper for SearchInTable('borrowers').
160 For C<$filter>, C<$orderby>, C<$limit>, C<&columns_out>, C<&search_on_fields> and C<&searchtype>
161 refer to C4::SQLHelper:SearchInTable().
163 Special C<$filter> key '' is effectively expanded to search on surname firstname othernamescw
164 and cardnumber unless C<&search_on_fields> is defined
166 Examples:
168 $borrowers = Search('abcd', 'cardnumber');
170 $borrowers = Search({''=>'abcd', category_type=>'I'}, 'surname');
172 =cut
174 sub _express_member_find {
175 my ($filter) = @_;
177 # this is used by circulation everytime a new borrowers cardnumber is scanned
178 # so we can check an exact match first, if that works return, otherwise do the rest
179 my $dbh = C4::Context->dbh;
180 my $query = "SELECT borrowernumber FROM borrowers WHERE cardnumber = ?";
181 if ( my $borrowernumber = $dbh->selectrow_array($query, undef, $filter) ) {
182 return( {"borrowernumber"=>$borrowernumber} );
185 my ($search_on_fields, $searchtype);
186 if ( length($filter) == 1 ) {
187 $search_on_fields = [ qw(surname) ];
188 $searchtype = 'start_with';
189 } else {
190 $search_on_fields = [ qw(surname firstname othernames cardnumber) ];
191 $searchtype = 'contain';
194 return (undef, $search_on_fields, $searchtype);
197 sub Search {
198 my ( $filter, $orderby, $limit, $columns_out, $search_on_fields, $searchtype ) = @_;
200 my $search_string;
201 my $found_borrower;
203 if ( my $fr = ref $filter ) {
204 if ( $fr eq "HASH" ) {
205 if ( my $search_string = $filter->{''} ) {
206 my ($member_filter, $member_search_on_fields, $member_searchtype) = _express_member_find($search_string);
207 if ($member_filter) {
208 $filter = $member_filter;
209 $found_borrower = 1;
210 } else {
211 $search_on_fields ||= $member_search_on_fields;
212 $searchtype ||= $member_searchtype;
216 else {
217 $search_string = $filter;
220 else {
221 $search_string = $filter;
222 my ($member_filter, $member_search_on_fields, $member_searchtype) = _express_member_find($search_string);
223 if ($member_filter) {
224 $filter = $member_filter;
225 $found_borrower = 1;
226 } else {
227 $search_on_fields ||= $member_search_on_fields;
228 $searchtype ||= $member_searchtype;
232 if ( !$found_borrower && C4::Context->preference('ExtendedPatronAttributes') && $search_string ) {
233 my $matching_records = C4::Members::Attributes::SearchIdMatchingAttribute($search_string);
234 if(scalar(@$matching_records)>0) {
235 if ( my $fr = ref $filter ) {
236 if ( $fr eq "HASH" ) {
237 my %f = %$filter;
238 $filter = [ $filter ];
239 delete $f{''};
240 push @$filter, { %f, "borrowernumber"=>$$matching_records };
242 else {
243 push @$filter, {"borrowernumber"=>$matching_records};
246 else {
247 $filter = [ $filter ];
248 push @$filter, {"borrowernumber"=>$matching_records};
253 # $showallbranches was not used at the time SearchMember() was mainstreamed into Search().
254 # Mentioning for the reference
256 if ( C4::Context->preference("IndependantBranches") ) { # && !$showallbranches){
257 if ( my $userenv = C4::Context->userenv ) {
258 my $branch = $userenv->{'branch'};
259 if ( ($userenv->{flags} % 2 !=1) &&
260 $branch && $branch ne "insecure" ){
262 if (my $fr = ref $filter) {
263 if ( $fr eq "HASH" ) {
264 $filter->{branchcode} = $branch;
266 else {
267 foreach (@$filter) {
268 $_ = { '' => $_ } unless ref $_;
269 $_->{branchcode} = $branch;
273 else {
274 $filter = { '' => $filter, branchcode => $branch };
280 if ($found_borrower) {
281 $searchtype = "exact";
283 $searchtype ||= "start_with";
285 return SearchInTable( "borrowers", $filter, $orderby, $limit, $columns_out, $search_on_fields, $searchtype );
288 =head2 GetMemberDetails
290 ($borrower) = &GetMemberDetails($borrowernumber, $cardnumber);
292 Looks up a patron and returns information about him or her. If
293 C<$borrowernumber> is true (nonzero), C<&GetMemberDetails> looks
294 up the borrower by number; otherwise, it looks up the borrower by card
295 number.
297 C<$borrower> is a reference-to-hash whose keys are the fields of the
298 borrowers table in the Koha database. In addition,
299 C<$borrower-E<gt>{flags}> is a hash giving more detailed information
300 about the patron. Its keys act as flags :
302 if $borrower->{flags}->{LOST} {
303 # Patron's card was reported lost
306 If the state of a flag means that the patron should not be
307 allowed to borrow any more books, then it will have a C<noissues> key
308 with a true value.
310 See patronflags for more details.
312 C<$borrower-E<gt>{authflags}> is a hash giving more detailed information
313 about the top-level permissions flags set for the borrower. For example,
314 if a user has the "editcatalogue" permission,
315 C<$borrower-E<gt>{authflags}-E<gt>{editcatalogue}> will exist and have
316 the value "1".
318 =cut
320 sub GetMemberDetails {
321 my ( $borrowernumber, $cardnumber ) = @_;
322 my $dbh = C4::Context->dbh;
323 my $query;
324 my $sth;
325 if ($borrowernumber) {
326 $sth = $dbh->prepare("SELECT borrowers.*,category_type,categories.description,reservefee,enrolmentperiod FROM borrowers LEFT JOIN categories ON borrowers.categorycode=categories.categorycode WHERE borrowernumber=?");
327 $sth->execute($borrowernumber);
329 elsif ($cardnumber) {
330 $sth = $dbh->prepare("SELECT borrowers.*,category_type,categories.description,reservefee,enrolmentperiod FROM borrowers LEFT JOIN categories ON borrowers.categorycode=categories.categorycode WHERE cardnumber=?");
331 $sth->execute($cardnumber);
333 else {
334 return;
336 my $borrower = $sth->fetchrow_hashref;
337 my ($amount) = GetMemberAccountRecords( $borrowernumber);
338 $borrower->{'amountoutstanding'} = $amount;
339 # FIXME - patronflags calls GetMemberAccountRecords... just have patronflags return $amount
340 my $flags = patronflags( $borrower);
341 my $accessflagshash;
343 $sth = $dbh->prepare("select bit,flag from userflags");
344 $sth->execute;
345 while ( my ( $bit, $flag ) = $sth->fetchrow ) {
346 if ( $borrower->{'flags'} && $borrower->{'flags'} & 2**$bit ) {
347 $accessflagshash->{$flag} = 1;
350 $borrower->{'flags'} = $flags;
351 $borrower->{'authflags'} = $accessflagshash;
353 # For the purposes of making templates easier, we'll define a
354 # 'showname' which is the alternate form the user's first name if
355 # 'other name' is defined.
356 if ($borrower->{category_type} eq 'I') {
357 $borrower->{'showname'} = $borrower->{'othernames'};
358 $borrower->{'showname'} .= " $borrower->{'firstname'}" if $borrower->{'firstname'};
359 } else {
360 $borrower->{'showname'} = $borrower->{'firstname'};
363 return ($borrower); #, $flags, $accessflagshash);
366 =head2 patronflags
368 $flags = &patronflags($patron);
370 This function is not exported.
372 The following will be set where applicable:
373 $flags->{CHARGES}->{amount} Amount of debt
374 $flags->{CHARGES}->{noissues} Set if debt amount >$5.00 (or syspref noissuescharge)
375 $flags->{CHARGES}->{message} Message -- deprecated
377 $flags->{CREDITS}->{amount} Amount of credit
378 $flags->{CREDITS}->{message} Message -- deprecated
380 $flags->{ GNA } Patron has no valid address
381 $flags->{ GNA }->{noissues} Set for each GNA
382 $flags->{ GNA }->{message} "Borrower has no valid address" -- deprecated
384 $flags->{ LOST } Patron's card reported lost
385 $flags->{ LOST }->{noissues} Set for each LOST
386 $flags->{ LOST }->{message} Message -- deprecated
388 $flags->{DBARRED} Set if patron debarred, no access
389 $flags->{DBARRED}->{noissues} Set for each DBARRED
390 $flags->{DBARRED}->{message} Message -- deprecated
392 $flags->{ NOTES }
393 $flags->{ NOTES }->{message} The note itself. NOT deprecated
395 $flags->{ ODUES } Set if patron has overdue books.
396 $flags->{ ODUES }->{message} "Yes" -- deprecated
397 $flags->{ ODUES }->{itemlist} ref-to-array: list of overdue books
398 $flags->{ ODUES }->{itemlisttext} Text list of overdue items -- deprecated
400 $flags->{WAITING} Set if any of patron's reserves are available
401 $flags->{WAITING}->{message} Message -- deprecated
402 $flags->{WAITING}->{itemlist} ref-to-array: list of available items
404 =over
406 =item C<$flags-E<gt>{ODUES}-E<gt>{itemlist}> is a reference-to-array listing the
407 overdue items. Its elements are references-to-hash, each describing an
408 overdue item. The keys are selected fields from the issues, biblio,
409 biblioitems, and items tables of the Koha database.
411 =item C<$flags-E<gt>{ODUES}-E<gt>{itemlisttext}> is a string giving a text listing of
412 the overdue items, one per line. Deprecated.
414 =item C<$flags-E<gt>{WAITING}-E<gt>{itemlist}> is a reference-to-array listing the
415 available items. Each element is a reference-to-hash whose keys are
416 fields from the reserves table of the Koha database.
418 =back
420 All the "message" fields that include language generated in this function are deprecated,
421 because such strings belong properly in the display layer.
423 The "message" field that comes from the DB is OK.
425 =cut
427 # TODO: use {anonymous => hashes} instead of a dozen %flaginfo
428 # FIXME rename this function.
429 sub patronflags {
430 my %flags;
431 my ( $patroninformation) = @_;
432 my $dbh=C4::Context->dbh;
433 my ($amount) = GetMemberAccountRecords( $patroninformation->{'borrowernumber'});
434 if ( $amount > 0 ) {
435 my %flaginfo;
436 my $noissuescharge = C4::Context->preference("noissuescharge") || 5;
437 $flaginfo{'message'} = sprintf "Patron owes \$%.02f", $amount;
438 $flaginfo{'amount'} = sprintf "%.02f", $amount;
439 if ( $amount > $noissuescharge && !C4::Context->preference("AllowFineOverride") ) {
440 $flaginfo{'noissues'} = 1;
442 $flags{'CHARGES'} = \%flaginfo;
444 elsif ( $amount < 0 ) {
445 my %flaginfo;
446 $flaginfo{'message'} = sprintf "Patron has credit of \$%.02f", -$amount;
447 $flaginfo{'amount'} = sprintf "%.02f", $amount;
448 $flags{'CREDITS'} = \%flaginfo;
450 if ( $patroninformation->{'gonenoaddress'}
451 && $patroninformation->{'gonenoaddress'} == 1 )
453 my %flaginfo;
454 $flaginfo{'message'} = 'Borrower has no valid address.';
455 $flaginfo{'noissues'} = 1;
456 $flags{'GNA'} = \%flaginfo;
458 if ( $patroninformation->{'lost'} && $patroninformation->{'lost'} == 1 ) {
459 my %flaginfo;
460 $flaginfo{'message'} = 'Borrower\'s card reported lost.';
461 $flaginfo{'noissues'} = 1;
462 $flags{'LOST'} = \%flaginfo;
464 if ( $patroninformation->{'debarred'} && check_date( split( /-/, $patroninformation->{'debarred'} ) ) ) {
465 if ( Date_to_Days(Date::Calc::Today) < Date_to_Days( split( /-/, $patroninformation->{'debarred'} ) ) ) {
466 my %flaginfo;
467 $flaginfo{'debarredcomment'} = $patroninformation->{'debarredcomment'};
468 $flaginfo{'message'} = $patroninformation->{'debarredcomment'};
469 $flaginfo{'noissues'} = 1;
470 $flaginfo{'dateend'} = $patroninformation->{'debarred'};
471 $flags{'DBARRED'} = \%flaginfo;
474 if ( $patroninformation->{'borrowernotes'}
475 && $patroninformation->{'borrowernotes'} )
477 my %flaginfo;
478 $flaginfo{'message'} = $patroninformation->{'borrowernotes'};
479 $flags{'NOTES'} = \%flaginfo;
481 my ( $odues, $itemsoverdue ) = C4::Overdues::checkoverdues($patroninformation->{'borrowernumber'});
482 if ( $odues && $odues > 0 ) {
483 my %flaginfo;
484 $flaginfo{'message'} = "Yes";
485 $flaginfo{'itemlist'} = $itemsoverdue;
486 foreach ( sort { $a->{'date_due'} cmp $b->{'date_due'} }
487 @$itemsoverdue )
489 $flaginfo{'itemlisttext'} .=
490 "$_->{'date_due'} $_->{'barcode'} $_->{'title'} \n"; # newline is display layer
492 $flags{'ODUES'} = \%flaginfo;
494 my @itemswaiting = C4::Reserves::GetReservesFromBorrowernumber( $patroninformation->{'borrowernumber'},'W' );
495 my $nowaiting = scalar @itemswaiting;
496 if ( $nowaiting > 0 ) {
497 my %flaginfo;
498 $flaginfo{'message'} = "Reserved items available";
499 $flaginfo{'itemlist'} = \@itemswaiting;
500 $flags{'WAITING'} = \%flaginfo;
502 return ( \%flags );
506 =head2 GetMember
508 $borrower = &GetMember(%information);
510 Retrieve the first patron record meeting on criteria listed in the
511 C<%information> hash, which should contain one or more
512 pairs of borrowers column names and values, e.g.,
514 $borrower = GetMember(borrowernumber => id);
516 C<&GetBorrower> returns a reference-to-hash whose keys are the fields of
517 the C<borrowers> table in the Koha database.
519 FIXME: GetMember() is used throughout the code as a lookup
520 on a unique key such as the borrowernumber, but this meaning is not
521 enforced in the routine itself.
523 =cut
526 sub GetMember {
527 my ( %information ) = @_;
528 if (exists $information{borrowernumber} && !defined $information{borrowernumber}) {
529 #passing mysql's kohaadmin?? Makes no sense as a query
530 return;
532 my $dbh = C4::Context->dbh;
533 my $select =
534 q{SELECT borrowers.*, categories.category_type, categories.description
535 FROM borrowers
536 LEFT JOIN categories on borrowers.categorycode=categories.categorycode WHERE };
537 my $more_p = 0;
538 my @values = ();
539 for (keys %information ) {
540 if ($more_p) {
541 $select .= ' AND ';
543 else {
544 $more_p++;
547 if (defined $information{$_}) {
548 $select .= "$_ = ?";
549 push @values, $information{$_};
551 else {
552 $select .= "$_ IS NULL";
555 $debug && warn $select, " ",values %information;
556 my $sth = $dbh->prepare("$select");
557 $sth->execute(map{$information{$_}} keys %information);
558 my $data = $sth->fetchall_arrayref({});
559 #FIXME interface to this routine now allows generation of a result set
560 #so whole array should be returned but bowhere in the current code expects this
561 if (@{$data} ) {
562 return $data->[0];
565 return;
568 =head2 GetMemberRelatives
570 @borrowernumbers = GetMemberRelatives($borrowernumber);
572 C<GetMemberRelatives> returns a borrowersnumber's list of guarantor/guarantees of the member given in parameter
574 =cut
575 sub GetMemberRelatives {
576 my $borrowernumber = shift;
577 my $dbh = C4::Context->dbh;
578 my @glist;
580 # Getting guarantor
581 my $query = "SELECT guarantorid FROM borrowers WHERE borrowernumber=?";
582 my $sth = $dbh->prepare($query);
583 $sth->execute($borrowernumber);
584 my $data = $sth->fetchrow_arrayref();
585 push @glist, $data->[0] if $data->[0];
586 my $guarantor = $data->[0] ? $data->[0] : undef;
588 # Getting guarantees
589 $query = "SELECT borrowernumber FROM borrowers WHERE guarantorid=?";
590 $sth = $dbh->prepare($query);
591 $sth->execute($borrowernumber);
592 while ($data = $sth->fetchrow_arrayref()) {
593 push @glist, $data->[0];
596 # Getting sibling guarantees
597 if ($guarantor) {
598 $query = "SELECT borrowernumber FROM borrowers WHERE guarantorid=?";
599 $sth = $dbh->prepare($query);
600 $sth->execute($guarantor);
601 while ($data = $sth->fetchrow_arrayref()) {
602 push @glist, $data->[0] if ($data->[0] != $borrowernumber);
606 return @glist;
609 =head2 IsMemberBlocked
611 my ($block_status, $count) = IsMemberBlocked( $borrowernumber );
613 Returns whether a patron has overdue items that may result
614 in a block or whether the patron has active fine days
615 that would block circulation privileges.
617 C<$block_status> can have the following values:
619 1 if the patron has outstanding fine days, in which case C<$count> is the number of them
621 -1 if the patron has overdue items, in which case C<$count> is the number of them
623 0 if the patron has no overdue items or outstanding fine days, in which case C<$count> is 0
625 Outstanding fine days are checked before current overdue items
626 are.
628 FIXME: this needs to be split into two functions; a potential block
629 based on the number of current overdue items could be orthogonal
630 to a block based on whether the patron has any fine days accrued.
632 =cut
634 sub IsMemberBlocked {
635 my $borrowernumber = shift;
636 my $dbh = C4::Context->dbh;
638 my $blockeddate = CheckBorrowerDebarred($borrowernumber);
640 return ( 1, $blockeddate ) if $blockeddate;
642 # if he have late issues
643 my $sth = $dbh->prepare(
644 "SELECT COUNT(*) as latedocs
645 FROM issues
646 WHERE borrowernumber = ?
647 AND date_due < now()"
649 $sth->execute($borrowernumber);
650 my $latedocs = $sth->fetchrow_hashref->{'latedocs'};
652 return ( -1, $latedocs ) if $latedocs > 0;
654 return ( 0, 0 );
657 =head2 GetMemberIssuesAndFines
659 ($overdue_count, $issue_count, $total_fines) = &GetMemberIssuesAndFines($borrowernumber);
661 Returns aggregate data about items borrowed by the patron with the
662 given borrowernumber.
664 C<&GetMemberIssuesAndFines> returns a three-element array. C<$overdue_count> is the
665 number of overdue items the patron currently has borrowed. C<$issue_count> is the
666 number of books the patron currently has borrowed. C<$total_fines> is
667 the total fine currently due by the borrower.
669 =cut
672 sub GetMemberIssuesAndFines {
673 my ( $borrowernumber ) = @_;
674 my $dbh = C4::Context->dbh;
675 my $query = "SELECT COUNT(*) FROM issues WHERE borrowernumber = ?";
677 $debug and warn $query."\n";
678 my $sth = $dbh->prepare($query);
679 $sth->execute($borrowernumber);
680 my $issue_count = $sth->fetchrow_arrayref->[0];
682 $sth = $dbh->prepare(
683 "SELECT COUNT(*) FROM issues
684 WHERE borrowernumber = ?
685 AND date_due < now()"
687 $sth->execute($borrowernumber);
688 my $overdue_count = $sth->fetchrow_arrayref->[0];
690 $sth = $dbh->prepare("SELECT SUM(amountoutstanding) FROM accountlines WHERE borrowernumber = ?");
691 $sth->execute($borrowernumber);
692 my $total_fines = $sth->fetchrow_arrayref->[0];
694 return ($overdue_count, $issue_count, $total_fines);
697 sub columns(;$) {
698 return @{C4::Context->dbh->selectcol_arrayref("SHOW columns from borrowers")};
701 =head2 ModMember
703 my $success = ModMember(borrowernumber => $borrowernumber,
704 [ field => value ]... );
706 Modify borrower's data. All date fields should ALREADY be in ISO format.
708 return :
709 true on success, or false on failure
711 =cut
713 sub ModMember {
714 my (%data) = @_;
715 # test to know if you must update or not the borrower password
716 if (exists $data{password}) {
717 if ($data{password} eq '****' or $data{password} eq '') {
718 delete $data{password};
719 } else {
720 $data{password} = md5_base64($data{password});
723 my $execute_success=UpdateInTable("borrowers",\%data);
724 if ($execute_success) { # only proceed if the update was a success
725 # ok if its an adult (type) it may have borrowers that depend on it as a guarantor
726 # so when we update information for an adult we should check for guarantees and update the relevant part
727 # of their records, ie addresses and phone numbers
728 my $borrowercategory= GetBorrowercategory( $data{'category_type'} );
729 if ( exists $borrowercategory->{'category_type'} && $borrowercategory->{'category_type'} eq ('A' || 'S') ) {
730 # is adult check guarantees;
731 UpdateGuarantees(%data);
733 logaction("MEMBERS", "MODIFY", $data{'borrowernumber'}, "UPDATE (executed w/ arg: $data{'borrowernumber'})") if C4::Context->preference("BorrowersLog");
735 return $execute_success;
739 =head2 AddMember
741 $borrowernumber = &AddMember(%borrower);
743 insert new borrower into table
744 Returns the borrowernumber upon success
746 Returns as undef upon any db error without further processing
748 =cut
751 sub AddMember {
752 my (%data) = @_;
753 my $dbh = C4::Context->dbh;
754 # generate a proper login if none provided
755 $data{'userid'} = Generate_Userid($data{'borrowernumber'}, $data{'firstname'}, $data{'surname'}) if $data{'userid'} eq '';
756 # create a disabled account if no password provided
757 $data{'password'} = ($data{'password'})? md5_base64($data{'password'}) : '!';
758 $data{'borrowernumber'}=InsertInTable("borrowers",\%data);
759 # mysql_insertid is probably bad. not necessarily accurate and mysql-specific at best.
760 logaction("MEMBERS", "CREATE", $data{'borrowernumber'}, "") if C4::Context->preference("BorrowersLog");
762 # check for enrollment fee & add it if needed
763 my $sth = $dbh->prepare("SELECT enrolmentfee FROM categories WHERE categorycode=?");
764 $sth->execute($data{'categorycode'});
765 my ($enrolmentfee) = $sth->fetchrow;
766 if ($sth->err) {
767 warn sprintf('Database returned the following error: %s', $sth->errstr);
768 return;
770 if ($enrolmentfee && $enrolmentfee > 0) {
771 # insert fee in patron debts
772 manualinvoice($data{'borrowernumber'}, '', '', 'A', $enrolmentfee);
775 return $data{'borrowernumber'};
779 sub Check_Userid {
780 my ($uid,$member) = @_;
781 my $dbh = C4::Context->dbh;
782 # Make sure the userid chosen is unique and not theirs if non-empty. If it is not,
783 # Then we need to tell the user and have them create a new one.
784 my $sth =
785 $dbh->prepare(
786 "SELECT * FROM borrowers WHERE userid=? AND borrowernumber != ?");
787 $sth->execute( $uid, $member );
788 if ( ( $uid ne '' ) && ( my $row = $sth->fetchrow_hashref ) ) {
789 return 0;
791 else {
792 return 1;
796 sub Generate_Userid {
797 my ($borrowernumber, $firstname, $surname) = @_;
798 my $newuid;
799 my $offset = 0;
800 do {
801 $firstname =~ s/[[:digit:][:space:][:blank:][:punct:][:cntrl:]]//g;
802 $surname =~ s/[[:digit:][:space:][:blank:][:punct:][:cntrl:]]//g;
803 $newuid = lc(($firstname)? "$firstname.$surname" : $surname);
804 $newuid = unac_string('utf-8',$newuid);
805 $newuid .= $offset unless $offset == 0;
806 $offset++;
808 } while (!Check_Userid($newuid,$borrowernumber));
810 return $newuid;
813 sub changepassword {
814 my ( $uid, $member, $digest ) = @_;
815 my $dbh = C4::Context->dbh;
817 #Make sure the userid chosen is unique and not theirs if non-empty. If it is not,
818 #Then we need to tell the user and have them create a new one.
819 my $resultcode;
820 my $sth =
821 $dbh->prepare(
822 "SELECT * FROM borrowers WHERE userid=? AND borrowernumber != ?");
823 $sth->execute( $uid, $member );
824 if ( ( $uid ne '' ) && ( my $row = $sth->fetchrow_hashref ) ) {
825 $resultcode=0;
827 else {
828 #Everything is good so we can update the information.
829 $sth =
830 $dbh->prepare(
831 "update borrowers set userid=?, password=? where borrowernumber=?");
832 $sth->execute( $uid, $digest, $member );
833 $resultcode=1;
836 logaction("MEMBERS", "CHANGE PASS", $member, "") if C4::Context->preference("BorrowersLog");
837 return $resultcode;
842 =head2 fixup_cardnumber
844 Warning: The caller is responsible for locking the members table in write
845 mode, to avoid database corruption.
847 =cut
849 use vars qw( @weightings );
850 my @weightings = ( 8, 4, 6, 3, 5, 2, 1 );
852 sub fixup_cardnumber {
853 my ($cardnumber) = @_;
854 my $autonumber_members = C4::Context->boolean_preference('autoMemberNum') || 0;
856 # Find out whether member numbers should be generated
857 # automatically. Should be either "1" or something else.
858 # Defaults to "0", which is interpreted as "no".
860 # if ($cardnumber !~ /\S/ && $autonumber_members) {
861 ($autonumber_members) or return $cardnumber;
862 my $checkdigit = C4::Context->preference('checkdigit');
863 my $dbh = C4::Context->dbh;
864 if ( $checkdigit and $checkdigit eq 'katipo' ) {
866 # if checkdigit is selected, calculate katipo-style cardnumber.
867 # otherwise, just use the max()
868 # purpose: generate checksum'd member numbers.
869 # We'll assume we just got the max value of digits 2-8 of member #'s
870 # from the database and our job is to increment that by one,
871 # determine the 1st and 9th digits and return the full string.
872 my $sth = $dbh->prepare(
873 "select max(substring(borrowers.cardnumber,2,7)) as new_num from borrowers"
875 $sth->execute;
876 my $data = $sth->fetchrow_hashref;
877 $cardnumber = $data->{new_num};
878 if ( !$cardnumber ) { # If DB has no values,
879 $cardnumber = 1000000; # start at 1000000
880 } else {
881 $cardnumber += 1;
884 my $sum = 0;
885 for ( my $i = 0 ; $i < 8 ; $i += 1 ) {
886 # read weightings, left to right, 1 char at a time
887 my $temp1 = $weightings[$i];
889 # sequence left to right, 1 char at a time
890 my $temp2 = substr( $cardnumber, $i, 1 );
892 # mult each char 1-7 by its corresponding weighting
893 $sum += $temp1 * $temp2;
896 my $rem = ( $sum % 11 );
897 $rem = 'X' if $rem == 10;
899 return "V$cardnumber$rem";
900 } else {
902 my $sth = $dbh->prepare(
903 'SELECT MAX( CAST( cardnumber AS SIGNED ) ) FROM borrowers WHERE cardnumber REGEXP "^-?[0-9]+$"'
905 $sth->execute;
906 my ($result) = $sth->fetchrow;
907 return $result + 1;
909 return $cardnumber; # just here as a fallback/reminder
912 =head2 GetGuarantees
914 ($num_children, $children_arrayref) = &GetGuarantees($parent_borrno);
915 $child0_cardno = $children_arrayref->[0]{"cardnumber"};
916 $child0_borrno = $children_arrayref->[0]{"borrowernumber"};
918 C<&GetGuarantees> takes a borrower number (e.g., that of a patron
919 with children) and looks up the borrowers who are guaranteed by that
920 borrower (i.e., the patron's children).
922 C<&GetGuarantees> returns two values: an integer giving the number of
923 borrowers guaranteed by C<$parent_borrno>, and a reference to an array
924 of references to hash, which gives the actual results.
926 =cut
929 sub GetGuarantees {
930 my ($borrowernumber) = @_;
931 my $dbh = C4::Context->dbh;
932 my $sth =
933 $dbh->prepare(
934 "select cardnumber,borrowernumber, firstname, surname from borrowers where guarantorid=?"
936 $sth->execute($borrowernumber);
938 my @dat;
939 my $data = $sth->fetchall_arrayref({});
940 return ( scalar(@$data), $data );
943 =head2 UpdateGuarantees
945 &UpdateGuarantees($parent_borrno);
948 C<&UpdateGuarantees> borrower data for an adult and updates all the guarantees
949 with the modified information
951 =cut
954 sub UpdateGuarantees {
955 my %data = shift;
956 my $dbh = C4::Context->dbh;
957 my ( $count, $guarantees ) = GetGuarantees( $data{'borrowernumber'} );
958 foreach my $guarantee (@$guarantees){
959 my $guaquery = qq|UPDATE borrowers
960 SET address=?,fax=?,B_city=?,mobile=?,city=?,phone=?
961 WHERE borrowernumber=?
963 my $sth = $dbh->prepare($guaquery);
964 $sth->execute($data{'address'},$data{'fax'},$data{'B_city'},$data{'mobile'},$data{'city'},$data{'phone'},$guarantee->{'borrowernumber'});
967 =head2 GetPendingIssues
969 my $issues = &GetPendingIssues(@borrowernumber);
971 Looks up what the patron with the given borrowernumber has borrowed.
973 C<&GetPendingIssues> returns a
974 reference-to-array where each element is a reference-to-hash; the
975 keys are the fields from the C<issues>, C<biblio>, and C<items> tables.
976 The keys include C<biblioitems> fields except marc and marcxml.
978 =cut
981 sub GetPendingIssues {
982 my @borrowernumbers = @_;
984 unless (@borrowernumbers ) { # return a ref_to_array
985 return \@borrowernumbers; # to not cause surprise to caller
988 # Borrowers part of the query
989 my $bquery = '';
990 for (my $i = 0; $i < @borrowernumbers; $i++) {
991 $bquery .= ' issues.borrowernumber = ?';
992 if ($i < $#borrowernumbers ) {
993 $bquery .= ' OR';
997 # must avoid biblioitems.* to prevent large marc and marcxml fields from killing performance
998 # FIXME: namespace collision: each table has "timestamp" fields. Which one is "timestamp" ?
999 # FIXME: circ/ciculation.pl tries to sort by timestamp!
1000 # FIXME: namespace collision: other collisions possible.
1001 # FIXME: most of this data isn't really being used by callers.
1002 my $query =
1003 "SELECT issues.*,
1004 items.*,
1005 biblio.*,
1006 biblioitems.volume,
1007 biblioitems.number,
1008 biblioitems.itemtype,
1009 biblioitems.isbn,
1010 biblioitems.issn,
1011 biblioitems.publicationyear,
1012 biblioitems.publishercode,
1013 biblioitems.volumedate,
1014 biblioitems.volumedesc,
1015 biblioitems.lccn,
1016 biblioitems.url,
1017 borrowers.firstname,
1018 borrowers.surname,
1019 borrowers.cardnumber,
1020 issues.timestamp AS timestamp,
1021 issues.renewals AS renewals,
1022 issues.borrowernumber AS borrowernumber,
1023 items.renewals AS totalrenewals
1024 FROM issues
1025 LEFT JOIN items ON items.itemnumber = issues.itemnumber
1026 LEFT JOIN biblio ON items.biblionumber = biblio.biblionumber
1027 LEFT JOIN biblioitems ON items.biblioitemnumber = biblioitems.biblioitemnumber
1028 LEFT JOIN borrowers ON issues.borrowernumber = borrowers.borrowernumber
1029 WHERE
1030 $bquery
1031 ORDER BY issues.issuedate"
1034 my $sth = C4::Context->dbh->prepare($query);
1035 $sth->execute(@borrowernumbers);
1036 my $data = $sth->fetchall_arrayref({});
1037 my $tz = C4::Context->tz();
1038 my $today = DateTime->now( time_zone => $tz);
1039 foreach (@{$data}) {
1040 if ($_->{issuedate}) {
1041 $_->{issuedate} = dt_from_string($_->{issuedate}, 'sql');
1043 $_->{date_due} or next;
1044 $_->{date_due} = DateTime::Format::DateParse->parse_datetime($_->{date_due}, $tz->name());
1045 if ( DateTime->compare($_->{date_due}, $today) == -1 ) {
1046 $_->{overdue} = 1;
1049 return $data;
1052 =head2 GetAllIssues
1054 $issues = &GetAllIssues($borrowernumber, $sortkey, $limit);
1056 Looks up what the patron with the given borrowernumber has borrowed,
1057 and sorts the results.
1059 C<$sortkey> is the name of a field on which to sort the results. This
1060 should be the name of a field in the C<issues>, C<biblio>,
1061 C<biblioitems>, or C<items> table in the Koha database.
1063 C<$limit> is the maximum number of results to return.
1065 C<&GetAllIssues> an arrayref, C<$issues>, of hashrefs, the keys of which
1066 are the fields from the C<issues>, C<biblio>, C<biblioitems>, and
1067 C<items> tables of the Koha database.
1069 =cut
1072 sub GetAllIssues {
1073 my ( $borrowernumber, $order, $limit ) = @_;
1075 my $dbh = C4::Context->dbh;
1076 my $query =
1077 'SELECT *, issues.timestamp as issuestimestamp, issues.renewals AS renewals,items.renewals AS totalrenewals,items.timestamp AS itemstimestamp
1078 FROM issues
1079 LEFT JOIN items on items.itemnumber=issues.itemnumber
1080 LEFT JOIN biblio ON items.biblionumber=biblio.biblionumber
1081 LEFT JOIN biblioitems ON items.biblioitemnumber=biblioitems.biblioitemnumber
1082 WHERE borrowernumber=?
1083 UNION ALL
1084 SELECT *, old_issues.timestamp as issuestimestamp, old_issues.renewals AS renewals,items.renewals AS totalrenewals,items.timestamp AS itemstimestamp
1085 FROM old_issues
1086 LEFT JOIN items on items.itemnumber=old_issues.itemnumber
1087 LEFT JOIN biblio ON items.biblionumber=biblio.biblionumber
1088 LEFT JOIN biblioitems ON items.biblioitemnumber=biblioitems.biblioitemnumber
1089 WHERE borrowernumber=? AND old_issues.itemnumber IS NOT NULL
1090 order by ' . $order;
1091 if ($limit) {
1092 $query .= " limit $limit";
1095 my $sth = $dbh->prepare($query);
1096 $sth->execute( $borrowernumber, $borrowernumber );
1097 return $sth->fetchall_arrayref( {} );
1101 =head2 GetMemberAccountRecords
1103 ($total, $acctlines, $count) = &GetMemberAccountRecords($borrowernumber);
1105 Looks up accounting data for the patron with the given borrowernumber.
1107 C<&GetMemberAccountRecords> returns a three-element array. C<$acctlines> is a
1108 reference-to-array, where each element is a reference-to-hash; the
1109 keys are the fields of the C<accountlines> table in the Koha database.
1110 C<$count> is the number of elements in C<$acctlines>. C<$total> is the
1111 total amount outstanding for all of the account lines.
1113 =cut
1116 sub GetMemberAccountRecords {
1117 my ($borrowernumber,$date) = @_;
1118 my $dbh = C4::Context->dbh;
1119 my @acctlines;
1120 my $numlines = 0;
1121 my $strsth = qq(
1122 SELECT *
1123 FROM accountlines
1124 WHERE borrowernumber=?);
1125 my @bind = ($borrowernumber);
1126 if ($date && $date ne ''){
1127 $strsth.=" AND date < ? ";
1128 push(@bind,$date);
1130 $strsth.=" ORDER BY date desc,timestamp DESC";
1131 my $sth= $dbh->prepare( $strsth );
1132 $sth->execute( @bind );
1133 my $total = 0;
1134 while ( my $data = $sth->fetchrow_hashref ) {
1135 if ( $data->{itemnumber} ) {
1136 my $biblio = GetBiblioFromItemNumber( $data->{itemnumber} );
1137 $data->{biblionumber} = $biblio->{biblionumber};
1138 $data->{title} = $biblio->{title};
1140 $acctlines[$numlines] = $data;
1141 $numlines++;
1142 $total += int(1000 * $data->{'amountoutstanding'}); # convert float to integer to avoid round-off errors
1144 $total /= 1000;
1145 return ( $total, \@acctlines,$numlines);
1148 =head2 GetBorNotifyAcctRecord
1150 ($total, $acctlines, $count) = &GetBorNotifyAcctRecord($params,$notifyid);
1152 Looks up accounting data for the patron with the given borrowernumber per file number.
1154 C<&GetBorNotifyAcctRecord> returns a three-element array. C<$acctlines> is a
1155 reference-to-array, where each element is a reference-to-hash; the
1156 keys are the fields of the C<accountlines> table in the Koha database.
1157 C<$count> is the number of elements in C<$acctlines>. C<$total> is the
1158 total amount outstanding for all of the account lines.
1160 =cut
1162 sub GetBorNotifyAcctRecord {
1163 my ( $borrowernumber, $notifyid ) = @_;
1164 my $dbh = C4::Context->dbh;
1165 my @acctlines;
1166 my $numlines = 0;
1167 my $sth = $dbh->prepare(
1168 "SELECT *
1169 FROM accountlines
1170 WHERE borrowernumber=?
1171 AND notify_id=?
1172 AND amountoutstanding != '0'
1173 ORDER BY notify_id,accounttype
1176 $sth->execute( $borrowernumber, $notifyid );
1177 my $total = 0;
1178 while ( my $data = $sth->fetchrow_hashref ) {
1179 if ( $data->{itemnumber} ) {
1180 my $biblio = GetBiblioFromItemNumber( $data->{itemnumber} );
1181 $data->{biblionumber} = $biblio->{biblionumber};
1182 $data->{title} = $biblio->{title};
1184 $acctlines[$numlines] = $data;
1185 $numlines++;
1186 $total += int(100 * $data->{'amountoutstanding'});
1188 $total /= 100;
1189 return ( $total, \@acctlines, $numlines );
1192 =head2 checkuniquemember (OUEST-PROVENCE)
1194 ($result,$categorycode) = &checkuniquemember($collectivity,$surname,$firstname,$dateofbirth);
1196 Checks that a member exists or not in the database.
1198 C<&result> is nonzero (=exist) or 0 (=does not exist)
1199 C<&categorycode> is from categorycode table
1200 C<&collectivity> is 1 (= we add a collectivity) or 0 (= we add a physical member)
1201 C<&surname> is the surname
1202 C<&firstname> is the firstname (only if collectivity=0)
1203 C<&dateofbirth> is the date of birth in ISO format (only if collectivity=0)
1205 =cut
1207 # FIXME: This function is not legitimate. Multiple patrons might have the same first/last name and birthdate.
1208 # This is especially true since first name is not even a required field.
1210 sub checkuniquemember {
1211 my ( $collectivity, $surname, $firstname, $dateofbirth ) = @_;
1212 my $dbh = C4::Context->dbh;
1213 my $request = ($collectivity) ?
1214 "SELECT borrowernumber,categorycode FROM borrowers WHERE surname=? " :
1215 ($dateofbirth) ?
1216 "SELECT borrowernumber,categorycode FROM borrowers WHERE surname=? and firstname=? and dateofbirth=?" :
1217 "SELECT borrowernumber,categorycode FROM borrowers WHERE surname=? and firstname=?";
1218 my $sth = $dbh->prepare($request);
1219 if ($collectivity) {
1220 $sth->execute( uc($surname) );
1221 } elsif($dateofbirth){
1222 $sth->execute( uc($surname), ucfirst($firstname), $dateofbirth );
1223 }else{
1224 $sth->execute( uc($surname), ucfirst($firstname));
1226 my @data = $sth->fetchrow;
1227 ( $data[0] ) and return $data[0], $data[1];
1228 return 0;
1231 sub checkcardnumber {
1232 my ($cardnumber,$borrowernumber) = @_;
1233 # If cardnumber is null, we assume they're allowed.
1234 return 0 if !defined($cardnumber);
1235 my $dbh = C4::Context->dbh;
1236 my $query = "SELECT * FROM borrowers WHERE cardnumber=?";
1237 $query .= " AND borrowernumber <> ?" if ($borrowernumber);
1238 my $sth = $dbh->prepare($query);
1239 if ($borrowernumber) {
1240 $sth->execute($cardnumber,$borrowernumber);
1241 } else {
1242 $sth->execute($cardnumber);
1244 if (my $data= $sth->fetchrow_hashref()){
1245 return 1;
1247 else {
1248 return 0;
1253 =head2 getzipnamecity (OUEST-PROVENCE)
1255 take all info from table city for the fields city and zip
1256 check for the name and the zip code of the city selected
1258 =cut
1260 sub getzipnamecity {
1261 my ($cityid) = @_;
1262 my $dbh = C4::Context->dbh;
1263 my $sth =
1264 $dbh->prepare(
1265 "select city_name,city_state,city_zipcode,city_country from cities where cityid=? ");
1266 $sth->execute($cityid);
1267 my @data = $sth->fetchrow;
1268 return $data[0], $data[1], $data[2], $data[3];
1272 =head2 getdcity (OUEST-PROVENCE)
1274 recover cityid with city_name condition
1276 =cut
1278 sub getidcity {
1279 my ($city_name) = @_;
1280 my $dbh = C4::Context->dbh;
1281 my $sth = $dbh->prepare("select cityid from cities where city_name=? ");
1282 $sth->execute($city_name);
1283 my $data = $sth->fetchrow;
1284 return $data;
1287 =head2 GetFirstValidEmailAddress
1289 $email = GetFirstValidEmailAddress($borrowernumber);
1291 Return the first valid email address for a borrower, given the borrowernumber. For now, the order
1292 is defined as email, emailpro, B_email. Returns the empty string if the borrower has no email
1293 addresses.
1295 =cut
1297 sub GetFirstValidEmailAddress {
1298 my $borrowernumber = shift;
1299 my $dbh = C4::Context->dbh;
1300 my $sth = $dbh->prepare( "SELECT email, emailpro, B_email FROM borrowers where borrowernumber = ? ");
1301 $sth->execute( $borrowernumber );
1302 my $data = $sth->fetchrow_hashref;
1304 if ($data->{'email'}) {
1305 return $data->{'email'};
1306 } elsif ($data->{'emailpro'}) {
1307 return $data->{'emailpro'};
1308 } elsif ($data->{'B_email'}) {
1309 return $data->{'B_email'};
1310 } else {
1311 return '';
1315 =head2 GetExpiryDate
1317 $expirydate = GetExpiryDate($categorycode, $dateenrolled);
1319 Calculate expiry date given a categorycode and starting date. Date argument must be in ISO format.
1320 Return date is also in ISO format.
1322 =cut
1324 sub GetExpiryDate {
1325 my ( $categorycode, $dateenrolled ) = @_;
1326 my $enrolments;
1327 if ($categorycode) {
1328 my $dbh = C4::Context->dbh;
1329 my $sth = $dbh->prepare("SELECT enrolmentperiod,enrolmentperioddate FROM categories WHERE categorycode=?");
1330 $sth->execute($categorycode);
1331 $enrolments = $sth->fetchrow_hashref;
1333 # die "GetExpiryDate: for enrollmentperiod $enrolmentperiod (category '$categorycode') starting $dateenrolled.\n";
1334 my @date = split (/-/,$dateenrolled);
1335 if($enrolments->{enrolmentperiod}){
1336 return sprintf("%04d-%02d-%02d", Add_Delta_YM(@date,0,$enrolments->{enrolmentperiod}));
1337 }else{
1338 return $enrolments->{enrolmentperioddate};
1342 =head2 checkuserpassword (OUEST-PROVENCE)
1344 check for the password and login are not used
1345 return the number of record
1346 0=> NOT USED 1=> USED
1348 =cut
1350 sub checkuserpassword {
1351 my ( $borrowernumber, $userid, $password ) = @_;
1352 $password = md5_base64($password);
1353 my $dbh = C4::Context->dbh;
1354 my $sth =
1355 $dbh->prepare(
1356 "Select count(*) from borrowers where borrowernumber !=? and userid =? and password=? "
1358 $sth->execute( $borrowernumber, $userid, $password );
1359 my $number_rows = $sth->fetchrow;
1360 return $number_rows;
1364 =head2 GetborCatFromCatType
1366 ($codes_arrayref, $labels_hashref) = &GetborCatFromCatType();
1368 Looks up the different types of borrowers in the database. Returns two
1369 elements: a reference-to-array, which lists the borrower category
1370 codes, and a reference-to-hash, which maps the borrower category codes
1371 to category descriptions.
1373 =cut
1376 sub GetborCatFromCatType {
1377 my ( $category_type, $action ) = @_;
1378 # FIXME - This API seems both limited and dangerous.
1379 my $dbh = C4::Context->dbh;
1380 my $request = qq| SELECT categorycode,description
1381 FROM categories
1382 $action
1383 ORDER BY categorycode|;
1384 my $sth = $dbh->prepare($request);
1385 if ($action) {
1386 $sth->execute($category_type);
1388 else {
1389 $sth->execute();
1392 my %labels;
1393 my @codes;
1395 while ( my $data = $sth->fetchrow_hashref ) {
1396 push @codes, $data->{'categorycode'};
1397 $labels{ $data->{'categorycode'} } = $data->{'description'};
1399 return ( \@codes, \%labels );
1402 =head2 GetBorrowercategory
1404 $hashref = &GetBorrowercategory($categorycode);
1406 Given the borrower's category code, the function returns the corresponding
1407 data hashref for a comprehensive information display.
1409 =cut
1411 sub GetBorrowercategory {
1412 my ($catcode) = @_;
1413 my $dbh = C4::Context->dbh;
1414 if ($catcode){
1415 my $sth =
1416 $dbh->prepare(
1417 "SELECT description,dateofbirthrequired,upperagelimit,category_type
1418 FROM categories
1419 WHERE categorycode = ?"
1421 $sth->execute($catcode);
1422 my $data =
1423 $sth->fetchrow_hashref;
1424 return $data;
1426 return;
1427 } # sub getborrowercategory
1430 =head2 GetBorrowerCategorycode
1432 $categorycode = &GetBorrowerCategoryCode( $borrowernumber );
1434 Given the borrowernumber, the function returns the corresponding categorycode
1435 =cut
1437 sub GetBorrowerCategorycode {
1438 my ( $borrowernumber ) = @_;
1439 my $dbh = C4::Context->dbh;
1440 my $sth = $dbh->prepare( qq{
1441 SELECT categorycode
1442 FROM borrowers
1443 WHERE borrowernumber = ?
1444 } );
1445 $sth->execute( $borrowernumber );
1446 return $sth->fetchrow;
1449 =head2 GetBorrowercategoryList
1451 $arrayref_hashref = &GetBorrowercategoryList;
1452 If no category code provided, the function returns all the categories.
1454 =cut
1456 sub GetBorrowercategoryList {
1457 my $dbh = C4::Context->dbh;
1458 my $sth =
1459 $dbh->prepare(
1460 "SELECT *
1461 FROM categories
1462 ORDER BY description"
1464 $sth->execute;
1465 my $data =
1466 $sth->fetchall_arrayref({});
1467 return $data;
1468 } # sub getborrowercategory
1470 =head2 ethnicitycategories
1472 ($codes_arrayref, $labels_hashref) = &ethnicitycategories();
1474 Looks up the different ethnic types in the database. Returns two
1475 elements: a reference-to-array, which lists the ethnicity codes, and a
1476 reference-to-hash, which maps the ethnicity codes to ethnicity
1477 descriptions.
1479 =cut
1483 sub ethnicitycategories {
1484 my $dbh = C4::Context->dbh;
1485 my $sth = $dbh->prepare("Select code,name from ethnicity order by name");
1486 $sth->execute;
1487 my %labels;
1488 my @codes;
1489 while ( my $data = $sth->fetchrow_hashref ) {
1490 push @codes, $data->{'code'};
1491 $labels{ $data->{'code'} } = $data->{'name'};
1493 return ( \@codes, \%labels );
1496 =head2 fixEthnicity
1498 $ethn_name = &fixEthnicity($ethn_code);
1500 Takes an ethnicity code (e.g., "european" or "pi") and returns the
1501 corresponding descriptive name from the C<ethnicity> table in the
1502 Koha database ("European" or "Pacific Islander").
1504 =cut
1508 sub fixEthnicity {
1509 my $ethnicity = shift;
1510 return unless $ethnicity;
1511 my $dbh = C4::Context->dbh;
1512 my $sth = $dbh->prepare("Select name from ethnicity where code = ?");
1513 $sth->execute($ethnicity);
1514 my $data = $sth->fetchrow_hashref;
1515 return $data->{'name'};
1516 } # sub fixEthnicity
1518 =head2 GetAge
1520 $dateofbirth,$date = &GetAge($date);
1522 this function return the borrowers age with the value of dateofbirth
1524 =cut
1527 sub GetAge{
1528 my ( $date, $date_ref ) = @_;
1530 if ( not defined $date_ref ) {
1531 $date_ref = sprintf( '%04d-%02d-%02d', Today() );
1534 my ( $year1, $month1, $day1 ) = split /-/, $date;
1535 my ( $year2, $month2, $day2 ) = split /-/, $date_ref;
1537 my $age = $year2 - $year1;
1538 if ( $month1 . $day1 > $month2 . $day2 ) {
1539 $age--;
1542 return $age;
1543 } # sub get_age
1545 =head2 get_institutions
1547 $insitutions = get_institutions();
1549 Just returns a list of all the borrowers of type I, borrownumber and name
1551 =cut
1554 sub get_institutions {
1555 my $dbh = C4::Context->dbh();
1556 my $sth =
1557 $dbh->prepare(
1558 "SELECT borrowernumber,surname FROM borrowers WHERE categorycode=? ORDER BY surname"
1560 $sth->execute('I');
1561 my %orgs;
1562 while ( my $data = $sth->fetchrow_hashref() ) {
1563 $orgs{ $data->{'borrowernumber'} } = $data;
1565 return ( \%orgs );
1567 } # sub get_institutions
1569 =head2 add_member_orgs
1571 add_member_orgs($borrowernumber,$borrowernumbers);
1573 Takes a borrowernumber and a list of other borrowernumbers and inserts them into the borrowers_to_borrowers table
1575 =cut
1578 sub add_member_orgs {
1579 my ( $borrowernumber, $otherborrowers ) = @_;
1580 my $dbh = C4::Context->dbh();
1581 my $query =
1582 "INSERT INTO borrowers_to_borrowers (borrower1,borrower2) VALUES (?,?)";
1583 my $sth = $dbh->prepare($query);
1584 foreach my $otherborrowernumber (@$otherborrowers) {
1585 $sth->execute( $borrowernumber, $otherborrowernumber );
1588 } # sub add_member_orgs
1590 =head2 GetCities
1592 $cityarrayref = GetCities();
1594 Returns an array_ref of the entries in the cities table
1595 If there are entries in the table an empty row is returned
1596 This is currently only used to populate a popup in memberentry
1598 =cut
1600 sub GetCities {
1602 my $dbh = C4::Context->dbh;
1603 my $city_arr = $dbh->selectall_arrayref(
1604 q|SELECT cityid,city_zipcode,city_name,city_state,city_country FROM cities ORDER BY city_name|,
1605 { Slice => {} });
1606 if ( @{$city_arr} ) {
1607 unshift @{$city_arr}, {
1608 city_zipcode => q{},
1609 city_name => q{},
1610 cityid => q{},
1611 city_state => q{},
1612 city_country => q{},
1616 return $city_arr;
1619 =head2 GetSortDetails (OUEST-PROVENCE)
1621 ($lib) = &GetSortDetails($category,$sortvalue);
1623 Returns the authorized value details
1624 C<&$lib>return value of authorized value details
1625 C<&$sortvalue>this is the value of authorized value
1626 C<&$category>this is the value of authorized value category
1628 =cut
1630 sub GetSortDetails {
1631 my ( $category, $sortvalue ) = @_;
1632 my $dbh = C4::Context->dbh;
1633 my $query = qq|SELECT lib
1634 FROM authorised_values
1635 WHERE category=?
1636 AND authorised_value=? |;
1637 my $sth = $dbh->prepare($query);
1638 $sth->execute( $category, $sortvalue );
1639 my $lib = $sth->fetchrow;
1640 return ($lib) if ($lib);
1641 return ($sortvalue) unless ($lib);
1644 =head2 MoveMemberToDeleted
1646 $result = &MoveMemberToDeleted($borrowernumber);
1648 Copy the record from borrowers to deletedborrowers table.
1650 =cut
1652 # FIXME: should do it in one SQL statement w/ subquery
1653 # Otherwise, we should return the @data on success
1655 sub MoveMemberToDeleted {
1656 my ($member) = shift or return;
1657 my $dbh = C4::Context->dbh;
1658 my $query = qq|SELECT *
1659 FROM borrowers
1660 WHERE borrowernumber=?|;
1661 my $sth = $dbh->prepare($query);
1662 $sth->execute($member);
1663 my @data = $sth->fetchrow_array;
1664 (@data) or return; # if we got a bad borrowernumber, there's nothing to insert
1665 $sth =
1666 $dbh->prepare( "INSERT INTO deletedborrowers VALUES ("
1667 . ( "?," x ( scalar(@data) - 1 ) )
1668 . "?)" );
1669 $sth->execute(@data);
1672 =head2 DelMember
1674 DelMember($borrowernumber);
1676 This function remove directly a borrower whitout writing it on deleteborrower.
1677 + Deletes reserves for the borrower
1679 =cut
1681 sub DelMember {
1682 my $dbh = C4::Context->dbh;
1683 my $borrowernumber = shift;
1684 #warn "in delmember with $borrowernumber";
1685 return unless $borrowernumber; # borrowernumber is mandatory.
1687 my $query = qq|DELETE
1688 FROM reserves
1689 WHERE borrowernumber=?|;
1690 my $sth = $dbh->prepare($query);
1691 $sth->execute($borrowernumber);
1692 $query = "
1693 DELETE
1694 FROM borrowers
1695 WHERE borrowernumber = ?
1697 $sth = $dbh->prepare($query);
1698 $sth->execute($borrowernumber);
1699 logaction("MEMBERS", "DELETE", $borrowernumber, "") if C4::Context->preference("BorrowersLog");
1700 return $sth->rows;
1703 =head2 ExtendMemberSubscriptionTo (OUEST-PROVENCE)
1705 $date = ExtendMemberSubscriptionTo($borrowerid, $date);
1707 Extending the subscription to a given date or to the expiry date calculated on ISO date.
1708 Returns ISO date.
1710 =cut
1712 sub ExtendMemberSubscriptionTo {
1713 my ( $borrowerid,$date) = @_;
1714 my $dbh = C4::Context->dbh;
1715 my $borrower = GetMember('borrowernumber'=>$borrowerid);
1716 unless ($date){
1717 $date = (C4::Context->preference('BorrowerRenewalPeriodBase') eq 'dateexpiry') ?
1718 C4::Dates->new($borrower->{'dateexpiry'}, 'iso')->output("iso") :
1719 C4::Dates->new()->output("iso");
1720 $date = GetExpiryDate( $borrower->{'categorycode'}, $date );
1722 my $sth = $dbh->do(<<EOF);
1723 UPDATE borrowers
1724 SET dateexpiry='$date'
1725 WHERE borrowernumber='$borrowerid'
1727 # add enrolmentfee if needed
1728 $sth = $dbh->prepare("SELECT enrolmentfee FROM categories WHERE categorycode=?");
1729 $sth->execute($borrower->{'categorycode'});
1730 my ($enrolmentfee) = $sth->fetchrow;
1731 if ($enrolmentfee && $enrolmentfee > 0) {
1732 # insert fee in patron debts
1733 manualinvoice($borrower->{'borrowernumber'}, '', '', 'A', $enrolmentfee);
1735 logaction("MEMBERS", "RENEW", $borrower->{'borrowernumber'}, "Membership renewed")if C4::Context->preference("BorrowersLog");
1736 return $date if ($sth);
1737 return 0;
1740 =head2 GetRoadTypes (OUEST-PROVENCE)
1742 ($idroadtypearrayref, $roadttype_hashref) = &GetRoadTypes();
1744 Looks up the different road type . Returns two
1745 elements: a reference-to-array, which lists the id_roadtype
1746 codes, and a reference-to-hash, which maps the road type of the road .
1748 =cut
1750 sub GetRoadTypes {
1751 my $dbh = C4::Context->dbh;
1752 my $query = qq|
1753 SELECT roadtypeid,road_type
1754 FROM roadtype
1755 ORDER BY road_type|;
1756 my $sth = $dbh->prepare($query);
1757 $sth->execute();
1758 my %roadtype;
1759 my @id;
1761 # insert empty value to create a empty choice in cgi popup
1763 while ( my $data = $sth->fetchrow_hashref ) {
1765 push @id, $data->{'roadtypeid'};
1766 $roadtype{ $data->{'roadtypeid'} } = $data->{'road_type'};
1769 #test to know if the table contain some records if no the function return nothing
1770 my $id = @id;
1771 if ( $id eq 0 ) {
1772 return ();
1774 else {
1775 unshift( @id, "" );
1776 return ( \@id, \%roadtype );
1782 =head2 GetTitles (OUEST-PROVENCE)
1784 ($borrowertitle)= &GetTitles();
1786 Looks up the different title . Returns array with all borrowers title
1788 =cut
1790 sub GetTitles {
1791 my @borrowerTitle = split (/,|\|/,C4::Context->preference('BorrowersTitles'));
1792 unshift( @borrowerTitle, "" );
1793 my $count=@borrowerTitle;
1794 if ($count == 1){
1795 return ();
1797 else {
1798 return ( \@borrowerTitle);
1802 =head2 GetPatronImage
1804 my ($imagedata, $dberror) = GetPatronImage($cardnumber);
1806 Returns the mimetype and binary image data of the image for the patron with the supplied cardnumber.
1808 =cut
1810 sub GetPatronImage {
1811 my ($cardnumber) = @_;
1812 warn "Cardnumber passed to GetPatronImage is $cardnumber" if $debug;
1813 my $dbh = C4::Context->dbh;
1814 my $query = 'SELECT mimetype, imagefile FROM patronimage WHERE cardnumber = ?';
1815 my $sth = $dbh->prepare($query);
1816 $sth->execute($cardnumber);
1817 my $imagedata = $sth->fetchrow_hashref;
1818 warn "Database error!" if $sth->errstr;
1819 return $imagedata, $sth->errstr;
1822 =head2 PutPatronImage
1824 PutPatronImage($cardnumber, $mimetype, $imgfile);
1826 Stores patron binary image data and mimetype in database.
1827 NOTE: This function is good for updating images as well as inserting new images in the database.
1829 =cut
1831 sub PutPatronImage {
1832 my ($cardnumber, $mimetype, $imgfile) = @_;
1833 warn "Parameters passed in: Cardnumber=$cardnumber, Mimetype=$mimetype, " . ($imgfile ? "Imagefile" : "No Imagefile") if $debug;
1834 my $dbh = C4::Context->dbh;
1835 my $query = "INSERT INTO patronimage (cardnumber, mimetype, imagefile) VALUES (?,?,?) ON DUPLICATE KEY UPDATE imagefile = ?;";
1836 my $sth = $dbh->prepare($query);
1837 $sth->execute($cardnumber,$mimetype,$imgfile,$imgfile);
1838 warn "Error returned inserting $cardnumber.$mimetype." if $sth->errstr;
1839 return $sth->errstr;
1842 =head2 RmPatronImage
1844 my ($dberror) = RmPatronImage($cardnumber);
1846 Removes the image for the patron with the supplied cardnumber.
1848 =cut
1850 sub RmPatronImage {
1851 my ($cardnumber) = @_;
1852 warn "Cardnumber passed to GetPatronImage is $cardnumber" if $debug;
1853 my $dbh = C4::Context->dbh;
1854 my $query = "DELETE FROM patronimage WHERE cardnumber = ?;";
1855 my $sth = $dbh->prepare($query);
1856 $sth->execute($cardnumber);
1857 my $dberror = $sth->errstr;
1858 warn "Database error!" if $sth->errstr;
1859 return $dberror;
1862 =head2 GetHideLostItemsPreference
1864 $hidelostitemspref = &GetHideLostItemsPreference($borrowernumber);
1866 Returns the HideLostItems preference for the patron category of the supplied borrowernumber
1867 C<&$hidelostitemspref>return value of function, 0 or 1
1869 =cut
1871 sub GetHideLostItemsPreference {
1872 my ($borrowernumber) = @_;
1873 my $dbh = C4::Context->dbh;
1874 my $query = "SELECT hidelostitems FROM borrowers,categories WHERE borrowers.categorycode = categories.categorycode AND borrowernumber = ?";
1875 my $sth = $dbh->prepare($query);
1876 $sth->execute($borrowernumber);
1877 my $hidelostitems = $sth->fetchrow;
1878 return $hidelostitems;
1881 =head2 GetRoadTypeDetails (OUEST-PROVENCE)
1883 ($roadtype) = &GetRoadTypeDetails($roadtypeid);
1885 Returns the description of roadtype
1886 C<&$roadtype>return description of road type
1887 C<&$roadtypeid>this is the value of roadtype s
1889 =cut
1891 sub GetRoadTypeDetails {
1892 my ($roadtypeid) = @_;
1893 my $dbh = C4::Context->dbh;
1894 my $query = qq|
1895 SELECT road_type
1896 FROM roadtype
1897 WHERE roadtypeid=?|;
1898 my $sth = $dbh->prepare($query);
1899 $sth->execute($roadtypeid);
1900 my $roadtype = $sth->fetchrow;
1901 return ($roadtype);
1904 =head2 GetBorrowersWhoHaveNotBorrowedSince
1906 &GetBorrowersWhoHaveNotBorrowedSince($date)
1908 this function get all borrowers who haven't borrowed since the date given on input arg.
1910 =cut
1912 sub GetBorrowersWhoHaveNotBorrowedSince {
1913 my $filterdate = shift||POSIX::strftime("%Y-%m-%d",localtime());
1914 my $filterexpiry = shift;
1915 my $filterbranch = shift ||
1916 ((C4::Context->preference('IndependantBranches')
1917 && C4::Context->userenv
1918 && C4::Context->userenv->{flags} % 2 !=1
1919 && C4::Context->userenv->{branch})
1920 ? C4::Context->userenv->{branch}
1921 : "");
1922 my $dbh = C4::Context->dbh;
1923 my $query = "
1924 SELECT borrowers.borrowernumber,
1925 max(old_issues.timestamp) as latestissue,
1926 max(issues.timestamp) as currentissue
1927 FROM borrowers
1928 JOIN categories USING (categorycode)
1929 LEFT JOIN old_issues USING (borrowernumber)
1930 LEFT JOIN issues USING (borrowernumber)
1931 WHERE category_type <> 'S'
1932 AND borrowernumber NOT IN (SELECT guarantorid FROM borrowers WHERE guarantorid IS NOT NULL AND guarantorid <> 0)
1934 my @query_params;
1935 if ($filterbranch && $filterbranch ne ""){
1936 $query.=" AND borrowers.branchcode= ?";
1937 push @query_params,$filterbranch;
1939 if($filterexpiry){
1940 $query .= " AND dateexpiry < ? ";
1941 push @query_params,$filterdate;
1943 $query.=" GROUP BY borrowers.borrowernumber";
1944 if ($filterdate){
1945 $query.=" HAVING (latestissue < ? OR latestissue IS NULL)
1946 AND currentissue IS NULL";
1947 push @query_params,$filterdate;
1949 warn $query if $debug;
1950 my $sth = $dbh->prepare($query);
1951 if (scalar(@query_params)>0){
1952 $sth->execute(@query_params);
1954 else {
1955 $sth->execute;
1958 my @results;
1959 while ( my $data = $sth->fetchrow_hashref ) {
1960 push @results, $data;
1962 return \@results;
1965 =head2 GetBorrowersWhoHaveNeverBorrowed
1967 $results = &GetBorrowersWhoHaveNeverBorrowed
1969 This function get all borrowers who have never borrowed.
1971 I<$result> is a ref to an array which all elements are a hasref.
1973 =cut
1975 sub GetBorrowersWhoHaveNeverBorrowed {
1976 my $filterbranch = shift ||
1977 ((C4::Context->preference('IndependantBranches')
1978 && C4::Context->userenv
1979 && C4::Context->userenv->{flags} % 2 !=1
1980 && C4::Context->userenv->{branch})
1981 ? C4::Context->userenv->{branch}
1982 : "");
1983 my $dbh = C4::Context->dbh;
1984 my $query = "
1985 SELECT borrowers.borrowernumber,max(timestamp) as latestissue
1986 FROM borrowers
1987 LEFT JOIN issues ON borrowers.borrowernumber = issues.borrowernumber
1988 WHERE issues.borrowernumber IS NULL
1990 my @query_params;
1991 if ($filterbranch && $filterbranch ne ""){
1992 $query.=" AND borrowers.branchcode= ?";
1993 push @query_params,$filterbranch;
1995 warn $query if $debug;
1997 my $sth = $dbh->prepare($query);
1998 if (scalar(@query_params)>0){
1999 $sth->execute(@query_params);
2001 else {
2002 $sth->execute;
2005 my @results;
2006 while ( my $data = $sth->fetchrow_hashref ) {
2007 push @results, $data;
2009 return \@results;
2012 =head2 GetBorrowersWithIssuesHistoryOlderThan
2014 $results = &GetBorrowersWithIssuesHistoryOlderThan($date)
2016 this function get all borrowers who has an issue history older than I<$date> given on input arg.
2018 I<$result> is a ref to an array which all elements are a hashref.
2019 This hashref is containt the number of time this borrowers has borrowed before I<$date> and the borrowernumber.
2021 =cut
2023 sub GetBorrowersWithIssuesHistoryOlderThan {
2024 my $dbh = C4::Context->dbh;
2025 my $date = shift ||POSIX::strftime("%Y-%m-%d",localtime());
2026 my $filterbranch = shift ||
2027 ((C4::Context->preference('IndependantBranches')
2028 && C4::Context->userenv
2029 && C4::Context->userenv->{flags} % 2 !=1
2030 && C4::Context->userenv->{branch})
2031 ? C4::Context->userenv->{branch}
2032 : "");
2033 my $query = "
2034 SELECT count(borrowernumber) as n,borrowernumber
2035 FROM old_issues
2036 WHERE returndate < ?
2037 AND borrowernumber IS NOT NULL
2039 my @query_params;
2040 push @query_params, $date;
2041 if ($filterbranch){
2042 $query.=" AND branchcode = ?";
2043 push @query_params, $filterbranch;
2045 $query.=" GROUP BY borrowernumber ";
2046 warn $query if $debug;
2047 my $sth = $dbh->prepare($query);
2048 $sth->execute(@query_params);
2049 my @results;
2051 while ( my $data = $sth->fetchrow_hashref ) {
2052 push @results, $data;
2054 return \@results;
2057 =head2 GetBorrowersNamesAndLatestIssue
2059 $results = &GetBorrowersNamesAndLatestIssueList(@borrowernumbers)
2061 this function get borrowers Names and surnames and Issue information.
2063 I<@borrowernumbers> is an array which all elements are borrowernumbers.
2064 This hashref is containt the number of time this borrowers has borrowed before I<$date> and the borrowernumber.
2066 =cut
2068 sub GetBorrowersNamesAndLatestIssue {
2069 my $dbh = C4::Context->dbh;
2070 my @borrowernumbers=@_;
2071 my $query = "
2072 SELECT surname,lastname, phone, email,max(timestamp)
2073 FROM borrowers
2074 LEFT JOIN issues ON borrowers.borrowernumber=issues.borrowernumber
2075 GROUP BY borrowernumber
2077 my $sth = $dbh->prepare($query);
2078 $sth->execute;
2079 my $results = $sth->fetchall_arrayref({});
2080 return $results;
2083 =head2 DebarMember
2085 my $success = DebarMember( $borrowernumber, $todate );
2087 marks a Member as debarred, and therefore unable to checkout any more
2088 items.
2090 return :
2091 true on success, false on failure
2093 =cut
2095 sub DebarMember {
2096 my $borrowernumber = shift;
2097 my $todate = shift;
2099 return unless defined $borrowernumber;
2100 return unless $borrowernumber =~ /^\d+$/;
2102 return ModMember(
2103 borrowernumber => $borrowernumber,
2104 debarred => $todate
2109 =head2 ModPrivacy
2111 =over 4
2113 my $success = ModPrivacy( $borrowernumber, $privacy );
2115 Update the privacy of a patron.
2117 return :
2118 true on success, false on failure
2120 =back
2122 =cut
2124 sub ModPrivacy {
2125 my $borrowernumber = shift;
2126 my $privacy = shift;
2127 return unless defined $borrowernumber;
2128 return unless $borrowernumber =~ /^\d+$/;
2130 return ModMember( borrowernumber => $borrowernumber,
2131 privacy => $privacy );
2134 =head2 AddMessage
2136 AddMessage( $borrowernumber, $message_type, $message, $branchcode );
2138 Adds a message to the messages table for the given borrower.
2140 Returns:
2141 True on success
2142 False on failure
2144 =cut
2146 sub AddMessage {
2147 my ( $borrowernumber, $message_type, $message, $branchcode ) = @_;
2149 my $dbh = C4::Context->dbh;
2151 if ( ! ( $borrowernumber && $message_type && $message && $branchcode ) ) {
2152 return;
2155 my $query = "INSERT INTO messages ( borrowernumber, branchcode, message_type, message ) VALUES ( ?, ?, ?, ? )";
2156 my $sth = $dbh->prepare($query);
2157 $sth->execute( $borrowernumber, $branchcode, $message_type, $message );
2158 logaction("MEMBERS", "ADDCIRCMESSAGE", $borrowernumber, $message) if C4::Context->preference("BorrowersLog");
2159 return 1;
2162 =head2 GetMessages
2164 GetMessages( $borrowernumber, $type );
2166 $type is message type, B for borrower, or L for Librarian.
2167 Empty type returns all messages of any type.
2169 Returns all messages for the given borrowernumber
2171 =cut
2173 sub GetMessages {
2174 my ( $borrowernumber, $type, $branchcode ) = @_;
2176 if ( ! $type ) {
2177 $type = '%';
2180 my $dbh = C4::Context->dbh;
2182 my $query = "SELECT
2183 branches.branchname,
2184 messages.*,
2185 message_date,
2186 messages.branchcode LIKE '$branchcode' AS can_delete
2187 FROM messages, branches
2188 WHERE borrowernumber = ?
2189 AND message_type LIKE ?
2190 AND messages.branchcode = branches.branchcode
2191 ORDER BY message_date DESC";
2192 my $sth = $dbh->prepare($query);
2193 $sth->execute( $borrowernumber, $type ) ;
2194 my @results;
2196 while ( my $data = $sth->fetchrow_hashref ) {
2197 my $d = C4::Dates->new( $data->{message_date}, 'iso' );
2198 $data->{message_date_formatted} = $d->output;
2199 push @results, $data;
2201 return \@results;
2205 =head2 GetMessages
2207 GetMessagesCount( $borrowernumber, $type );
2209 $type is message type, B for borrower, or L for Librarian.
2210 Empty type returns all messages of any type.
2212 Returns the number of messages for the given borrowernumber
2214 =cut
2216 sub GetMessagesCount {
2217 my ( $borrowernumber, $type, $branchcode ) = @_;
2219 if ( ! $type ) {
2220 $type = '%';
2223 my $dbh = C4::Context->dbh;
2225 my $query = "SELECT COUNT(*) as MsgCount FROM messages WHERE borrowernumber = ? AND message_type LIKE ?";
2226 my $sth = $dbh->prepare($query);
2227 $sth->execute( $borrowernumber, $type ) ;
2228 my @results;
2230 my $data = $sth->fetchrow_hashref;
2231 my $count = $data->{'MsgCount'};
2233 return $count;
2238 =head2 DeleteMessage
2240 DeleteMessage( $message_id );
2242 =cut
2244 sub DeleteMessage {
2245 my ( $message_id ) = @_;
2247 my $dbh = C4::Context->dbh;
2248 my $query = "SELECT * FROM messages WHERE message_id = ?";
2249 my $sth = $dbh->prepare($query);
2250 $sth->execute( $message_id );
2251 my $message = $sth->fetchrow_hashref();
2253 $query = "DELETE FROM messages WHERE message_id = ?";
2254 $sth = $dbh->prepare($query);
2255 $sth->execute( $message_id );
2256 logaction("MEMBERS", "DELCIRCMESSAGE", $message->{'borrowernumber'}, $message->{'message'}) if C4::Context->preference("BorrowersLog");
2259 =head2 IssueSlip
2261 IssueSlip($branchcode, $borrowernumber, $quickslip)
2263 Returns letter hash ( see C4::Letters::GetPreparedLetter )
2265 $quickslip is boolean, to indicate whether we want a quick slip
2267 =cut
2269 sub IssueSlip {
2270 my ($branch, $borrowernumber, $quickslip) = @_;
2272 # return unless ( C4::Context->boolean_preference('printcirculationslips') );
2274 my $now = POSIX::strftime("%Y-%m-%d", localtime);
2276 my $issueslist = GetPendingIssues($borrowernumber);
2277 foreach my $it (@$issueslist){
2278 if ((substr $it->{'issuedate'}, 0, 10) eq $now) {
2279 $it->{'now'} = 1;
2281 elsif ((substr $it->{'date_due'}, 0, 10) le $now) {
2282 $it->{'overdue'} = 1;
2285 $it->{'date_due'}=format_date($it->{'date_due'});
2287 my @issues = sort { $b->{'timestamp'} <=> $a->{'timestamp'} } @$issueslist;
2289 my ($letter_code, %repeat);
2290 if ( $quickslip ) {
2291 $letter_code = 'ISSUEQSLIP';
2292 %repeat = (
2293 'checkedout' => [ map {
2294 'biblio' => $_,
2295 'items' => $_,
2296 'issues' => $_,
2297 }, grep { $_->{'now'} } @issues ],
2300 else {
2301 $letter_code = 'ISSUESLIP';
2302 %repeat = (
2303 'checkedout' => [ map {
2304 'biblio' => $_,
2305 'items' => $_,
2306 'issues' => $_,
2307 }, grep { !$_->{'overdue'} } @issues ],
2309 'overdue' => [ map {
2310 'biblio' => $_,
2311 'items' => $_,
2312 'issues' => $_,
2313 }, grep { $_->{'overdue'} } @issues ],
2315 'news' => [ map {
2316 $_->{'timestamp'} = $_->{'newdate'};
2317 { opac_news => $_ }
2318 } @{ GetNewsToDisplay("slip") } ],
2322 return C4::Letters::GetPreparedLetter (
2323 module => 'circulation',
2324 letter_code => $letter_code,
2325 branchcode => $branch,
2326 tables => {
2327 'branches' => $branch,
2328 'borrowers' => $borrowernumber,
2330 repeat => \%repeat,
2334 =head2 GetBorrowersWithEmail
2336 ([$borrnum,$userid], ...) = GetBorrowersWithEmail('me@example.com');
2338 This gets a list of users and their basic details from their email address.
2339 As it's possible for multiple user to have the same email address, it provides
2340 you with all of them. If there is no userid for the user, there will be an
2341 C<undef> there. An empty list will be returned if there are no matches.
2343 =cut
2345 sub GetBorrowersWithEmail {
2346 my $email = shift;
2348 my $dbh = C4::Context->dbh;
2350 my $query = "SELECT borrowernumber, userid FROM borrowers WHERE email=?";
2351 my $sth=$dbh->prepare($query);
2352 $sth->execute($email);
2353 my @result = ();
2354 while (my $ref = $sth->fetch) {
2355 push @result, $ref;
2357 die "Failure searching for borrowers by email address: $sth->errstr" if $sth->err;
2358 return @result;
2362 END { } # module clean-up code here (global destructor)
2366 __END__
2368 =head1 AUTHOR
2370 Koha Team
2372 =cut