Bug 7767 - acqui/basketgroup.pl: our $template scoping for plack
[koha.git] / C4 / Members.pm
blob6161ac9f3003f9258d697dfd3f3e7f8be81b5a34
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;
42 our ($VERSION,@ISA,@EXPORT,@EXPORT_OK,$debug);
44 BEGIN {
45 $VERSION = 3.02;
46 $debug = $ENV{DEBUG} || 0;
47 require Exporter;
48 @ISA = qw(Exporter);
49 #Get data
50 push @EXPORT, qw(
51 &Search
52 &GetMemberDetails
53 &GetMemberRelatives
54 &GetMember
56 &GetGuarantees
58 &GetMemberIssuesAndFines
59 &GetPendingIssues
60 &GetAllIssues
62 &get_institutions
63 &getzipnamecity
64 &getidcity
66 &GetFirstValidEmailAddress
68 &GetAge
69 &GetCities
70 &GetRoadTypes
71 &GetRoadTypeDetails
72 &GetSortDetails
73 &GetTitles
75 &GetPatronImage
76 &PutPatronImage
77 &RmPatronImage
79 &GetHideLostItemsPreference
81 &IsMemberBlocked
82 &GetMemberAccountRecords
83 &GetBorNotifyAcctRecord
85 &GetborCatFromCatType
86 &GetBorrowercategory
87 &GetBorrowercategoryList
89 &GetBorrowersWhoHaveNotBorrowedSince
90 &GetBorrowersWhoHaveNeverBorrowed
91 &GetBorrowersWithIssuesHistoryOlderThan
93 &GetExpiryDate
95 &AddMessage
96 &DeleteMessage
97 &GetMessages
98 &GetMessagesCount
100 &IssueSlip
101 GetBorrowersWithEmail
104 #Modify data
105 push @EXPORT, qw(
106 &ModMember
107 &changepassword
108 &ModPrivacy
111 #Delete data
112 push @EXPORT, qw(
113 &DelMember
116 #Insert data
117 push @EXPORT, qw(
118 &AddMember
119 &add_member_orgs
120 &MoveMemberToDeleted
121 &ExtendMemberSubscriptionTo
124 #Check data
125 push @EXPORT, qw(
126 &checkuniquemember
127 &checkuserpassword
128 &Check_Userid
129 &Generate_Userid
130 &fixEthnicity
131 &ethnicitycategories
132 &fixup_cardnumber
133 &checkcardnumber
137 =head1 NAME
139 C4::Members - Perl Module containing convenience functions for member handling
141 =head1 SYNOPSIS
143 use C4::Members;
145 =head1 DESCRIPTION
147 This module contains routines for adding, modifying and deleting members/patrons/borrowers
149 =head1 FUNCTIONS
151 =head2 Search
153 $borrowers_result_array_ref = &Search($filter,$orderby, $limit,
154 $columns_out, $search_on_fields,$searchtype);
156 Looks up patrons (borrowers) on filter. A wrapper for SearchInTable('borrowers').
158 For C<$filter>, C<$orderby>, C<$limit>, C<&columns_out>, C<&search_on_fields> and C<&searchtype>
159 refer to C4::SQLHelper:SearchInTable().
161 Special C<$filter> key '' is effectively expanded to search on surname firstname othernamescw
162 and cardnumber unless C<&search_on_fields> is defined
164 Examples:
166 $borrowers = Search('abcd', 'cardnumber');
168 $borrowers = Search({''=>'abcd', category_type=>'I'}, 'surname');
170 =cut
172 sub _express_member_find {
173 my ($filter) = @_;
175 # this is used by circulation everytime a new borrowers cardnumber is scanned
176 # so we can check an exact match first, if that works return, otherwise do the rest
177 my $dbh = C4::Context->dbh;
178 my $query = "SELECT borrowernumber FROM borrowers WHERE cardnumber = ?";
179 if ( my $borrowernumber = $dbh->selectrow_array($query, undef, $filter) ) {
180 return( {"borrowernumber"=>$borrowernumber} );
183 my ($search_on_fields, $searchtype);
184 if ( length($filter) == 1 ) {
185 $search_on_fields = [ qw(surname) ];
186 $searchtype = 'start_with';
187 } else {
188 $search_on_fields = [ qw(surname firstname othernames cardnumber) ];
189 $searchtype = 'contain';
192 return (undef, $search_on_fields, $searchtype);
195 sub Search {
196 my ( $filter, $orderby, $limit, $columns_out, $search_on_fields, $searchtype ) = @_;
198 my $search_string;
199 my $found_borrower;
201 if ( my $fr = ref $filter ) {
202 if ( $fr eq "HASH" ) {
203 if ( my $search_string = $filter->{''} ) {
204 my ($member_filter, $member_search_on_fields, $member_searchtype) = _express_member_find($search_string);
205 if ($member_filter) {
206 $filter = $member_filter;
207 $found_borrower = 1;
208 } else {
209 $search_on_fields ||= $member_search_on_fields;
210 $searchtype ||= $member_searchtype;
214 else {
215 $search_string = $filter;
218 else {
219 $search_string = $filter;
220 my ($member_filter, $member_search_on_fields, $member_searchtype) = _express_member_find($search_string);
221 if ($member_filter) {
222 $filter = $member_filter;
223 $found_borrower = 1;
224 } else {
225 $search_on_fields ||= $member_search_on_fields;
226 $searchtype ||= $member_searchtype;
230 if ( !$found_borrower && C4::Context->preference('ExtendedPatronAttributes') && $search_string ) {
231 my $matching_records = C4::Members::Attributes::SearchIdMatchingAttribute($search_string);
232 if(scalar(@$matching_records)>0) {
233 if ( my $fr = ref $filter ) {
234 if ( $fr eq "HASH" ) {
235 my %f = %$filter;
236 $filter = [ $filter ];
237 delete $f{''};
238 push @$filter, { %f, "borrowernumber"=>$$matching_records };
240 else {
241 push @$filter, {"borrowernumber"=>$matching_records};
244 else {
245 $filter = [ $filter ];
246 push @$filter, {"borrowernumber"=>$matching_records};
251 # $showallbranches was not used at the time SearchMember() was mainstreamed into Search().
252 # Mentioning for the reference
254 if ( C4::Context->preference("IndependantBranches") ) { # && !$showallbranches){
255 if ( my $userenv = C4::Context->userenv ) {
256 my $branch = $userenv->{'branch'};
257 if ( ($userenv->{flags} % 2 !=1) &&
258 $branch && $branch ne "insecure" ){
260 if (my $fr = ref $filter) {
261 if ( $fr eq "HASH" ) {
262 $filter->{branchcode} = $branch;
264 else {
265 foreach (@$filter) {
266 $_ = { '' => $_ } unless ref $_;
267 $_->{branchcode} = $branch;
271 else {
272 $filter = { '' => $filter, branchcode => $branch };
278 if ($found_borrower) {
279 $searchtype = "exact";
281 $searchtype ||= "start_with";
283 return SearchInTable( "borrowers", $filter, $orderby, $limit, $columns_out, $search_on_fields, $searchtype );
286 =head2 GetMemberDetails
288 ($borrower) = &GetMemberDetails($borrowernumber, $cardnumber);
290 Looks up a patron and returns information about him or her. If
291 C<$borrowernumber> is true (nonzero), C<&GetMemberDetails> looks
292 up the borrower by number; otherwise, it looks up the borrower by card
293 number.
295 C<$borrower> is a reference-to-hash whose keys are the fields of the
296 borrowers table in the Koha database. In addition,
297 C<$borrower-E<gt>{flags}> is a hash giving more detailed information
298 about the patron. Its keys act as flags :
300 if $borrower->{flags}->{LOST} {
301 # Patron's card was reported lost
304 If the state of a flag means that the patron should not be
305 allowed to borrow any more books, then it will have a C<noissues> key
306 with a true value.
308 See patronflags for more details.
310 C<$borrower-E<gt>{authflags}> is a hash giving more detailed information
311 about the top-level permissions flags set for the borrower. For example,
312 if a user has the "editcatalogue" permission,
313 C<$borrower-E<gt>{authflags}-E<gt>{editcatalogue}> will exist and have
314 the value "1".
316 =cut
318 sub GetMemberDetails {
319 my ( $borrowernumber, $cardnumber ) = @_;
320 my $dbh = C4::Context->dbh;
321 my $query;
322 my $sth;
323 if ($borrowernumber) {
324 $sth = $dbh->prepare("SELECT borrowers.*,category_type,categories.description,reservefee,enrolmentperiod FROM borrowers LEFT JOIN categories ON borrowers.categorycode=categories.categorycode WHERE borrowernumber=?");
325 $sth->execute($borrowernumber);
327 elsif ($cardnumber) {
328 $sth = $dbh->prepare("SELECT borrowers.*,category_type,categories.description,reservefee,enrolmentperiod FROM borrowers LEFT JOIN categories ON borrowers.categorycode=categories.categorycode WHERE cardnumber=?");
329 $sth->execute($cardnumber);
331 else {
332 return undef;
334 my $borrower = $sth->fetchrow_hashref;
335 my ($amount) = GetMemberAccountRecords( $borrowernumber);
336 $borrower->{'amountoutstanding'} = $amount;
337 # FIXME - patronflags calls GetMemberAccountRecords... just have patronflags return $amount
338 my $flags = patronflags( $borrower);
339 my $accessflagshash;
341 $sth = $dbh->prepare("select bit,flag from userflags");
342 $sth->execute;
343 while ( my ( $bit, $flag ) = $sth->fetchrow ) {
344 if ( $borrower->{'flags'} && $borrower->{'flags'} & 2**$bit ) {
345 $accessflagshash->{$flag} = 1;
348 $borrower->{'flags'} = $flags;
349 $borrower->{'authflags'} = $accessflagshash;
351 # For the purposes of making templates easier, we'll define a
352 # 'showname' which is the alternate form the user's first name if
353 # 'other name' is defined.
354 if ($borrower->{category_type} eq 'I') {
355 $borrower->{'showname'} = $borrower->{'othernames'};
356 $borrower->{'showname'} .= " $borrower->{'firstname'}" if $borrower->{'firstname'};
357 } else {
358 $borrower->{'showname'} = $borrower->{'firstname'};
361 return ($borrower); #, $flags, $accessflagshash);
364 =head2 patronflags
366 $flags = &patronflags($patron);
368 This function is not exported.
370 The following will be set where applicable:
371 $flags->{CHARGES}->{amount} Amount of debt
372 $flags->{CHARGES}->{noissues} Set if debt amount >$5.00 (or syspref noissuescharge)
373 $flags->{CHARGES}->{message} Message -- deprecated
375 $flags->{CREDITS}->{amount} Amount of credit
376 $flags->{CREDITS}->{message} Message -- deprecated
378 $flags->{ GNA } Patron has no valid address
379 $flags->{ GNA }->{noissues} Set for each GNA
380 $flags->{ GNA }->{message} "Borrower has no valid address" -- deprecated
382 $flags->{ LOST } Patron's card reported lost
383 $flags->{ LOST }->{noissues} Set for each LOST
384 $flags->{ LOST }->{message} Message -- deprecated
386 $flags->{DBARRED} Set if patron debarred, no access
387 $flags->{DBARRED}->{noissues} Set for each DBARRED
388 $flags->{DBARRED}->{message} Message -- deprecated
390 $flags->{ NOTES }
391 $flags->{ NOTES }->{message} The note itself. NOT deprecated
393 $flags->{ ODUES } Set if patron has overdue books.
394 $flags->{ ODUES }->{message} "Yes" -- deprecated
395 $flags->{ ODUES }->{itemlist} ref-to-array: list of overdue books
396 $flags->{ ODUES }->{itemlisttext} Text list of overdue items -- deprecated
398 $flags->{WAITING} Set if any of patron's reserves are available
399 $flags->{WAITING}->{message} Message -- deprecated
400 $flags->{WAITING}->{itemlist} ref-to-array: list of available items
402 =over
404 =item C<$flags-E<gt>{ODUES}-E<gt>{itemlist}> is a reference-to-array listing the
405 overdue items. Its elements are references-to-hash, each describing an
406 overdue item. The keys are selected fields from the issues, biblio,
407 biblioitems, and items tables of the Koha database.
409 =item C<$flags-E<gt>{ODUES}-E<gt>{itemlisttext}> is a string giving a text listing of
410 the overdue items, one per line. Deprecated.
412 =item C<$flags-E<gt>{WAITING}-E<gt>{itemlist}> is a reference-to-array listing the
413 available items. Each element is a reference-to-hash whose keys are
414 fields from the reserves table of the Koha database.
416 =back
418 All the "message" fields that include language generated in this function are deprecated,
419 because such strings belong properly in the display layer.
421 The "message" field that comes from the DB is OK.
423 =cut
425 # TODO: use {anonymous => hashes} instead of a dozen %flaginfo
426 # FIXME rename this function.
427 sub patronflags {
428 my %flags;
429 my ( $patroninformation) = @_;
430 my $dbh=C4::Context->dbh;
431 my ($amount) = GetMemberAccountRecords( $patroninformation->{'borrowernumber'});
432 if ( $amount > 0 ) {
433 my %flaginfo;
434 my $noissuescharge = C4::Context->preference("noissuescharge") || 5;
435 $flaginfo{'message'} = sprintf "Patron owes \$%.02f", $amount;
436 $flaginfo{'amount'} = sprintf "%.02f", $amount;
437 if ( $amount > $noissuescharge && !C4::Context->preference("AllowFineOverride") ) {
438 $flaginfo{'noissues'} = 1;
440 $flags{'CHARGES'} = \%flaginfo;
442 elsif ( $amount < 0 ) {
443 my %flaginfo;
444 $flaginfo{'message'} = sprintf "Patron has credit of \$%.02f", -$amount;
445 $flaginfo{'amount'} = sprintf "%.02f", $amount;
446 $flags{'CREDITS'} = \%flaginfo;
448 if ( $patroninformation->{'gonenoaddress'}
449 && $patroninformation->{'gonenoaddress'} == 1 )
451 my %flaginfo;
452 $flaginfo{'message'} = 'Borrower has no valid address.';
453 $flaginfo{'noissues'} = 1;
454 $flags{'GNA'} = \%flaginfo;
456 if ( $patroninformation->{'lost'} && $patroninformation->{'lost'} == 1 ) {
457 my %flaginfo;
458 $flaginfo{'message'} = 'Borrower\'s card reported lost.';
459 $flaginfo{'noissues'} = 1;
460 $flags{'LOST'} = \%flaginfo;
462 if ( $patroninformation->{'debarred'} && check_date( split( /-/, $patroninformation->{'debarred'} ) ) ) {
463 if ( Date_to_Days(Date::Calc::Today) < Date_to_Days( split( /-/, $patroninformation->{'debarred'} ) ) ) {
464 my %flaginfo;
465 $flaginfo{'debarredcomment'} = $patroninformation->{'debarredcomment'};
466 $flaginfo{'message'} = $patroninformation->{'debarredcomment'};
467 $flaginfo{'noissues'} = 1;
468 $flaginfo{'dateend'} = $patroninformation->{'debarred'};
469 $flags{'DBARRED'} = \%flaginfo;
472 if ( $patroninformation->{'borrowernotes'}
473 && $patroninformation->{'borrowernotes'} )
475 my %flaginfo;
476 $flaginfo{'message'} = $patroninformation->{'borrowernotes'};
477 $flags{'NOTES'} = \%flaginfo;
479 my ( $odues, $itemsoverdue ) = C4::Overdues::checkoverdues($patroninformation->{'borrowernumber'});
480 if ( $odues && $odues > 0 ) {
481 my %flaginfo;
482 $flaginfo{'message'} = "Yes";
483 $flaginfo{'itemlist'} = $itemsoverdue;
484 foreach ( sort { $a->{'date_due'} cmp $b->{'date_due'} }
485 @$itemsoverdue )
487 $flaginfo{'itemlisttext'} .=
488 "$_->{'date_due'} $_->{'barcode'} $_->{'title'} \n"; # newline is display layer
490 $flags{'ODUES'} = \%flaginfo;
492 my @itemswaiting = C4::Reserves::GetReservesFromBorrowernumber( $patroninformation->{'borrowernumber'},'W' );
493 my $nowaiting = scalar @itemswaiting;
494 if ( $nowaiting > 0 ) {
495 my %flaginfo;
496 $flaginfo{'message'} = "Reserved items available";
497 $flaginfo{'itemlist'} = \@itemswaiting;
498 $flags{'WAITING'} = \%flaginfo;
500 return ( \%flags );
504 =head2 GetMember
506 $borrower = &GetMember(%information);
508 Retrieve the first patron record meeting on criteria listed in the
509 C<%information> hash, which should contain one or more
510 pairs of borrowers column names and values, e.g.,
512 $borrower = GetMember(borrowernumber => id);
514 C<&GetBorrower> returns a reference-to-hash whose keys are the fields of
515 the C<borrowers> table in the Koha database.
517 FIXME: GetMember() is used throughout the code as a lookup
518 on a unique key such as the borrowernumber, but this meaning is not
519 enforced in the routine itself.
521 =cut
524 sub GetMember {
525 my ( %information ) = @_;
526 if (exists $information{borrowernumber} && !defined $information{borrowernumber}) {
527 #passing mysql's kohaadmin?? Makes no sense as a query
528 return;
530 my $dbh = C4::Context->dbh;
531 my $select =
532 q{SELECT borrowers.*, categories.category_type, categories.description
533 FROM borrowers
534 LEFT JOIN categories on borrowers.categorycode=categories.categorycode WHERE };
535 my $more_p = 0;
536 my @values = ();
537 for (keys %information ) {
538 if ($more_p) {
539 $select .= ' AND ';
541 else {
542 $more_p++;
545 if (defined $information{$_}) {
546 $select .= "$_ = ?";
547 push @values, $information{$_};
549 else {
550 $select .= "$_ IS NULL";
553 $debug && warn $select, " ",values %information;
554 my $sth = $dbh->prepare("$select");
555 $sth->execute(map{$information{$_}} keys %information);
556 my $data = $sth->fetchall_arrayref({});
557 #FIXME interface to this routine now allows generation of a result set
558 #so whole array should be returned but bowhere in the current code expects this
559 if (@{$data} ) {
560 return $data->[0];
563 return;
566 =head2 GetMemberRelatives
568 @borrowernumbers = GetMemberRelatives($borrowernumber);
570 C<GetMemberRelatives> returns a borrowersnumber's list of guarantor/guarantees of the member given in parameter
572 =cut
573 sub GetMemberRelatives {
574 my $borrowernumber = shift;
575 my $dbh = C4::Context->dbh;
576 my @glist;
578 # Getting guarantor
579 my $query = "SELECT guarantorid FROM borrowers WHERE borrowernumber=?";
580 my $sth = $dbh->prepare($query);
581 $sth->execute($borrowernumber);
582 my $data = $sth->fetchrow_arrayref();
583 push @glist, $data->[0] if $data->[0];
584 my $guarantor = $data->[0] if $data->[0];
586 # Getting guarantees
587 $query = "SELECT borrowernumber FROM borrowers WHERE guarantorid=?";
588 $sth = $dbh->prepare($query);
589 $sth->execute($borrowernumber);
590 while ($data = $sth->fetchrow_arrayref()) {
591 push @glist, $data->[0];
594 # Getting sibling guarantees
595 if ($guarantor) {
596 $query = "SELECT borrowernumber FROM borrowers WHERE guarantorid=?";
597 $sth = $dbh->prepare($query);
598 $sth->execute($guarantor);
599 while ($data = $sth->fetchrow_arrayref()) {
600 push @glist, $data->[0] if ($data->[0] != $borrowernumber);
604 return @glist;
607 =head2 IsMemberBlocked
609 my ($block_status, $count) = IsMemberBlocked( $borrowernumber );
611 Returns whether a patron has overdue items that may result
612 in a block or whether the patron has active fine days
613 that would block circulation privileges.
615 C<$block_status> can have the following values:
617 1 if the patron has outstanding fine days, in which case C<$count> is the number of them
619 -1 if the patron has overdue items, in which case C<$count> is the number of them
621 0 if the patron has no overdue items or outstanding fine days, in which case C<$count> is 0
623 Outstanding fine days are checked before current overdue items
624 are.
626 FIXME: this needs to be split into two functions; a potential block
627 based on the number of current overdue items could be orthogonal
628 to a block based on whether the patron has any fine days accrued.
630 =cut
632 sub IsMemberBlocked {
633 my $borrowernumber = shift;
634 my $dbh = C4::Context->dbh;
636 my $blockeddate = CheckBorrowerDebarred($borrowernumber);
638 return ( 1, $blockeddate ) if $blockeddate;
640 # if he have late issues
641 my $sth = $dbh->prepare(
642 "SELECT COUNT(*) as latedocs
643 FROM issues
644 WHERE borrowernumber = ?
645 AND date_due < now()"
647 $sth->execute($borrowernumber);
648 my $latedocs = $sth->fetchrow_hashref->{'latedocs'};
650 return ( -1, $latedocs ) if $latedocs > 0;
652 return ( 0, 0 );
655 =head2 GetMemberIssuesAndFines
657 ($overdue_count, $issue_count, $total_fines) = &GetMemberIssuesAndFines($borrowernumber);
659 Returns aggregate data about items borrowed by the patron with the
660 given borrowernumber.
662 C<&GetMemberIssuesAndFines> returns a three-element array. C<$overdue_count> is the
663 number of overdue items the patron currently has borrowed. C<$issue_count> is the
664 number of books the patron currently has borrowed. C<$total_fines> is
665 the total fine currently due by the borrower.
667 =cut
670 sub GetMemberIssuesAndFines {
671 my ( $borrowernumber ) = @_;
672 my $dbh = C4::Context->dbh;
673 my $query = "SELECT COUNT(*) FROM issues WHERE borrowernumber = ?";
675 $debug and warn $query."\n";
676 my $sth = $dbh->prepare($query);
677 $sth->execute($borrowernumber);
678 my $issue_count = $sth->fetchrow_arrayref->[0];
680 $sth = $dbh->prepare(
681 "SELECT COUNT(*) FROM issues
682 WHERE borrowernumber = ?
683 AND date_due < now()"
685 $sth->execute($borrowernumber);
686 my $overdue_count = $sth->fetchrow_arrayref->[0];
688 $sth = $dbh->prepare("SELECT SUM(amountoutstanding) FROM accountlines WHERE borrowernumber = ?");
689 $sth->execute($borrowernumber);
690 my $total_fines = $sth->fetchrow_arrayref->[0];
692 return ($overdue_count, $issue_count, $total_fines);
695 sub columns(;$) {
696 return @{C4::Context->dbh->selectcol_arrayref("SHOW columns from borrowers")};
699 =head2 ModMember
701 my $success = ModMember(borrowernumber => $borrowernumber,
702 [ field => value ]... );
704 Modify borrower's data. All date fields should ALREADY be in ISO format.
706 return :
707 true on success, or false on failure
709 =cut
711 sub ModMember {
712 my (%data) = @_;
713 # test to know if you must update or not the borrower password
714 if (exists $data{password}) {
715 if ($data{password} eq '****' or $data{password} eq '') {
716 delete $data{password};
717 } else {
718 $data{password} = md5_base64($data{password});
721 my $execute_success=UpdateInTable("borrowers",\%data);
722 if ($execute_success) { # only proceed if the update was a success
723 # ok if its an adult (type) it may have borrowers that depend on it as a guarantor
724 # so when we update information for an adult we should check for guarantees and update the relevant part
725 # of their records, ie addresses and phone numbers
726 my $borrowercategory= GetBorrowercategory( $data{'category_type'} );
727 if ( exists $borrowercategory->{'category_type'} && $borrowercategory->{'category_type'} eq ('A' || 'S') ) {
728 # is adult check guarantees;
729 UpdateGuarantees(%data);
731 logaction("MEMBERS", "MODIFY", $data{'borrowernumber'}, "UPDATE (executed w/ arg: $data{'borrowernumber'})") if C4::Context->preference("BorrowersLog");
733 return $execute_success;
737 =head2 AddMember
739 $borrowernumber = &AddMember(%borrower);
741 insert new borrower into table
742 Returns the borrowernumber upon success
744 Returns as undef upon any db error without further processing
746 =cut
749 sub AddMember {
750 my (%data) = @_;
751 my $dbh = C4::Context->dbh;
752 # generate a proper login if none provided
753 $data{'userid'} = Generate_Userid($data{'borrowernumber'}, $data{'firstname'}, $data{'surname'}) if $data{'userid'} eq '';
754 # create a disabled account if no password provided
755 $data{'password'} = ($data{'password'})? md5_base64($data{'password'}) : '!';
756 $data{'borrowernumber'}=InsertInTable("borrowers",\%data);
757 # mysql_insertid is probably bad. not necessarily accurate and mysql-specific at best.
758 logaction("MEMBERS", "CREATE", $data{'borrowernumber'}, "") if C4::Context->preference("BorrowersLog");
760 # check for enrollment fee & add it if needed
761 my $sth = $dbh->prepare("SELECT enrolmentfee FROM categories WHERE categorycode=?");
762 $sth->execute($data{'categorycode'});
763 my ($enrolmentfee) = $sth->fetchrow;
764 if ($sth->err) {
765 warn sprintf('Database returned the following error: %s', $sth->errstr);
766 return;
768 if ($enrolmentfee && $enrolmentfee > 0) {
769 # insert fee in patron debts
770 manualinvoice($data{'borrowernumber'}, '', '', 'A', $enrolmentfee);
773 return $data{'borrowernumber'};
777 sub Check_Userid {
778 my ($uid,$member) = @_;
779 my $dbh = C4::Context->dbh;
780 # Make sure the userid chosen is unique and not theirs if non-empty. If it is not,
781 # Then we need to tell the user and have them create a new one.
782 my $sth =
783 $dbh->prepare(
784 "SELECT * FROM borrowers WHERE userid=? AND borrowernumber != ?");
785 $sth->execute( $uid, $member );
786 if ( ( $uid ne '' ) && ( my $row = $sth->fetchrow_hashref ) ) {
787 return 0;
789 else {
790 return 1;
794 sub Generate_Userid {
795 my ($borrowernumber, $firstname, $surname) = @_;
796 my $newuid;
797 my $offset = 0;
798 do {
799 $firstname =~ s/[[:digit:][:space:][:blank:][:punct:][:cntrl:]]//g;
800 $surname =~ s/[[:digit:][:space:][:blank:][:punct:][:cntrl:]]//g;
801 $newuid = lc(($firstname)? "$firstname.$surname" : $surname);
802 $newuid .= $offset unless $offset == 0;
803 $offset++;
805 } while (!Check_Userid($newuid,$borrowernumber));
807 return $newuid;
810 sub changepassword {
811 my ( $uid, $member, $digest ) = @_;
812 my $dbh = C4::Context->dbh;
814 #Make sure the userid chosen is unique and not theirs if non-empty. If it is not,
815 #Then we need to tell the user and have them create a new one.
816 my $resultcode;
817 my $sth =
818 $dbh->prepare(
819 "SELECT * FROM borrowers WHERE userid=? AND borrowernumber != ?");
820 $sth->execute( $uid, $member );
821 if ( ( $uid ne '' ) && ( my $row = $sth->fetchrow_hashref ) ) {
822 $resultcode=0;
824 else {
825 #Everything is good so we can update the information.
826 $sth =
827 $dbh->prepare(
828 "update borrowers set userid=?, password=? where borrowernumber=?");
829 $sth->execute( $uid, $digest, $member );
830 $resultcode=1;
833 logaction("MEMBERS", "CHANGE PASS", $member, "") if C4::Context->preference("BorrowersLog");
834 return $resultcode;
839 =head2 fixup_cardnumber
841 Warning: The caller is responsible for locking the members table in write
842 mode, to avoid database corruption.
844 =cut
846 use vars qw( @weightings );
847 my @weightings = ( 8, 4, 6, 3, 5, 2, 1 );
849 sub fixup_cardnumber ($) {
850 my ($cardnumber) = @_;
851 my $autonumber_members = C4::Context->boolean_preference('autoMemberNum') || 0;
853 # Find out whether member numbers should be generated
854 # automatically. Should be either "1" or something else.
855 # Defaults to "0", which is interpreted as "no".
857 # if ($cardnumber !~ /\S/ && $autonumber_members) {
858 ($autonumber_members) or return $cardnumber;
859 my $checkdigit = C4::Context->preference('checkdigit');
860 my $dbh = C4::Context->dbh;
861 if ( $checkdigit and $checkdigit eq 'katipo' ) {
863 # if checkdigit is selected, calculate katipo-style cardnumber.
864 # otherwise, just use the max()
865 # purpose: generate checksum'd member numbers.
866 # We'll assume we just got the max value of digits 2-8 of member #'s
867 # from the database and our job is to increment that by one,
868 # determine the 1st and 9th digits and return the full string.
869 my $sth = $dbh->prepare(
870 "select max(substring(borrowers.cardnumber,2,7)) as new_num from borrowers"
872 $sth->execute;
873 my $data = $sth->fetchrow_hashref;
874 $cardnumber = $data->{new_num};
875 if ( !$cardnumber ) { # If DB has no values,
876 $cardnumber = 1000000; # start at 1000000
877 } else {
878 $cardnumber += 1;
881 my $sum = 0;
882 for ( my $i = 0 ; $i < 8 ; $i += 1 ) {
883 # read weightings, left to right, 1 char at a time
884 my $temp1 = $weightings[$i];
886 # sequence left to right, 1 char at a time
887 my $temp2 = substr( $cardnumber, $i, 1 );
889 # mult each char 1-7 by its corresponding weighting
890 $sum += $temp1 * $temp2;
893 my $rem = ( $sum % 11 );
894 $rem = 'X' if $rem == 10;
896 return "V$cardnumber$rem";
897 } else {
899 # MODIFIED BY JF: mysql4.1 allows casting as an integer, which is probably
900 # better. I'll leave the original in in case it needs to be changed for you
901 # my $sth=$dbh->prepare("select max(borrowers.cardnumber) from borrowers");
902 my $sth = $dbh->prepare(
903 "select max(cast(cardnumber as signed)) from borrowers"
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: C4::Print::printslip tries to sort by timestamp!
1001 # FIXME: namespace collision: other collisions possible.
1002 # FIXME: most of this data isn't really being used by callers.
1003 my $query =
1004 "SELECT issues.*,
1005 items.*,
1006 biblio.*,
1007 biblioitems.volume,
1008 biblioitems.number,
1009 biblioitems.itemtype,
1010 biblioitems.isbn,
1011 biblioitems.issn,
1012 biblioitems.publicationyear,
1013 biblioitems.publishercode,
1014 biblioitems.volumedate,
1015 biblioitems.volumedesc,
1016 biblioitems.lccn,
1017 biblioitems.url,
1018 borrowers.firstname,
1019 borrowers.surname,
1020 borrowers.cardnumber,
1021 issues.timestamp AS timestamp,
1022 issues.renewals AS renewals,
1023 issues.borrowernumber AS borrowernumber,
1024 items.renewals AS totalrenewals
1025 FROM issues
1026 LEFT JOIN items ON items.itemnumber = issues.itemnumber
1027 LEFT JOIN biblio ON items.biblionumber = biblio.biblionumber
1028 LEFT JOIN biblioitems ON items.biblioitemnumber = biblioitems.biblioitemnumber
1029 LEFT JOIN borrowers ON issues.borrowernumber = borrowers.borrowernumber
1030 WHERE
1031 $bquery
1032 ORDER BY issues.issuedate"
1035 my $sth = C4::Context->dbh->prepare($query);
1036 $sth->execute(@borrowernumbers);
1037 my $data = $sth->fetchall_arrayref({});
1038 my $tz = C4::Context->tz();
1039 my $today = DateTime->now( time_zone => $tz);
1040 foreach (@{$data}) {
1041 if ($_->{issuedate}) {
1042 $_->{issuedate} = dt_from_string($_->{issuedate}, 'sql');
1044 $_->{date_due} or next;
1045 $_->{date_due} = DateTime::Format::DateParse->parse_datetime($_->{date_due}, $tz->name());
1046 if ( DateTime->compare($_->{date_due}, $today) == -1 ) {
1047 $_->{overdue} = 1;
1050 return $data;
1053 =head2 GetAllIssues
1055 $issues = &GetAllIssues($borrowernumber, $sortkey, $limit);
1057 Looks up what the patron with the given borrowernumber has borrowed,
1058 and sorts the results.
1060 C<$sortkey> is the name of a field on which to sort the results. This
1061 should be the name of a field in the C<issues>, C<biblio>,
1062 C<biblioitems>, or C<items> table in the Koha database.
1064 C<$limit> is the maximum number of results to return.
1066 C<&GetAllIssues> an arrayref, C<$issues>, of hashrefs, the keys of which
1067 are the fields from the C<issues>, C<biblio>, C<biblioitems>, and
1068 C<items> tables of the Koha database.
1070 =cut
1073 sub GetAllIssues {
1074 my ( $borrowernumber, $order, $limit ) = @_;
1076 #FIXME: sanity-check order and limit
1077 my $dbh = C4::Context->dbh;
1078 my $query =
1079 "SELECT *, issues.timestamp as issuestimestamp, issues.renewals AS renewals,items.renewals AS totalrenewals,items.timestamp AS itemstimestamp
1080 FROM issues
1081 LEFT JOIN items on items.itemnumber=issues.itemnumber
1082 LEFT JOIN biblio ON items.biblionumber=biblio.biblionumber
1083 LEFT JOIN biblioitems ON items.biblioitemnumber=biblioitems.biblioitemnumber
1084 WHERE borrowernumber=?
1085 UNION ALL
1086 SELECT *, old_issues.timestamp as issuestimestamp, old_issues.renewals AS renewals,items.renewals AS totalrenewals,items.timestamp AS itemstimestamp
1087 FROM old_issues
1088 LEFT JOIN items on items.itemnumber=old_issues.itemnumber
1089 LEFT JOIN biblio ON items.biblionumber=biblio.biblionumber
1090 LEFT JOIN biblioitems ON items.biblioitemnumber=biblioitems.biblioitemnumber
1091 WHERE borrowernumber=? AND old_issues.itemnumber IS NOT NULL
1092 order by $order";
1093 if ( $limit != 0 ) {
1094 $query .= " limit $limit";
1097 my $sth = $dbh->prepare($query);
1098 $sth->execute($borrowernumber, $borrowernumber);
1099 my @result;
1100 my $i = 0;
1101 while ( my $data = $sth->fetchrow_hashref ) {
1102 push @result, $data;
1105 return \@result;
1109 =head2 GetMemberAccountRecords
1111 ($total, $acctlines, $count) = &GetMemberAccountRecords($borrowernumber);
1113 Looks up accounting data for the patron with the given borrowernumber.
1115 C<&GetMemberAccountRecords> returns a three-element array. C<$acctlines> is a
1116 reference-to-array, where each element is a reference-to-hash; the
1117 keys are the fields of the C<accountlines> table in the Koha database.
1118 C<$count> is the number of elements in C<$acctlines>. C<$total> is the
1119 total amount outstanding for all of the account lines.
1121 =cut
1124 sub GetMemberAccountRecords {
1125 my ($borrowernumber,$date) = @_;
1126 my $dbh = C4::Context->dbh;
1127 my @acctlines;
1128 my $numlines = 0;
1129 my $strsth = qq(
1130 SELECT *
1131 FROM accountlines
1132 WHERE borrowernumber=?);
1133 my @bind = ($borrowernumber);
1134 if ($date && $date ne ''){
1135 $strsth.=" AND date < ? ";
1136 push(@bind,$date);
1138 $strsth.=" ORDER BY date desc,timestamp DESC";
1139 my $sth= $dbh->prepare( $strsth );
1140 $sth->execute( @bind );
1141 my $total = 0;
1142 while ( my $data = $sth->fetchrow_hashref ) {
1143 if ( $data->{itemnumber} ) {
1144 my $biblio = GetBiblioFromItemNumber( $data->{itemnumber} );
1145 $data->{biblionumber} = $biblio->{biblionumber};
1146 $data->{title} = $biblio->{title};
1148 $acctlines[$numlines] = $data;
1149 $numlines++;
1150 $total += int(1000 * $data->{'amountoutstanding'}); # convert float to integer to avoid round-off errors
1152 $total /= 1000;
1153 return ( $total, \@acctlines,$numlines);
1156 =head2 GetBorNotifyAcctRecord
1158 ($total, $acctlines, $count) = &GetBorNotifyAcctRecord($params,$notifyid);
1160 Looks up accounting data for the patron with the given borrowernumber per file number.
1162 C<&GetBorNotifyAcctRecord> returns a three-element array. C<$acctlines> is a
1163 reference-to-array, where each element is a reference-to-hash; the
1164 keys are the fields of the C<accountlines> table in the Koha database.
1165 C<$count> is the number of elements in C<$acctlines>. C<$total> is the
1166 total amount outstanding for all of the account lines.
1168 =cut
1170 sub GetBorNotifyAcctRecord {
1171 my ( $borrowernumber, $notifyid ) = @_;
1172 my $dbh = C4::Context->dbh;
1173 my @acctlines;
1174 my $numlines = 0;
1175 my $sth = $dbh->prepare(
1176 "SELECT *
1177 FROM accountlines
1178 WHERE borrowernumber=?
1179 AND notify_id=?
1180 AND amountoutstanding != '0'
1181 ORDER BY notify_id,accounttype
1184 $sth->execute( $borrowernumber, $notifyid );
1185 my $total = 0;
1186 while ( my $data = $sth->fetchrow_hashref ) {
1187 $acctlines[$numlines] = $data;
1188 $numlines++;
1189 $total += int(100 * $data->{'amountoutstanding'});
1191 $total /= 100;
1192 return ( $total, \@acctlines, $numlines );
1195 =head2 checkuniquemember (OUEST-PROVENCE)
1197 ($result,$categorycode) = &checkuniquemember($collectivity,$surname,$firstname,$dateofbirth);
1199 Checks that a member exists or not in the database.
1201 C<&result> is nonzero (=exist) or 0 (=does not exist)
1202 C<&categorycode> is from categorycode table
1203 C<&collectivity> is 1 (= we add a collectivity) or 0 (= we add a physical member)
1204 C<&surname> is the surname
1205 C<&firstname> is the firstname (only if collectivity=0)
1206 C<&dateofbirth> is the date of birth in ISO format (only if collectivity=0)
1208 =cut
1210 # FIXME: This function is not legitimate. Multiple patrons might have the same first/last name and birthdate.
1211 # This is especially true since first name is not even a required field.
1213 sub checkuniquemember {
1214 my ( $collectivity, $surname, $firstname, $dateofbirth ) = @_;
1215 my $dbh = C4::Context->dbh;
1216 my $request = ($collectivity) ?
1217 "SELECT borrowernumber,categorycode FROM borrowers WHERE surname=? " :
1218 ($dateofbirth) ?
1219 "SELECT borrowernumber,categorycode FROM borrowers WHERE surname=? and firstname=? and dateofbirth=?" :
1220 "SELECT borrowernumber,categorycode FROM borrowers WHERE surname=? and firstname=?";
1221 my $sth = $dbh->prepare($request);
1222 if ($collectivity) {
1223 $sth->execute( uc($surname) );
1224 } elsif($dateofbirth){
1225 $sth->execute( uc($surname), ucfirst($firstname), $dateofbirth );
1226 }else{
1227 $sth->execute( uc($surname), ucfirst($firstname));
1229 my @data = $sth->fetchrow;
1230 ( $data[0] ) and return $data[0], $data[1];
1231 return 0;
1234 sub checkcardnumber {
1235 my ($cardnumber,$borrowernumber) = @_;
1236 # If cardnumber is null, we assume they're allowed.
1237 return 0 if !defined($cardnumber);
1238 my $dbh = C4::Context->dbh;
1239 my $query = "SELECT * FROM borrowers WHERE cardnumber=?";
1240 $query .= " AND borrowernumber <> ?" if ($borrowernumber);
1241 my $sth = $dbh->prepare($query);
1242 if ($borrowernumber) {
1243 $sth->execute($cardnumber,$borrowernumber);
1244 } else {
1245 $sth->execute($cardnumber);
1247 if (my $data= $sth->fetchrow_hashref()){
1248 return 1;
1250 else {
1251 return 0;
1256 =head2 getzipnamecity (OUEST-PROVENCE)
1258 take all info from table city for the fields city and zip
1259 check for the name and the zip code of the city selected
1261 =cut
1263 sub getzipnamecity {
1264 my ($cityid) = @_;
1265 my $dbh = C4::Context->dbh;
1266 my $sth =
1267 $dbh->prepare(
1268 "select city_name,city_state,city_zipcode,city_country from cities where cityid=? ");
1269 $sth->execute($cityid);
1270 my @data = $sth->fetchrow;
1271 return $data[0], $data[1], $data[2], $data[3];
1275 =head2 getdcity (OUEST-PROVENCE)
1277 recover cityid with city_name condition
1279 =cut
1281 sub getidcity {
1282 my ($city_name) = @_;
1283 my $dbh = C4::Context->dbh;
1284 my $sth = $dbh->prepare("select cityid from cities where city_name=? ");
1285 $sth->execute($city_name);
1286 my $data = $sth->fetchrow;
1287 return $data;
1290 =head2 GetFirstValidEmailAddress
1292 $email = GetFirstValidEmailAddress($borrowernumber);
1294 Return the first valid email address for a borrower, given the borrowernumber. For now, the order
1295 is defined as email, emailpro, B_email. Returns the empty string if the borrower has no email
1296 addresses.
1298 =cut
1300 sub GetFirstValidEmailAddress {
1301 my $borrowernumber = shift;
1302 my $dbh = C4::Context->dbh;
1303 my $sth = $dbh->prepare( "SELECT email, emailpro, B_email FROM borrowers where borrowernumber = ? ");
1304 $sth->execute( $borrowernumber );
1305 my $data = $sth->fetchrow_hashref;
1307 if ($data->{'email'}) {
1308 return $data->{'email'};
1309 } elsif ($data->{'emailpro'}) {
1310 return $data->{'emailpro'};
1311 } elsif ($data->{'B_email'}) {
1312 return $data->{'B_email'};
1313 } else {
1314 return '';
1318 =head2 GetExpiryDate
1320 $expirydate = GetExpiryDate($categorycode, $dateenrolled);
1322 Calculate expiry date given a categorycode and starting date. Date argument must be in ISO format.
1323 Return date is also in ISO format.
1325 =cut
1327 sub GetExpiryDate {
1328 my ( $categorycode, $dateenrolled ) = @_;
1329 my $enrolments;
1330 if ($categorycode) {
1331 my $dbh = C4::Context->dbh;
1332 my $sth = $dbh->prepare("SELECT enrolmentperiod,enrolmentperioddate FROM categories WHERE categorycode=?");
1333 $sth->execute($categorycode);
1334 $enrolments = $sth->fetchrow_hashref;
1336 # die "GetExpiryDate: for enrollmentperiod $enrolmentperiod (category '$categorycode') starting $dateenrolled.\n";
1337 my @date = split (/-/,$dateenrolled);
1338 if($enrolments->{enrolmentperiod}){
1339 return sprintf("%04d-%02d-%02d", Add_Delta_YM(@date,0,$enrolments->{enrolmentperiod}));
1340 }else{
1341 return $enrolments->{enrolmentperioddate};
1345 =head2 checkuserpassword (OUEST-PROVENCE)
1347 check for the password and login are not used
1348 return the number of record
1349 0=> NOT USED 1=> USED
1351 =cut
1353 sub checkuserpassword {
1354 my ( $borrowernumber, $userid, $password ) = @_;
1355 $password = md5_base64($password);
1356 my $dbh = C4::Context->dbh;
1357 my $sth =
1358 $dbh->prepare(
1359 "Select count(*) from borrowers where borrowernumber !=? and userid =? and password=? "
1361 $sth->execute( $borrowernumber, $userid, $password );
1362 my $number_rows = $sth->fetchrow;
1363 return $number_rows;
1367 =head2 GetborCatFromCatType
1369 ($codes_arrayref, $labels_hashref) = &GetborCatFromCatType();
1371 Looks up the different types of borrowers in the database. Returns two
1372 elements: a reference-to-array, which lists the borrower category
1373 codes, and a reference-to-hash, which maps the borrower category codes
1374 to category descriptions.
1376 =cut
1379 sub GetborCatFromCatType {
1380 my ( $category_type, $action ) = @_;
1381 # FIXME - This API seems both limited and dangerous.
1382 my $dbh = C4::Context->dbh;
1383 my $request = qq| SELECT categorycode,description
1384 FROM categories
1385 $action
1386 ORDER BY categorycode|;
1387 my $sth = $dbh->prepare($request);
1388 if ($action) {
1389 $sth->execute($category_type);
1391 else {
1392 $sth->execute();
1395 my %labels;
1396 my @codes;
1398 while ( my $data = $sth->fetchrow_hashref ) {
1399 push @codes, $data->{'categorycode'};
1400 $labels{ $data->{'categorycode'} } = $data->{'description'};
1402 return ( \@codes, \%labels );
1405 =head2 GetBorrowercategory
1407 $hashref = &GetBorrowercategory($categorycode);
1409 Given the borrower's category code, the function returns the corresponding
1410 data hashref for a comprehensive information display.
1412 $arrayref_hashref = &GetBorrowercategory;
1414 If no category code provided, the function returns all the categories.
1416 =cut
1418 sub GetBorrowercategory {
1419 my ($catcode) = @_;
1420 my $dbh = C4::Context->dbh;
1421 if ($catcode){
1422 my $sth =
1423 $dbh->prepare(
1424 "SELECT description,dateofbirthrequired,upperagelimit,category_type
1425 FROM categories
1426 WHERE categorycode = ?"
1428 $sth->execute($catcode);
1429 my $data =
1430 $sth->fetchrow_hashref;
1431 return $data;
1433 return;
1434 } # sub getborrowercategory
1436 =head2 GetBorrowercategoryList
1438 $arrayref_hashref = &GetBorrowercategoryList;
1439 If no category code provided, the function returns all the categories.
1441 =cut
1443 sub GetBorrowercategoryList {
1444 my $dbh = C4::Context->dbh;
1445 my $sth =
1446 $dbh->prepare(
1447 "SELECT *
1448 FROM categories
1449 ORDER BY description"
1451 $sth->execute;
1452 my $data =
1453 $sth->fetchall_arrayref({});
1454 return $data;
1455 } # sub getborrowercategory
1457 =head2 ethnicitycategories
1459 ($codes_arrayref, $labels_hashref) = &ethnicitycategories();
1461 Looks up the different ethnic types in the database. Returns two
1462 elements: a reference-to-array, which lists the ethnicity codes, and a
1463 reference-to-hash, which maps the ethnicity codes to ethnicity
1464 descriptions.
1466 =cut
1470 sub ethnicitycategories {
1471 my $dbh = C4::Context->dbh;
1472 my $sth = $dbh->prepare("Select code,name from ethnicity order by name");
1473 $sth->execute;
1474 my %labels;
1475 my @codes;
1476 while ( my $data = $sth->fetchrow_hashref ) {
1477 push @codes, $data->{'code'};
1478 $labels{ $data->{'code'} } = $data->{'name'};
1480 return ( \@codes, \%labels );
1483 =head2 fixEthnicity
1485 $ethn_name = &fixEthnicity($ethn_code);
1487 Takes an ethnicity code (e.g., "european" or "pi") and returns the
1488 corresponding descriptive name from the C<ethnicity> table in the
1489 Koha database ("European" or "Pacific Islander").
1491 =cut
1495 sub fixEthnicity {
1496 my $ethnicity = shift;
1497 return unless $ethnicity;
1498 my $dbh = C4::Context->dbh;
1499 my $sth = $dbh->prepare("Select name from ethnicity where code = ?");
1500 $sth->execute($ethnicity);
1501 my $data = $sth->fetchrow_hashref;
1502 return $data->{'name'};
1503 } # sub fixEthnicity
1505 =head2 GetAge
1507 $dateofbirth,$date = &GetAge($date);
1509 this function return the borrowers age with the value of dateofbirth
1511 =cut
1514 sub GetAge{
1515 my ( $date, $date_ref ) = @_;
1517 if ( not defined $date_ref ) {
1518 $date_ref = sprintf( '%04d-%02d-%02d', Today() );
1521 my ( $year1, $month1, $day1 ) = split /-/, $date;
1522 my ( $year2, $month2, $day2 ) = split /-/, $date_ref;
1524 my $age = $year2 - $year1;
1525 if ( $month1 . $day1 > $month2 . $day2 ) {
1526 $age--;
1529 return $age;
1530 } # sub get_age
1532 =head2 get_institutions
1534 $insitutions = get_institutions();
1536 Just returns a list of all the borrowers of type I, borrownumber and name
1538 =cut
1541 sub get_institutions {
1542 my $dbh = C4::Context->dbh();
1543 my $sth =
1544 $dbh->prepare(
1545 "SELECT borrowernumber,surname FROM borrowers WHERE categorycode=? ORDER BY surname"
1547 $sth->execute('I');
1548 my %orgs;
1549 while ( my $data = $sth->fetchrow_hashref() ) {
1550 $orgs{ $data->{'borrowernumber'} } = $data;
1552 return ( \%orgs );
1554 } # sub get_institutions
1556 =head2 add_member_orgs
1558 add_member_orgs($borrowernumber,$borrowernumbers);
1560 Takes a borrowernumber and a list of other borrowernumbers and inserts them into the borrowers_to_borrowers table
1562 =cut
1565 sub add_member_orgs {
1566 my ( $borrowernumber, $otherborrowers ) = @_;
1567 my $dbh = C4::Context->dbh();
1568 my $query =
1569 "INSERT INTO borrowers_to_borrowers (borrower1,borrower2) VALUES (?,?)";
1570 my $sth = $dbh->prepare($query);
1571 foreach my $otherborrowernumber (@$otherborrowers) {
1572 $sth->execute( $borrowernumber, $otherborrowernumber );
1575 } # sub add_member_orgs
1577 =head2 GetCities
1579 $cityarrayref = GetCities();
1581 Returns an array_ref of the entries in the cities table
1582 If there are entries in the table an empty row is returned
1583 This is currently only used to populate a popup in memberentry
1585 =cut
1587 sub GetCities {
1589 my $dbh = C4::Context->dbh;
1590 my $city_arr = $dbh->selectall_arrayref(
1591 q|SELECT cityid,city_zipcode,city_name,city_state,city_country FROM cities ORDER BY city_name|,
1592 { Slice => {} });
1593 if ( @{$city_arr} ) {
1594 unshift @{$city_arr}, {
1595 city_zipcode => q{},
1596 city_name => q{},
1597 cityid => q{},
1598 city_state => q{},
1599 city_country => q{},
1603 return $city_arr;
1606 =head2 GetSortDetails (OUEST-PROVENCE)
1608 ($lib) = &GetSortDetails($category,$sortvalue);
1610 Returns the authorized value details
1611 C<&$lib>return value of authorized value details
1612 C<&$sortvalue>this is the value of authorized value
1613 C<&$category>this is the value of authorized value category
1615 =cut
1617 sub GetSortDetails {
1618 my ( $category, $sortvalue ) = @_;
1619 my $dbh = C4::Context->dbh;
1620 my $query = qq|SELECT lib
1621 FROM authorised_values
1622 WHERE category=?
1623 AND authorised_value=? |;
1624 my $sth = $dbh->prepare($query);
1625 $sth->execute( $category, $sortvalue );
1626 my $lib = $sth->fetchrow;
1627 return ($lib) if ($lib);
1628 return ($sortvalue) unless ($lib);
1631 =head2 MoveMemberToDeleted
1633 $result = &MoveMemberToDeleted($borrowernumber);
1635 Copy the record from borrowers to deletedborrowers table.
1637 =cut
1639 # FIXME: should do it in one SQL statement w/ subquery
1640 # Otherwise, we should return the @data on success
1642 sub MoveMemberToDeleted {
1643 my ($member) = shift or return;
1644 my $dbh = C4::Context->dbh;
1645 my $query = qq|SELECT *
1646 FROM borrowers
1647 WHERE borrowernumber=?|;
1648 my $sth = $dbh->prepare($query);
1649 $sth->execute($member);
1650 my @data = $sth->fetchrow_array;
1651 (@data) or return; # if we got a bad borrowernumber, there's nothing to insert
1652 $sth =
1653 $dbh->prepare( "INSERT INTO deletedborrowers VALUES ("
1654 . ( "?," x ( scalar(@data) - 1 ) )
1655 . "?)" );
1656 $sth->execute(@data);
1659 =head2 DelMember
1661 DelMember($borrowernumber);
1663 This function remove directly a borrower whitout writing it on deleteborrower.
1664 + Deletes reserves for the borrower
1666 =cut
1668 sub DelMember {
1669 my $dbh = C4::Context->dbh;
1670 my $borrowernumber = shift;
1671 #warn "in delmember with $borrowernumber";
1672 return unless $borrowernumber; # borrowernumber is mandatory.
1674 my $query = qq|DELETE
1675 FROM reserves
1676 WHERE borrowernumber=?|;
1677 my $sth = $dbh->prepare($query);
1678 $sth->execute($borrowernumber);
1679 $query = "
1680 DELETE
1681 FROM borrowers
1682 WHERE borrowernumber = ?
1684 $sth = $dbh->prepare($query);
1685 $sth->execute($borrowernumber);
1686 logaction("MEMBERS", "DELETE", $borrowernumber, "") if C4::Context->preference("BorrowersLog");
1687 return $sth->rows;
1690 =head2 ExtendMemberSubscriptionTo (OUEST-PROVENCE)
1692 $date = ExtendMemberSubscriptionTo($borrowerid, $date);
1694 Extending the subscription to a given date or to the expiry date calculated on ISO date.
1695 Returns ISO date.
1697 =cut
1699 sub ExtendMemberSubscriptionTo {
1700 my ( $borrowerid,$date) = @_;
1701 my $dbh = C4::Context->dbh;
1702 my $borrower = GetMember('borrowernumber'=>$borrowerid);
1703 unless ($date){
1704 $date = (C4::Context->preference('BorrowerRenewalPeriodBase') eq 'dateexpiry') ?
1705 C4::Dates->new($borrower->{'dateexpiry'}, 'iso')->output("iso") :
1706 C4::Dates->new()->output("iso");
1707 $date = GetExpiryDate( $borrower->{'categorycode'}, $date );
1709 my $sth = $dbh->do(<<EOF);
1710 UPDATE borrowers
1711 SET dateexpiry='$date'
1712 WHERE borrowernumber='$borrowerid'
1714 # add enrolmentfee if needed
1715 $sth = $dbh->prepare("SELECT enrolmentfee FROM categories WHERE categorycode=?");
1716 $sth->execute($borrower->{'categorycode'});
1717 my ($enrolmentfee) = $sth->fetchrow;
1718 if ($enrolmentfee && $enrolmentfee > 0) {
1719 # insert fee in patron debts
1720 manualinvoice($borrower->{'borrowernumber'}, '', '', 'A', $enrolmentfee);
1722 logaction("MEMBERS", "RENEW", $borrower->{'borrowernumber'}, "Membership renewed")if C4::Context->preference("BorrowersLog");
1723 return $date if ($sth);
1724 return 0;
1727 =head2 GetRoadTypes (OUEST-PROVENCE)
1729 ($idroadtypearrayref, $roadttype_hashref) = &GetRoadTypes();
1731 Looks up the different road type . Returns two
1732 elements: a reference-to-array, which lists the id_roadtype
1733 codes, and a reference-to-hash, which maps the road type of the road .
1735 =cut
1737 sub GetRoadTypes {
1738 my $dbh = C4::Context->dbh;
1739 my $query = qq|
1740 SELECT roadtypeid,road_type
1741 FROM roadtype
1742 ORDER BY road_type|;
1743 my $sth = $dbh->prepare($query);
1744 $sth->execute();
1745 my %roadtype;
1746 my @id;
1748 # insert empty value to create a empty choice in cgi popup
1750 while ( my $data = $sth->fetchrow_hashref ) {
1752 push @id, $data->{'roadtypeid'};
1753 $roadtype{ $data->{'roadtypeid'} } = $data->{'road_type'};
1756 #test to know if the table contain some records if no the function return nothing
1757 my $id = @id;
1758 if ( $id eq 0 ) {
1759 return ();
1761 else {
1762 unshift( @id, "" );
1763 return ( \@id, \%roadtype );
1769 =head2 GetTitles (OUEST-PROVENCE)
1771 ($borrowertitle)= &GetTitles();
1773 Looks up the different title . Returns array with all borrowers title
1775 =cut
1777 sub GetTitles {
1778 my @borrowerTitle = split (/,|\|/,C4::Context->preference('BorrowersTitles'));
1779 unshift( @borrowerTitle, "" );
1780 my $count=@borrowerTitle;
1781 if ($count == 1){
1782 return ();
1784 else {
1785 return ( \@borrowerTitle);
1789 =head2 GetPatronImage
1791 my ($imagedata, $dberror) = GetPatronImage($cardnumber);
1793 Returns the mimetype and binary image data of the image for the patron with the supplied cardnumber.
1795 =cut
1797 sub GetPatronImage {
1798 my ($cardnumber) = @_;
1799 warn "Cardnumber passed to GetPatronImage is $cardnumber" if $debug;
1800 my $dbh = C4::Context->dbh;
1801 my $query = 'SELECT mimetype, imagefile FROM patronimage WHERE cardnumber = ?';
1802 my $sth = $dbh->prepare($query);
1803 $sth->execute($cardnumber);
1804 my $imagedata = $sth->fetchrow_hashref;
1805 warn "Database error!" if $sth->errstr;
1806 return $imagedata, $sth->errstr;
1809 =head2 PutPatronImage
1811 PutPatronImage($cardnumber, $mimetype, $imgfile);
1813 Stores patron binary image data and mimetype in database.
1814 NOTE: This function is good for updating images as well as inserting new images in the database.
1816 =cut
1818 sub PutPatronImage {
1819 my ($cardnumber, $mimetype, $imgfile) = @_;
1820 warn "Parameters passed in: Cardnumber=$cardnumber, Mimetype=$mimetype, " . ($imgfile ? "Imagefile" : "No Imagefile") if $debug;
1821 my $dbh = C4::Context->dbh;
1822 my $query = "INSERT INTO patronimage (cardnumber, mimetype, imagefile) VALUES (?,?,?) ON DUPLICATE KEY UPDATE imagefile = ?;";
1823 my $sth = $dbh->prepare($query);
1824 $sth->execute($cardnumber,$mimetype,$imgfile,$imgfile);
1825 warn "Error returned inserting $cardnumber.$mimetype." if $sth->errstr;
1826 return $sth->errstr;
1829 =head2 RmPatronImage
1831 my ($dberror) = RmPatronImage($cardnumber);
1833 Removes the image for the patron with the supplied cardnumber.
1835 =cut
1837 sub RmPatronImage {
1838 my ($cardnumber) = @_;
1839 warn "Cardnumber passed to GetPatronImage is $cardnumber" if $debug;
1840 my $dbh = C4::Context->dbh;
1841 my $query = "DELETE FROM patronimage WHERE cardnumber = ?;";
1842 my $sth = $dbh->prepare($query);
1843 $sth->execute($cardnumber);
1844 my $dberror = $sth->errstr;
1845 warn "Database error!" if $sth->errstr;
1846 return $dberror;
1849 =head2 GetHideLostItemsPreference
1851 $hidelostitemspref = &GetHideLostItemsPreference($borrowernumber);
1853 Returns the HideLostItems preference for the patron category of the supplied borrowernumber
1854 C<&$hidelostitemspref>return value of function, 0 or 1
1856 =cut
1858 sub GetHideLostItemsPreference {
1859 my ($borrowernumber) = @_;
1860 my $dbh = C4::Context->dbh;
1861 my $query = "SELECT hidelostitems FROM borrowers,categories WHERE borrowers.categorycode = categories.categorycode AND borrowernumber = ?";
1862 my $sth = $dbh->prepare($query);
1863 $sth->execute($borrowernumber);
1864 my $hidelostitems = $sth->fetchrow;
1865 return $hidelostitems;
1868 =head2 GetRoadTypeDetails (OUEST-PROVENCE)
1870 ($roadtype) = &GetRoadTypeDetails($roadtypeid);
1872 Returns the description of roadtype
1873 C<&$roadtype>return description of road type
1874 C<&$roadtypeid>this is the value of roadtype s
1876 =cut
1878 sub GetRoadTypeDetails {
1879 my ($roadtypeid) = @_;
1880 my $dbh = C4::Context->dbh;
1881 my $query = qq|
1882 SELECT road_type
1883 FROM roadtype
1884 WHERE roadtypeid=?|;
1885 my $sth = $dbh->prepare($query);
1886 $sth->execute($roadtypeid);
1887 my $roadtype = $sth->fetchrow;
1888 return ($roadtype);
1891 =head2 GetBorrowersWhoHaveNotBorrowedSince
1893 &GetBorrowersWhoHaveNotBorrowedSince($date)
1895 this function get all borrowers who haven't borrowed since the date given on input arg.
1897 =cut
1899 sub GetBorrowersWhoHaveNotBorrowedSince {
1900 my $filterdate = shift||POSIX::strftime("%Y-%m-%d",localtime());
1901 my $filterexpiry = shift;
1902 my $filterbranch = shift ||
1903 ((C4::Context->preference('IndependantBranches')
1904 && C4::Context->userenv
1905 && C4::Context->userenv->{flags} % 2 !=1
1906 && C4::Context->userenv->{branch})
1907 ? C4::Context->userenv->{branch}
1908 : "");
1909 my $dbh = C4::Context->dbh;
1910 my $query = "
1911 SELECT borrowers.borrowernumber,
1912 max(old_issues.timestamp) as latestissue,
1913 max(issues.timestamp) as currentissue
1914 FROM borrowers
1915 JOIN categories USING (categorycode)
1916 LEFT JOIN old_issues USING (borrowernumber)
1917 LEFT JOIN issues USING (borrowernumber)
1918 WHERE category_type <> 'S'
1919 AND borrowernumber NOT IN (SELECT guarantorid FROM borrowers WHERE guarantorid IS NOT NULL AND guarantorid <> 0)
1921 my @query_params;
1922 if ($filterbranch && $filterbranch ne ""){
1923 $query.=" AND borrowers.branchcode= ?";
1924 push @query_params,$filterbranch;
1926 if($filterexpiry){
1927 $query .= " AND dateexpiry < ? ";
1928 push @query_params,$filterdate;
1930 $query.=" GROUP BY borrowers.borrowernumber";
1931 if ($filterdate){
1932 $query.=" HAVING (latestissue < ? OR latestissue IS NULL)
1933 AND currentissue IS NULL";
1934 push @query_params,$filterdate;
1936 warn $query if $debug;
1937 my $sth = $dbh->prepare($query);
1938 if (scalar(@query_params)>0){
1939 $sth->execute(@query_params);
1941 else {
1942 $sth->execute;
1945 my @results;
1946 while ( my $data = $sth->fetchrow_hashref ) {
1947 push @results, $data;
1949 return \@results;
1952 =head2 GetBorrowersWhoHaveNeverBorrowed
1954 $results = &GetBorrowersWhoHaveNeverBorrowed
1956 This function get all borrowers who have never borrowed.
1958 I<$result> is a ref to an array which all elements are a hasref.
1960 =cut
1962 sub GetBorrowersWhoHaveNeverBorrowed {
1963 my $filterbranch = shift ||
1964 ((C4::Context->preference('IndependantBranches')
1965 && C4::Context->userenv
1966 && C4::Context->userenv->{flags} % 2 !=1
1967 && C4::Context->userenv->{branch})
1968 ? C4::Context->userenv->{branch}
1969 : "");
1970 my $dbh = C4::Context->dbh;
1971 my $query = "
1972 SELECT borrowers.borrowernumber,max(timestamp) as latestissue
1973 FROM borrowers
1974 LEFT JOIN issues ON borrowers.borrowernumber = issues.borrowernumber
1975 WHERE issues.borrowernumber IS NULL
1977 my @query_params;
1978 if ($filterbranch && $filterbranch ne ""){
1979 $query.=" AND borrowers.branchcode= ?";
1980 push @query_params,$filterbranch;
1982 warn $query if $debug;
1984 my $sth = $dbh->prepare($query);
1985 if (scalar(@query_params)>0){
1986 $sth->execute(@query_params);
1988 else {
1989 $sth->execute;
1992 my @results;
1993 while ( my $data = $sth->fetchrow_hashref ) {
1994 push @results, $data;
1996 return \@results;
1999 =head2 GetBorrowersWithIssuesHistoryOlderThan
2001 $results = &GetBorrowersWithIssuesHistoryOlderThan($date)
2003 this function get all borrowers who has an issue history older than I<$date> given on input arg.
2005 I<$result> is a ref to an array which all elements are a hashref.
2006 This hashref is containt the number of time this borrowers has borrowed before I<$date> and the borrowernumber.
2008 =cut
2010 sub GetBorrowersWithIssuesHistoryOlderThan {
2011 my $dbh = C4::Context->dbh;
2012 my $date = shift ||POSIX::strftime("%Y-%m-%d",localtime());
2013 my $filterbranch = shift ||
2014 ((C4::Context->preference('IndependantBranches')
2015 && C4::Context->userenv
2016 && C4::Context->userenv->{flags} % 2 !=1
2017 && C4::Context->userenv->{branch})
2018 ? C4::Context->userenv->{branch}
2019 : "");
2020 my $query = "
2021 SELECT count(borrowernumber) as n,borrowernumber
2022 FROM old_issues
2023 WHERE returndate < ?
2024 AND borrowernumber IS NOT NULL
2026 my @query_params;
2027 push @query_params, $date;
2028 if ($filterbranch){
2029 $query.=" AND branchcode = ?";
2030 push @query_params, $filterbranch;
2032 $query.=" GROUP BY borrowernumber ";
2033 warn $query if $debug;
2034 my $sth = $dbh->prepare($query);
2035 $sth->execute(@query_params);
2036 my @results;
2038 while ( my $data = $sth->fetchrow_hashref ) {
2039 push @results, $data;
2041 return \@results;
2044 =head2 GetBorrowersNamesAndLatestIssue
2046 $results = &GetBorrowersNamesAndLatestIssueList(@borrowernumbers)
2048 this function get borrowers Names and surnames and Issue information.
2050 I<@borrowernumbers> is an array which all elements are borrowernumbers.
2051 This hashref is containt the number of time this borrowers has borrowed before I<$date> and the borrowernumber.
2053 =cut
2055 sub GetBorrowersNamesAndLatestIssue {
2056 my $dbh = C4::Context->dbh;
2057 my @borrowernumbers=@_;
2058 my $query = "
2059 SELECT surname,lastname, phone, email,max(timestamp)
2060 FROM borrowers
2061 LEFT JOIN issues ON borrowers.borrowernumber=issues.borrowernumber
2062 GROUP BY borrowernumber
2064 my $sth = $dbh->prepare($query);
2065 $sth->execute;
2066 my $results = $sth->fetchall_arrayref({});
2067 return $results;
2070 =head2 DebarMember
2072 my $success = DebarMember( $borrowernumber, $todate );
2074 marks a Member as debarred, and therefore unable to checkout any more
2075 items.
2077 return :
2078 true on success, false on failure
2080 =cut
2082 sub DebarMember {
2083 my $borrowernumber = shift;
2084 my $todate = shift;
2086 return unless defined $borrowernumber;
2087 return unless $borrowernumber =~ /^\d+$/;
2089 return ModMember(
2090 borrowernumber => $borrowernumber,
2091 debarred => $todate
2096 =head2 ModPrivacy
2098 =over 4
2100 my $success = ModPrivacy( $borrowernumber, $privacy );
2102 Update the privacy of a patron.
2104 return :
2105 true on success, false on failure
2107 =back
2109 =cut
2111 sub ModPrivacy {
2112 my $borrowernumber = shift;
2113 my $privacy = shift;
2114 return unless defined $borrowernumber;
2115 return unless $borrowernumber =~ /^\d+$/;
2117 return ModMember( borrowernumber => $borrowernumber,
2118 privacy => $privacy );
2121 =head2 AddMessage
2123 AddMessage( $borrowernumber, $message_type, $message, $branchcode );
2125 Adds a message to the messages table for the given borrower.
2127 Returns:
2128 True on success
2129 False on failure
2131 =cut
2133 sub AddMessage {
2134 my ( $borrowernumber, $message_type, $message, $branchcode ) = @_;
2136 my $dbh = C4::Context->dbh;
2138 if ( ! ( $borrowernumber && $message_type && $message && $branchcode ) ) {
2139 return;
2142 my $query = "INSERT INTO messages ( borrowernumber, branchcode, message_type, message ) VALUES ( ?, ?, ?, ? )";
2143 my $sth = $dbh->prepare($query);
2144 $sth->execute( $borrowernumber, $branchcode, $message_type, $message );
2145 logaction("MEMBERS", "ADDCIRCMESSAGE", $borrowernumber, $message) if C4::Context->preference("BorrowersLog");
2146 return 1;
2149 =head2 GetMessages
2151 GetMessages( $borrowernumber, $type );
2153 $type is message type, B for borrower, or L for Librarian.
2154 Empty type returns all messages of any type.
2156 Returns all messages for the given borrowernumber
2158 =cut
2160 sub GetMessages {
2161 my ( $borrowernumber, $type, $branchcode ) = @_;
2163 if ( ! $type ) {
2164 $type = '%';
2167 my $dbh = C4::Context->dbh;
2169 my $query = "SELECT
2170 branches.branchname,
2171 messages.*,
2172 message_date,
2173 messages.branchcode LIKE '$branchcode' AS can_delete
2174 FROM messages, branches
2175 WHERE borrowernumber = ?
2176 AND message_type LIKE ?
2177 AND messages.branchcode = branches.branchcode
2178 ORDER BY message_date DESC";
2179 my $sth = $dbh->prepare($query);
2180 $sth->execute( $borrowernumber, $type ) ;
2181 my @results;
2183 while ( my $data = $sth->fetchrow_hashref ) {
2184 my $d = C4::Dates->new( $data->{message_date}, 'iso' );
2185 $data->{message_date_formatted} = $d->output;
2186 push @results, $data;
2188 return \@results;
2192 =head2 GetMessages
2194 GetMessagesCount( $borrowernumber, $type );
2196 $type is message type, B for borrower, or L for Librarian.
2197 Empty type returns all messages of any type.
2199 Returns the number of messages for the given borrowernumber
2201 =cut
2203 sub GetMessagesCount {
2204 my ( $borrowernumber, $type, $branchcode ) = @_;
2206 if ( ! $type ) {
2207 $type = '%';
2210 my $dbh = C4::Context->dbh;
2212 my $query = "SELECT COUNT(*) as MsgCount FROM messages WHERE borrowernumber = ? AND message_type LIKE ?";
2213 my $sth = $dbh->prepare($query);
2214 $sth->execute( $borrowernumber, $type ) ;
2215 my @results;
2217 my $data = $sth->fetchrow_hashref;
2218 my $count = $data->{'MsgCount'};
2220 return $count;
2225 =head2 DeleteMessage
2227 DeleteMessage( $message_id );
2229 =cut
2231 sub DeleteMessage {
2232 my ( $message_id ) = @_;
2234 my $dbh = C4::Context->dbh;
2235 my $query = "SELECT * FROM messages WHERE message_id = ?";
2236 my $sth = $dbh->prepare($query);
2237 $sth->execute( $message_id );
2238 my $message = $sth->fetchrow_hashref();
2240 $query = "DELETE FROM messages WHERE message_id = ?";
2241 $sth = $dbh->prepare($query);
2242 $sth->execute( $message_id );
2243 logaction("MEMBERS", "DELCIRCMESSAGE", $message->{'borrowernumber'}, $message->{'message'}) if C4::Context->preference("BorrowersLog");
2246 =head2 IssueSlip
2248 IssueSlip($branchcode, $borrowernumber, $quickslip)
2250 Returns letter hash ( see C4::Letters::GetPreparedLetter )
2252 $quickslip is boolean, to indicate whether we want a quick slip
2254 =cut
2256 sub IssueSlip {
2257 my ($branch, $borrowernumber, $quickslip) = @_;
2259 # return unless ( C4::Context->boolean_preference('printcirculationslips') );
2261 my $today = POSIX::strftime("%Y-%m-%d", localtime);
2263 my $issueslist = GetPendingIssues($borrowernumber);
2264 foreach my $it (@$issueslist){
2265 if ($it->{'issuedate'} eq $today) {
2266 $it->{'today'} = 1;
2268 elsif ($it->{'date_due'} le $today) {
2269 $it->{'overdue'} = 1;
2272 $it->{'date_due'}=format_date($it->{'date_due'});
2274 my @issues = sort { $b->{'timestamp'} <=> $a->{'timestamp'} } @$issueslist;
2276 my ($letter_code, %repeat);
2277 if ( $quickslip ) {
2278 $letter_code = 'ISSUEQSLIP';
2279 %repeat = (
2280 'checkedout' => [ map {
2281 'biblio' => $_,
2282 'items' => $_,
2283 'issues' => $_,
2284 }, grep { $_->{'today'} } @issues ],
2287 else {
2288 $letter_code = 'ISSUESLIP';
2289 %repeat = (
2290 'checkedout' => [ map {
2291 'biblio' => $_,
2292 'items' => $_,
2293 'issues' => $_,
2294 }, grep { !$_->{'overdue'} } @issues ],
2296 'overdue' => [ map {
2297 'biblio' => $_,
2298 'items' => $_,
2299 'issues' => $_,
2300 }, grep { $_->{'overdue'} } @issues ],
2302 'news' => [ map {
2303 $_->{'timestamp'} = $_->{'newdate'};
2304 { opac_news => $_ }
2305 } @{ GetNewsToDisplay("slip") } ],
2309 return C4::Letters::GetPreparedLetter (
2310 module => 'circulation',
2311 letter_code => $letter_code,
2312 branchcode => $branch,
2313 tables => {
2314 'branches' => $branch,
2315 'borrowers' => $borrowernumber,
2317 repeat => \%repeat,
2321 =head2 GetBorrowersWithEmail
2323 ([$borrnum,$userid], ...) = GetBorrowersWithEmail('me@example.com');
2325 This gets a list of users and their basic details from their email address.
2326 As it's possible for multiple user to have the same email address, it provides
2327 you with all of them. If there is no userid for the user, there will be an
2328 C<undef> there. An empty list will be returned if there are no matches.
2330 =cut
2332 sub GetBorrowersWithEmail {
2333 my $email = shift;
2335 my $dbh = C4::Context->dbh;
2337 my $query = "SELECT borrowernumber, userid FROM borrowers WHERE email=?";
2338 my $sth=$dbh->prepare($query);
2339 $sth->execute($email);
2340 my @result = ();
2341 while (my $ref = $sth->fetch) {
2342 push @result, $ref;
2344 die "Failure searching for borrowers by email address: $sth->errstr" if $sth->err;
2345 return @result;
2349 END { } # module clean-up code here (global destructor)
2353 __END__
2355 =head1 AUTHOR
2357 Koha Team
2359 =cut