Bug 10063: Correct documentation of C4::Members::IsMemberBlocked
[koha.git] / C4 / Members.pm
1 package C4::Members;
2
3 # Copyright 2000-2003 Katipo Communications
4 # Copyright 2010 BibLibre
5 # Parts Copyright 2010 Catalyst IT
6 #
7 # This file is part of Koha.
8 #
9 # Koha is free software; you can redistribute it and/or modify it
10 # under the terms of the GNU General Public License as published by
11 # the Free Software Foundation; either version 3 of the License, or
12 # (at your option) any later version.
13 #
14 # Koha is distributed in the hope that it will be useful, but
15 # WITHOUT ANY WARRANTY; without even the implied warranty of
16 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 # GNU General Public License for more details.
18 #
19 # You should have received a copy of the GNU General Public License
20 # along with Koha; if not, see <http://www.gnu.org/licenses>.
21
22
23 use strict;
24 #use warnings; FIXME - Bug 2505
25 use C4::Context;
26 use C4::Dates qw(format_date_in_iso format_date);
27 use String::Random qw( random_string );
28 use Date::Calc qw/Today Add_Delta_YM check_date Date_to_Days/;
29 use C4::Log; # logaction
30 use C4::Overdues;
31 use C4::Reserves;
32 use C4::Accounts;
33 use C4::Biblio;
34 use C4::Letters;
35 use C4::Members::Attributes qw(SearchIdMatchingAttribute UpdateBorrowerAttribute);
36 use C4::NewsChannels; #get slip news
37 use DateTime;
38 use Koha::Database;
39 use Koha::DateUtils;
40 use Koha::Borrower::Debarments qw(IsDebarred);
41 use Text::Unaccent qw( unac_string );
42 use Koha::AuthUtils qw(hash_password);
43 use Koha::Database;
44 use Module::Load;
45 if ( C4::Context->preference('NorwegianPatronDBEnable') && C4::Context->preference('NorwegianPatronDBEnable') == 1 ) {
46     load Koha::NorwegianPatronDB, qw( NLUpdateHashedPIN NLEncryptPIN NLSync );
47 }
48
49 our ($VERSION,@ISA,@EXPORT,@EXPORT_OK,$debug);
50
51 BEGIN {
52     $VERSION = 3.07.00.049;
53     $debug = $ENV{DEBUG} || 0;
54     require Exporter;
55     @ISA = qw(Exporter);
56     #Get data
57     push @EXPORT, qw(
58         &Search
59         &GetMemberDetails
60         &GetMemberRelatives
61         &GetMember
62
63         &GetGuarantees
64
65         &GetMemberIssuesAndFines
66         &GetPendingIssues
67         &GetAllIssues
68
69         &getzipnamecity
70         &getidcity
71
72         &GetFirstValidEmailAddress
73         &GetNoticeEmailAddress
74
75         &GetAge
76         &GetCities
77         &GetSortDetails
78         &GetTitles
79
80         &GetPatronImage
81         &PutPatronImage
82         &RmPatronImage
83
84         &GetHideLostItemsPreference
85
86         &IsMemberBlocked
87         &GetMemberAccountRecords
88         &GetBorNotifyAcctRecord
89
90         &GetborCatFromCatType
91         &GetBorrowercategory
92         GetBorrowerCategorycode
93         &GetBorrowercategoryList
94
95         &GetBorrowersToExpunge
96         &GetBorrowersWhoHaveNeverBorrowed
97         &GetBorrowersWithIssuesHistoryOlderThan
98
99         &GetExpiryDate
100
101         &AddMessage
102         &DeleteMessage
103         &GetMessages
104         &GetMessagesCount
105
106         &IssueSlip
107         GetBorrowersWithEmail
108
109         HasOverdues
110     );
111
112     #Modify data
113     push @EXPORT, qw(
114         &ModMember
115         &changepassword
116          &ModPrivacy
117     );
118
119     #Delete data
120     push @EXPORT, qw(
121         &DelMember
122     );
123
124     #Insert data
125     push @EXPORT, qw(
126         &AddMember
127         &AddMember_Opac
128         &MoveMemberToDeleted
129         &ExtendMemberSubscriptionTo
130     );
131
132     #Check data
133     push @EXPORT, qw(
134         &checkuniquemember
135         &checkuserpassword
136         &Check_Userid
137         &Generate_Userid
138         &fixEthnicity
139         &ethnicitycategories
140         &fixup_cardnumber
141         &checkcardnumber
142     );
143 }
144
145 =head1 NAME
146
147 C4::Members - Perl Module containing convenience functions for member handling
148
149 =head1 SYNOPSIS
150
151 use C4::Members;
152
153 =head1 DESCRIPTION
154
155 This module contains routines for adding, modifying and deleting members/patrons/borrowers 
156
157 =head1 FUNCTIONS
158
159 =head2 GetMemberDetails
160
161 ($borrower) = &GetMemberDetails($borrowernumber, $cardnumber);
162
163 Looks up a patron and returns information about him or her. If
164 C<$borrowernumber> is true (nonzero), C<&GetMemberDetails> looks
165 up the borrower by number; otherwise, it looks up the borrower by card
166 number.
167
168 C<$borrower> is a reference-to-hash whose keys are the fields of the
169 borrowers table in the Koha database. In addition,
170 C<$borrower-E<gt>{flags}> is a hash giving more detailed information
171 about the patron. Its keys act as flags :
172
173     if $borrower->{flags}->{LOST} {
174         # Patron's card was reported lost
175     }
176
177 If the state of a flag means that the patron should not be
178 allowed to borrow any more books, then it will have a C<noissues> key
179 with a true value.
180
181 See patronflags for more details.
182
183 C<$borrower-E<gt>{authflags}> is a hash giving more detailed information
184 about the top-level permissions flags set for the borrower.  For example,
185 if a user has the "editcatalogue" permission,
186 C<$borrower-E<gt>{authflags}-E<gt>{editcatalogue}> will exist and have
187 the value "1".
188
189 =cut
190
191 sub GetMemberDetails {
192     my ( $borrowernumber, $cardnumber ) = @_;
193     my $dbh = C4::Context->dbh;
194     my $query;
195     my $sth;
196     if ($borrowernumber) {
197         $sth = $dbh->prepare("
198             SELECT borrowers.*,
199                    category_type,
200                    categories.description,
201                    categories.BlockExpiredPatronOpacActions,
202                    reservefee,
203                    enrolmentperiod
204             FROM borrowers
205             LEFT JOIN categories ON borrowers.categorycode=categories.categorycode
206             WHERE borrowernumber = ?
207         ");
208         $sth->execute($borrowernumber);
209     }
210     elsif ($cardnumber) {
211         $sth = $dbh->prepare("
212             SELECT borrowers.*,
213                    category_type,
214                    categories.description,
215                    categories.BlockExpiredPatronOpacActions,
216                    reservefee,
217                    enrolmentperiod
218             FROM borrowers
219             LEFT JOIN categories ON borrowers.categorycode = categories.categorycode
220             WHERE cardnumber = ?
221         ");
222         $sth->execute($cardnumber);
223     }
224     else {
225         return;
226     }
227     my $borrower = $sth->fetchrow_hashref;
228     return unless $borrower;
229     my ($amount) = GetMemberAccountRecords($borrower->{borrowernumber});
230     $borrower->{'amountoutstanding'} = $amount;
231     # FIXME - patronflags calls GetMemberAccountRecords... just have patronflags return $amount
232     my $flags = patronflags( $borrower);
233     my $accessflagshash;
234
235     $sth = $dbh->prepare("select bit,flag from userflags");
236     $sth->execute;
237     while ( my ( $bit, $flag ) = $sth->fetchrow ) {
238         if ( $borrower->{'flags'} && $borrower->{'flags'} & 2**$bit ) {
239             $accessflagshash->{$flag} = 1;
240         }
241     }
242     $borrower->{'flags'}     = $flags;
243     $borrower->{'authflags'} = $accessflagshash;
244
245     # For the purposes of making templates easier, we'll define a
246     # 'showname' which is the alternate form the user's first name if 
247     # 'other name' is defined.
248     if ($borrower->{category_type} eq 'I') {
249         $borrower->{'showname'} = $borrower->{'othernames'};
250         $borrower->{'showname'} .= " $borrower->{'firstname'}" if $borrower->{'firstname'};
251     } else {
252         $borrower->{'showname'} = $borrower->{'firstname'};
253     }
254
255     # Handle setting the true behavior for BlockExpiredPatronOpacActions
256     $borrower->{'BlockExpiredPatronOpacActions'} =
257       C4::Context->preference('BlockExpiredPatronOpacActions')
258       if ( $borrower->{'BlockExpiredPatronOpacActions'} == -1 );
259
260     $borrower->{'is_expired'} = 0;
261     $borrower->{'is_expired'} = 1 if
262       defined($borrower->{dateexpiry}) &&
263       $borrower->{'dateexpiry'} ne '0000-00-00' &&
264       Date_to_Days( Today() ) >
265       Date_to_Days( split /-/, $borrower->{'dateexpiry'} );
266
267     return ($borrower);    #, $flags, $accessflagshash);
268 }
269
270 =head2 patronflags
271
272  $flags = &patronflags($patron);
273
274 This function is not exported.
275
276 The following will be set where applicable:
277  $flags->{CHARGES}->{amount}        Amount of debt
278  $flags->{CHARGES}->{noissues}      Set if debt amount >$5.00 (or syspref noissuescharge)
279  $flags->{CHARGES}->{message}       Message -- deprecated
280
281  $flags->{CREDITS}->{amount}        Amount of credit
282  $flags->{CREDITS}->{message}       Message -- deprecated
283
284  $flags->{  GNA  }                  Patron has no valid address
285  $flags->{  GNA  }->{noissues}      Set for each GNA
286  $flags->{  GNA  }->{message}       "Borrower has no valid address" -- deprecated
287
288  $flags->{ LOST  }                  Patron's card reported lost
289  $flags->{ LOST  }->{noissues}      Set for each LOST
290  $flags->{ LOST  }->{message}       Message -- deprecated
291
292  $flags->{DBARRED}                  Set if patron debarred, no access
293  $flags->{DBARRED}->{noissues}      Set for each DBARRED
294  $flags->{DBARRED}->{message}       Message -- deprecated
295
296  $flags->{ NOTES }
297  $flags->{ NOTES }->{message}       The note itself.  NOT deprecated
298
299  $flags->{ ODUES }                  Set if patron has overdue books.
300  $flags->{ ODUES }->{message}       "Yes"  -- deprecated
301  $flags->{ ODUES }->{itemlist}      ref-to-array: list of overdue books
302  $flags->{ ODUES }->{itemlisttext}  Text list of overdue items -- deprecated
303
304  $flags->{WAITING}                  Set if any of patron's reserves are available
305  $flags->{WAITING}->{message}       Message -- deprecated
306  $flags->{WAITING}->{itemlist}      ref-to-array: list of available items
307
308 =over 
309
310 =item C<$flags-E<gt>{ODUES}-E<gt>{itemlist}> is a reference-to-array listing the
311 overdue items. Its elements are references-to-hash, each describing an
312 overdue item. The keys are selected fields from the issues, biblio,
313 biblioitems, and items tables of the Koha database.
314
315 =item C<$flags-E<gt>{ODUES}-E<gt>{itemlisttext}> is a string giving a text listing of
316 the overdue items, one per line.  Deprecated.
317
318 =item C<$flags-E<gt>{WAITING}-E<gt>{itemlist}> is a reference-to-array listing the
319 available items. Each element is a reference-to-hash whose keys are
320 fields from the reserves table of the Koha database.
321
322 =back
323
324 All the "message" fields that include language generated in this function are deprecated, 
325 because such strings belong properly in the display layer.
326
327 The "message" field that comes from the DB is OK.
328
329 =cut
330
331 # TODO: use {anonymous => hashes} instead of a dozen %flaginfo
332 # FIXME rename this function.
333 sub patronflags {
334     my %flags;
335     my ( $patroninformation) = @_;
336     my $dbh=C4::Context->dbh;
337     my ($balance, $owing) = GetMemberAccountBalance( $patroninformation->{'borrowernumber'});
338     if ( $owing > 0 ) {
339         my %flaginfo;
340         my $noissuescharge = C4::Context->preference("noissuescharge") || 5;
341         $flaginfo{'message'} = sprintf 'Patron owes %.02f', $owing;
342         $flaginfo{'amount'}  = sprintf "%.02f", $owing;
343         if ( $owing > $noissuescharge && !C4::Context->preference("AllowFineOverride") ) {
344             $flaginfo{'noissues'} = 1;
345         }
346         $flags{'CHARGES'} = \%flaginfo;
347     }
348     elsif ( $balance < 0 ) {
349         my %flaginfo;
350         $flaginfo{'message'} = sprintf 'Patron has credit of %.02f', -$balance;
351         $flaginfo{'amount'}  = sprintf "%.02f", $balance;
352         $flags{'CREDITS'} = \%flaginfo;
353     }
354     if (   $patroninformation->{'gonenoaddress'}
355         && $patroninformation->{'gonenoaddress'} == 1 )
356     {
357         my %flaginfo;
358         $flaginfo{'message'}  = 'Borrower has no valid address.';
359         $flaginfo{'noissues'} = 1;
360         $flags{'GNA'}         = \%flaginfo;
361     }
362     if ( $patroninformation->{'lost'} && $patroninformation->{'lost'} == 1 ) {
363         my %flaginfo;
364         $flaginfo{'message'}  = 'Borrower\'s card reported lost.';
365         $flaginfo{'noissues'} = 1;
366         $flags{'LOST'}        = \%flaginfo;
367     }
368     if ( $patroninformation->{'debarred'} && check_date( split( /-/, $patroninformation->{'debarred'} ) ) ) {
369         if ( Date_to_Days(Date::Calc::Today) < Date_to_Days( split( /-/, $patroninformation->{'debarred'} ) ) ) {
370             my %flaginfo;
371             $flaginfo{'debarredcomment'} = $patroninformation->{'debarredcomment'};
372             $flaginfo{'message'}         = $patroninformation->{'debarredcomment'};
373             $flaginfo{'noissues'}        = 1;
374             $flaginfo{'dateend'}         = $patroninformation->{'debarred'};
375             $flags{'DBARRED'}           = \%flaginfo;
376         }
377     }
378     if (   $patroninformation->{'borrowernotes'}
379         && $patroninformation->{'borrowernotes'} )
380     {
381         my %flaginfo;
382         $flaginfo{'message'} = $patroninformation->{'borrowernotes'};
383         $flags{'NOTES'}      = \%flaginfo;
384     }
385     my ( $odues, $itemsoverdue ) = C4::Overdues::checkoverdues($patroninformation->{'borrowernumber'});
386     if ( $odues && $odues > 0 ) {
387         my %flaginfo;
388         $flaginfo{'message'}  = "Yes";
389         $flaginfo{'itemlist'} = $itemsoverdue;
390         foreach ( sort { $a->{'date_due'} cmp $b->{'date_due'} }
391             @$itemsoverdue )
392         {
393             $flaginfo{'itemlisttext'} .=
394               "$_->{'date_due'} $_->{'barcode'} $_->{'title'} \n";  # newline is display layer
395         }
396         $flags{'ODUES'} = \%flaginfo;
397     }
398     my @itemswaiting = C4::Reserves::GetReservesFromBorrowernumber( $patroninformation->{'borrowernumber'},'W' );
399     my $nowaiting = scalar @itemswaiting;
400     if ( $nowaiting > 0 ) {
401         my %flaginfo;
402         $flaginfo{'message'}  = "Reserved items available";
403         $flaginfo{'itemlist'} = \@itemswaiting;
404         $flags{'WAITING'}     = \%flaginfo;
405     }
406     return ( \%flags );
407 }
408
409
410 =head2 GetMember
411
412   $borrower = &GetMember(%information);
413
414 Retrieve the first patron record meeting on criteria listed in the
415 C<%information> hash, which should contain one or more
416 pairs of borrowers column names and values, e.g.,
417
418    $borrower = GetMember(borrowernumber => id);
419
420 C<&GetBorrower> returns a reference-to-hash whose keys are the fields of
421 the C<borrowers> table in the Koha database.
422
423 FIXME: GetMember() is used throughout the code as a lookup
424 on a unique key such as the borrowernumber, but this meaning is not
425 enforced in the routine itself.
426
427 =cut
428
429 #'
430 sub GetMember {
431     my ( %information ) = @_;
432     if (exists $information{borrowernumber} && !defined $information{borrowernumber}) {
433         #passing mysql's kohaadmin?? Makes no sense as a query
434         return;
435     }
436     my $dbh = C4::Context->dbh;
437     my $select =
438     q{SELECT borrowers.*, categories.category_type, categories.description
439     FROM borrowers 
440     LEFT JOIN categories on borrowers.categorycode=categories.categorycode WHERE };
441     my $more_p = 0;
442     my @values = ();
443     for (keys %information ) {
444         if ($more_p) {
445             $select .= ' AND ';
446         }
447         else {
448             $more_p++;
449         }
450
451         if (defined $information{$_}) {
452             $select .= "$_ = ?";
453             push @values, $information{$_};
454         }
455         else {
456             $select .= "$_ IS NULL";
457         }
458     }
459     $debug && warn $select, " ",values %information;
460     my $sth = $dbh->prepare("$select");
461     $sth->execute(map{$information{$_}} keys %information);
462     my $data = $sth->fetchall_arrayref({});
463     #FIXME interface to this routine now allows generation of a result set
464     #so whole array should be returned but bowhere in the current code expects this
465     if (@{$data} ) {
466         return $data->[0];
467     }
468
469     return;
470 }
471
472 =head2 GetMemberRelatives
473
474  @borrowernumbers = GetMemberRelatives($borrowernumber);
475
476  C<GetMemberRelatives> returns a borrowersnumber's list of guarantor/guarantees of the member given in parameter
477
478 =cut
479
480 sub GetMemberRelatives {
481     my $borrowernumber = shift;
482     my $dbh = C4::Context->dbh;
483     my @glist;
484
485     # Getting guarantor
486     my $query = "SELECT guarantorid FROM borrowers WHERE borrowernumber=?";
487     my $sth = $dbh->prepare($query);
488     $sth->execute($borrowernumber);
489     my $data = $sth->fetchrow_arrayref();
490     push @glist, $data->[0] if $data->[0];
491     my $guarantor = $data->[0] ? $data->[0] : undef;
492
493     # Getting guarantees
494     $query = "SELECT borrowernumber FROM borrowers WHERE guarantorid=?";
495     $sth = $dbh->prepare($query);
496     $sth->execute($borrowernumber);
497     while ($data = $sth->fetchrow_arrayref()) {
498        push @glist, $data->[0];
499     }
500
501     # Getting sibling guarantees
502     if ($guarantor) {
503         $query = "SELECT borrowernumber FROM borrowers WHERE guarantorid=?";
504         $sth = $dbh->prepare($query);
505         $sth->execute($guarantor);
506         while ($data = $sth->fetchrow_arrayref()) {
507            push @glist, $data->[0] if ($data->[0] != $borrowernumber);
508         }
509     }
510
511     return @glist;
512 }
513
514 =head2 IsMemberBlocked
515
516   my ($block_status, $count) = IsMemberBlocked( $borrowernumber );
517
518 Returns whether a patron is restricted or has overdue items that may result
519 in a block of circulation privileges.
520
521 C<$block_status> can have the following values:
522
523 1 if the patron is currently restricted, in which case
524 C<$count> is the expiration date (9999-12-31 for indefinite)
525
526 -1 if the patron has overdue items, in which case C<$count> is the number of them
527
528 0 if the patron has no overdue items or outstanding fine days, in which case C<$count> is 0
529
530 Existing active restrictions are checked before current overdue items.
531
532 FIXME: this needs to be split into two functions; a potential block
533 based on the number of current overdue items could be orthogonal
534 to a block based on whether the patron has any restrictions.
535
536 =cut
537
538 sub IsMemberBlocked {
539     my $borrowernumber = shift;
540     my $dbh            = C4::Context->dbh;
541
542     my $blockeddate = Koha::Borrower::Debarments::IsDebarred($borrowernumber);
543
544     return ( 1, $blockeddate ) if $blockeddate;
545
546     # if he have late issues
547     my $sth = $dbh->prepare(
548         "SELECT COUNT(*) as latedocs
549          FROM issues
550          WHERE borrowernumber = ?
551          AND date_due < now()"
552     );
553     $sth->execute($borrowernumber);
554     my $latedocs = $sth->fetchrow_hashref->{'latedocs'};
555
556     return ( -1, $latedocs ) if $latedocs > 0;
557
558     return ( 0, 0 );
559 }
560
561 =head2 GetMemberIssuesAndFines
562
563   ($overdue_count, $issue_count, $total_fines) = &GetMemberIssuesAndFines($borrowernumber);
564
565 Returns aggregate data about items borrowed by the patron with the
566 given borrowernumber.
567
568 C<&GetMemberIssuesAndFines> returns a three-element array.  C<$overdue_count> is the
569 number of overdue items the patron currently has borrowed. C<$issue_count> is the
570 number of books the patron currently has borrowed.  C<$total_fines> is
571 the total fine currently due by the borrower.
572
573 =cut
574
575 #'
576 sub GetMemberIssuesAndFines {
577     my ( $borrowernumber ) = @_;
578     my $dbh   = C4::Context->dbh;
579     my $query = "SELECT COUNT(*) FROM issues WHERE borrowernumber = ?";
580
581     $debug and warn $query."\n";
582     my $sth = $dbh->prepare($query);
583     $sth->execute($borrowernumber);
584     my $issue_count = $sth->fetchrow_arrayref->[0];
585
586     $sth = $dbh->prepare(
587         "SELECT COUNT(*) FROM issues 
588          WHERE borrowernumber = ? 
589          AND date_due < now()"
590     );
591     $sth->execute($borrowernumber);
592     my $overdue_count = $sth->fetchrow_arrayref->[0];
593
594     $sth = $dbh->prepare("SELECT SUM(amountoutstanding) FROM accountlines WHERE borrowernumber = ?");
595     $sth->execute($borrowernumber);
596     my $total_fines = $sth->fetchrow_arrayref->[0];
597
598     return ($overdue_count, $issue_count, $total_fines);
599 }
600
601
602 =head2 columns
603
604   my @columns = C4::Member::columns();
605
606 Returns an array of borrowers' table columns on success,
607 and an empty array on failure.
608
609 =cut
610
611 sub columns {
612
613     # Pure ANSI SQL goodness.
614     my $sql = 'SELECT * FROM borrowers WHERE 1=0;';
615
616     # Get the database handle.
617     my $dbh = C4::Context->dbh;
618
619     # Run the SQL statement to load STH's readonly properties.
620     my $sth = $dbh->prepare($sql);
621     my $rv = $sth->execute();
622
623     # This only fails if the table doesn't exist.
624     # This will always be called AFTER an install or upgrade,
625     # so borrowers will exist!
626     my @data;
627     if ($sth->{NUM_OF_FIELDS}>0) {
628         @data = @{$sth->{NAME}};
629     }
630     else {
631         @data = ();
632     }
633     return @data;
634 }
635
636
637 =head2 ModMember
638
639   my $success = ModMember(borrowernumber => $borrowernumber,
640                                             [ field => value ]... );
641
642 Modify borrower's data.  All date fields should ALREADY be in ISO format.
643
644 return :
645 true on success, or false on failure
646
647 =cut
648
649 sub ModMember {
650     my (%data) = @_;
651     # test to know if you must update or not the borrower password
652     if (exists $data{password}) {
653         if ($data{password} eq '****' or $data{password} eq '') {
654             delete $data{password};
655         } else {
656             if ( C4::Context->preference('NorwegianPatronDBEnable') && C4::Context->preference('NorwegianPatronDBEnable') == 1 ) {
657                 # Update the hashed PIN in borrower_sync.hashed_pin, before Koha hashes it
658                 NLUpdateHashedPIN( $data{'borrowernumber'}, $data{password} );
659             }
660             $data{password} = hash_password($data{password});
661         }
662     }
663     my $old_categorycode = GetBorrowerCategorycode( $data{borrowernumber} );
664
665     # get only the columns of a borrower
666     my $schema = Koha::Database->new()->schema;
667     my @columns = $schema->source('Borrower')->columns;
668     my $new_borrower = { map { join(' ', @columns) =~ /$_/ ? ( $_ => $data{$_} ) : () } keys(%data) };
669     delete $new_borrower->{flags};
670
671     $new_borrower->{dateofbirth}  ||= undef if exists $new_borrower->{dateofbirth};
672     $new_borrower->{dateenrolled} ||= undef if exists $new_borrower->{dateenrolled};
673     $new_borrower->{dateexpiry}   ||= undef if exists $new_borrower->{dateexpiry};
674     my $rs = $schema->resultset('Borrower')->search({
675         borrowernumber => $new_borrower->{borrowernumber},
676      });
677     my $execute_success = $rs->update($new_borrower);
678     if ($execute_success ne '0E0') { # only proceed if the update was a success
679         # ok if its an adult (type) it may have borrowers that depend on it as a guarantor
680         # so when we update information for an adult we should check for guarantees and update the relevant part
681         # of their records, ie addresses and phone numbers
682         my $borrowercategory= GetBorrowercategory( $data{'category_type'} );
683         if ( exists  $borrowercategory->{'category_type'} && $borrowercategory->{'category_type'} eq ('A' || 'S') ) {
684             # is adult check guarantees;
685             UpdateGuarantees(%data);
686         }
687
688         # If the patron changes to a category with enrollment fee, we add a fee
689         if ( $data{categorycode} and $data{categorycode} ne $old_categorycode ) {
690             AddEnrolmentFeeIfNeeded( $data{categorycode}, $data{borrowernumber} );
691         }
692
693         # If NorwegianPatronDBEnable is enabled, we set syncstatus to something that a
694         # cronjob will use for syncing with NL
695         if ( C4::Context->preference('NorwegianPatronDBEnable') && C4::Context->preference('NorwegianPatronDBEnable') == 1 ) {
696             my $borrowersync = Koha::Database->new->schema->resultset('BorrowerSync')->find({
697                 'synctype'       => 'norwegianpatrondb',
698                 'borrowernumber' => $data{'borrowernumber'}
699             });
700             # Do not set to "edited" if syncstatus is "new". We need to sync as new before
701             # we can sync as changed. And the "new sync" will pick up all changes since
702             # the patron was created anyway.
703             if ( $borrowersync->syncstatus ne 'new' && $borrowersync->syncstatus ne 'delete' ) {
704                 $borrowersync->update( { 'syncstatus' => 'edited' } );
705             }
706             # Set the value of 'sync'
707             $borrowersync->update( { 'sync' => $data{'sync'} } );
708             # Try to do the live sync
709             NLSync({ 'borrowernumber' => $data{'borrowernumber'} });
710         }
711
712         logaction("MEMBERS", "MODIFY", $data{'borrowernumber'}, "UPDATE (executed w/ arg: $data{'borrowernumber'})") if C4::Context->preference("BorrowersLog");
713     }
714     return $execute_success;
715 }
716
717 =head2 AddMember
718
719   $borrowernumber = &AddMember(%borrower);
720
721 insert new borrower into table
722
723 (%borrower keys are database columns. Database columns could be
724 different in different versions. Please look into database for correct
725 column names.)
726
727 Returns the borrowernumber upon success
728
729 Returns as undef upon any db error without further processing
730
731 =cut
732
733 #'
734 sub AddMember {
735     my (%data) = @_;
736     my $dbh = C4::Context->dbh;
737     my $schema = Koha::Database->new()->schema;
738
739     # generate a proper login if none provided
740     $data{'userid'} = Generate_Userid( $data{'borrowernumber'}, $data{'firstname'}, $data{'surname'} )
741       if ( $data{'userid'} eq '' || !Check_Userid( $data{'userid'} ) );
742
743     # add expiration date if it isn't already there
744     unless ( $data{'dateexpiry'} ) {
745         $data{'dateexpiry'} = GetExpiryDate( $data{'categorycode'}, C4::Dates->new()->output("iso") );
746     }
747
748     # add enrollment date if it isn't already there
749     unless ( $data{'dateenrolled'} ) {
750         $data{'dateenrolled'} = C4::Dates->new()->output("iso");
751     }
752
753     my $patron_category = $schema->resultset('Category')->find( $data{'categorycode'} );
754     $data{'privacy'} =
755         $patron_category->default_privacy() eq 'default' ? 1
756       : $patron_category->default_privacy() eq 'never'   ? 2
757       : $patron_category->default_privacy() eq 'forever' ? 0
758       :                                                    undef;
759     # Make a copy of the plain text password for later use
760     my $plain_text_password = $data{'password'};
761
762     # create a disabled account if no password provided
763     $data{'password'} = ($data{'password'})? hash_password($data{'password'}) : '!';
764     $data{'dateofbirth'} = undef if( not $data{'dateofbirth'} );
765
766     # get only the columns of Borrower
767     my @columns = $schema->source('Borrower')->columns;
768     my $new_member = { map { join(' ',@columns) =~ /$_/ ? ( $_ => $data{$_} )  : () } keys(%data) } ;
769     delete $new_member->{borrowernumber};
770
771     my $rs = $schema->resultset('Borrower');
772     $data{borrowernumber} = $rs->create($new_member)->id;
773
774     # If NorwegianPatronDBEnable is enabled, we set syncstatus to something that a
775     # cronjob will use for syncing with NL
776     if ( exists $data{'borrowernumber'} && C4::Context->preference('NorwegianPatronDBEnable') && C4::Context->preference('NorwegianPatronDBEnable') == 1 ) {
777         Koha::Database->new->schema->resultset('BorrowerSync')->create({
778             'borrowernumber' => $data{'borrowernumber'},
779             'synctype'       => 'norwegianpatrondb',
780             'sync'           => 1,
781             'syncstatus'     => 'new',
782             'hashed_pin'     => NLEncryptPIN( $plain_text_password ),
783         });
784     }
785
786     # mysql_insertid is probably bad.  not necessarily accurate and mysql-specific at best.
787     logaction("MEMBERS", "CREATE", $data{'borrowernumber'}, "") if C4::Context->preference("BorrowersLog");
788
789     AddEnrolmentFeeIfNeeded( $data{categorycode}, $data{borrowernumber} );
790
791     return $data{borrowernumber};
792 }
793
794 =head2 Check_Userid
795
796     my $uniqueness = Check_Userid($userid,$borrowernumber);
797
798     $borrowernumber is optional (i.e. it can contain a blank value). If $userid is passed with a blank $borrowernumber variable, the database will be checked for all instances of that userid (i.e. userid=? AND borrowernumber != '').
799
800     If $borrowernumber is provided, the database will be checked for every instance of that userid coupled with a different borrower(number) than the one provided.
801
802     return :
803         0 for not unique (i.e. this $userid already exists)
804         1 for unique (i.e. this $userid does not exist, or this $userid/$borrowernumber combination already exists)
805
806 =cut
807
808 sub Check_Userid {
809     my ( $uid, $borrowernumber ) = @_;
810
811     return 0 unless ($uid); # userid is a unique column, we should assume NULL is not unique
812
813     return 0 if ( $uid eq C4::Context->config('user') );
814
815     my $rs = Koha::Database->new()->schema()->resultset('Borrower');
816
817     my $params;
818     $params->{userid} = $uid;
819     $params->{borrowernumber} = { '!=' => $borrowernumber } if ($borrowernumber);
820
821     my $count = $rs->count( $params );
822
823     return $count ? 0 : 1;
824 }
825
826 =head2 Generate_Userid
827
828     my $newuid = Generate_Userid($borrowernumber, $firstname, $surname);
829
830     Generate a userid using the $surname and the $firstname (if there is a value in $firstname).
831
832     $borrowernumber is optional (i.e. it can contain a blank value). A value is passed when generating a new userid for an existing borrower. When a new userid is created for a new borrower, a blank value is passed to this sub.
833
834     return :
835         new userid ($firstname.$surname if there is a $firstname, or $surname if there is no value in $firstname) plus offset (0 if the $newuid is unique, or a higher numeric value if Check_Userid finds an existing match for the $newuid in the database).
836
837 =cut
838
839 sub Generate_Userid {
840   my ($borrowernumber, $firstname, $surname) = @_;
841   my $newuid;
842   my $offset = 0;
843   #The script will "do" the following code and increment the $offset until Check_Userid = 1 (i.e. until $newuid comes back as unique)
844   do {
845     $firstname =~ s/[[:digit:][:space:][:blank:][:punct:][:cntrl:]]//g;
846     $surname =~ s/[[:digit:][:space:][:blank:][:punct:][:cntrl:]]//g;
847     $newuid = lc(($firstname)? "$firstname.$surname" : $surname);
848     $newuid = unac_string('utf-8',$newuid);
849     $newuid .= $offset unless $offset == 0;
850     $offset++;
851
852    } while (!Check_Userid($newuid,$borrowernumber));
853
854    return $newuid;
855 }
856
857 sub changepassword {
858     my ( $uid, $member, $digest ) = @_;
859     my $dbh = C4::Context->dbh;
860
861 #Make sure the userid chosen is unique and not theirs if non-empty. If it is not,
862 #Then we need to tell the user and have them create a new one.
863     my $resultcode;
864     my $sth =
865       $dbh->prepare(
866         "SELECT * FROM borrowers WHERE userid=? AND borrowernumber != ?");
867     $sth->execute( $uid, $member );
868     if ( ( $uid ne '' ) && ( my $row = $sth->fetchrow_hashref ) ) {
869         $resultcode=0;
870     }
871     else {
872         #Everything is good so we can update the information.
873         $sth =
874           $dbh->prepare(
875             "update borrowers set userid=?, password=? where borrowernumber=?");
876         $sth->execute( $uid, $digest, $member );
877         $resultcode=1;
878     }
879     
880     logaction("MEMBERS", "CHANGE PASS", $member, "") if C4::Context->preference("BorrowersLog");
881     return $resultcode;    
882 }
883
884
885
886 =head2 fixup_cardnumber
887
888 Warning: The caller is responsible for locking the members table in write
889 mode, to avoid database corruption.
890
891 =cut
892
893 use vars qw( @weightings );
894 my @weightings = ( 8, 4, 6, 3, 5, 2, 1 );
895
896 sub fixup_cardnumber {
897     my ($cardnumber) = @_;
898     my $autonumber_members = C4::Context->boolean_preference('autoMemberNum') || 0;
899
900     # Find out whether member numbers should be generated
901     # automatically. Should be either "1" or something else.
902     # Defaults to "0", which is interpreted as "no".
903
904     #     if ($cardnumber !~ /\S/ && $autonumber_members) {
905     ($autonumber_members) or return $cardnumber;
906     my $checkdigit = C4::Context->preference('checkdigit');
907     my $dbh = C4::Context->dbh;
908     if ( $checkdigit and $checkdigit eq 'katipo' ) {
909
910         # if checkdigit is selected, calculate katipo-style cardnumber.
911         # otherwise, just use the max()
912         # purpose: generate checksum'd member numbers.
913         # We'll assume we just got the max value of digits 2-8 of member #'s
914         # from the database and our job is to increment that by one,
915         # determine the 1st and 9th digits and return the full string.
916         my $sth = $dbh->prepare(
917             "select max(substring(borrowers.cardnumber,2,7)) as new_num from borrowers"
918         );
919         $sth->execute;
920         my $data = $sth->fetchrow_hashref;
921         $cardnumber = $data->{new_num};
922         if ( !$cardnumber ) {    # If DB has no values,
923             $cardnumber = 1000000;    # start at 1000000
924         } else {
925             $cardnumber += 1;
926         }
927
928         my $sum = 0;
929         for ( my $i = 0 ; $i < 8 ; $i += 1 ) {
930             # read weightings, left to right, 1 char at a time
931             my $temp1 = $weightings[$i];
932
933             # sequence left to right, 1 char at a time
934             my $temp2 = substr( $cardnumber, $i, 1 );
935
936             # mult each char 1-7 by its corresponding weighting
937             $sum += $temp1 * $temp2;
938         }
939
940         my $rem = ( $sum % 11 );
941         $rem = 'X' if $rem == 10;
942
943         return "V$cardnumber$rem";
944      } else {
945
946         my $sth = $dbh->prepare(
947             'SELECT MAX( CAST( cardnumber AS SIGNED ) ) FROM borrowers WHERE cardnumber REGEXP "^-?[0-9]+$"'
948         );
949         $sth->execute;
950         my ($result) = $sth->fetchrow;
951         return $result + 1;
952     }
953     return $cardnumber;     # just here as a fallback/reminder 
954 }
955
956 =head2 GetGuarantees
957
958   ($num_children, $children_arrayref) = &GetGuarantees($parent_borrno);
959   $child0_cardno = $children_arrayref->[0]{"cardnumber"};
960   $child0_borrno = $children_arrayref->[0]{"borrowernumber"};
961
962 C<&GetGuarantees> takes a borrower number (e.g., that of a patron
963 with children) and looks up the borrowers who are guaranteed by that
964 borrower (i.e., the patron's children).
965
966 C<&GetGuarantees> returns two values: an integer giving the number of
967 borrowers guaranteed by C<$parent_borrno>, and a reference to an array
968 of references to hash, which gives the actual results.
969
970 =cut
971
972 #'
973 sub GetGuarantees {
974     my ($borrowernumber) = @_;
975     my $dbh              = C4::Context->dbh;
976     my $sth              =
977       $dbh->prepare(
978 "select cardnumber,borrowernumber, firstname, surname from borrowers where guarantorid=?"
979       );
980     $sth->execute($borrowernumber);
981
982     my @dat;
983     my $data = $sth->fetchall_arrayref({}); 
984     return ( scalar(@$data), $data );
985 }
986
987 =head2 UpdateGuarantees
988
989   &UpdateGuarantees($parent_borrno);
990   
991
992 C<&UpdateGuarantees> borrower data for an adult and updates all the guarantees
993 with the modified information
994
995 =cut
996
997 #'
998 sub UpdateGuarantees {
999     my %data = shift;
1000     my $dbh = C4::Context->dbh;
1001     my ( $count, $guarantees ) = GetGuarantees( $data{'borrowernumber'} );
1002     foreach my $guarantee (@$guarantees){
1003         my $guaquery = qq|UPDATE borrowers 
1004               SET address=?,fax=?,B_city=?,mobile=?,city=?,phone=?
1005               WHERE borrowernumber=?
1006         |;
1007         my $sth = $dbh->prepare($guaquery);
1008         $sth->execute($data{'address'},$data{'fax'},$data{'B_city'},$data{'mobile'},$data{'city'},$data{'phone'},$guarantee->{'borrowernumber'});
1009     }
1010 }
1011 =head2 GetPendingIssues
1012
1013   my $issues = &GetPendingIssues(@borrowernumber);
1014
1015 Looks up what the patron with the given borrowernumber has borrowed.
1016
1017 C<&GetPendingIssues> returns a
1018 reference-to-array where each element is a reference-to-hash; the
1019 keys are the fields from the C<issues>, C<biblio>, and C<items> tables.
1020 The keys include C<biblioitems> fields except marc and marcxml.
1021
1022 =cut
1023
1024 #'
1025 sub GetPendingIssues {
1026     my @borrowernumbers = @_;
1027
1028     unless (@borrowernumbers ) { # return a ref_to_array
1029         return \@borrowernumbers; # to not cause surprise to caller
1030     }
1031
1032     # Borrowers part of the query
1033     my $bquery = '';
1034     for (my $i = 0; $i < @borrowernumbers; $i++) {
1035         $bquery .= ' issues.borrowernumber = ?';
1036         if ($i < $#borrowernumbers ) {
1037             $bquery .= ' OR';
1038         }
1039     }
1040
1041     # must avoid biblioitems.* to prevent large marc and marcxml fields from killing performance
1042     # FIXME: namespace collision: each table has "timestamp" fields.  Which one is "timestamp" ?
1043     # FIXME: circ/ciculation.pl tries to sort by timestamp!
1044     # FIXME: namespace collision: other collisions possible.
1045     # FIXME: most of this data isn't really being used by callers.
1046     my $query =
1047    "SELECT issues.*,
1048             items.*,
1049            biblio.*,
1050            biblioitems.volume,
1051            biblioitems.number,
1052            biblioitems.itemtype,
1053            biblioitems.isbn,
1054            biblioitems.issn,
1055            biblioitems.publicationyear,
1056            biblioitems.publishercode,
1057            biblioitems.volumedate,
1058            biblioitems.volumedesc,
1059            biblioitems.lccn,
1060            biblioitems.url,
1061            borrowers.firstname,
1062            borrowers.surname,
1063            borrowers.cardnumber,
1064            issues.timestamp AS timestamp,
1065            issues.renewals  AS renewals,
1066            issues.borrowernumber AS borrowernumber,
1067             items.renewals  AS totalrenewals
1068     FROM   issues
1069     LEFT JOIN items       ON items.itemnumber       =      issues.itemnumber
1070     LEFT JOIN biblio      ON items.biblionumber     =      biblio.biblionumber
1071     LEFT JOIN biblioitems ON items.biblioitemnumber = biblioitems.biblioitemnumber
1072     LEFT JOIN borrowers ON issues.borrowernumber = borrowers.borrowernumber
1073     WHERE
1074       $bquery
1075     ORDER BY issues.issuedate"
1076     ;
1077
1078     my $sth = C4::Context->dbh->prepare($query);
1079     $sth->execute(@borrowernumbers);
1080     my $data = $sth->fetchall_arrayref({});
1081     my $today = dt_from_string;
1082     foreach (@{$data}) {
1083         if ($_->{issuedate}) {
1084             $_->{issuedate} = dt_from_string($_->{issuedate}, 'sql');
1085         }
1086         $_->{date_due_sql} = $_->{date_due};
1087         # FIXME no need to have this value
1088         $_->{date_due} or next;
1089         $_->{date_due_sql} = $_->{date_due};
1090         # FIXME no need to have this value
1091         $_->{date_due} = dt_from_string($_->{date_due}, 'sql');
1092         if ( DateTime->compare($_->{date_due}, $today) == -1 ) {
1093             $_->{overdue} = 1;
1094         }
1095     }
1096     return $data;
1097 }
1098
1099 =head2 GetAllIssues
1100
1101   $issues = &GetAllIssues($borrowernumber, $sortkey, $limit);
1102
1103 Looks up what the patron with the given borrowernumber has borrowed,
1104 and sorts the results.
1105
1106 C<$sortkey> is the name of a field on which to sort the results. This
1107 should be the name of a field in the C<issues>, C<biblio>,
1108 C<biblioitems>, or C<items> table in the Koha database.
1109
1110 C<$limit> is the maximum number of results to return.
1111
1112 C<&GetAllIssues> an arrayref, C<$issues>, of hashrefs, the keys of which
1113 are the fields from the C<issues>, C<biblio>, C<biblioitems>, and
1114 C<items> tables of the Koha database.
1115
1116 =cut
1117
1118 #'
1119 sub GetAllIssues {
1120     my ( $borrowernumber, $order, $limit ) = @_;
1121
1122     return unless $borrowernumber;
1123     $order = 'date_due desc' unless $order;
1124
1125     my $dbh = C4::Context->dbh;
1126     my $query =
1127 'SELECT *, issues.timestamp as issuestimestamp, issues.renewals AS renewals,items.renewals AS totalrenewals,items.timestamp AS itemstimestamp
1128   FROM issues 
1129   LEFT JOIN items on items.itemnumber=issues.itemnumber
1130   LEFT JOIN biblio ON items.biblionumber=biblio.biblionumber
1131   LEFT JOIN biblioitems ON items.biblioitemnumber=biblioitems.biblioitemnumber
1132   WHERE borrowernumber=? 
1133   UNION ALL
1134   SELECT *, old_issues.timestamp as issuestimestamp, old_issues.renewals AS renewals,items.renewals AS totalrenewals,items.timestamp AS itemstimestamp 
1135   FROM old_issues 
1136   LEFT JOIN items on items.itemnumber=old_issues.itemnumber
1137   LEFT JOIN biblio ON items.biblionumber=biblio.biblionumber
1138   LEFT JOIN biblioitems ON items.biblioitemnumber=biblioitems.biblioitemnumber
1139   WHERE borrowernumber=? AND old_issues.itemnumber IS NOT NULL
1140   order by ' . $order;
1141     if ($limit) {
1142         $query .= " limit $limit";
1143     }
1144
1145     my $sth = $dbh->prepare($query);
1146     $sth->execute( $borrowernumber, $borrowernumber );
1147     return $sth->fetchall_arrayref( {} );
1148 }
1149
1150
1151 =head2 GetMemberAccountRecords
1152
1153   ($total, $acctlines, $count) = &GetMemberAccountRecords($borrowernumber);
1154
1155 Looks up accounting data for the patron with the given borrowernumber.
1156
1157 C<&GetMemberAccountRecords> returns a three-element array. C<$acctlines> is a
1158 reference-to-array, where each element is a reference-to-hash; the
1159 keys are the fields of the C<accountlines> table in the Koha database.
1160 C<$count> is the number of elements in C<$acctlines>. C<$total> is the
1161 total amount outstanding for all of the account lines.
1162
1163 =cut
1164
1165 sub GetMemberAccountRecords {
1166     my ($borrowernumber) = @_;
1167     my $dbh = C4::Context->dbh;
1168     my @acctlines;
1169     my $numlines = 0;
1170     my $strsth      = qq(
1171                         SELECT * 
1172                         FROM accountlines 
1173                         WHERE borrowernumber=?);
1174     $strsth.=" ORDER BY date desc,timestamp DESC";
1175     my $sth= $dbh->prepare( $strsth );
1176     $sth->execute( $borrowernumber );
1177
1178     my $total = 0;
1179     while ( my $data = $sth->fetchrow_hashref ) {
1180         if ( $data->{itemnumber} ) {
1181             my $biblio = GetBiblioFromItemNumber( $data->{itemnumber} );
1182             $data->{biblionumber} = $biblio->{biblionumber};
1183             $data->{title}        = $biblio->{title};
1184         }
1185         $acctlines[$numlines] = $data;
1186         $numlines++;
1187         $total += int(1000 * $data->{'amountoutstanding'}); # convert float to integer to avoid round-off errors
1188     }
1189     $total /= 1000;
1190     return ( $total, \@acctlines,$numlines);
1191 }
1192
1193 =head2 GetMemberAccountBalance
1194
1195   ($total_balance, $non_issue_balance, $other_charges) = &GetMemberAccountBalance($borrowernumber);
1196
1197 Calculates amount immediately owing by the patron - non-issue charges.
1198 Based on GetMemberAccountRecords.
1199 Charges exempt from non-issue are:
1200 * Res (reserves)
1201 * Rent (rental) if RentalsInNoissuesCharge syspref is set to false
1202 * Manual invoices if ManInvInNoissuesCharge syspref is set to false
1203
1204 =cut
1205
1206 sub GetMemberAccountBalance {
1207     my ($borrowernumber) = @_;
1208
1209     my $ACCOUNT_TYPE_LENGTH = 5; # this is plain ridiculous...
1210
1211     my @not_fines;
1212     push @not_fines, 'Res' unless C4::Context->preference('HoldsInNoissuesCharge');
1213     push @not_fines, 'Rent' unless C4::Context->preference('RentalsInNoissuesCharge');
1214     unless ( C4::Context->preference('ManInvInNoissuesCharge') ) {
1215         my $dbh = C4::Context->dbh;
1216         my $man_inv_types = $dbh->selectcol_arrayref(qq{SELECT authorised_value FROM authorised_values WHERE category = 'MANUAL_INV'});
1217         push @not_fines, map substr($_, 0, $ACCOUNT_TYPE_LENGTH), @$man_inv_types;
1218     }
1219     my %not_fine = map {$_ => 1} @not_fines;
1220
1221     my ($total, $acctlines) = GetMemberAccountRecords($borrowernumber);
1222     my $other_charges = 0;
1223     foreach (@$acctlines) {
1224         $other_charges += $_->{amountoutstanding} if $not_fine{ substr($_->{accounttype}, 0, $ACCOUNT_TYPE_LENGTH) };
1225     }
1226
1227     return ( $total, $total - $other_charges, $other_charges);
1228 }
1229
1230 =head2 GetBorNotifyAcctRecord
1231
1232   ($total, $acctlines, $count) = &GetBorNotifyAcctRecord($params,$notifyid);
1233
1234 Looks up accounting data for the patron with the given borrowernumber per file number.
1235
1236 C<&GetBorNotifyAcctRecord> returns a three-element array. C<$acctlines> is a
1237 reference-to-array, where each element is a reference-to-hash; the
1238 keys are the fields of the C<accountlines> table in the Koha database.
1239 C<$count> is the number of elements in C<$acctlines>. C<$total> is the
1240 total amount outstanding for all of the account lines.
1241
1242 =cut
1243
1244 sub GetBorNotifyAcctRecord {
1245     my ( $borrowernumber, $notifyid ) = @_;
1246     my $dbh = C4::Context->dbh;
1247     my @acctlines;
1248     my $numlines = 0;
1249     my $sth = $dbh->prepare(
1250             "SELECT * 
1251                 FROM accountlines 
1252                 WHERE borrowernumber=? 
1253                     AND notify_id=? 
1254                     AND amountoutstanding != '0' 
1255                 ORDER BY notify_id,accounttype
1256                 ");
1257
1258     $sth->execute( $borrowernumber, $notifyid );
1259     my $total = 0;
1260     while ( my $data = $sth->fetchrow_hashref ) {
1261         if ( $data->{itemnumber} ) {
1262             my $biblio = GetBiblioFromItemNumber( $data->{itemnumber} );
1263             $data->{biblionumber} = $biblio->{biblionumber};
1264             $data->{title}        = $biblio->{title};
1265         }
1266         $acctlines[$numlines] = $data;
1267         $numlines++;
1268         $total += int(100 * $data->{'amountoutstanding'});
1269     }
1270     $total /= 100;
1271     return ( $total, \@acctlines, $numlines );
1272 }
1273
1274 =head2 checkuniquemember (OUEST-PROVENCE)
1275
1276   ($result,$categorycode)  = &checkuniquemember($collectivity,$surname,$firstname,$dateofbirth);
1277
1278 Checks that a member exists or not in the database.
1279
1280 C<&result> is nonzero (=exist) or 0 (=does not exist)
1281 C<&categorycode> is from categorycode table
1282 C<&collectivity> is 1 (= we add a collectivity) or 0 (= we add a physical member)
1283 C<&surname> is the surname
1284 C<&firstname> is the firstname (only if collectivity=0)
1285 C<&dateofbirth> is the date of birth in ISO format (only if collectivity=0)
1286
1287 =cut
1288
1289 # FIXME: This function is not legitimate.  Multiple patrons might have the same first/last name and birthdate.
1290 # This is especially true since first name is not even a required field.
1291
1292 sub checkuniquemember {
1293     my ( $collectivity, $surname, $firstname, $dateofbirth ) = @_;
1294     my $dbh = C4::Context->dbh;
1295     my $request = ($collectivity) ?
1296         "SELECT borrowernumber,categorycode FROM borrowers WHERE surname=? " :
1297             ($dateofbirth) ?
1298             "SELECT borrowernumber,categorycode FROM borrowers WHERE surname=? and firstname=?  and dateofbirth=?" :
1299             "SELECT borrowernumber,categorycode FROM borrowers WHERE surname=? and firstname=?";
1300     my $sth = $dbh->prepare($request);
1301     if ($collectivity) {
1302         $sth->execute( uc($surname) );
1303     } elsif($dateofbirth){
1304         $sth->execute( uc($surname), ucfirst($firstname), $dateofbirth );
1305     }else{
1306         $sth->execute( uc($surname), ucfirst($firstname));
1307     }
1308     my @data = $sth->fetchrow;
1309     ( $data[0] ) and return $data[0], $data[1];
1310     return 0;
1311 }
1312
1313 sub checkcardnumber {
1314     my ( $cardnumber, $borrowernumber ) = @_;
1315
1316     # If cardnumber is null, we assume they're allowed.
1317     return 0 unless defined $cardnumber;
1318
1319     my $dbh = C4::Context->dbh;
1320     my $query = "SELECT * FROM borrowers WHERE cardnumber=?";
1321     $query .= " AND borrowernumber <> ?" if ($borrowernumber);
1322     my $sth = $dbh->prepare($query);
1323     $sth->execute(
1324         $cardnumber,
1325         ( $borrowernumber ? $borrowernumber : () )
1326     );
1327
1328     return 1 if $sth->fetchrow_hashref;
1329
1330     my ( $min_length, $max_length ) = get_cardnumber_length();
1331     return 2
1332         if length $cardnumber > $max_length
1333         or length $cardnumber < $min_length;
1334
1335     return 0;
1336 }
1337
1338 =head2 get_cardnumber_length
1339
1340     my ($min, $max) = C4::Members::get_cardnumber_length()
1341
1342 Returns the minimum and maximum length for patron cardnumbers as
1343 determined by the CardnumberLength system preference, the
1344 BorrowerMandatoryField system preference, and the width of the
1345 database column.
1346
1347 =cut
1348
1349 sub get_cardnumber_length {
1350     my ( $min, $max ) = ( 0, 16 ); # borrowers.cardnumber is a nullable varchar(16)
1351     $min = 1 if C4::Context->preference('BorrowerMandatoryField') =~ /cardnumber/;
1352     if ( my $cardnumber_length = C4::Context->preference('CardnumberLength') ) {
1353         # Is integer and length match
1354         if ( $cardnumber_length =~ m|^\d+$| ) {
1355             $min = $max = $cardnumber_length
1356                 if $cardnumber_length >= $min
1357                     and $cardnumber_length <= $max;
1358         }
1359         # Else assuming it is a range
1360         elsif ( $cardnumber_length =~ m|(\d*),(\d*)| ) {
1361             $min = $1 if $1 and $min < $1;
1362             $max = $2 if $2 and $max > $2;
1363         }
1364
1365     }
1366     return ( $min, $max );
1367 }
1368
1369 =head2 getzipnamecity (OUEST-PROVENCE)
1370
1371 take all info from table city for the fields city and  zip
1372 check for the name and the zip code of the city selected
1373
1374 =cut
1375
1376 sub getzipnamecity {
1377     my ($cityid) = @_;
1378     my $dbh      = C4::Context->dbh;
1379     my $sth      =
1380       $dbh->prepare(
1381         "select city_name,city_state,city_zipcode,city_country from cities where cityid=? ");
1382     $sth->execute($cityid);
1383     my @data = $sth->fetchrow;
1384     return $data[0], $data[1], $data[2], $data[3];
1385 }
1386
1387
1388 =head2 getdcity (OUEST-PROVENCE)
1389
1390 recover cityid  with city_name condition
1391
1392 =cut
1393
1394 sub getidcity {
1395     my ($city_name) = @_;
1396     my $dbh = C4::Context->dbh;
1397     my $sth = $dbh->prepare("select cityid from cities where city_name=? ");
1398     $sth->execute($city_name);
1399     my $data = $sth->fetchrow;
1400     return $data;
1401 }
1402
1403 =head2 GetFirstValidEmailAddress
1404
1405   $email = GetFirstValidEmailAddress($borrowernumber);
1406
1407 Return the first valid email address for a borrower, given the borrowernumber.  For now, the order 
1408 is defined as email, emailpro, B_email.  Returns the empty string if the borrower has no email 
1409 addresses.
1410
1411 =cut
1412
1413 sub GetFirstValidEmailAddress {
1414     my $borrowernumber = shift;
1415     my $dbh = C4::Context->dbh;
1416     my $sth = $dbh->prepare( "SELECT email, emailpro, B_email FROM borrowers where borrowernumber = ? ");
1417     $sth->execute( $borrowernumber );
1418     my $data = $sth->fetchrow_hashref;
1419
1420     if ($data->{'email'}) {
1421        return $data->{'email'};
1422     } elsif ($data->{'emailpro'}) {
1423        return $data->{'emailpro'};
1424     } elsif ($data->{'B_email'}) {
1425        return $data->{'B_email'};
1426     } else {
1427        return '';
1428     }
1429 }
1430
1431 =head2 GetNoticeEmailAddress
1432
1433   $email = GetNoticeEmailAddress($borrowernumber);
1434
1435 Return the email address of borrower used for notices, given the borrowernumber.
1436 Returns the empty string if no email address.
1437
1438 =cut
1439
1440 sub GetNoticeEmailAddress {
1441     my $borrowernumber = shift;
1442
1443     my $which_address = C4::Context->preference("AutoEmailPrimaryAddress");
1444     # if syspref is set to 'first valid' (value == OFF), look up email address
1445     if ( $which_address eq 'OFF' ) {
1446         return GetFirstValidEmailAddress($borrowernumber);
1447     }
1448     # specified email address field
1449     my $dbh = C4::Context->dbh;
1450     my $sth = $dbh->prepare( qq{
1451         SELECT $which_address AS primaryemail
1452         FROM borrowers
1453         WHERE borrowernumber=?
1454     } );
1455     $sth->execute($borrowernumber);
1456     my $data = $sth->fetchrow_hashref;
1457     return $data->{'primaryemail'} || '';
1458 }
1459
1460 =head2 GetExpiryDate 
1461
1462   $expirydate = GetExpiryDate($categorycode, $dateenrolled);
1463
1464 Calculate expiry date given a categorycode and starting date.  Date argument must be in ISO format.
1465 Return date is also in ISO format.
1466
1467 =cut
1468
1469 sub GetExpiryDate {
1470     my ( $categorycode, $dateenrolled ) = @_;
1471     my $enrolments;
1472     if ($categorycode) {
1473         my $dbh = C4::Context->dbh;
1474         my $sth = $dbh->prepare("SELECT enrolmentperiod,enrolmentperioddate FROM categories WHERE categorycode=?");
1475         $sth->execute($categorycode);
1476         $enrolments = $sth->fetchrow_hashref;
1477     }
1478     # die "GetExpiryDate: for enrollmentperiod $enrolmentperiod (category '$categorycode') starting $dateenrolled.\n";
1479     my @date = split (/-/,$dateenrolled);
1480     if($enrolments->{enrolmentperiod}){
1481         return sprintf("%04d-%02d-%02d", Add_Delta_YM(@date,0,$enrolments->{enrolmentperiod}));
1482     }else{
1483         return $enrolments->{enrolmentperioddate};
1484     }
1485 }
1486
1487 =head2 GetborCatFromCatType
1488
1489   ($codes_arrayref, $labels_hashref) = &GetborCatFromCatType();
1490
1491 Looks up the different types of borrowers in the database. Returns two
1492 elements: a reference-to-array, which lists the borrower category
1493 codes, and a reference-to-hash, which maps the borrower category codes
1494 to category descriptions.
1495
1496 =cut
1497
1498 #'
1499 sub GetborCatFromCatType {
1500     my ( $category_type, $action, $no_branch_limit ) = @_;
1501
1502     my $branch_limit = $no_branch_limit
1503         ? 0
1504         : C4::Context->userenv ? C4::Context->userenv->{"branch"} : "";
1505
1506     # FIXME - This API  seems both limited and dangerous.
1507     my $dbh     = C4::Context->dbh;
1508
1509     my $request = qq{
1510         SELECT categories.categorycode, categories.description
1511         FROM categories
1512     };
1513     $request .= qq{
1514         LEFT JOIN categories_branches ON categories.categorycode = categories_branches.categorycode
1515     } if $branch_limit;
1516     if($action) {
1517         $request .= " $action ";
1518         $request .= " AND (branchcode = ? OR branchcode IS NULL) GROUP BY description" if $branch_limit;
1519     } else {
1520         $request .= " WHERE branchcode = ? OR branchcode IS NULL GROUP BY description" if $branch_limit;
1521     }
1522     $request .= " ORDER BY categorycode";
1523
1524     my $sth = $dbh->prepare($request);
1525     $sth->execute(
1526         $action ? $category_type : (),
1527         $branch_limit ? $branch_limit : ()
1528     );
1529
1530     my %labels;
1531     my @codes;
1532
1533     while ( my $data = $sth->fetchrow_hashref ) {
1534         push @codes, $data->{'categorycode'};
1535         $labels{ $data->{'categorycode'} } = $data->{'description'};
1536     }
1537     $sth->finish;
1538     return ( \@codes, \%labels );
1539 }
1540
1541 =head2 GetBorrowercategory
1542
1543   $hashref = &GetBorrowercategory($categorycode);
1544
1545 Given the borrower's category code, the function returns the corresponding
1546 data hashref for a comprehensive information display.
1547
1548 =cut
1549
1550 sub GetBorrowercategory {
1551     my ($catcode) = @_;
1552     my $dbh       = C4::Context->dbh;
1553     if ($catcode){
1554         my $sth       =
1555         $dbh->prepare(
1556     "SELECT description,dateofbirthrequired,upperagelimit,category_type 
1557     FROM categories 
1558     WHERE categorycode = ?"
1559         );
1560         $sth->execute($catcode);
1561         my $data =
1562         $sth->fetchrow_hashref;
1563         return $data;
1564     } 
1565     return;  
1566 }    # sub getborrowercategory
1567
1568
1569 =head2 GetBorrowerCategorycode
1570
1571     $categorycode = &GetBorrowerCategoryCode( $borrowernumber );
1572
1573 Given the borrowernumber, the function returns the corresponding categorycode
1574
1575 =cut
1576
1577 sub GetBorrowerCategorycode {
1578     my ( $borrowernumber ) = @_;
1579     my $dbh = C4::Context->dbh;
1580     my $sth = $dbh->prepare( qq{
1581         SELECT categorycode
1582         FROM borrowers
1583         WHERE borrowernumber = ?
1584     } );
1585     $sth->execute( $borrowernumber );
1586     return $sth->fetchrow;
1587 }
1588
1589 =head2 GetBorrowercategoryList
1590
1591   $arrayref_hashref = &GetBorrowercategoryList;
1592 If no category code provided, the function returns all the categories.
1593
1594 =cut
1595
1596 sub GetBorrowercategoryList {
1597     my $no_branch_limit = @_ ? shift : 0;
1598     my $branch_limit = $no_branch_limit
1599         ? 0
1600         : C4::Context->userenv ? C4::Context->userenv->{"branch"} : "";
1601     my $dbh       = C4::Context->dbh;
1602     my $query = "SELECT categories.* FROM categories";
1603     $query .= qq{
1604         LEFT JOIN categories_branches ON categories.categorycode = categories_branches.categorycode
1605         WHERE branchcode = ? OR branchcode IS NULL GROUP BY description
1606     } if $branch_limit;
1607     $query .= " ORDER BY description";
1608     my $sth = $dbh->prepare( $query );
1609     $sth->execute( $branch_limit ? $branch_limit : () );
1610     my $data = $sth->fetchall_arrayref( {} );
1611     $sth->finish;
1612     return $data;
1613 }    # sub getborrowercategory
1614
1615 =head2 ethnicitycategories
1616
1617   ($codes_arrayref, $labels_hashref) = &ethnicitycategories();
1618
1619 Looks up the different ethnic types in the database. Returns two
1620 elements: a reference-to-array, which lists the ethnicity codes, and a
1621 reference-to-hash, which maps the ethnicity codes to ethnicity
1622 descriptions.
1623
1624 =cut
1625
1626 #'
1627
1628 sub ethnicitycategories {
1629     my $dbh = C4::Context->dbh;
1630     my $sth = $dbh->prepare("Select code,name from ethnicity order by name");
1631     $sth->execute;
1632     my %labels;
1633     my @codes;
1634     while ( my $data = $sth->fetchrow_hashref ) {
1635         push @codes, $data->{'code'};
1636         $labels{ $data->{'code'} } = $data->{'name'};
1637     }
1638     return ( \@codes, \%labels );
1639 }
1640
1641 =head2 fixEthnicity
1642
1643   $ethn_name = &fixEthnicity($ethn_code);
1644
1645 Takes an ethnicity code (e.g., "european" or "pi") and returns the
1646 corresponding descriptive name from the C<ethnicity> table in the
1647 Koha database ("European" or "Pacific Islander").
1648
1649 =cut
1650
1651 #'
1652
1653 sub fixEthnicity {
1654     my $ethnicity = shift;
1655     return unless $ethnicity;
1656     my $dbh       = C4::Context->dbh;
1657     my $sth       = $dbh->prepare("Select name from ethnicity where code = ?");
1658     $sth->execute($ethnicity);
1659     my $data = $sth->fetchrow_hashref;
1660     return $data->{'name'};
1661 }    # sub fixEthnicity
1662
1663 =head2 GetAge
1664
1665   $dateofbirth,$date = &GetAge($date);
1666
1667 this function return the borrowers age with the value of dateofbirth
1668
1669 =cut
1670
1671 #'
1672 sub GetAge{
1673     my ( $date, $date_ref ) = @_;
1674
1675     if ( not defined $date_ref ) {
1676         $date_ref = sprintf( '%04d-%02d-%02d', Today() );
1677     }
1678
1679     my ( $year1, $month1, $day1 ) = split /-/, $date;
1680     my ( $year2, $month2, $day2 ) = split /-/, $date_ref;
1681
1682     my $age = $year2 - $year1;
1683     if ( $month1 . $day1 > $month2 . $day2 ) {
1684         $age--;
1685     }
1686
1687     return $age;
1688 }    # sub get_age
1689
1690 =head2 SetAge
1691
1692   $borrower = C4::Members::SetAge($borrower, $datetimeduration);
1693   $borrower = C4::Members::SetAge($borrower, '0015-12-10');
1694   $borrower = C4::Members::SetAge($borrower, $datetimeduration, $datetime_reference);
1695
1696   eval { $borrower = C4::Members::SetAge($borrower, '015-1-10'); };
1697   if ($@) {print $@;} #Catch a bad ISO Date or kill your script!
1698
1699 This function sets the borrower's dateofbirth to match the given age.
1700 Optionally relative to the given $datetime_reference.
1701
1702 @PARAM1 koha.borrowers-object
1703 @PARAM2 DateTime::Duration-object as the desired age
1704         OR a ISO 8601 Date. (To make the API more pleasant)
1705 @PARAM3 DateTime-object as the relative date, defaults to now().
1706 RETURNS The given borrower reference @PARAM1.
1707 DIES    If there was an error with the ISO Date handling.
1708
1709 =cut
1710
1711 #'
1712 sub SetAge{
1713     my ( $borrower, $datetimeduration, $datetime_ref ) = @_;
1714     $datetime_ref = DateTime->now() unless $datetime_ref;
1715
1716     if ($datetimeduration && ref $datetimeduration ne 'DateTime::Duration') {
1717         if ($datetimeduration =~ /^(\d{4})-(\d{2})-(\d{2})/) {
1718             $datetimeduration = DateTime::Duration->new(years => $1, months => $2, days => $3);
1719         }
1720         else {
1721             die "C4::Members::SetAge($borrower, $datetimeduration), datetimeduration not a valid ISO 8601 Date!\n";
1722         }
1723     }
1724
1725     my $new_datetime_ref = $datetime_ref->clone();
1726     $new_datetime_ref->subtract_duration( $datetimeduration );
1727
1728     $borrower->{dateofbirth} = $new_datetime_ref->ymd();
1729
1730     return $borrower;
1731 }    # sub SetAge
1732
1733 =head2 GetCities
1734
1735   $cityarrayref = GetCities();
1736
1737   Returns an array_ref of the entries in the cities table
1738   If there are entries in the table an empty row is returned
1739   This is currently only used to populate a popup in memberentry
1740
1741 =cut
1742
1743 sub GetCities {
1744
1745     my $dbh   = C4::Context->dbh;
1746     my $city_arr = $dbh->selectall_arrayref(
1747         q|SELECT cityid,city_zipcode,city_name,city_state,city_country FROM cities ORDER BY city_name|,
1748         { Slice => {} });
1749     if ( @{$city_arr} ) {
1750         unshift @{$city_arr}, {
1751             city_zipcode => q{},
1752             city_name    => q{},
1753             cityid       => q{},
1754             city_state   => q{},
1755             city_country => q{},
1756         };
1757     }
1758
1759     return  $city_arr;
1760 }
1761
1762 =head2 GetSortDetails (OUEST-PROVENCE)
1763
1764   ($lib) = &GetSortDetails($category,$sortvalue);
1765
1766 Returns the authorized value  details
1767 C<&$lib>return value of authorized value details
1768 C<&$sortvalue>this is the value of authorized value 
1769 C<&$category>this is the value of authorized value category
1770
1771 =cut
1772
1773 sub GetSortDetails {
1774     my ( $category, $sortvalue ) = @_;
1775     my $dbh   = C4::Context->dbh;
1776     my $query = qq|SELECT lib 
1777         FROM authorised_values 
1778         WHERE category=?
1779         AND authorised_value=? |;
1780     my $sth = $dbh->prepare($query);
1781     $sth->execute( $category, $sortvalue );
1782     my $lib = $sth->fetchrow;
1783     return ($lib) if ($lib);
1784     return ($sortvalue) unless ($lib);
1785 }
1786
1787 =head2 MoveMemberToDeleted
1788
1789   $result = &MoveMemberToDeleted($borrowernumber);
1790
1791 Copy the record from borrowers to deletedborrowers table.
1792 The routine returns 1 for success, undef for failure.
1793
1794 =cut
1795
1796 sub MoveMemberToDeleted {
1797     my ($member) = shift or return;
1798
1799     my $schema       = Koha::Database->new()->schema();
1800     my $borrowers_rs = $schema->resultset('Borrower');
1801     $borrowers_rs->result_class('DBIx::Class::ResultClass::HashRefInflator');
1802     my $borrower = $borrowers_rs->find($member);
1803     return unless $borrower;
1804
1805     my $deleted = $schema->resultset('Deletedborrower')->create($borrower);
1806
1807     return $deleted ? 1 : undef;
1808 }
1809
1810 =head2 DelMember
1811
1812     DelMember($borrowernumber);
1813
1814 This function remove directly a borrower whitout writing it on deleteborrower.
1815 + Deletes reserves for the borrower
1816
1817 =cut
1818
1819 sub DelMember {
1820     my $dbh            = C4::Context->dbh;
1821     my $borrowernumber = shift;
1822     #warn "in delmember with $borrowernumber";
1823     return unless $borrowernumber;    # borrowernumber is mandatory.
1824
1825     my $query = qq|DELETE 
1826           FROM  reserves 
1827           WHERE borrowernumber=?|;
1828     my $sth = $dbh->prepare($query);
1829     $sth->execute($borrowernumber);
1830     $query = "
1831        DELETE
1832        FROM borrowers
1833        WHERE borrowernumber = ?
1834    ";
1835     $sth = $dbh->prepare($query);
1836     $sth->execute($borrowernumber);
1837     logaction("MEMBERS", "DELETE", $borrowernumber, "") if C4::Context->preference("BorrowersLog");
1838     return $sth->rows;
1839 }
1840
1841 =head2 ExtendMemberSubscriptionTo (OUEST-PROVENCE)
1842
1843     $date = ExtendMemberSubscriptionTo($borrowerid, $date);
1844
1845 Extending the subscription to a given date or to the expiry date calculated on ISO date.
1846 Returns ISO date.
1847
1848 =cut
1849
1850 sub ExtendMemberSubscriptionTo {
1851     my ( $borrowerid,$date) = @_;
1852     my $dbh = C4::Context->dbh;
1853     my $borrower = GetMember('borrowernumber'=>$borrowerid);
1854     unless ($date){
1855       $date = (C4::Context->preference('BorrowerRenewalPeriodBase') eq 'dateexpiry') ?
1856                                         C4::Dates->new($borrower->{'dateexpiry'}, 'iso')->output("iso") :
1857                                         C4::Dates->new()->output("iso");
1858       $date = GetExpiryDate( $borrower->{'categorycode'}, $date );
1859     }
1860     my $sth = $dbh->do(<<EOF);
1861 UPDATE borrowers 
1862 SET  dateexpiry='$date' 
1863 WHERE borrowernumber='$borrowerid'
1864 EOF
1865
1866     AddEnrolmentFeeIfNeeded( $borrower->{categorycode}, $borrower->{borrowernumber} );
1867
1868     logaction("MEMBERS", "RENEW", $borrower->{'borrowernumber'}, "Membership renewed")if C4::Context->preference("BorrowersLog");
1869     return $date if ($sth);
1870     return 0;
1871 }
1872
1873 =head2 GetTitles (OUEST-PROVENCE)
1874
1875   ($borrowertitle)= &GetTitles();
1876
1877 Looks up the different title . Returns array  with all borrowers title
1878
1879 =cut
1880
1881 sub GetTitles {
1882     my @borrowerTitle = split (/,|\|/,C4::Context->preference('BorrowersTitles'));
1883     unshift( @borrowerTitle, "" );
1884     my $count=@borrowerTitle;
1885     if ($count == 1){
1886         return ();
1887     }
1888     else {
1889         return ( \@borrowerTitle);
1890     }
1891 }
1892
1893 =head2 GetPatronImage
1894
1895     my ($imagedata, $dberror) = GetPatronImage($borrowernumber);
1896
1897 Returns the mimetype and binary image data of the image for the patron with the supplied borrowernumber.
1898
1899 =cut
1900
1901 sub GetPatronImage {
1902     my ($borrowernumber) = @_;
1903     warn "Borrowernumber passed to GetPatronImage is $borrowernumber" if $debug;
1904     my $dbh = C4::Context->dbh;
1905     my $query = 'SELECT mimetype, imagefile FROM patronimage WHERE borrowernumber = ?';
1906     my $sth = $dbh->prepare($query);
1907     $sth->execute($borrowernumber);
1908     my $imagedata = $sth->fetchrow_hashref;
1909     warn "Database error!" if $sth->errstr;
1910     return $imagedata, $sth->errstr;
1911 }
1912
1913 =head2 PutPatronImage
1914
1915     PutPatronImage($cardnumber, $mimetype, $imgfile);
1916
1917 Stores patron binary image data and mimetype in database.
1918 NOTE: This function is good for updating images as well as inserting new images in the database.
1919
1920 =cut
1921
1922 sub PutPatronImage {
1923     my ($cardnumber, $mimetype, $imgfile) = @_;
1924     warn "Parameters passed in: Cardnumber=$cardnumber, Mimetype=$mimetype, " . ($imgfile ? "Imagefile" : "No Imagefile") if $debug;
1925     my $dbh = C4::Context->dbh;
1926     my $query = "INSERT INTO patronimage (borrowernumber, mimetype, imagefile) VALUES ( ( SELECT borrowernumber from borrowers WHERE cardnumber = ? ),?,?) ON DUPLICATE KEY UPDATE imagefile = ?;";
1927     my $sth = $dbh->prepare($query);
1928     $sth->execute($cardnumber,$mimetype,$imgfile,$imgfile);
1929     warn "Error returned inserting $cardnumber.$mimetype." if $sth->errstr;
1930     return $sth->errstr;
1931 }
1932
1933 =head2 RmPatronImage
1934
1935     my ($dberror) = RmPatronImage($borrowernumber);
1936
1937 Removes the image for the patron with the supplied borrowernumber.
1938
1939 =cut
1940
1941 sub RmPatronImage {
1942     my ($borrowernumber) = @_;
1943     warn "Borrowernumber passed to GetPatronImage is $borrowernumber" if $debug;
1944     my $dbh = C4::Context->dbh;
1945     my $query = "DELETE FROM patronimage WHERE borrowernumber = ?;";
1946     my $sth = $dbh->prepare($query);
1947     $sth->execute($borrowernumber);
1948     my $dberror = $sth->errstr;
1949     warn "Database error!" if $sth->errstr;
1950     return $dberror;
1951 }
1952
1953 =head2 GetHideLostItemsPreference
1954
1955   $hidelostitemspref = &GetHideLostItemsPreference($borrowernumber);
1956
1957 Returns the HideLostItems preference for the patron category of the supplied borrowernumber
1958 C<&$hidelostitemspref>return value of function, 0 or 1
1959
1960 =cut
1961
1962 sub GetHideLostItemsPreference {
1963     my ($borrowernumber) = @_;
1964     my $dbh = C4::Context->dbh;
1965     my $query = "SELECT hidelostitems FROM borrowers,categories WHERE borrowers.categorycode = categories.categorycode AND borrowernumber = ?";
1966     my $sth = $dbh->prepare($query);
1967     $sth->execute($borrowernumber);
1968     my $hidelostitems = $sth->fetchrow;    
1969     return $hidelostitems;    
1970 }
1971
1972 =head2 GetBorrowersToExpunge
1973
1974   $borrowers = &GetBorrowersToExpunge(
1975       not_borrowered_since => $not_borrowered_since,
1976       expired_before       => $expired_before,
1977       category_code        => $category_code,
1978       branchcode           => $branchcode
1979   );
1980
1981   This function get all borrowers based on the given criteria.
1982
1983 =cut
1984
1985 sub GetBorrowersToExpunge {
1986     my $params = shift;
1987
1988     my $filterdate     = $params->{'not_borrowered_since'};
1989     my $filterexpiry   = $params->{'expired_before'};
1990     my $filtercategory = $params->{'category_code'};
1991     my $filterbranch   = $params->{'branchcode'} ||
1992                         ((C4::Context->preference('IndependentBranches')
1993                              && C4::Context->userenv 
1994                              && !C4::Context->IsSuperLibrarian()
1995                              && C4::Context->userenv->{branch})
1996                          ? C4::Context->userenv->{branch}
1997                          : "");  
1998
1999     my $dbh   = C4::Context->dbh;
2000     my $query = q|
2001         SELECT borrowers.borrowernumber,
2002                MAX(old_issues.timestamp) AS latestissue,
2003                MAX(issues.timestamp) AS currentissue
2004         FROM   borrowers
2005         JOIN   categories USING (categorycode)
2006         LEFT JOIN (
2007             SELECT guarantorid
2008             FROM borrowers
2009             WHERE guarantorid IS NOT NULL
2010                 AND guarantorid <> 0
2011         ) as tmp ON borrowers.borrowernumber=tmp.guarantorid
2012         LEFT JOIN old_issues USING (borrowernumber)
2013         LEFT JOIN issues USING (borrowernumber) 
2014         WHERE  category_type <> 'S'
2015         AND tmp.guarantorid IS NULL
2016    |;
2017
2018     my @query_params;
2019     if ( $filterbranch && $filterbranch ne "" ) {
2020         $query.= " AND borrowers.branchcode = ? ";
2021         push( @query_params, $filterbranch );
2022     }
2023     if ( $filterexpiry ) {
2024         $query .= " AND dateexpiry < ? ";
2025         push( @query_params, $filterexpiry );
2026     }
2027     if ( $filtercategory ) {
2028         $query .= " AND categorycode = ? ";
2029         push( @query_params, $filtercategory );
2030     }
2031     $query.=" GROUP BY borrowers.borrowernumber HAVING currentissue IS NULL ";
2032     if ( $filterdate ) {
2033         $query.=" AND ( latestissue < ? OR latestissue IS NULL ) ";
2034         push @query_params,$filterdate;
2035     }
2036     warn $query if $debug;
2037
2038     my $sth = $dbh->prepare($query);
2039     if (scalar(@query_params)>0){  
2040         $sth->execute(@query_params);
2041     } 
2042     else {
2043         $sth->execute;
2044     }      
2045     
2046     my @results;
2047     while ( my $data = $sth->fetchrow_hashref ) {
2048         push @results, $data;
2049     }
2050     return \@results;
2051 }
2052
2053 =head2 GetBorrowersWhoHaveNeverBorrowed
2054
2055   $results = &GetBorrowersWhoHaveNeverBorrowed
2056
2057 This function get all borrowers who have never borrowed.
2058
2059 I<$result> is a ref to an array which all elements are a hasref.
2060
2061 =cut
2062
2063 sub GetBorrowersWhoHaveNeverBorrowed {
2064     my $filterbranch = shift || 
2065                         ((C4::Context->preference('IndependentBranches')
2066                              && C4::Context->userenv 
2067                              && !C4::Context->IsSuperLibrarian()
2068                              && C4::Context->userenv->{branch})
2069                          ? C4::Context->userenv->{branch}
2070                          : "");  
2071     my $dbh   = C4::Context->dbh;
2072     my $query = "
2073         SELECT borrowers.borrowernumber,max(timestamp) as latestissue
2074         FROM   borrowers
2075           LEFT JOIN issues ON borrowers.borrowernumber = issues.borrowernumber
2076         WHERE issues.borrowernumber IS NULL
2077    ";
2078     my @query_params;
2079     if ($filterbranch && $filterbranch ne ""){ 
2080         $query.=" AND borrowers.branchcode= ?";
2081         push @query_params,$filterbranch;
2082     }
2083     warn $query if $debug;
2084   
2085     my $sth = $dbh->prepare($query);
2086     if (scalar(@query_params)>0){  
2087         $sth->execute(@query_params);
2088     } 
2089     else {
2090         $sth->execute;
2091     }      
2092     
2093     my @results;
2094     while ( my $data = $sth->fetchrow_hashref ) {
2095         push @results, $data;
2096     }
2097     return \@results;
2098 }
2099
2100 =head2 GetBorrowersWithIssuesHistoryOlderThan
2101
2102   $results = &GetBorrowersWithIssuesHistoryOlderThan($date)
2103
2104 this function get all borrowers who has an issue history older than I<$date> given on input arg.
2105
2106 I<$result> is a ref to an array which all elements are a hashref.
2107 This hashref is containt the number of time this borrowers has borrowed before I<$date> and the borrowernumber.
2108
2109 =cut
2110
2111 sub GetBorrowersWithIssuesHistoryOlderThan {
2112     my $dbh  = C4::Context->dbh;
2113     my $date = shift ||POSIX::strftime("%Y-%m-%d",localtime());
2114     my $filterbranch = shift || 
2115                         ((C4::Context->preference('IndependentBranches')
2116                              && C4::Context->userenv 
2117                              && !C4::Context->IsSuperLibrarian()
2118                              && C4::Context->userenv->{branch})
2119                          ? C4::Context->userenv->{branch}
2120                          : "");  
2121     my $query = "
2122        SELECT count(borrowernumber) as n,borrowernumber
2123        FROM old_issues
2124        WHERE returndate < ?
2125          AND borrowernumber IS NOT NULL 
2126     "; 
2127     my @query_params;
2128     push @query_params, $date;
2129     if ($filterbranch){
2130         $query.="   AND branchcode = ?";
2131         push @query_params, $filterbranch;
2132     }    
2133     $query.=" GROUP BY borrowernumber ";
2134     warn $query if $debug;
2135     my $sth = $dbh->prepare($query);
2136     $sth->execute(@query_params);
2137     my @results;
2138
2139     while ( my $data = $sth->fetchrow_hashref ) {
2140         push @results, $data;
2141     }
2142     return \@results;
2143 }
2144
2145 =head2 GetBorrowersNamesAndLatestIssue
2146
2147   $results = &GetBorrowersNamesAndLatestIssueList(@borrowernumbers)
2148
2149 this function get borrowers Names and surnames and Issue information.
2150
2151 I<@borrowernumbers> is an array which all elements are borrowernumbers.
2152 This hashref is containt the number of time this borrowers has borrowed before I<$date> and the borrowernumber.
2153
2154 =cut
2155
2156 sub GetBorrowersNamesAndLatestIssue {
2157     my $dbh  = C4::Context->dbh;
2158     my @borrowernumbers=@_;  
2159     my $query = "
2160        SELECT surname,lastname, phone, email,max(timestamp)
2161        FROM borrowers 
2162          LEFT JOIN issues ON borrowers.borrowernumber=issues.borrowernumber
2163        GROUP BY borrowernumber
2164    ";
2165     my $sth = $dbh->prepare($query);
2166     $sth->execute;
2167     my $results = $sth->fetchall_arrayref({});
2168     return $results;
2169 }
2170
2171 =head2 ModPrivacy
2172
2173   my $success = ModPrivacy( $borrowernumber, $privacy );
2174
2175 Update the privacy of a patron.
2176
2177 return :
2178 true on success, false on failure
2179
2180 =cut
2181
2182 sub ModPrivacy {
2183     my $borrowernumber = shift;
2184     my $privacy = shift;
2185     return unless defined $borrowernumber;
2186     return unless $borrowernumber =~ /^\d+$/;
2187
2188     return ModMember( borrowernumber => $borrowernumber,
2189                       privacy        => $privacy );
2190 }
2191
2192 =head2 AddMessage
2193
2194   AddMessage( $borrowernumber, $message_type, $message, $branchcode );
2195
2196 Adds a message to the messages table for the given borrower.
2197
2198 Returns:
2199   True on success
2200   False on failure
2201
2202 =cut
2203
2204 sub AddMessage {
2205     my ( $borrowernumber, $message_type, $message, $branchcode ) = @_;
2206
2207     my $dbh  = C4::Context->dbh;
2208
2209     if ( ! ( $borrowernumber && $message_type && $message && $branchcode ) ) {
2210       return;
2211     }
2212
2213     my $query = "INSERT INTO messages ( borrowernumber, branchcode, message_type, message ) VALUES ( ?, ?, ?, ? )";
2214     my $sth = $dbh->prepare($query);
2215     $sth->execute( $borrowernumber, $branchcode, $message_type, $message );
2216     logaction("MEMBERS", "ADDCIRCMESSAGE", $borrowernumber, $message) if C4::Context->preference("BorrowersLog");
2217     return 1;
2218 }
2219
2220 =head2 GetMessages
2221
2222   GetMessages( $borrowernumber, $type );
2223
2224 $type is message type, B for borrower, or L for Librarian.
2225 Empty type returns all messages of any type.
2226
2227 Returns all messages for the given borrowernumber
2228
2229 =cut
2230
2231 sub GetMessages {
2232     my ( $borrowernumber, $type, $branchcode ) = @_;
2233
2234     if ( ! $type ) {
2235       $type = '%';
2236     }
2237
2238     my $dbh  = C4::Context->dbh;
2239
2240     my $query = "SELECT
2241                   branches.branchname,
2242                   messages.*,
2243                   message_date,
2244                   messages.branchcode LIKE '$branchcode' AS can_delete
2245                   FROM messages, branches
2246                   WHERE borrowernumber = ?
2247                   AND message_type LIKE ?
2248                   AND messages.branchcode = branches.branchcode
2249                   ORDER BY message_date DESC";
2250     my $sth = $dbh->prepare($query);
2251     $sth->execute( $borrowernumber, $type ) ;
2252     my @results;
2253
2254     while ( my $data = $sth->fetchrow_hashref ) {
2255         my $d = C4::Dates->new( $data->{message_date}, 'iso' );
2256         $data->{message_date_formatted} = $d->output;
2257         push @results, $data;
2258     }
2259     return \@results;
2260
2261 }
2262
2263 =head2 GetMessages
2264
2265   GetMessagesCount( $borrowernumber, $type );
2266
2267 $type is message type, B for borrower, or L for Librarian.
2268 Empty type returns all messages of any type.
2269
2270 Returns the number of messages for the given borrowernumber
2271
2272 =cut
2273
2274 sub GetMessagesCount {
2275     my ( $borrowernumber, $type, $branchcode ) = @_;
2276
2277     if ( ! $type ) {
2278       $type = '%';
2279     }
2280
2281     my $dbh  = C4::Context->dbh;
2282
2283     my $query = "SELECT COUNT(*) as MsgCount FROM messages WHERE borrowernumber = ? AND message_type LIKE ?";
2284     my $sth = $dbh->prepare($query);
2285     $sth->execute( $borrowernumber, $type ) ;
2286     my @results;
2287
2288     my $data = $sth->fetchrow_hashref;
2289     my $count = $data->{'MsgCount'};
2290
2291     return $count;
2292 }
2293
2294
2295
2296 =head2 DeleteMessage
2297
2298   DeleteMessage( $message_id );
2299
2300 =cut
2301
2302 sub DeleteMessage {
2303     my ( $message_id ) = @_;
2304
2305     my $dbh = C4::Context->dbh;
2306     my $query = "SELECT * FROM messages WHERE message_id = ?";
2307     my $sth = $dbh->prepare($query);
2308     $sth->execute( $message_id );
2309     my $message = $sth->fetchrow_hashref();
2310
2311     $query = "DELETE FROM messages WHERE message_id = ?";
2312     $sth = $dbh->prepare($query);
2313     $sth->execute( $message_id );
2314     logaction("MEMBERS", "DELCIRCMESSAGE", $message->{'borrowernumber'}, $message->{'message'}) if C4::Context->preference("BorrowersLog");
2315 }
2316
2317 =head2 IssueSlip
2318
2319   IssueSlip($branchcode, $borrowernumber, $quickslip)
2320
2321   Returns letter hash ( see C4::Letters::GetPreparedLetter )
2322
2323   $quickslip is boolean, to indicate whether we want a quick slip
2324
2325   IssueSlip populates ISSUESLIP and ISSUEQSLIP, and will make the following expansions:
2326
2327   Both slips:
2328
2329       <<branches.*>>
2330       <<borrowers.*>>
2331
2332   ISSUESLIP:
2333
2334       <checkedout>
2335          <<biblio.*>>
2336          <<items.*>>
2337          <<biblioitems.*>>
2338          <<issues.*>>
2339       </checkedout>
2340
2341       <overdue>
2342          <<biblio.*>>
2343          <<items.*>>
2344          <<biblioitems.*>>
2345          <<issues.*>>
2346       </overdue>
2347
2348       <news>
2349          <<opac_news.*>>
2350       </news>
2351
2352   ISSUEQSLIP:
2353
2354       <checkedout>
2355          <<biblio.*>>
2356          <<items.*>>
2357          <<biblioitems.*>>
2358          <<issues.*>>
2359       </checkedout>
2360
2361   NOTE: Not all table fields are available, pleasee see GetPendingIssues for a list of available fields.
2362
2363 =cut
2364
2365 sub IssueSlip {
2366     my ($branch, $borrowernumber, $quickslip) = @_;
2367
2368     # FIXME Check callers before removing this statement
2369     #return unless $borrowernumber;
2370
2371     my @issues = @{ GetPendingIssues($borrowernumber) };
2372
2373     for my $issue (@issues) {
2374         $issue->{date_due} = $issue->{date_due_sql};
2375         if ($quickslip) {
2376             my $today = output_pref({ dt => dt_from_string, dateformat => 'iso', dateonly => 1 });
2377             if ( substr( $issue->{issuedate}, 0, 10 ) eq $today
2378                 or substr( $issue->{lastreneweddate}, 0, 10 ) eq $today ) {
2379                   $issue->{now} = 1;
2380             };
2381         }
2382     }
2383
2384     # Sort on timestamp then on issuedate (useful for tests and could be if modified in a batch
2385     @issues = sort {
2386         my $s = $b->{timestamp} <=> $a->{timestamp};
2387         $s == 0 ?
2388              $b->{issuedate} <=> $a->{issuedate} : $s;
2389     } @issues;
2390
2391     my ($letter_code, %repeat);
2392     if ( $quickslip ) {
2393         $letter_code = 'ISSUEQSLIP';
2394         %repeat =  (
2395             'checkedout' => [ map {
2396                 'biblio'       => $_,
2397                 'items'        => $_,
2398                 'biblioitems'  => $_,
2399                 'issues'       => $_,
2400             }, grep { $_->{'now'} } @issues ],
2401         );
2402     }
2403     else {
2404         $letter_code = 'ISSUESLIP';
2405         %repeat =  (
2406             'checkedout' => [ map {
2407                 'biblio'       => $_,
2408                 'items'        => $_,
2409                 'biblioitems'  => $_,
2410                 'issues'       => $_,
2411             }, grep { !$_->{'overdue'} } @issues ],
2412
2413             'overdue' => [ map {
2414                 'biblio'       => $_,
2415                 'items'        => $_,
2416                 'biblioitems'  => $_,
2417                 'issues'       => $_,
2418             }, grep { $_->{'overdue'} } @issues ],
2419
2420             'news' => [ map {
2421                 $_->{'timestamp'} = $_->{'newdate'};
2422                 { opac_news => $_ }
2423             } @{ GetNewsToDisplay("slip",$branch) } ],
2424         );
2425     }
2426
2427     return  C4::Letters::GetPreparedLetter (
2428         module => 'circulation',
2429         letter_code => $letter_code,
2430         branchcode => $branch,
2431         tables => {
2432             'branches'    => $branch,
2433             'borrowers'   => $borrowernumber,
2434         },
2435         repeat => \%repeat,
2436     );
2437 }
2438
2439 =head2 GetBorrowersWithEmail
2440
2441     ([$borrnum,$userid], ...) = GetBorrowersWithEmail('me@example.com');
2442
2443 This gets a list of users and their basic details from their email address.
2444 As it's possible for multiple user to have the same email address, it provides
2445 you with all of them. If there is no userid for the user, there will be an
2446 C<undef> there. An empty list will be returned if there are no matches.
2447
2448 =cut
2449
2450 sub GetBorrowersWithEmail {
2451     my $email = shift;
2452
2453     my $dbh = C4::Context->dbh;
2454
2455     my $query = "SELECT borrowernumber, userid FROM borrowers WHERE email=?";
2456     my $sth=$dbh->prepare($query);
2457     $sth->execute($email);
2458     my @result = ();
2459     while (my $ref = $sth->fetch) {
2460         push @result, $ref;
2461     }
2462     die "Failure searching for borrowers by email address: $sth->errstr" if $sth->err;
2463     return @result;
2464 }
2465
2466 sub AddMember_Opac {
2467     my ( %borrower ) = @_;
2468
2469     $borrower{'categorycode'} = C4::Context->preference('PatronSelfRegistrationDefaultCategory');
2470
2471     my $sr = new String::Random;
2472     $sr->{'A'} = [ 'A'..'Z', 'a'..'z' ];
2473     my $password = $sr->randpattern("AAAAAAAAAA");
2474     $borrower{'password'} = $password;
2475
2476     $borrower{'cardnumber'} = fixup_cardnumber();
2477
2478     my $borrowernumber = AddMember(%borrower);
2479
2480     return ( $borrowernumber, $password );
2481 }
2482
2483 =head2 AddEnrolmentFeeIfNeeded
2484
2485     AddEnrolmentFeeIfNeeded( $borrower->{categorycode}, $borrower->{borrowernumber} );
2486
2487 Add enrolment fee for a patron if needed.
2488
2489 =cut
2490
2491 sub AddEnrolmentFeeIfNeeded {
2492     my ( $categorycode, $borrowernumber ) = @_;
2493     # check for enrollment fee & add it if needed
2494     my $dbh = C4::Context->dbh;
2495     my $sth = $dbh->prepare(q{
2496         SELECT enrolmentfee
2497         FROM categories
2498         WHERE categorycode=?
2499     });
2500     $sth->execute( $categorycode );
2501     if ( $sth->err ) {
2502         warn sprintf('Database returned the following error: %s', $sth->errstr);
2503         return;
2504     }
2505     my ($enrolmentfee) = $sth->fetchrow;
2506     if ($enrolmentfee && $enrolmentfee > 0) {
2507         # insert fee in patron debts
2508         C4::Accounts::manualinvoice( $borrowernumber, '', '', 'A', $enrolmentfee );
2509     }
2510 }
2511
2512 sub HasOverdues {
2513     my ( $borrowernumber ) = @_;
2514
2515     my $sql = "SELECT COUNT(*) FROM issues WHERE date_due < NOW() AND borrowernumber = ?";
2516     my $sth = C4::Context->dbh->prepare( $sql );
2517     $sth->execute( $borrowernumber );
2518     my ( $count ) = $sth->fetchrow_array();
2519
2520     return $count;
2521 }
2522
2523 END { }    # module clean-up code here (global destructor)
2524
2525 1;
2526
2527 __END__
2528
2529 =head1 AUTHOR
2530
2531 Koha Team
2532
2533 =cut