Bug 7952 - PDF::Reuse under plack writes to console STDOUT instead to browser
[koha.git] / C4 / Members.pm
blob2e59c916ca4ddb8d7d821de6ab93d77cfd3af9e3
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 # MODIFIED BY JF: mysql4.1 allows casting as an integer, which is probably
903 # better. I'll leave the original in in case it needs to be changed for you
904 # my $sth=$dbh->prepare("select max(borrowers.cardnumber) from borrowers");
905 my $sth = $dbh->prepare(
906 "select max(cast(cardnumber as signed)) from borrowers"
908 $sth->execute;
909 my ($result) = $sth->fetchrow;
910 return $result + 1;
912 return $cardnumber; # just here as a fallback/reminder
915 =head2 GetGuarantees
917 ($num_children, $children_arrayref) = &GetGuarantees($parent_borrno);
918 $child0_cardno = $children_arrayref->[0]{"cardnumber"};
919 $child0_borrno = $children_arrayref->[0]{"borrowernumber"};
921 C<&GetGuarantees> takes a borrower number (e.g., that of a patron
922 with children) and looks up the borrowers who are guaranteed by that
923 borrower (i.e., the patron's children).
925 C<&GetGuarantees> returns two values: an integer giving the number of
926 borrowers guaranteed by C<$parent_borrno>, and a reference to an array
927 of references to hash, which gives the actual results.
929 =cut
932 sub GetGuarantees {
933 my ($borrowernumber) = @_;
934 my $dbh = C4::Context->dbh;
935 my $sth =
936 $dbh->prepare(
937 "select cardnumber,borrowernumber, firstname, surname from borrowers where guarantorid=?"
939 $sth->execute($borrowernumber);
941 my @dat;
942 my $data = $sth->fetchall_arrayref({});
943 return ( scalar(@$data), $data );
946 =head2 UpdateGuarantees
948 &UpdateGuarantees($parent_borrno);
951 C<&UpdateGuarantees> borrower data for an adult and updates all the guarantees
952 with the modified information
954 =cut
957 sub UpdateGuarantees {
958 my %data = shift;
959 my $dbh = C4::Context->dbh;
960 my ( $count, $guarantees ) = GetGuarantees( $data{'borrowernumber'} );
961 foreach my $guarantee (@$guarantees){
962 my $guaquery = qq|UPDATE borrowers
963 SET address=?,fax=?,B_city=?,mobile=?,city=?,phone=?
964 WHERE borrowernumber=?
966 my $sth = $dbh->prepare($guaquery);
967 $sth->execute($data{'address'},$data{'fax'},$data{'B_city'},$data{'mobile'},$data{'city'},$data{'phone'},$guarantee->{'borrowernumber'});
970 =head2 GetPendingIssues
972 my $issues = &GetPendingIssues(@borrowernumber);
974 Looks up what the patron with the given borrowernumber has borrowed.
976 C<&GetPendingIssues> returns a
977 reference-to-array where each element is a reference-to-hash; the
978 keys are the fields from the C<issues>, C<biblio>, and C<items> tables.
979 The keys include C<biblioitems> fields except marc and marcxml.
981 =cut
984 sub GetPendingIssues {
985 my @borrowernumbers = @_;
987 unless (@borrowernumbers ) { # return a ref_to_array
988 return \@borrowernumbers; # to not cause surprise to caller
991 # Borrowers part of the query
992 my $bquery = '';
993 for (my $i = 0; $i < @borrowernumbers; $i++) {
994 $bquery .= ' issues.borrowernumber = ?';
995 if ($i < $#borrowernumbers ) {
996 $bquery .= ' OR';
1000 # must avoid biblioitems.* to prevent large marc and marcxml fields from killing performance
1001 # FIXME: namespace collision: each table has "timestamp" fields. Which one is "timestamp" ?
1002 # FIXME: circ/ciculation.pl tries to sort by timestamp!
1003 # FIXME: namespace collision: other collisions possible.
1004 # FIXME: most of this data isn't really being used by callers.
1005 my $query =
1006 "SELECT issues.*,
1007 items.*,
1008 biblio.*,
1009 biblioitems.volume,
1010 biblioitems.number,
1011 biblioitems.itemtype,
1012 biblioitems.isbn,
1013 biblioitems.issn,
1014 biblioitems.publicationyear,
1015 biblioitems.publishercode,
1016 biblioitems.volumedate,
1017 biblioitems.volumedesc,
1018 biblioitems.lccn,
1019 biblioitems.url,
1020 borrowers.firstname,
1021 borrowers.surname,
1022 borrowers.cardnumber,
1023 issues.timestamp AS timestamp,
1024 issues.renewals AS renewals,
1025 issues.borrowernumber AS borrowernumber,
1026 items.renewals AS totalrenewals
1027 FROM issues
1028 LEFT JOIN items ON items.itemnumber = issues.itemnumber
1029 LEFT JOIN biblio ON items.biblionumber = biblio.biblionumber
1030 LEFT JOIN biblioitems ON items.biblioitemnumber = biblioitems.biblioitemnumber
1031 LEFT JOIN borrowers ON issues.borrowernumber = borrowers.borrowernumber
1032 WHERE
1033 $bquery
1034 ORDER BY issues.issuedate"
1037 my $sth = C4::Context->dbh->prepare($query);
1038 $sth->execute(@borrowernumbers);
1039 my $data = $sth->fetchall_arrayref({});
1040 my $tz = C4::Context->tz();
1041 my $today = DateTime->now( time_zone => $tz);
1042 foreach (@{$data}) {
1043 if ($_->{issuedate}) {
1044 $_->{issuedate} = dt_from_string($_->{issuedate}, 'sql');
1046 $_->{date_due} or next;
1047 $_->{date_due} = DateTime::Format::DateParse->parse_datetime($_->{date_due}, $tz->name());
1048 if ( DateTime->compare($_->{date_due}, $today) == -1 ) {
1049 $_->{overdue} = 1;
1052 return $data;
1055 =head2 GetAllIssues
1057 $issues = &GetAllIssues($borrowernumber, $sortkey, $limit);
1059 Looks up what the patron with the given borrowernumber has borrowed,
1060 and sorts the results.
1062 C<$sortkey> is the name of a field on which to sort the results. This
1063 should be the name of a field in the C<issues>, C<biblio>,
1064 C<biblioitems>, or C<items> table in the Koha database.
1066 C<$limit> is the maximum number of results to return.
1068 C<&GetAllIssues> an arrayref, C<$issues>, of hashrefs, the keys of which
1069 are the fields from the C<issues>, C<biblio>, C<biblioitems>, and
1070 C<items> tables of the Koha database.
1072 =cut
1075 sub GetAllIssues {
1076 my ( $borrowernumber, $order, $limit ) = @_;
1078 #FIXME: sanity-check order and limit
1079 my $dbh = C4::Context->dbh;
1080 my $query =
1081 "SELECT *, issues.timestamp as issuestimestamp, issues.renewals AS renewals,items.renewals AS totalrenewals,items.timestamp AS itemstimestamp
1082 FROM issues
1083 LEFT JOIN items on items.itemnumber=issues.itemnumber
1084 LEFT JOIN biblio ON items.biblionumber=biblio.biblionumber
1085 LEFT JOIN biblioitems ON items.biblioitemnumber=biblioitems.biblioitemnumber
1086 WHERE borrowernumber=?
1087 UNION ALL
1088 SELECT *, old_issues.timestamp as issuestimestamp, old_issues.renewals AS renewals,items.renewals AS totalrenewals,items.timestamp AS itemstimestamp
1089 FROM old_issues
1090 LEFT JOIN items on items.itemnumber=old_issues.itemnumber
1091 LEFT JOIN biblio ON items.biblionumber=biblio.biblionumber
1092 LEFT JOIN biblioitems ON items.biblioitemnumber=biblioitems.biblioitemnumber
1093 WHERE borrowernumber=? AND old_issues.itemnumber IS NOT NULL
1094 order by $order";
1095 if ( $limit != 0 ) {
1096 $query .= " limit $limit";
1099 my $sth = $dbh->prepare($query);
1100 $sth->execute($borrowernumber, $borrowernumber);
1101 my @result;
1102 my $i = 0;
1103 while ( my $data = $sth->fetchrow_hashref ) {
1104 push @result, $data;
1107 return \@result;
1111 =head2 GetMemberAccountRecords
1113 ($total, $acctlines, $count) = &GetMemberAccountRecords($borrowernumber);
1115 Looks up accounting data for the patron with the given borrowernumber.
1117 C<&GetMemberAccountRecords> returns a three-element array. C<$acctlines> is a
1118 reference-to-array, where each element is a reference-to-hash; the
1119 keys are the fields of the C<accountlines> table in the Koha database.
1120 C<$count> is the number of elements in C<$acctlines>. C<$total> is the
1121 total amount outstanding for all of the account lines.
1123 =cut
1126 sub GetMemberAccountRecords {
1127 my ($borrowernumber,$date) = @_;
1128 my $dbh = C4::Context->dbh;
1129 my @acctlines;
1130 my $numlines = 0;
1131 my $strsth = qq(
1132 SELECT *
1133 FROM accountlines
1134 WHERE borrowernumber=?);
1135 my @bind = ($borrowernumber);
1136 if ($date && $date ne ''){
1137 $strsth.=" AND date < ? ";
1138 push(@bind,$date);
1140 $strsth.=" ORDER BY date desc,timestamp DESC";
1141 my $sth= $dbh->prepare( $strsth );
1142 $sth->execute( @bind );
1143 my $total = 0;
1144 while ( my $data = $sth->fetchrow_hashref ) {
1145 if ( $data->{itemnumber} ) {
1146 my $biblio = GetBiblioFromItemNumber( $data->{itemnumber} );
1147 $data->{biblionumber} = $biblio->{biblionumber};
1148 $data->{title} = $biblio->{title};
1150 $acctlines[$numlines] = $data;
1151 $numlines++;
1152 $total += int(1000 * $data->{'amountoutstanding'}); # convert float to integer to avoid round-off errors
1154 $total /= 1000;
1155 return ( $total, \@acctlines,$numlines);
1158 =head2 GetBorNotifyAcctRecord
1160 ($total, $acctlines, $count) = &GetBorNotifyAcctRecord($params,$notifyid);
1162 Looks up accounting data for the patron with the given borrowernumber per file number.
1164 C<&GetBorNotifyAcctRecord> returns a three-element array. C<$acctlines> is a
1165 reference-to-array, where each element is a reference-to-hash; the
1166 keys are the fields of the C<accountlines> table in the Koha database.
1167 C<$count> is the number of elements in C<$acctlines>. C<$total> is the
1168 total amount outstanding for all of the account lines.
1170 =cut
1172 sub GetBorNotifyAcctRecord {
1173 my ( $borrowernumber, $notifyid ) = @_;
1174 my $dbh = C4::Context->dbh;
1175 my @acctlines;
1176 my $numlines = 0;
1177 my $sth = $dbh->prepare(
1178 "SELECT *
1179 FROM accountlines
1180 WHERE borrowernumber=?
1181 AND notify_id=?
1182 AND amountoutstanding != '0'
1183 ORDER BY notify_id,accounttype
1186 $sth->execute( $borrowernumber, $notifyid );
1187 my $total = 0;
1188 while ( my $data = $sth->fetchrow_hashref ) {
1189 if ( $data->{itemnumber} ) {
1190 my $biblio = GetBiblioFromItemNumber( $data->{itemnumber} );
1191 $data->{biblionumber} = $biblio->{biblionumber};
1192 $data->{title} = $biblio->{title};
1194 $acctlines[$numlines] = $data;
1195 $numlines++;
1196 $total += int(100 * $data->{'amountoutstanding'});
1198 $total /= 100;
1199 return ( $total, \@acctlines, $numlines );
1202 =head2 checkuniquemember (OUEST-PROVENCE)
1204 ($result,$categorycode) = &checkuniquemember($collectivity,$surname,$firstname,$dateofbirth);
1206 Checks that a member exists or not in the database.
1208 C<&result> is nonzero (=exist) or 0 (=does not exist)
1209 C<&categorycode> is from categorycode table
1210 C<&collectivity> is 1 (= we add a collectivity) or 0 (= we add a physical member)
1211 C<&surname> is the surname
1212 C<&firstname> is the firstname (only if collectivity=0)
1213 C<&dateofbirth> is the date of birth in ISO format (only if collectivity=0)
1215 =cut
1217 # FIXME: This function is not legitimate. Multiple patrons might have the same first/last name and birthdate.
1218 # This is especially true since first name is not even a required field.
1220 sub checkuniquemember {
1221 my ( $collectivity, $surname, $firstname, $dateofbirth ) = @_;
1222 my $dbh = C4::Context->dbh;
1223 my $request = ($collectivity) ?
1224 "SELECT borrowernumber,categorycode FROM borrowers WHERE surname=? " :
1225 ($dateofbirth) ?
1226 "SELECT borrowernumber,categorycode FROM borrowers WHERE surname=? and firstname=? and dateofbirth=?" :
1227 "SELECT borrowernumber,categorycode FROM borrowers WHERE surname=? and firstname=?";
1228 my $sth = $dbh->prepare($request);
1229 if ($collectivity) {
1230 $sth->execute( uc($surname) );
1231 } elsif($dateofbirth){
1232 $sth->execute( uc($surname), ucfirst($firstname), $dateofbirth );
1233 }else{
1234 $sth->execute( uc($surname), ucfirst($firstname));
1236 my @data = $sth->fetchrow;
1237 ( $data[0] ) and return $data[0], $data[1];
1238 return 0;
1241 sub checkcardnumber {
1242 my ($cardnumber,$borrowernumber) = @_;
1243 # If cardnumber is null, we assume they're allowed.
1244 return 0 if !defined($cardnumber);
1245 my $dbh = C4::Context->dbh;
1246 my $query = "SELECT * FROM borrowers WHERE cardnumber=?";
1247 $query .= " AND borrowernumber <> ?" if ($borrowernumber);
1248 my $sth = $dbh->prepare($query);
1249 if ($borrowernumber) {
1250 $sth->execute($cardnumber,$borrowernumber);
1251 } else {
1252 $sth->execute($cardnumber);
1254 if (my $data= $sth->fetchrow_hashref()){
1255 return 1;
1257 else {
1258 return 0;
1263 =head2 getzipnamecity (OUEST-PROVENCE)
1265 take all info from table city for the fields city and zip
1266 check for the name and the zip code of the city selected
1268 =cut
1270 sub getzipnamecity {
1271 my ($cityid) = @_;
1272 my $dbh = C4::Context->dbh;
1273 my $sth =
1274 $dbh->prepare(
1275 "select city_name,city_state,city_zipcode,city_country from cities where cityid=? ");
1276 $sth->execute($cityid);
1277 my @data = $sth->fetchrow;
1278 return $data[0], $data[1], $data[2], $data[3];
1282 =head2 getdcity (OUEST-PROVENCE)
1284 recover cityid with city_name condition
1286 =cut
1288 sub getidcity {
1289 my ($city_name) = @_;
1290 my $dbh = C4::Context->dbh;
1291 my $sth = $dbh->prepare("select cityid from cities where city_name=? ");
1292 $sth->execute($city_name);
1293 my $data = $sth->fetchrow;
1294 return $data;
1297 =head2 GetFirstValidEmailAddress
1299 $email = GetFirstValidEmailAddress($borrowernumber);
1301 Return the first valid email address for a borrower, given the borrowernumber. For now, the order
1302 is defined as email, emailpro, B_email. Returns the empty string if the borrower has no email
1303 addresses.
1305 =cut
1307 sub GetFirstValidEmailAddress {
1308 my $borrowernumber = shift;
1309 my $dbh = C4::Context->dbh;
1310 my $sth = $dbh->prepare( "SELECT email, emailpro, B_email FROM borrowers where borrowernumber = ? ");
1311 $sth->execute( $borrowernumber );
1312 my $data = $sth->fetchrow_hashref;
1314 if ($data->{'email'}) {
1315 return $data->{'email'};
1316 } elsif ($data->{'emailpro'}) {
1317 return $data->{'emailpro'};
1318 } elsif ($data->{'B_email'}) {
1319 return $data->{'B_email'};
1320 } else {
1321 return '';
1325 =head2 GetExpiryDate
1327 $expirydate = GetExpiryDate($categorycode, $dateenrolled);
1329 Calculate expiry date given a categorycode and starting date. Date argument must be in ISO format.
1330 Return date is also in ISO format.
1332 =cut
1334 sub GetExpiryDate {
1335 my ( $categorycode, $dateenrolled ) = @_;
1336 my $enrolments;
1337 if ($categorycode) {
1338 my $dbh = C4::Context->dbh;
1339 my $sth = $dbh->prepare("SELECT enrolmentperiod,enrolmentperioddate FROM categories WHERE categorycode=?");
1340 $sth->execute($categorycode);
1341 $enrolments = $sth->fetchrow_hashref;
1343 # die "GetExpiryDate: for enrollmentperiod $enrolmentperiod (category '$categorycode') starting $dateenrolled.\n";
1344 my @date = split (/-/,$dateenrolled);
1345 if($enrolments->{enrolmentperiod}){
1346 return sprintf("%04d-%02d-%02d", Add_Delta_YM(@date,0,$enrolments->{enrolmentperiod}));
1347 }else{
1348 return $enrolments->{enrolmentperioddate};
1352 =head2 checkuserpassword (OUEST-PROVENCE)
1354 check for the password and login are not used
1355 return the number of record
1356 0=> NOT USED 1=> USED
1358 =cut
1360 sub checkuserpassword {
1361 my ( $borrowernumber, $userid, $password ) = @_;
1362 $password = md5_base64($password);
1363 my $dbh = C4::Context->dbh;
1364 my $sth =
1365 $dbh->prepare(
1366 "Select count(*) from borrowers where borrowernumber !=? and userid =? and password=? "
1368 $sth->execute( $borrowernumber, $userid, $password );
1369 my $number_rows = $sth->fetchrow;
1370 return $number_rows;
1374 =head2 GetborCatFromCatType
1376 ($codes_arrayref, $labels_hashref) = &GetborCatFromCatType();
1378 Looks up the different types of borrowers in the database. Returns two
1379 elements: a reference-to-array, which lists the borrower category
1380 codes, and a reference-to-hash, which maps the borrower category codes
1381 to category descriptions.
1383 =cut
1386 sub GetborCatFromCatType {
1387 my ( $category_type, $action ) = @_;
1388 # FIXME - This API seems both limited and dangerous.
1389 my $dbh = C4::Context->dbh;
1390 my $request = qq| SELECT categorycode,description
1391 FROM categories
1392 $action
1393 ORDER BY categorycode|;
1394 my $sth = $dbh->prepare($request);
1395 if ($action) {
1396 $sth->execute($category_type);
1398 else {
1399 $sth->execute();
1402 my %labels;
1403 my @codes;
1405 while ( my $data = $sth->fetchrow_hashref ) {
1406 push @codes, $data->{'categorycode'};
1407 $labels{ $data->{'categorycode'} } = $data->{'description'};
1409 return ( \@codes, \%labels );
1412 =head2 GetBorrowercategory
1414 $hashref = &GetBorrowercategory($categorycode);
1416 Given the borrower's category code, the function returns the corresponding
1417 data hashref for a comprehensive information display.
1419 =cut
1421 sub GetBorrowercategory {
1422 my ($catcode) = @_;
1423 my $dbh = C4::Context->dbh;
1424 if ($catcode){
1425 my $sth =
1426 $dbh->prepare(
1427 "SELECT description,dateofbirthrequired,upperagelimit,category_type
1428 FROM categories
1429 WHERE categorycode = ?"
1431 $sth->execute($catcode);
1432 my $data =
1433 $sth->fetchrow_hashref;
1434 return $data;
1436 return;
1437 } # sub getborrowercategory
1440 =head2 GetBorrowerCategorycode
1442 $categorycode = &GetBorrowerCategoryCode( $borrowernumber );
1444 Given the borrowernumber, the function returns the corresponding categorycode
1445 =cut
1447 sub GetBorrowerCategorycode {
1448 my ( $borrowernumber ) = @_;
1449 my $dbh = C4::Context->dbh;
1450 my $sth = $dbh->prepare( qq{
1451 SELECT categorycode
1452 FROM borrowers
1453 WHERE borrowernumber = ?
1454 } );
1455 $sth->execute( $borrowernumber );
1456 return $sth->fetchrow;
1459 =head2 GetBorrowercategoryList
1461 $arrayref_hashref = &GetBorrowercategoryList;
1462 If no category code provided, the function returns all the categories.
1464 =cut
1466 sub GetBorrowercategoryList {
1467 my $dbh = C4::Context->dbh;
1468 my $sth =
1469 $dbh->prepare(
1470 "SELECT *
1471 FROM categories
1472 ORDER BY description"
1474 $sth->execute;
1475 my $data =
1476 $sth->fetchall_arrayref({});
1477 return $data;
1478 } # sub getborrowercategory
1480 =head2 ethnicitycategories
1482 ($codes_arrayref, $labels_hashref) = &ethnicitycategories();
1484 Looks up the different ethnic types in the database. Returns two
1485 elements: a reference-to-array, which lists the ethnicity codes, and a
1486 reference-to-hash, which maps the ethnicity codes to ethnicity
1487 descriptions.
1489 =cut
1493 sub ethnicitycategories {
1494 my $dbh = C4::Context->dbh;
1495 my $sth = $dbh->prepare("Select code,name from ethnicity order by name");
1496 $sth->execute;
1497 my %labels;
1498 my @codes;
1499 while ( my $data = $sth->fetchrow_hashref ) {
1500 push @codes, $data->{'code'};
1501 $labels{ $data->{'code'} } = $data->{'name'};
1503 return ( \@codes, \%labels );
1506 =head2 fixEthnicity
1508 $ethn_name = &fixEthnicity($ethn_code);
1510 Takes an ethnicity code (e.g., "european" or "pi") and returns the
1511 corresponding descriptive name from the C<ethnicity> table in the
1512 Koha database ("European" or "Pacific Islander").
1514 =cut
1518 sub fixEthnicity {
1519 my $ethnicity = shift;
1520 return unless $ethnicity;
1521 my $dbh = C4::Context->dbh;
1522 my $sth = $dbh->prepare("Select name from ethnicity where code = ?");
1523 $sth->execute($ethnicity);
1524 my $data = $sth->fetchrow_hashref;
1525 return $data->{'name'};
1526 } # sub fixEthnicity
1528 =head2 GetAge
1530 $dateofbirth,$date = &GetAge($date);
1532 this function return the borrowers age with the value of dateofbirth
1534 =cut
1537 sub GetAge{
1538 my ( $date, $date_ref ) = @_;
1540 if ( not defined $date_ref ) {
1541 $date_ref = sprintf( '%04d-%02d-%02d', Today() );
1544 my ( $year1, $month1, $day1 ) = split /-/, $date;
1545 my ( $year2, $month2, $day2 ) = split /-/, $date_ref;
1547 my $age = $year2 - $year1;
1548 if ( $month1 . $day1 > $month2 . $day2 ) {
1549 $age--;
1552 return $age;
1553 } # sub get_age
1555 =head2 get_institutions
1557 $insitutions = get_institutions();
1559 Just returns a list of all the borrowers of type I, borrownumber and name
1561 =cut
1564 sub get_institutions {
1565 my $dbh = C4::Context->dbh();
1566 my $sth =
1567 $dbh->prepare(
1568 "SELECT borrowernumber,surname FROM borrowers WHERE categorycode=? ORDER BY surname"
1570 $sth->execute('I');
1571 my %orgs;
1572 while ( my $data = $sth->fetchrow_hashref() ) {
1573 $orgs{ $data->{'borrowernumber'} } = $data;
1575 return ( \%orgs );
1577 } # sub get_institutions
1579 =head2 add_member_orgs
1581 add_member_orgs($borrowernumber,$borrowernumbers);
1583 Takes a borrowernumber and a list of other borrowernumbers and inserts them into the borrowers_to_borrowers table
1585 =cut
1588 sub add_member_orgs {
1589 my ( $borrowernumber, $otherborrowers ) = @_;
1590 my $dbh = C4::Context->dbh();
1591 my $query =
1592 "INSERT INTO borrowers_to_borrowers (borrower1,borrower2) VALUES (?,?)";
1593 my $sth = $dbh->prepare($query);
1594 foreach my $otherborrowernumber (@$otherborrowers) {
1595 $sth->execute( $borrowernumber, $otherborrowernumber );
1598 } # sub add_member_orgs
1600 =head2 GetCities
1602 $cityarrayref = GetCities();
1604 Returns an array_ref of the entries in the cities table
1605 If there are entries in the table an empty row is returned
1606 This is currently only used to populate a popup in memberentry
1608 =cut
1610 sub GetCities {
1612 my $dbh = C4::Context->dbh;
1613 my $city_arr = $dbh->selectall_arrayref(
1614 q|SELECT cityid,city_zipcode,city_name,city_state,city_country FROM cities ORDER BY city_name|,
1615 { Slice => {} });
1616 if ( @{$city_arr} ) {
1617 unshift @{$city_arr}, {
1618 city_zipcode => q{},
1619 city_name => q{},
1620 cityid => q{},
1621 city_state => q{},
1622 city_country => q{},
1626 return $city_arr;
1629 =head2 GetSortDetails (OUEST-PROVENCE)
1631 ($lib) = &GetSortDetails($category,$sortvalue);
1633 Returns the authorized value details
1634 C<&$lib>return value of authorized value details
1635 C<&$sortvalue>this is the value of authorized value
1636 C<&$category>this is the value of authorized value category
1638 =cut
1640 sub GetSortDetails {
1641 my ( $category, $sortvalue ) = @_;
1642 my $dbh = C4::Context->dbh;
1643 my $query = qq|SELECT lib
1644 FROM authorised_values
1645 WHERE category=?
1646 AND authorised_value=? |;
1647 my $sth = $dbh->prepare($query);
1648 $sth->execute( $category, $sortvalue );
1649 my $lib = $sth->fetchrow;
1650 return ($lib) if ($lib);
1651 return ($sortvalue) unless ($lib);
1654 =head2 MoveMemberToDeleted
1656 $result = &MoveMemberToDeleted($borrowernumber);
1658 Copy the record from borrowers to deletedborrowers table.
1660 =cut
1662 # FIXME: should do it in one SQL statement w/ subquery
1663 # Otherwise, we should return the @data on success
1665 sub MoveMemberToDeleted {
1666 my ($member) = shift or return;
1667 my $dbh = C4::Context->dbh;
1668 my $query = qq|SELECT *
1669 FROM borrowers
1670 WHERE borrowernumber=?|;
1671 my $sth = $dbh->prepare($query);
1672 $sth->execute($member);
1673 my @data = $sth->fetchrow_array;
1674 (@data) or return; # if we got a bad borrowernumber, there's nothing to insert
1675 $sth =
1676 $dbh->prepare( "INSERT INTO deletedborrowers VALUES ("
1677 . ( "?," x ( scalar(@data) - 1 ) )
1678 . "?)" );
1679 $sth->execute(@data);
1682 =head2 DelMember
1684 DelMember($borrowernumber);
1686 This function remove directly a borrower whitout writing it on deleteborrower.
1687 + Deletes reserves for the borrower
1689 =cut
1691 sub DelMember {
1692 my $dbh = C4::Context->dbh;
1693 my $borrowernumber = shift;
1694 #warn "in delmember with $borrowernumber";
1695 return unless $borrowernumber; # borrowernumber is mandatory.
1697 my $query = qq|DELETE
1698 FROM reserves
1699 WHERE borrowernumber=?|;
1700 my $sth = $dbh->prepare($query);
1701 $sth->execute($borrowernumber);
1702 $query = "
1703 DELETE
1704 FROM borrowers
1705 WHERE borrowernumber = ?
1707 $sth = $dbh->prepare($query);
1708 $sth->execute($borrowernumber);
1709 logaction("MEMBERS", "DELETE", $borrowernumber, "") if C4::Context->preference("BorrowersLog");
1710 return $sth->rows;
1713 =head2 ExtendMemberSubscriptionTo (OUEST-PROVENCE)
1715 $date = ExtendMemberSubscriptionTo($borrowerid, $date);
1717 Extending the subscription to a given date or to the expiry date calculated on ISO date.
1718 Returns ISO date.
1720 =cut
1722 sub ExtendMemberSubscriptionTo {
1723 my ( $borrowerid,$date) = @_;
1724 my $dbh = C4::Context->dbh;
1725 my $borrower = GetMember('borrowernumber'=>$borrowerid);
1726 unless ($date){
1727 $date = (C4::Context->preference('BorrowerRenewalPeriodBase') eq 'dateexpiry') ?
1728 C4::Dates->new($borrower->{'dateexpiry'}, 'iso')->output("iso") :
1729 C4::Dates->new()->output("iso");
1730 $date = GetExpiryDate( $borrower->{'categorycode'}, $date );
1732 my $sth = $dbh->do(<<EOF);
1733 UPDATE borrowers
1734 SET dateexpiry='$date'
1735 WHERE borrowernumber='$borrowerid'
1737 # add enrolmentfee if needed
1738 $sth = $dbh->prepare("SELECT enrolmentfee FROM categories WHERE categorycode=?");
1739 $sth->execute($borrower->{'categorycode'});
1740 my ($enrolmentfee) = $sth->fetchrow;
1741 if ($enrolmentfee && $enrolmentfee > 0) {
1742 # insert fee in patron debts
1743 manualinvoice($borrower->{'borrowernumber'}, '', '', 'A', $enrolmentfee);
1745 logaction("MEMBERS", "RENEW", $borrower->{'borrowernumber'}, "Membership renewed")if C4::Context->preference("BorrowersLog");
1746 return $date if ($sth);
1747 return 0;
1750 =head2 GetRoadTypes (OUEST-PROVENCE)
1752 ($idroadtypearrayref, $roadttype_hashref) = &GetRoadTypes();
1754 Looks up the different road type . Returns two
1755 elements: a reference-to-array, which lists the id_roadtype
1756 codes, and a reference-to-hash, which maps the road type of the road .
1758 =cut
1760 sub GetRoadTypes {
1761 my $dbh = C4::Context->dbh;
1762 my $query = qq|
1763 SELECT roadtypeid,road_type
1764 FROM roadtype
1765 ORDER BY road_type|;
1766 my $sth = $dbh->prepare($query);
1767 $sth->execute();
1768 my %roadtype;
1769 my @id;
1771 # insert empty value to create a empty choice in cgi popup
1773 while ( my $data = $sth->fetchrow_hashref ) {
1775 push @id, $data->{'roadtypeid'};
1776 $roadtype{ $data->{'roadtypeid'} } = $data->{'road_type'};
1779 #test to know if the table contain some records if no the function return nothing
1780 my $id = @id;
1781 if ( $id eq 0 ) {
1782 return ();
1784 else {
1785 unshift( @id, "" );
1786 return ( \@id, \%roadtype );
1792 =head2 GetTitles (OUEST-PROVENCE)
1794 ($borrowertitle)= &GetTitles();
1796 Looks up the different title . Returns array with all borrowers title
1798 =cut
1800 sub GetTitles {
1801 my @borrowerTitle = split (/,|\|/,C4::Context->preference('BorrowersTitles'));
1802 unshift( @borrowerTitle, "" );
1803 my $count=@borrowerTitle;
1804 if ($count == 1){
1805 return ();
1807 else {
1808 return ( \@borrowerTitle);
1812 =head2 GetPatronImage
1814 my ($imagedata, $dberror) = GetPatronImage($cardnumber);
1816 Returns the mimetype and binary image data of the image for the patron with the supplied cardnumber.
1818 =cut
1820 sub GetPatronImage {
1821 my ($cardnumber) = @_;
1822 warn "Cardnumber passed to GetPatronImage is $cardnumber" if $debug;
1823 my $dbh = C4::Context->dbh;
1824 my $query = 'SELECT mimetype, imagefile FROM patronimage WHERE cardnumber = ?';
1825 my $sth = $dbh->prepare($query);
1826 $sth->execute($cardnumber);
1827 my $imagedata = $sth->fetchrow_hashref;
1828 warn "Database error!" if $sth->errstr;
1829 return $imagedata, $sth->errstr;
1832 =head2 PutPatronImage
1834 PutPatronImage($cardnumber, $mimetype, $imgfile);
1836 Stores patron binary image data and mimetype in database.
1837 NOTE: This function is good for updating images as well as inserting new images in the database.
1839 =cut
1841 sub PutPatronImage {
1842 my ($cardnumber, $mimetype, $imgfile) = @_;
1843 warn "Parameters passed in: Cardnumber=$cardnumber, Mimetype=$mimetype, " . ($imgfile ? "Imagefile" : "No Imagefile") if $debug;
1844 my $dbh = C4::Context->dbh;
1845 my $query = "INSERT INTO patronimage (cardnumber, mimetype, imagefile) VALUES (?,?,?) ON DUPLICATE KEY UPDATE imagefile = ?;";
1846 my $sth = $dbh->prepare($query);
1847 $sth->execute($cardnumber,$mimetype,$imgfile,$imgfile);
1848 warn "Error returned inserting $cardnumber.$mimetype." if $sth->errstr;
1849 return $sth->errstr;
1852 =head2 RmPatronImage
1854 my ($dberror) = RmPatronImage($cardnumber);
1856 Removes the image for the patron with the supplied cardnumber.
1858 =cut
1860 sub RmPatronImage {
1861 my ($cardnumber) = @_;
1862 warn "Cardnumber passed to GetPatronImage is $cardnumber" if $debug;
1863 my $dbh = C4::Context->dbh;
1864 my $query = "DELETE FROM patronimage WHERE cardnumber = ?;";
1865 my $sth = $dbh->prepare($query);
1866 $sth->execute($cardnumber);
1867 my $dberror = $sth->errstr;
1868 warn "Database error!" if $sth->errstr;
1869 return $dberror;
1872 =head2 GetHideLostItemsPreference
1874 $hidelostitemspref = &GetHideLostItemsPreference($borrowernumber);
1876 Returns the HideLostItems preference for the patron category of the supplied borrowernumber
1877 C<&$hidelostitemspref>return value of function, 0 or 1
1879 =cut
1881 sub GetHideLostItemsPreference {
1882 my ($borrowernumber) = @_;
1883 my $dbh = C4::Context->dbh;
1884 my $query = "SELECT hidelostitems FROM borrowers,categories WHERE borrowers.categorycode = categories.categorycode AND borrowernumber = ?";
1885 my $sth = $dbh->prepare($query);
1886 $sth->execute($borrowernumber);
1887 my $hidelostitems = $sth->fetchrow;
1888 return $hidelostitems;
1891 =head2 GetRoadTypeDetails (OUEST-PROVENCE)
1893 ($roadtype) = &GetRoadTypeDetails($roadtypeid);
1895 Returns the description of roadtype
1896 C<&$roadtype>return description of road type
1897 C<&$roadtypeid>this is the value of roadtype s
1899 =cut
1901 sub GetRoadTypeDetails {
1902 my ($roadtypeid) = @_;
1903 my $dbh = C4::Context->dbh;
1904 my $query = qq|
1905 SELECT road_type
1906 FROM roadtype
1907 WHERE roadtypeid=?|;
1908 my $sth = $dbh->prepare($query);
1909 $sth->execute($roadtypeid);
1910 my $roadtype = $sth->fetchrow;
1911 return ($roadtype);
1914 =head2 GetBorrowersWhoHaveNotBorrowedSince
1916 &GetBorrowersWhoHaveNotBorrowedSince($date)
1918 this function get all borrowers who haven't borrowed since the date given on input arg.
1920 =cut
1922 sub GetBorrowersWhoHaveNotBorrowedSince {
1923 my $filterdate = shift||POSIX::strftime("%Y-%m-%d",localtime());
1924 my $filterexpiry = shift;
1925 my $filterbranch = shift ||
1926 ((C4::Context->preference('IndependantBranches')
1927 && C4::Context->userenv
1928 && C4::Context->userenv->{flags} % 2 !=1
1929 && C4::Context->userenv->{branch})
1930 ? C4::Context->userenv->{branch}
1931 : "");
1932 my $dbh = C4::Context->dbh;
1933 my $query = "
1934 SELECT borrowers.borrowernumber,
1935 max(old_issues.timestamp) as latestissue,
1936 max(issues.timestamp) as currentissue
1937 FROM borrowers
1938 JOIN categories USING (categorycode)
1939 LEFT JOIN old_issues USING (borrowernumber)
1940 LEFT JOIN issues USING (borrowernumber)
1941 WHERE category_type <> 'S'
1942 AND borrowernumber NOT IN (SELECT guarantorid FROM borrowers WHERE guarantorid IS NOT NULL AND guarantorid <> 0)
1944 my @query_params;
1945 if ($filterbranch && $filterbranch ne ""){
1946 $query.=" AND borrowers.branchcode= ?";
1947 push @query_params,$filterbranch;
1949 if($filterexpiry){
1950 $query .= " AND dateexpiry < ? ";
1951 push @query_params,$filterdate;
1953 $query.=" GROUP BY borrowers.borrowernumber";
1954 if ($filterdate){
1955 $query.=" HAVING (latestissue < ? OR latestissue IS NULL)
1956 AND currentissue IS NULL";
1957 push @query_params,$filterdate;
1959 warn $query if $debug;
1960 my $sth = $dbh->prepare($query);
1961 if (scalar(@query_params)>0){
1962 $sth->execute(@query_params);
1964 else {
1965 $sth->execute;
1968 my @results;
1969 while ( my $data = $sth->fetchrow_hashref ) {
1970 push @results, $data;
1972 return \@results;
1975 =head2 GetBorrowersWhoHaveNeverBorrowed
1977 $results = &GetBorrowersWhoHaveNeverBorrowed
1979 This function get all borrowers who have never borrowed.
1981 I<$result> is a ref to an array which all elements are a hasref.
1983 =cut
1985 sub GetBorrowersWhoHaveNeverBorrowed {
1986 my $filterbranch = shift ||
1987 ((C4::Context->preference('IndependantBranches')
1988 && C4::Context->userenv
1989 && C4::Context->userenv->{flags} % 2 !=1
1990 && C4::Context->userenv->{branch})
1991 ? C4::Context->userenv->{branch}
1992 : "");
1993 my $dbh = C4::Context->dbh;
1994 my $query = "
1995 SELECT borrowers.borrowernumber,max(timestamp) as latestissue
1996 FROM borrowers
1997 LEFT JOIN issues ON borrowers.borrowernumber = issues.borrowernumber
1998 WHERE issues.borrowernumber IS NULL
2000 my @query_params;
2001 if ($filterbranch && $filterbranch ne ""){
2002 $query.=" AND borrowers.branchcode= ?";
2003 push @query_params,$filterbranch;
2005 warn $query if $debug;
2007 my $sth = $dbh->prepare($query);
2008 if (scalar(@query_params)>0){
2009 $sth->execute(@query_params);
2011 else {
2012 $sth->execute;
2015 my @results;
2016 while ( my $data = $sth->fetchrow_hashref ) {
2017 push @results, $data;
2019 return \@results;
2022 =head2 GetBorrowersWithIssuesHistoryOlderThan
2024 $results = &GetBorrowersWithIssuesHistoryOlderThan($date)
2026 this function get all borrowers who has an issue history older than I<$date> given on input arg.
2028 I<$result> is a ref to an array which all elements are a hashref.
2029 This hashref is containt the number of time this borrowers has borrowed before I<$date> and the borrowernumber.
2031 =cut
2033 sub GetBorrowersWithIssuesHistoryOlderThan {
2034 my $dbh = C4::Context->dbh;
2035 my $date = shift ||POSIX::strftime("%Y-%m-%d",localtime());
2036 my $filterbranch = shift ||
2037 ((C4::Context->preference('IndependantBranches')
2038 && C4::Context->userenv
2039 && C4::Context->userenv->{flags} % 2 !=1
2040 && C4::Context->userenv->{branch})
2041 ? C4::Context->userenv->{branch}
2042 : "");
2043 my $query = "
2044 SELECT count(borrowernumber) as n,borrowernumber
2045 FROM old_issues
2046 WHERE returndate < ?
2047 AND borrowernumber IS NOT NULL
2049 my @query_params;
2050 push @query_params, $date;
2051 if ($filterbranch){
2052 $query.=" AND branchcode = ?";
2053 push @query_params, $filterbranch;
2055 $query.=" GROUP BY borrowernumber ";
2056 warn $query if $debug;
2057 my $sth = $dbh->prepare($query);
2058 $sth->execute(@query_params);
2059 my @results;
2061 while ( my $data = $sth->fetchrow_hashref ) {
2062 push @results, $data;
2064 return \@results;
2067 =head2 GetBorrowersNamesAndLatestIssue
2069 $results = &GetBorrowersNamesAndLatestIssueList(@borrowernumbers)
2071 this function get borrowers Names and surnames and Issue information.
2073 I<@borrowernumbers> is an array which all elements are borrowernumbers.
2074 This hashref is containt the number of time this borrowers has borrowed before I<$date> and the borrowernumber.
2076 =cut
2078 sub GetBorrowersNamesAndLatestIssue {
2079 my $dbh = C4::Context->dbh;
2080 my @borrowernumbers=@_;
2081 my $query = "
2082 SELECT surname,lastname, phone, email,max(timestamp)
2083 FROM borrowers
2084 LEFT JOIN issues ON borrowers.borrowernumber=issues.borrowernumber
2085 GROUP BY borrowernumber
2087 my $sth = $dbh->prepare($query);
2088 $sth->execute;
2089 my $results = $sth->fetchall_arrayref({});
2090 return $results;
2093 =head2 DebarMember
2095 my $success = DebarMember( $borrowernumber, $todate );
2097 marks a Member as debarred, and therefore unable to checkout any more
2098 items.
2100 return :
2101 true on success, false on failure
2103 =cut
2105 sub DebarMember {
2106 my $borrowernumber = shift;
2107 my $todate = shift;
2109 return unless defined $borrowernumber;
2110 return unless $borrowernumber =~ /^\d+$/;
2112 return ModMember(
2113 borrowernumber => $borrowernumber,
2114 debarred => $todate
2119 =head2 ModPrivacy
2121 =over 4
2123 my $success = ModPrivacy( $borrowernumber, $privacy );
2125 Update the privacy of a patron.
2127 return :
2128 true on success, false on failure
2130 =back
2132 =cut
2134 sub ModPrivacy {
2135 my $borrowernumber = shift;
2136 my $privacy = shift;
2137 return unless defined $borrowernumber;
2138 return unless $borrowernumber =~ /^\d+$/;
2140 return ModMember( borrowernumber => $borrowernumber,
2141 privacy => $privacy );
2144 =head2 AddMessage
2146 AddMessage( $borrowernumber, $message_type, $message, $branchcode );
2148 Adds a message to the messages table for the given borrower.
2150 Returns:
2151 True on success
2152 False on failure
2154 =cut
2156 sub AddMessage {
2157 my ( $borrowernumber, $message_type, $message, $branchcode ) = @_;
2159 my $dbh = C4::Context->dbh;
2161 if ( ! ( $borrowernumber && $message_type && $message && $branchcode ) ) {
2162 return;
2165 my $query = "INSERT INTO messages ( borrowernumber, branchcode, message_type, message ) VALUES ( ?, ?, ?, ? )";
2166 my $sth = $dbh->prepare($query);
2167 $sth->execute( $borrowernumber, $branchcode, $message_type, $message );
2168 logaction("MEMBERS", "ADDCIRCMESSAGE", $borrowernumber, $message) if C4::Context->preference("BorrowersLog");
2169 return 1;
2172 =head2 GetMessages
2174 GetMessages( $borrowernumber, $type );
2176 $type is message type, B for borrower, or L for Librarian.
2177 Empty type returns all messages of any type.
2179 Returns all messages for the given borrowernumber
2181 =cut
2183 sub GetMessages {
2184 my ( $borrowernumber, $type, $branchcode ) = @_;
2186 if ( ! $type ) {
2187 $type = '%';
2190 my $dbh = C4::Context->dbh;
2192 my $query = "SELECT
2193 branches.branchname,
2194 messages.*,
2195 message_date,
2196 messages.branchcode LIKE '$branchcode' AS can_delete
2197 FROM messages, branches
2198 WHERE borrowernumber = ?
2199 AND message_type LIKE ?
2200 AND messages.branchcode = branches.branchcode
2201 ORDER BY message_date DESC";
2202 my $sth = $dbh->prepare($query);
2203 $sth->execute( $borrowernumber, $type ) ;
2204 my @results;
2206 while ( my $data = $sth->fetchrow_hashref ) {
2207 my $d = C4::Dates->new( $data->{message_date}, 'iso' );
2208 $data->{message_date_formatted} = $d->output;
2209 push @results, $data;
2211 return \@results;
2215 =head2 GetMessages
2217 GetMessagesCount( $borrowernumber, $type );
2219 $type is message type, B for borrower, or L for Librarian.
2220 Empty type returns all messages of any type.
2222 Returns the number of messages for the given borrowernumber
2224 =cut
2226 sub GetMessagesCount {
2227 my ( $borrowernumber, $type, $branchcode ) = @_;
2229 if ( ! $type ) {
2230 $type = '%';
2233 my $dbh = C4::Context->dbh;
2235 my $query = "SELECT COUNT(*) as MsgCount FROM messages WHERE borrowernumber = ? AND message_type LIKE ?";
2236 my $sth = $dbh->prepare($query);
2237 $sth->execute( $borrowernumber, $type ) ;
2238 my @results;
2240 my $data = $sth->fetchrow_hashref;
2241 my $count = $data->{'MsgCount'};
2243 return $count;
2248 =head2 DeleteMessage
2250 DeleteMessage( $message_id );
2252 =cut
2254 sub DeleteMessage {
2255 my ( $message_id ) = @_;
2257 my $dbh = C4::Context->dbh;
2258 my $query = "SELECT * FROM messages WHERE message_id = ?";
2259 my $sth = $dbh->prepare($query);
2260 $sth->execute( $message_id );
2261 my $message = $sth->fetchrow_hashref();
2263 $query = "DELETE FROM messages WHERE message_id = ?";
2264 $sth = $dbh->prepare($query);
2265 $sth->execute( $message_id );
2266 logaction("MEMBERS", "DELCIRCMESSAGE", $message->{'borrowernumber'}, $message->{'message'}) if C4::Context->preference("BorrowersLog");
2269 =head2 IssueSlip
2271 IssueSlip($branchcode, $borrowernumber, $quickslip)
2273 Returns letter hash ( see C4::Letters::GetPreparedLetter )
2275 $quickslip is boolean, to indicate whether we want a quick slip
2277 =cut
2279 sub IssueSlip {
2280 my ($branch, $borrowernumber, $quickslip) = @_;
2282 # return unless ( C4::Context->boolean_preference('printcirculationslips') );
2284 my $now = POSIX::strftime("%Y-%m-%d", localtime);
2286 my $issueslist = GetPendingIssues($borrowernumber);
2287 foreach my $it (@$issueslist){
2288 if ((substr $it->{'issuedate'}, 0, 10) eq $now) {
2289 $it->{'now'} = 1;
2291 elsif ((substr $it->{'date_due'}, 0, 10) le $now) {
2292 $it->{'overdue'} = 1;
2295 $it->{'date_due'}=format_date($it->{'date_due'});
2297 my @issues = sort { $b->{'timestamp'} <=> $a->{'timestamp'} } @$issueslist;
2299 my ($letter_code, %repeat);
2300 if ( $quickslip ) {
2301 $letter_code = 'ISSUEQSLIP';
2302 %repeat = (
2303 'checkedout' => [ map {
2304 'biblio' => $_,
2305 'items' => $_,
2306 'issues' => $_,
2307 }, grep { $_->{'now'} } @issues ],
2310 else {
2311 $letter_code = 'ISSUESLIP';
2312 %repeat = (
2313 'checkedout' => [ map {
2314 'biblio' => $_,
2315 'items' => $_,
2316 'issues' => $_,
2317 }, grep { !$_->{'overdue'} } @issues ],
2319 'overdue' => [ map {
2320 'biblio' => $_,
2321 'items' => $_,
2322 'issues' => $_,
2323 }, grep { $_->{'overdue'} } @issues ],
2325 'news' => [ map {
2326 $_->{'timestamp'} = $_->{'newdate'};
2327 { opac_news => $_ }
2328 } @{ GetNewsToDisplay("slip") } ],
2332 return C4::Letters::GetPreparedLetter (
2333 module => 'circulation',
2334 letter_code => $letter_code,
2335 branchcode => $branch,
2336 tables => {
2337 'branches' => $branch,
2338 'borrowers' => $borrowernumber,
2340 repeat => \%repeat,
2344 =head2 GetBorrowersWithEmail
2346 ([$borrnum,$userid], ...) = GetBorrowersWithEmail('me@example.com');
2348 This gets a list of users and their basic details from their email address.
2349 As it's possible for multiple user to have the same email address, it provides
2350 you with all of them. If there is no userid for the user, there will be an
2351 C<undef> there. An empty list will be returned if there are no matches.
2353 =cut
2355 sub GetBorrowersWithEmail {
2356 my $email = shift;
2358 my $dbh = C4::Context->dbh;
2360 my $query = "SELECT borrowernumber, userid FROM borrowers WHERE email=?";
2361 my $sth=$dbh->prepare($query);
2362 $sth->execute($email);
2363 my @result = ();
2364 while (my $ref = $sth->fetch) {
2365 push @result, $ref;
2367 die "Failure searching for borrowers by email address: $sth->errstr" if $sth->err;
2368 return @result;
2372 END { } # module clean-up code here (global destructor)
2376 __END__
2378 =head1 AUTHOR
2380 Koha Team
2382 =cut