Bug 14717: Prevent 0000-00-00 on updating a patron
[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 =cut
533
534 sub IsMemberBlocked {
535     my $borrowernumber = shift;
536     my $dbh            = C4::Context->dbh;
537
538     my $blockeddate = Koha::Borrower::Debarments::IsDebarred($borrowernumber);
539
540     return ( 1, $blockeddate ) if $blockeddate;
541
542     # if he have late issues
543     my $sth = $dbh->prepare(
544         "SELECT COUNT(*) as latedocs
545          FROM issues
546          WHERE borrowernumber = ?
547          AND date_due < now()"
548     );
549     $sth->execute($borrowernumber);
550     my $latedocs = $sth->fetchrow_hashref->{'latedocs'};
551
552     return ( -1, $latedocs ) if $latedocs > 0;
553
554     return ( 0, 0 );
555 }
556
557 =head2 GetMemberIssuesAndFines
558
559   ($overdue_count, $issue_count, $total_fines) = &GetMemberIssuesAndFines($borrowernumber);
560
561 Returns aggregate data about items borrowed by the patron with the
562 given borrowernumber.
563
564 C<&GetMemberIssuesAndFines> returns a three-element array.  C<$overdue_count> is the
565 number of overdue items the patron currently has borrowed. C<$issue_count> is the
566 number of books the patron currently has borrowed.  C<$total_fines> is
567 the total fine currently due by the borrower.
568
569 =cut
570
571 #'
572 sub GetMemberIssuesAndFines {
573     my ( $borrowernumber ) = @_;
574     my $dbh   = C4::Context->dbh;
575     my $query = "SELECT COUNT(*) FROM issues WHERE borrowernumber = ?";
576
577     $debug and warn $query."\n";
578     my $sth = $dbh->prepare($query);
579     $sth->execute($borrowernumber);
580     my $issue_count = $sth->fetchrow_arrayref->[0];
581
582     $sth = $dbh->prepare(
583         "SELECT COUNT(*) FROM issues 
584          WHERE borrowernumber = ? 
585          AND date_due < now()"
586     );
587     $sth->execute($borrowernumber);
588     my $overdue_count = $sth->fetchrow_arrayref->[0];
589
590     $sth = $dbh->prepare("SELECT SUM(amountoutstanding) FROM accountlines WHERE borrowernumber = ?");
591     $sth->execute($borrowernumber);
592     my $total_fines = $sth->fetchrow_arrayref->[0];
593
594     return ($overdue_count, $issue_count, $total_fines);
595 }
596
597
598 =head2 columns
599
600   my @columns = C4::Member::columns();
601
602 Returns an array of borrowers' table columns on success,
603 and an empty array on failure.
604
605 =cut
606
607 sub columns {
608
609     # Pure ANSI SQL goodness.
610     my $sql = 'SELECT * FROM borrowers WHERE 1=0;';
611
612     # Get the database handle.
613     my $dbh = C4::Context->dbh;
614
615     # Run the SQL statement to load STH's readonly properties.
616     my $sth = $dbh->prepare($sql);
617     my $rv = $sth->execute();
618
619     # This only fails if the table doesn't exist.
620     # This will always be called AFTER an install or upgrade,
621     # so borrowers will exist!
622     my @data;
623     if ($sth->{NUM_OF_FIELDS}>0) {
624         @data = @{$sth->{NAME}};
625     }
626     else {
627         @data = ();
628     }
629     return @data;
630 }
631
632
633 =head2 ModMember
634
635   my $success = ModMember(borrowernumber => $borrowernumber,
636                                             [ field => value ]... );
637
638 Modify borrower's data.  All date fields should ALREADY be in ISO format.
639
640 return :
641 true on success, or false on failure
642
643 =cut
644
645 sub ModMember {
646     my (%data) = @_;
647     # test to know if you must update or not the borrower password
648     if (exists $data{password}) {
649         if ($data{password} eq '****' or $data{password} eq '') {
650             delete $data{password};
651         } else {
652             if ( C4::Context->preference('NorwegianPatronDBEnable') && C4::Context->preference('NorwegianPatronDBEnable') == 1 ) {
653                 # Update the hashed PIN in borrower_sync.hashed_pin, before Koha hashes it
654                 NLUpdateHashedPIN( $data{'borrowernumber'}, $data{password} );
655             }
656             $data{password} = hash_password($data{password});
657         }
658     }
659     my $old_categorycode = GetBorrowerCategorycode( $data{borrowernumber} );
660
661     # get only the columns of a borrower
662     my $schema = Koha::Database->new()->schema;
663     my @columns = $schema->source('Borrower')->columns;
664     my $new_borrower = { map { join(' ', @columns) =~ /$_/ ? ( $_ => $data{$_} ) : () } keys(%data) };
665     delete $new_borrower->{flags};
666
667     $new_borrower->{dateofbirth}  ||= undef if exists $new_borrower->{dateofbirth};
668     $new_borrower->{dateenrolled} ||= undef if exists $new_borrower->{dateenrolled};
669     $new_borrower->{dateexpiry}   ||= undef if exists $new_borrower->{dateexpiry};
670     $new_borrower->{debarred}     ||= undef if exists $new_borrower->{debarred};
671     my $rs = $schema->resultset('Borrower')->search({
672         borrowernumber => $new_borrower->{borrowernumber},
673      });
674     my $execute_success = $rs->update($new_borrower);
675     if ($execute_success ne '0E0') { # only proceed if the update was a success
676         # ok if its an adult (type) it may have borrowers that depend on it as a guarantor
677         # so when we update information for an adult we should check for guarantees and update the relevant part
678         # of their records, ie addresses and phone numbers
679         my $borrowercategory= GetBorrowercategory( $data{'category_type'} );
680         if ( exists  $borrowercategory->{'category_type'} && $borrowercategory->{'category_type'} eq ('A' || 'S') ) {
681             # is adult check guarantees;
682             UpdateGuarantees(%data);
683         }
684
685         # If the patron changes to a category with enrollment fee, we add a fee
686         if ( $data{categorycode} and $data{categorycode} ne $old_categorycode ) {
687             if ( C4::Context->preference('FeeOnChangePatronCategory') ) {
688                 AddEnrolmentFeeIfNeeded( $data{categorycode}, $data{borrowernumber} );
689             }
690         }
691
692         # If NorwegianPatronDBEnable is enabled, we set syncstatus to something that a
693         # cronjob will use for syncing with NL
694         if ( C4::Context->preference('NorwegianPatronDBEnable') && C4::Context->preference('NorwegianPatronDBEnable') == 1 ) {
695             my $borrowersync = Koha::Database->new->schema->resultset('BorrowerSync')->find({
696                 'synctype'       => 'norwegianpatrondb',
697                 'borrowernumber' => $data{'borrowernumber'}
698             });
699             # Do not set to "edited" if syncstatus is "new". We need to sync as new before
700             # we can sync as changed. And the "new sync" will pick up all changes since
701             # the patron was created anyway.
702             if ( $borrowersync->syncstatus ne 'new' && $borrowersync->syncstatus ne 'delete' ) {
703                 $borrowersync->update( { 'syncstatus' => 'edited' } );
704             }
705             # Set the value of 'sync'
706             $borrowersync->update( { 'sync' => $data{'sync'} } );
707             # Try to do the live sync
708             NLSync({ 'borrowernumber' => $data{'borrowernumber'} });
709         }
710
711         logaction("MEMBERS", "MODIFY", $data{'borrowernumber'}, "UPDATE (executed w/ arg: $data{'borrowernumber'})") if C4::Context->preference("BorrowersLog");
712     }
713     return $execute_success;
714 }
715
716 =head2 AddMember
717
718   $borrowernumber = &AddMember(%borrower);
719
720 insert new borrower into table
721
722 (%borrower keys are database columns. Database columns could be
723 different in different versions. Please look into database for correct
724 column names.)
725
726 Returns the borrowernumber upon success
727
728 Returns as undef upon any db error without further processing
729
730 =cut
731
732 #'
733 sub AddMember {
734     my (%data) = @_;
735     my $dbh = C4::Context->dbh;
736     my $schema = Koha::Database->new()->schema;
737
738     # generate a proper login if none provided
739     $data{'userid'} = Generate_Userid( $data{'borrowernumber'}, $data{'firstname'}, $data{'surname'} )
740       if ( $data{'userid'} eq '' || !Check_Userid( $data{'userid'} ) );
741
742     # add expiration date if it isn't already there
743     unless ( $data{'dateexpiry'} ) {
744         $data{'dateexpiry'} = GetExpiryDate( $data{'categorycode'}, C4::Dates->new()->output("iso") );
745     }
746
747     # add enrollment date if it isn't already there
748     unless ( $data{'dateenrolled'} ) {
749         $data{'dateenrolled'} = C4::Dates->new()->output("iso");
750     }
751
752     my $patron_category = $schema->resultset('Category')->find( $data{'categorycode'} );
753     $data{'privacy'} =
754         $patron_category->default_privacy() eq 'default' ? 1
755       : $patron_category->default_privacy() eq 'never'   ? 2
756       : $patron_category->default_privacy() eq 'forever' ? 0
757       :                                                    undef;
758     # Make a copy of the plain text password for later use
759     my $plain_text_password = $data{'password'};
760
761     # create a disabled account if no password provided
762     $data{'password'} = ($data{'password'})? hash_password($data{'password'}) : '!';
763
764     # we don't want invalid dates in the db (mysql has a bad habit of inserting 0000-00-00
765     $data{'dateofbirth'} = undef if( not $data{'dateofbirth'} );
766     $data{'debarred'} = undef if ( not $data{'debarred'} );
767
768     # get only the columns of Borrower
769     my @columns = $schema->source('Borrower')->columns;
770     my $new_member = { map { join(' ',@columns) =~ /$_/ ? ( $_ => $data{$_} )  : () } keys(%data) } ;
771     delete $new_member->{borrowernumber};
772
773     my $rs = $schema->resultset('Borrower');
774     $data{borrowernumber} = $rs->create($new_member)->id;
775
776     # If NorwegianPatronDBEnable is enabled, we set syncstatus to something that a
777     # cronjob will use for syncing with NL
778     if ( exists $data{'borrowernumber'} && C4::Context->preference('NorwegianPatronDBEnable') && C4::Context->preference('NorwegianPatronDBEnable') == 1 ) {
779         Koha::Database->new->schema->resultset('BorrowerSync')->create({
780             'borrowernumber' => $data{'borrowernumber'},
781             'synctype'       => 'norwegianpatrondb',
782             'sync'           => 1,
783             'syncstatus'     => 'new',
784             'hashed_pin'     => NLEncryptPIN( $plain_text_password ),
785         });
786     }
787
788     # mysql_insertid is probably bad.  not necessarily accurate and mysql-specific at best.
789     logaction("MEMBERS", "CREATE", $data{'borrowernumber'}, "") if C4::Context->preference("BorrowersLog");
790
791     AddEnrolmentFeeIfNeeded( $data{categorycode}, $data{borrowernumber} );
792
793     return $data{borrowernumber};
794 }
795
796 =head2 Check_Userid
797
798     my $uniqueness = Check_Userid($userid,$borrowernumber);
799
800     $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 != '').
801
802     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.
803
804     return :
805         0 for not unique (i.e. this $userid already exists)
806         1 for unique (i.e. this $userid does not exist, or this $userid/$borrowernumber combination already exists)
807
808 =cut
809
810 sub Check_Userid {
811     my ( $uid, $borrowernumber ) = @_;
812
813     return 0 unless ($uid); # userid is a unique column, we should assume NULL is not unique
814
815     return 0 if ( $uid eq C4::Context->config('user') );
816
817     my $rs = Koha::Database->new()->schema()->resultset('Borrower');
818
819     my $params;
820     $params->{userid} = $uid;
821     $params->{borrowernumber} = { '!=' => $borrowernumber } if ($borrowernumber);
822
823     my $count = $rs->count( $params );
824
825     return $count ? 0 : 1;
826 }
827
828 =head2 Generate_Userid
829
830     my $newuid = Generate_Userid($borrowernumber, $firstname, $surname);
831
832     Generate a userid using the $surname and the $firstname (if there is a value in $firstname).
833
834     $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.
835
836     return :
837         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).
838
839 =cut
840
841 sub Generate_Userid {
842   my ($borrowernumber, $firstname, $surname) = @_;
843   my $newuid;
844   my $offset = 0;
845   #The script will "do" the following code and increment the $offset until Check_Userid = 1 (i.e. until $newuid comes back as unique)
846   do {
847     $firstname =~ s/[[:digit:][:space:][:blank:][:punct:][:cntrl:]]//g;
848     $surname =~ s/[[:digit:][:space:][:blank:][:punct:][:cntrl:]]//g;
849     $newuid = lc(($firstname)? "$firstname.$surname" : $surname);
850     $newuid = unac_string('utf-8',$newuid);
851     $newuid .= $offset unless $offset == 0;
852     $offset++;
853
854    } while (!Check_Userid($newuid,$borrowernumber));
855
856    return $newuid;
857 }
858
859 sub changepassword {
860     my ( $uid, $member, $digest ) = @_;
861     my $dbh = C4::Context->dbh;
862
863 #Make sure the userid chosen is unique and not theirs if non-empty. If it is not,
864 #Then we need to tell the user and have them create a new one.
865     my $resultcode;
866     my $sth =
867       $dbh->prepare(
868         "SELECT * FROM borrowers WHERE userid=? AND borrowernumber != ?");
869     $sth->execute( $uid, $member );
870     if ( ( $uid ne '' ) && ( my $row = $sth->fetchrow_hashref ) ) {
871         $resultcode=0;
872     }
873     else {
874         #Everything is good so we can update the information.
875         $sth =
876           $dbh->prepare(
877             "update borrowers set userid=?, password=? where borrowernumber=?");
878         $sth->execute( $uid, $digest, $member );
879         $resultcode=1;
880     }
881     
882     logaction("MEMBERS", "CHANGE PASS", $member, "") if C4::Context->preference("BorrowersLog");
883     return $resultcode;    
884 }
885
886
887
888 =head2 fixup_cardnumber
889
890 Warning: The caller is responsible for locking the members table in write
891 mode, to avoid database corruption.
892
893 =cut
894
895 use vars qw( @weightings );
896 my @weightings = ( 8, 4, 6, 3, 5, 2, 1 );
897
898 sub fixup_cardnumber {
899     my ($cardnumber) = @_;
900     my $autonumber_members = C4::Context->boolean_preference('autoMemberNum') || 0;
901
902     # Find out whether member numbers should be generated
903     # automatically. Should be either "1" or something else.
904     # Defaults to "0", which is interpreted as "no".
905
906     #     if ($cardnumber !~ /\S/ && $autonumber_members) {
907     ($autonumber_members) or return $cardnumber;
908     my $checkdigit = C4::Context->preference('checkdigit');
909     my $dbh = C4::Context->dbh;
910     if ( $checkdigit and $checkdigit eq 'katipo' ) {
911
912         # if checkdigit is selected, calculate katipo-style cardnumber.
913         # otherwise, just use the max()
914         # purpose: generate checksum'd member numbers.
915         # We'll assume we just got the max value of digits 2-8 of member #'s
916         # from the database and our job is to increment that by one,
917         # determine the 1st and 9th digits and return the full string.
918         my $sth = $dbh->prepare(
919             "select max(substring(borrowers.cardnumber,2,7)) as new_num from borrowers"
920         );
921         $sth->execute;
922         my $data = $sth->fetchrow_hashref;
923         $cardnumber = $data->{new_num};
924         if ( !$cardnumber ) {    # If DB has no values,
925             $cardnumber = 1000000;    # start at 1000000
926         } else {
927             $cardnumber += 1;
928         }
929
930         my $sum = 0;
931         for ( my $i = 0 ; $i < 8 ; $i += 1 ) {
932             # read weightings, left to right, 1 char at a time
933             my $temp1 = $weightings[$i];
934
935             # sequence left to right, 1 char at a time
936             my $temp2 = substr( $cardnumber, $i, 1 );
937
938             # mult each char 1-7 by its corresponding weighting
939             $sum += $temp1 * $temp2;
940         }
941
942         my $rem = ( $sum % 11 );
943         $rem = 'X' if $rem == 10;
944
945         return "V$cardnumber$rem";
946      } else {
947
948         my $sth = $dbh->prepare(
949             'SELECT MAX( CAST( cardnumber AS SIGNED ) ) FROM borrowers WHERE cardnumber REGEXP "^-?[0-9]+$"'
950         );
951         $sth->execute;
952         my ($result) = $sth->fetchrow;
953         return $result + 1;
954     }
955     return $cardnumber;     # just here as a fallback/reminder 
956 }
957
958 =head2 GetGuarantees
959
960   ($num_children, $children_arrayref) = &GetGuarantees($parent_borrno);
961   $child0_cardno = $children_arrayref->[0]{"cardnumber"};
962   $child0_borrno = $children_arrayref->[0]{"borrowernumber"};
963
964 C<&GetGuarantees> takes a borrower number (e.g., that of a patron
965 with children) and looks up the borrowers who are guaranteed by that
966 borrower (i.e., the patron's children).
967
968 C<&GetGuarantees> returns two values: an integer giving the number of
969 borrowers guaranteed by C<$parent_borrno>, and a reference to an array
970 of references to hash, which gives the actual results.
971
972 =cut
973
974 #'
975 sub GetGuarantees {
976     my ($borrowernumber) = @_;
977     my $dbh              = C4::Context->dbh;
978     my $sth              =
979       $dbh->prepare(
980 "select cardnumber,borrowernumber, firstname, surname from borrowers where guarantorid=?"
981       );
982     $sth->execute($borrowernumber);
983
984     my @dat;
985     my $data = $sth->fetchall_arrayref({}); 
986     return ( scalar(@$data), $data );
987 }
988
989 =head2 UpdateGuarantees
990
991   &UpdateGuarantees($parent_borrno);
992   
993
994 C<&UpdateGuarantees> borrower data for an adult and updates all the guarantees
995 with the modified information
996
997 =cut
998
999 #'
1000 sub UpdateGuarantees {
1001     my %data = shift;
1002     my $dbh = C4::Context->dbh;
1003     my ( $count, $guarantees ) = GetGuarantees( $data{'borrowernumber'} );
1004     foreach my $guarantee (@$guarantees){
1005         my $guaquery = qq|UPDATE borrowers 
1006               SET address=?,fax=?,B_city=?,mobile=?,city=?,phone=?
1007               WHERE borrowernumber=?
1008         |;
1009         my $sth = $dbh->prepare($guaquery);
1010         $sth->execute($data{'address'},$data{'fax'},$data{'B_city'},$data{'mobile'},$data{'city'},$data{'phone'},$guarantee->{'borrowernumber'});
1011     }
1012 }
1013 =head2 GetPendingIssues
1014
1015   my $issues = &GetPendingIssues(@borrowernumber);
1016
1017 Looks up what the patron with the given borrowernumber has borrowed.
1018
1019 C<&GetPendingIssues> returns a
1020 reference-to-array where each element is a reference-to-hash; the
1021 keys are the fields from the C<issues>, C<biblio>, and C<items> tables.
1022 The keys include C<biblioitems> fields except marc and marcxml.
1023
1024 =cut
1025
1026 #'
1027 sub GetPendingIssues {
1028     my @borrowernumbers = @_;
1029
1030     unless (@borrowernumbers ) { # return a ref_to_array
1031         return \@borrowernumbers; # to not cause surprise to caller
1032     }
1033
1034     # Borrowers part of the query
1035     my $bquery = '';
1036     for (my $i = 0; $i < @borrowernumbers; $i++) {
1037         $bquery .= ' issues.borrowernumber = ?';
1038         if ($i < $#borrowernumbers ) {
1039             $bquery .= ' OR';
1040         }
1041     }
1042
1043     # must avoid biblioitems.* to prevent large marc and marcxml fields from killing performance
1044     # FIXME: namespace collision: each table has "timestamp" fields.  Which one is "timestamp" ?
1045     # FIXME: circ/ciculation.pl tries to sort by timestamp!
1046     # FIXME: namespace collision: other collisions possible.
1047     # FIXME: most of this data isn't really being used by callers.
1048     my $query =
1049    "SELECT issues.*,
1050             items.*,
1051            biblio.*,
1052            biblioitems.volume,
1053            biblioitems.number,
1054            biblioitems.itemtype,
1055            biblioitems.isbn,
1056            biblioitems.issn,
1057            biblioitems.publicationyear,
1058            biblioitems.publishercode,
1059            biblioitems.volumedate,
1060            biblioitems.volumedesc,
1061            biblioitems.lccn,
1062            biblioitems.url,
1063            borrowers.firstname,
1064            borrowers.surname,
1065            borrowers.cardnumber,
1066            issues.timestamp AS timestamp,
1067            issues.renewals  AS renewals,
1068            issues.borrowernumber AS borrowernumber,
1069             items.renewals  AS totalrenewals
1070     FROM   issues
1071     LEFT JOIN items       ON items.itemnumber       =      issues.itemnumber
1072     LEFT JOIN biblio      ON items.biblionumber     =      biblio.biblionumber
1073     LEFT JOIN biblioitems ON items.biblioitemnumber = biblioitems.biblioitemnumber
1074     LEFT JOIN borrowers ON issues.borrowernumber = borrowers.borrowernumber
1075     WHERE
1076       $bquery
1077     ORDER BY issues.issuedate"
1078     ;
1079
1080     my $sth = C4::Context->dbh->prepare($query);
1081     $sth->execute(@borrowernumbers);
1082     my $data = $sth->fetchall_arrayref({});
1083     my $today = dt_from_string;
1084     foreach (@{$data}) {
1085         if ($_->{issuedate}) {
1086             $_->{issuedate} = dt_from_string($_->{issuedate}, 'sql');
1087         }
1088         $_->{date_due_sql} = $_->{date_due};
1089         # FIXME no need to have this value
1090         $_->{date_due} or next;
1091         $_->{date_due_sql} = $_->{date_due};
1092         # FIXME no need to have this value
1093         $_->{date_due} = dt_from_string($_->{date_due}, 'sql');
1094         if ( DateTime->compare($_->{date_due}, $today) == -1 ) {
1095             $_->{overdue} = 1;
1096         }
1097     }
1098     return $data;
1099 }
1100
1101 =head2 GetAllIssues
1102
1103   $issues = &GetAllIssues($borrowernumber, $sortkey, $limit);
1104
1105 Looks up what the patron with the given borrowernumber has borrowed,
1106 and sorts the results.
1107
1108 C<$sortkey> is the name of a field on which to sort the results. This
1109 should be the name of a field in the C<issues>, C<biblio>,
1110 C<biblioitems>, or C<items> table in the Koha database.
1111
1112 C<$limit> is the maximum number of results to return.
1113
1114 C<&GetAllIssues> an arrayref, C<$issues>, of hashrefs, the keys of which
1115 are the fields from the C<issues>, C<biblio>, C<biblioitems>, and
1116 C<items> tables of the Koha database.
1117
1118 =cut
1119
1120 #'
1121 sub GetAllIssues {
1122     my ( $borrowernumber, $order, $limit ) = @_;
1123
1124     return unless $borrowernumber;
1125     $order = 'date_due desc' unless $order;
1126
1127     my $dbh = C4::Context->dbh;
1128     my $query =
1129 'SELECT *, issues.timestamp as issuestimestamp, issues.renewals AS renewals,items.renewals AS totalrenewals,items.timestamp AS itemstimestamp
1130   FROM issues 
1131   LEFT JOIN items on items.itemnumber=issues.itemnumber
1132   LEFT JOIN biblio ON items.biblionumber=biblio.biblionumber
1133   LEFT JOIN biblioitems ON items.biblioitemnumber=biblioitems.biblioitemnumber
1134   WHERE borrowernumber=? 
1135   UNION ALL
1136   SELECT *, old_issues.timestamp as issuestimestamp, old_issues.renewals AS renewals,items.renewals AS totalrenewals,items.timestamp AS itemstimestamp 
1137   FROM old_issues 
1138   LEFT JOIN items on items.itemnumber=old_issues.itemnumber
1139   LEFT JOIN biblio ON items.biblionumber=biblio.biblionumber
1140   LEFT JOIN biblioitems ON items.biblioitemnumber=biblioitems.biblioitemnumber
1141   WHERE borrowernumber=? AND old_issues.itemnumber IS NOT NULL
1142   order by ' . $order;
1143     if ($limit) {
1144         $query .= " limit $limit";
1145     }
1146
1147     my $sth = $dbh->prepare($query);
1148     $sth->execute( $borrowernumber, $borrowernumber );
1149     return $sth->fetchall_arrayref( {} );
1150 }
1151
1152
1153 =head2 GetMemberAccountRecords
1154
1155   ($total, $acctlines, $count) = &GetMemberAccountRecords($borrowernumber);
1156
1157 Looks up accounting data for the patron with the given borrowernumber.
1158
1159 C<&GetMemberAccountRecords> returns a three-element array. C<$acctlines> is a
1160 reference-to-array, where each element is a reference-to-hash; the
1161 keys are the fields of the C<accountlines> table in the Koha database.
1162 C<$count> is the number of elements in C<$acctlines>. C<$total> is the
1163 total amount outstanding for all of the account lines.
1164
1165 =cut
1166
1167 sub GetMemberAccountRecords {
1168     my ($borrowernumber) = @_;
1169     my $dbh = C4::Context->dbh;
1170     my @acctlines;
1171     my $numlines = 0;
1172     my $strsth      = qq(
1173                         SELECT * 
1174                         FROM accountlines 
1175                         WHERE borrowernumber=?);
1176     $strsth.=" ORDER BY date desc,timestamp DESC";
1177     my $sth= $dbh->prepare( $strsth );
1178     $sth->execute( $borrowernumber );
1179
1180     my $total = 0;
1181     while ( my $data = $sth->fetchrow_hashref ) {
1182         if ( $data->{itemnumber} ) {
1183             my $biblio = GetBiblioFromItemNumber( $data->{itemnumber} );
1184             $data->{biblionumber} = $biblio->{biblionumber};
1185             $data->{title}        = $biblio->{title};
1186         }
1187         $acctlines[$numlines] = $data;
1188         $numlines++;
1189         $total += int(1000 * $data->{'amountoutstanding'}); # convert float to integer to avoid round-off errors
1190     }
1191     $total /= 1000;
1192     return ( $total, \@acctlines,$numlines);
1193 }
1194
1195 =head2 GetMemberAccountBalance
1196
1197   ($total_balance, $non_issue_balance, $other_charges) = &GetMemberAccountBalance($borrowernumber);
1198
1199 Calculates amount immediately owing by the patron - non-issue charges.
1200 Based on GetMemberAccountRecords.
1201 Charges exempt from non-issue are:
1202 * Res (reserves)
1203 * Rent (rental) if RentalsInNoissuesCharge syspref is set to false
1204 * Manual invoices if ManInvInNoissuesCharge syspref is set to false
1205
1206 =cut
1207
1208 sub GetMemberAccountBalance {
1209     my ($borrowernumber) = @_;
1210
1211     my $ACCOUNT_TYPE_LENGTH = 5; # this is plain ridiculous...
1212
1213     my @not_fines;
1214     push @not_fines, 'Res' unless C4::Context->preference('HoldsInNoissuesCharge');
1215     push @not_fines, 'Rent' unless C4::Context->preference('RentalsInNoissuesCharge');
1216     unless ( C4::Context->preference('ManInvInNoissuesCharge') ) {
1217         my $dbh = C4::Context->dbh;
1218         my $man_inv_types = $dbh->selectcol_arrayref(qq{SELECT authorised_value FROM authorised_values WHERE category = 'MANUAL_INV'});
1219         push @not_fines, map substr($_, 0, $ACCOUNT_TYPE_LENGTH), @$man_inv_types;
1220     }
1221     my %not_fine = map {$_ => 1} @not_fines;
1222
1223     my ($total, $acctlines) = GetMemberAccountRecords($borrowernumber);
1224     my $other_charges = 0;
1225     foreach (@$acctlines) {
1226         $other_charges += $_->{amountoutstanding} if $not_fine{ substr($_->{accounttype}, 0, $ACCOUNT_TYPE_LENGTH) };
1227     }
1228
1229     return ( $total, $total - $other_charges, $other_charges);
1230 }
1231
1232 =head2 GetBorNotifyAcctRecord
1233
1234   ($total, $acctlines, $count) = &GetBorNotifyAcctRecord($params,$notifyid);
1235
1236 Looks up accounting data for the patron with the given borrowernumber per file number.
1237
1238 C<&GetBorNotifyAcctRecord> returns a three-element array. C<$acctlines> is a
1239 reference-to-array, where each element is a reference-to-hash; the
1240 keys are the fields of the C<accountlines> table in the Koha database.
1241 C<$count> is the number of elements in C<$acctlines>. C<$total> is the
1242 total amount outstanding for all of the account lines.
1243
1244 =cut
1245
1246 sub GetBorNotifyAcctRecord {
1247     my ( $borrowernumber, $notifyid ) = @_;
1248     my $dbh = C4::Context->dbh;
1249     my @acctlines;
1250     my $numlines = 0;
1251     my $sth = $dbh->prepare(
1252             "SELECT * 
1253                 FROM accountlines 
1254                 WHERE borrowernumber=? 
1255                     AND notify_id=? 
1256                     AND amountoutstanding != '0' 
1257                 ORDER BY notify_id,accounttype
1258                 ");
1259
1260     $sth->execute( $borrowernumber, $notifyid );
1261     my $total = 0;
1262     while ( my $data = $sth->fetchrow_hashref ) {
1263         if ( $data->{itemnumber} ) {
1264             my $biblio = GetBiblioFromItemNumber( $data->{itemnumber} );
1265             $data->{biblionumber} = $biblio->{biblionumber};
1266             $data->{title}        = $biblio->{title};
1267         }
1268         $acctlines[$numlines] = $data;
1269         $numlines++;
1270         $total += int(100 * $data->{'amountoutstanding'});
1271     }
1272     $total /= 100;
1273     return ( $total, \@acctlines, $numlines );
1274 }
1275
1276 =head2 checkuniquemember (OUEST-PROVENCE)
1277
1278   ($result,$categorycode)  = &checkuniquemember($collectivity,$surname,$firstname,$dateofbirth);
1279
1280 Checks that a member exists or not in the database.
1281
1282 C<&result> is nonzero (=exist) or 0 (=does not exist)
1283 C<&categorycode> is from categorycode table
1284 C<&collectivity> is 1 (= we add a collectivity) or 0 (= we add a physical member)
1285 C<&surname> is the surname
1286 C<&firstname> is the firstname (only if collectivity=0)
1287 C<&dateofbirth> is the date of birth in ISO format (only if collectivity=0)
1288
1289 =cut
1290
1291 # FIXME: This function is not legitimate.  Multiple patrons might have the same first/last name and birthdate.
1292 # This is especially true since first name is not even a required field.
1293
1294 sub checkuniquemember {
1295     my ( $collectivity, $surname, $firstname, $dateofbirth ) = @_;
1296     my $dbh = C4::Context->dbh;
1297     my $request = ($collectivity) ?
1298         "SELECT borrowernumber,categorycode FROM borrowers WHERE surname=? " :
1299             ($dateofbirth) ?
1300             "SELECT borrowernumber,categorycode FROM borrowers WHERE surname=? and firstname=?  and dateofbirth=?" :
1301             "SELECT borrowernumber,categorycode FROM borrowers WHERE surname=? and firstname=?";
1302     my $sth = $dbh->prepare($request);
1303     if ($collectivity) {
1304         $sth->execute( uc($surname) );
1305     } elsif($dateofbirth){
1306         $sth->execute( uc($surname), ucfirst($firstname), $dateofbirth );
1307     }else{
1308         $sth->execute( uc($surname), ucfirst($firstname));
1309     }
1310     my @data = $sth->fetchrow;
1311     ( $data[0] ) and return $data[0], $data[1];
1312     return 0;
1313 }
1314
1315 sub checkcardnumber {
1316     my ( $cardnumber, $borrowernumber ) = @_;
1317
1318     # If cardnumber is null, we assume they're allowed.
1319     return 0 unless defined $cardnumber;
1320
1321     my $dbh = C4::Context->dbh;
1322     my $query = "SELECT * FROM borrowers WHERE cardnumber=?";
1323     $query .= " AND borrowernumber <> ?" if ($borrowernumber);
1324     my $sth = $dbh->prepare($query);
1325     $sth->execute(
1326         $cardnumber,
1327         ( $borrowernumber ? $borrowernumber : () )
1328     );
1329
1330     return 1 if $sth->fetchrow_hashref;
1331
1332     my ( $min_length, $max_length ) = get_cardnumber_length();
1333     return 2
1334         if length $cardnumber > $max_length
1335         or length $cardnumber < $min_length;
1336
1337     return 0;
1338 }
1339
1340 =head2 get_cardnumber_length
1341
1342     my ($min, $max) = C4::Members::get_cardnumber_length()
1343
1344 Returns the minimum and maximum length for patron cardnumbers as
1345 determined by the CardnumberLength system preference, the
1346 BorrowerMandatoryField system preference, and the width of the
1347 database column.
1348
1349 =cut
1350
1351 sub get_cardnumber_length {
1352     my ( $min, $max ) = ( 0, 16 ); # borrowers.cardnumber is a nullable varchar(16)
1353     $min = 1 if C4::Context->preference('BorrowerMandatoryField') =~ /cardnumber/;
1354     if ( my $cardnumber_length = C4::Context->preference('CardnumberLength') ) {
1355         # Is integer and length match
1356         if ( $cardnumber_length =~ m|^\d+$| ) {
1357             $min = $max = $cardnumber_length
1358                 if $cardnumber_length >= $min
1359                     and $cardnumber_length <= $max;
1360         }
1361         # Else assuming it is a range
1362         elsif ( $cardnumber_length =~ m|(\d*),(\d*)| ) {
1363             $min = $1 if $1 and $min < $1;
1364             $max = $2 if $2 and $max > $2;
1365         }
1366
1367     }
1368     return ( $min, $max );
1369 }
1370
1371 =head2 getzipnamecity (OUEST-PROVENCE)
1372
1373 take all info from table city for the fields city and  zip
1374 check for the name and the zip code of the city selected
1375
1376 =cut
1377
1378 sub getzipnamecity {
1379     my ($cityid) = @_;
1380     my $dbh      = C4::Context->dbh;
1381     my $sth      =
1382       $dbh->prepare(
1383         "select city_name,city_state,city_zipcode,city_country from cities where cityid=? ");
1384     $sth->execute($cityid);
1385     my @data = $sth->fetchrow;
1386     return $data[0], $data[1], $data[2], $data[3];
1387 }
1388
1389
1390 =head2 getdcity (OUEST-PROVENCE)
1391
1392 recover cityid  with city_name condition
1393
1394 =cut
1395
1396 sub getidcity {
1397     my ($city_name) = @_;
1398     my $dbh = C4::Context->dbh;
1399     my $sth = $dbh->prepare("select cityid from cities where city_name=? ");
1400     $sth->execute($city_name);
1401     my $data = $sth->fetchrow;
1402     return $data;
1403 }
1404
1405 =head2 GetFirstValidEmailAddress
1406
1407   $email = GetFirstValidEmailAddress($borrowernumber);
1408
1409 Return the first valid email address for a borrower, given the borrowernumber.  For now, the order 
1410 is defined as email, emailpro, B_email.  Returns the empty string if the borrower has no email 
1411 addresses.
1412
1413 =cut
1414
1415 sub GetFirstValidEmailAddress {
1416     my $borrowernumber = shift;
1417     my $dbh = C4::Context->dbh;
1418     my $sth = $dbh->prepare( "SELECT email, emailpro, B_email FROM borrowers where borrowernumber = ? ");
1419     $sth->execute( $borrowernumber );
1420     my $data = $sth->fetchrow_hashref;
1421
1422     if ($data->{'email'}) {
1423        return $data->{'email'};
1424     } elsif ($data->{'emailpro'}) {
1425        return $data->{'emailpro'};
1426     } elsif ($data->{'B_email'}) {
1427        return $data->{'B_email'};
1428     } else {
1429        return '';
1430     }
1431 }
1432
1433 =head2 GetNoticeEmailAddress
1434
1435   $email = GetNoticeEmailAddress($borrowernumber);
1436
1437 Return the email address of borrower used for notices, given the borrowernumber.
1438 Returns the empty string if no email address.
1439
1440 =cut
1441
1442 sub GetNoticeEmailAddress {
1443     my $borrowernumber = shift;
1444
1445     my $which_address = C4::Context->preference("AutoEmailPrimaryAddress");
1446     # if syspref is set to 'first valid' (value == OFF), look up email address
1447     if ( $which_address eq 'OFF' ) {
1448         return GetFirstValidEmailAddress($borrowernumber);
1449     }
1450     # specified email address field
1451     my $dbh = C4::Context->dbh;
1452     my $sth = $dbh->prepare( qq{
1453         SELECT $which_address AS primaryemail
1454         FROM borrowers
1455         WHERE borrowernumber=?
1456     } );
1457     $sth->execute($borrowernumber);
1458     my $data = $sth->fetchrow_hashref;
1459     return $data->{'primaryemail'} || '';
1460 }
1461
1462 =head2 GetExpiryDate 
1463
1464   $expirydate = GetExpiryDate($categorycode, $dateenrolled);
1465
1466 Calculate expiry date given a categorycode and starting date.  Date argument must be in ISO format.
1467 Return date is also in ISO format.
1468
1469 =cut
1470
1471 sub GetExpiryDate {
1472     my ( $categorycode, $dateenrolled ) = @_;
1473     my $enrolments;
1474     if ($categorycode) {
1475         my $dbh = C4::Context->dbh;
1476         my $sth = $dbh->prepare("SELECT enrolmentperiod,enrolmentperioddate FROM categories WHERE categorycode=?");
1477         $sth->execute($categorycode);
1478         $enrolments = $sth->fetchrow_hashref;
1479     }
1480     # die "GetExpiryDate: for enrollmentperiod $enrolmentperiod (category '$categorycode') starting $dateenrolled.\n";
1481     my @date = split (/-/,$dateenrolled);
1482     if($enrolments->{enrolmentperiod}){
1483         return sprintf("%04d-%02d-%02d", Add_Delta_YM(@date,0,$enrolments->{enrolmentperiod}));
1484     }else{
1485         return $enrolments->{enrolmentperioddate};
1486     }
1487 }
1488
1489 =head2 GetborCatFromCatType
1490
1491   ($codes_arrayref, $labels_hashref) = &GetborCatFromCatType();
1492
1493 Looks up the different types of borrowers in the database. Returns two
1494 elements: a reference-to-array, which lists the borrower category
1495 codes, and a reference-to-hash, which maps the borrower category codes
1496 to category descriptions.
1497
1498 =cut
1499
1500 #'
1501 sub GetborCatFromCatType {
1502     my ( $category_type, $action, $no_branch_limit ) = @_;
1503
1504     my $branch_limit = $no_branch_limit
1505         ? 0
1506         : C4::Context->userenv ? C4::Context->userenv->{"branch"} : "";
1507
1508     # FIXME - This API  seems both limited and dangerous.
1509     my $dbh     = C4::Context->dbh;
1510
1511     my $request = qq{
1512         SELECT categories.categorycode, categories.description
1513         FROM categories
1514     };
1515     $request .= qq{
1516         LEFT JOIN categories_branches ON categories.categorycode = categories_branches.categorycode
1517     } if $branch_limit;
1518     if($action) {
1519         $request .= " $action ";
1520         $request .= " AND (branchcode = ? OR branchcode IS NULL) GROUP BY description" if $branch_limit;
1521     } else {
1522         $request .= " WHERE branchcode = ? OR branchcode IS NULL GROUP BY description" if $branch_limit;
1523     }
1524     $request .= " ORDER BY categorycode";
1525
1526     my $sth = $dbh->prepare($request);
1527     $sth->execute(
1528         $action ? $category_type : (),
1529         $branch_limit ? $branch_limit : ()
1530     );
1531
1532     my %labels;
1533     my @codes;
1534
1535     while ( my $data = $sth->fetchrow_hashref ) {
1536         push @codes, $data->{'categorycode'};
1537         $labels{ $data->{'categorycode'} } = $data->{'description'};
1538     }
1539     $sth->finish;
1540     return ( \@codes, \%labels );
1541 }
1542
1543 =head2 GetBorrowercategory
1544
1545   $hashref = &GetBorrowercategory($categorycode);
1546
1547 Given the borrower's category code, the function returns the corresponding
1548 data hashref for a comprehensive information display.
1549
1550 =cut
1551
1552 sub GetBorrowercategory {
1553     my ($catcode) = @_;
1554     my $dbh       = C4::Context->dbh;
1555     if ($catcode){
1556         my $sth       =
1557         $dbh->prepare(
1558     "SELECT description,dateofbirthrequired,upperagelimit,category_type 
1559     FROM categories 
1560     WHERE categorycode = ?"
1561         );
1562         $sth->execute($catcode);
1563         my $data =
1564         $sth->fetchrow_hashref;
1565         return $data;
1566     } 
1567     return;  
1568 }    # sub getborrowercategory
1569
1570
1571 =head2 GetBorrowerCategorycode
1572
1573     $categorycode = &GetBorrowerCategoryCode( $borrowernumber );
1574
1575 Given the borrowernumber, the function returns the corresponding categorycode
1576
1577 =cut
1578
1579 sub GetBorrowerCategorycode {
1580     my ( $borrowernumber ) = @_;
1581     my $dbh = C4::Context->dbh;
1582     my $sth = $dbh->prepare( qq{
1583         SELECT categorycode
1584         FROM borrowers
1585         WHERE borrowernumber = ?
1586     } );
1587     $sth->execute( $borrowernumber );
1588     return $sth->fetchrow;
1589 }
1590
1591 =head2 GetBorrowercategoryList
1592
1593   $arrayref_hashref = &GetBorrowercategoryList;
1594 If no category code provided, the function returns all the categories.
1595
1596 =cut
1597
1598 sub GetBorrowercategoryList {
1599     my $no_branch_limit = @_ ? shift : 0;
1600     my $branch_limit = $no_branch_limit
1601         ? 0
1602         : C4::Context->userenv ? C4::Context->userenv->{"branch"} : "";
1603     my $dbh       = C4::Context->dbh;
1604     my $query = "SELECT categories.* FROM categories";
1605     $query .= qq{
1606         LEFT JOIN categories_branches ON categories.categorycode = categories_branches.categorycode
1607         WHERE branchcode = ? OR branchcode IS NULL GROUP BY description
1608     } if $branch_limit;
1609     $query .= " ORDER BY description";
1610     my $sth = $dbh->prepare( $query );
1611     $sth->execute( $branch_limit ? $branch_limit : () );
1612     my $data = $sth->fetchall_arrayref( {} );
1613     $sth->finish;
1614     return $data;
1615 }    # sub getborrowercategory
1616
1617 =head2 ethnicitycategories
1618
1619   ($codes_arrayref, $labels_hashref) = &ethnicitycategories();
1620
1621 Looks up the different ethnic types in the database. Returns two
1622 elements: a reference-to-array, which lists the ethnicity codes, and a
1623 reference-to-hash, which maps the ethnicity codes to ethnicity
1624 descriptions.
1625
1626 =cut
1627
1628 #'
1629
1630 sub ethnicitycategories {
1631     my $dbh = C4::Context->dbh;
1632     my $sth = $dbh->prepare("Select code,name from ethnicity order by name");
1633     $sth->execute;
1634     my %labels;
1635     my @codes;
1636     while ( my $data = $sth->fetchrow_hashref ) {
1637         push @codes, $data->{'code'};
1638         $labels{ $data->{'code'} } = $data->{'name'};
1639     }
1640     return ( \@codes, \%labels );
1641 }
1642
1643 =head2 fixEthnicity
1644
1645   $ethn_name = &fixEthnicity($ethn_code);
1646
1647 Takes an ethnicity code (e.g., "european" or "pi") and returns the
1648 corresponding descriptive name from the C<ethnicity> table in the
1649 Koha database ("European" or "Pacific Islander").
1650
1651 =cut
1652
1653 #'
1654
1655 sub fixEthnicity {
1656     my $ethnicity = shift;
1657     return unless $ethnicity;
1658     my $dbh       = C4::Context->dbh;
1659     my $sth       = $dbh->prepare("Select name from ethnicity where code = ?");
1660     $sth->execute($ethnicity);
1661     my $data = $sth->fetchrow_hashref;
1662     return $data->{'name'};
1663 }    # sub fixEthnicity
1664
1665 =head2 GetAge
1666
1667   $dateofbirth,$date = &GetAge($date);
1668
1669 this function return the borrowers age with the value of dateofbirth
1670
1671 =cut
1672
1673 #'
1674 sub GetAge{
1675     my ( $date, $date_ref ) = @_;
1676
1677     if ( not defined $date_ref ) {
1678         $date_ref = sprintf( '%04d-%02d-%02d', Today() );
1679     }
1680
1681     my ( $year1, $month1, $day1 ) = split /-/, $date;
1682     my ( $year2, $month2, $day2 ) = split /-/, $date_ref;
1683
1684     my $age = $year2 - $year1;
1685     if ( $month1 . $day1 > $month2 . $day2 ) {
1686         $age--;
1687     }
1688
1689     return $age;
1690 }    # sub get_age
1691
1692 =head2 SetAge
1693
1694   $borrower = C4::Members::SetAge($borrower, $datetimeduration);
1695   $borrower = C4::Members::SetAge($borrower, '0015-12-10');
1696   $borrower = C4::Members::SetAge($borrower, $datetimeduration, $datetime_reference);
1697
1698   eval { $borrower = C4::Members::SetAge($borrower, '015-1-10'); };
1699   if ($@) {print $@;} #Catch a bad ISO Date or kill your script!
1700
1701 This function sets the borrower's dateofbirth to match the given age.
1702 Optionally relative to the given $datetime_reference.
1703
1704 @PARAM1 koha.borrowers-object
1705 @PARAM2 DateTime::Duration-object as the desired age
1706         OR a ISO 8601 Date. (To make the API more pleasant)
1707 @PARAM3 DateTime-object as the relative date, defaults to now().
1708 RETURNS The given borrower reference @PARAM1.
1709 DIES    If there was an error with the ISO Date handling.
1710
1711 =cut
1712
1713 #'
1714 sub SetAge{
1715     my ( $borrower, $datetimeduration, $datetime_ref ) = @_;
1716     $datetime_ref = DateTime->now() unless $datetime_ref;
1717
1718     if ($datetimeduration && ref $datetimeduration ne 'DateTime::Duration') {
1719         if ($datetimeduration =~ /^(\d{4})-(\d{2})-(\d{2})/) {
1720             $datetimeduration = DateTime::Duration->new(years => $1, months => $2, days => $3);
1721         }
1722         else {
1723             die "C4::Members::SetAge($borrower, $datetimeduration), datetimeduration not a valid ISO 8601 Date!\n";
1724         }
1725     }
1726
1727     my $new_datetime_ref = $datetime_ref->clone();
1728     $new_datetime_ref->subtract_duration( $datetimeduration );
1729
1730     $borrower->{dateofbirth} = $new_datetime_ref->ymd();
1731
1732     return $borrower;
1733 }    # sub SetAge
1734
1735 =head2 GetCities
1736
1737   $cityarrayref = GetCities();
1738
1739   Returns an array_ref of the entries in the cities table
1740   If there are entries in the table an empty row is returned
1741   This is currently only used to populate a popup in memberentry
1742
1743 =cut
1744
1745 sub GetCities {
1746
1747     my $dbh   = C4::Context->dbh;
1748     my $city_arr = $dbh->selectall_arrayref(
1749         q|SELECT cityid,city_zipcode,city_name,city_state,city_country FROM cities ORDER BY city_name|,
1750         { Slice => {} });
1751     if ( @{$city_arr} ) {
1752         unshift @{$city_arr}, {
1753             city_zipcode => q{},
1754             city_name    => q{},
1755             cityid       => q{},
1756             city_state   => q{},
1757             city_country => q{},
1758         };
1759     }
1760
1761     return  $city_arr;
1762 }
1763
1764 =head2 GetSortDetails (OUEST-PROVENCE)
1765
1766   ($lib) = &GetSortDetails($category,$sortvalue);
1767
1768 Returns the authorized value  details
1769 C<&$lib>return value of authorized value details
1770 C<&$sortvalue>this is the value of authorized value 
1771 C<&$category>this is the value of authorized value category
1772
1773 =cut
1774
1775 sub GetSortDetails {
1776     my ( $category, $sortvalue ) = @_;
1777     my $dbh   = C4::Context->dbh;
1778     my $query = qq|SELECT lib 
1779         FROM authorised_values 
1780         WHERE category=?
1781         AND authorised_value=? |;
1782     my $sth = $dbh->prepare($query);
1783     $sth->execute( $category, $sortvalue );
1784     my $lib = $sth->fetchrow;
1785     return ($lib) if ($lib);
1786     return ($sortvalue) unless ($lib);
1787 }
1788
1789 =head2 MoveMemberToDeleted
1790
1791   $result = &MoveMemberToDeleted($borrowernumber);
1792
1793 Copy the record from borrowers to deletedborrowers table.
1794 The routine returns 1 for success, undef for failure.
1795
1796 =cut
1797
1798 sub MoveMemberToDeleted {
1799     my ($member) = shift or return;
1800
1801     my $schema       = Koha::Database->new()->schema();
1802     my $borrowers_rs = $schema->resultset('Borrower');
1803     $borrowers_rs->result_class('DBIx::Class::ResultClass::HashRefInflator');
1804     my $borrower = $borrowers_rs->find($member);
1805     return unless $borrower;
1806
1807     my $deleted = $schema->resultset('Deletedborrower')->create($borrower);
1808
1809     return $deleted ? 1 : undef;
1810 }
1811
1812 =head2 DelMember
1813
1814     DelMember($borrowernumber);
1815
1816 This function remove directly a borrower whitout writing it on deleteborrower.
1817 + Deletes reserves for the borrower
1818
1819 =cut
1820
1821 sub DelMember {
1822     my $dbh            = C4::Context->dbh;
1823     my $borrowernumber = shift;
1824     #warn "in delmember with $borrowernumber";
1825     return unless $borrowernumber;    # borrowernumber is mandatory.
1826
1827     my $query = qq|DELETE 
1828           FROM  reserves 
1829           WHERE borrowernumber=?|;
1830     my $sth = $dbh->prepare($query);
1831     $sth->execute($borrowernumber);
1832     $query = "
1833        DELETE
1834        FROM borrowers
1835        WHERE borrowernumber = ?
1836    ";
1837     $sth = $dbh->prepare($query);
1838     $sth->execute($borrowernumber);
1839     logaction("MEMBERS", "DELETE", $borrowernumber, "") if C4::Context->preference("BorrowersLog");
1840     return $sth->rows;
1841 }
1842
1843 =head2 ExtendMemberSubscriptionTo (OUEST-PROVENCE)
1844
1845     $date = ExtendMemberSubscriptionTo($borrowerid, $date);
1846
1847 Extending the subscription to a given date or to the expiry date calculated on ISO date.
1848 Returns ISO date.
1849
1850 =cut
1851
1852 sub ExtendMemberSubscriptionTo {
1853     my ( $borrowerid,$date) = @_;
1854     my $dbh = C4::Context->dbh;
1855     my $borrower = GetMember('borrowernumber'=>$borrowerid);
1856     unless ($date){
1857       $date = (C4::Context->preference('BorrowerRenewalPeriodBase') eq 'dateexpiry') ?
1858                                         C4::Dates->new($borrower->{'dateexpiry'}, 'iso')->output("iso") :
1859                                         C4::Dates->new()->output("iso");
1860       $date = GetExpiryDate( $borrower->{'categorycode'}, $date );
1861     }
1862     my $sth = $dbh->do(<<EOF);
1863 UPDATE borrowers 
1864 SET  dateexpiry='$date' 
1865 WHERE borrowernumber='$borrowerid'
1866 EOF
1867
1868     AddEnrolmentFeeIfNeeded( $borrower->{categorycode}, $borrower->{borrowernumber} );
1869
1870     logaction("MEMBERS", "RENEW", $borrower->{'borrowernumber'}, "Membership renewed")if C4::Context->preference("BorrowersLog");
1871     return $date if ($sth);
1872     return 0;
1873 }
1874
1875 =head2 GetTitles (OUEST-PROVENCE)
1876
1877   ($borrowertitle)= &GetTitles();
1878
1879 Looks up the different title . Returns array  with all borrowers title
1880
1881 =cut
1882
1883 sub GetTitles {
1884     my @borrowerTitle = split (/,|\|/,C4::Context->preference('BorrowersTitles'));
1885     unshift( @borrowerTitle, "" );
1886     my $count=@borrowerTitle;
1887     if ($count == 1){
1888         return ();
1889     }
1890     else {
1891         return ( \@borrowerTitle);
1892     }
1893 }
1894
1895 =head2 GetPatronImage
1896
1897     my ($imagedata, $dberror) = GetPatronImage($borrowernumber);
1898
1899 Returns the mimetype and binary image data of the image for the patron with the supplied borrowernumber.
1900
1901 =cut
1902
1903 sub GetPatronImage {
1904     my ($borrowernumber) = @_;
1905     warn "Borrowernumber passed to GetPatronImage is $borrowernumber" if $debug;
1906     my $dbh = C4::Context->dbh;
1907     my $query = 'SELECT mimetype, imagefile FROM patronimage WHERE borrowernumber = ?';
1908     my $sth = $dbh->prepare($query);
1909     $sth->execute($borrowernumber);
1910     my $imagedata = $sth->fetchrow_hashref;
1911     warn "Database error!" if $sth->errstr;
1912     return $imagedata, $sth->errstr;
1913 }
1914
1915 =head2 PutPatronImage
1916
1917     PutPatronImage($cardnumber, $mimetype, $imgfile);
1918
1919 Stores patron binary image data and mimetype in database.
1920 NOTE: This function is good for updating images as well as inserting new images in the database.
1921
1922 =cut
1923
1924 sub PutPatronImage {
1925     my ($cardnumber, $mimetype, $imgfile) = @_;
1926     warn "Parameters passed in: Cardnumber=$cardnumber, Mimetype=$mimetype, " . ($imgfile ? "Imagefile" : "No Imagefile") if $debug;
1927     my $dbh = C4::Context->dbh;
1928     my $query = "INSERT INTO patronimage (borrowernumber, mimetype, imagefile) VALUES ( ( SELECT borrowernumber from borrowers WHERE cardnumber = ? ),?,?) ON DUPLICATE KEY UPDATE imagefile = ?;";
1929     my $sth = $dbh->prepare($query);
1930     $sth->execute($cardnumber,$mimetype,$imgfile,$imgfile);
1931     warn "Error returned inserting $cardnumber.$mimetype." if $sth->errstr;
1932     return $sth->errstr;
1933 }
1934
1935 =head2 RmPatronImage
1936
1937     my ($dberror) = RmPatronImage($borrowernumber);
1938
1939 Removes the image for the patron with the supplied borrowernumber.
1940
1941 =cut
1942
1943 sub RmPatronImage {
1944     my ($borrowernumber) = @_;
1945     warn "Borrowernumber passed to GetPatronImage is $borrowernumber" if $debug;
1946     my $dbh = C4::Context->dbh;
1947     my $query = "DELETE FROM patronimage WHERE borrowernumber = ?;";
1948     my $sth = $dbh->prepare($query);
1949     $sth->execute($borrowernumber);
1950     my $dberror = $sth->errstr;
1951     warn "Database error!" if $sth->errstr;
1952     return $dberror;
1953 }
1954
1955 =head2 GetHideLostItemsPreference
1956
1957   $hidelostitemspref = &GetHideLostItemsPreference($borrowernumber);
1958
1959 Returns the HideLostItems preference for the patron category of the supplied borrowernumber
1960 C<&$hidelostitemspref>return value of function, 0 or 1
1961
1962 =cut
1963
1964 sub GetHideLostItemsPreference {
1965     my ($borrowernumber) = @_;
1966     my $dbh = C4::Context->dbh;
1967     my $query = "SELECT hidelostitems FROM borrowers,categories WHERE borrowers.categorycode = categories.categorycode AND borrowernumber = ?";
1968     my $sth = $dbh->prepare($query);
1969     $sth->execute($borrowernumber);
1970     my $hidelostitems = $sth->fetchrow;    
1971     return $hidelostitems;    
1972 }
1973
1974 =head2 GetBorrowersToExpunge
1975
1976   $borrowers = &GetBorrowersToExpunge(
1977       not_borrowered_since => $not_borrowered_since,
1978       expired_before       => $expired_before,
1979       category_code        => $category_code,
1980       branchcode           => $branchcode
1981   );
1982
1983   This function get all borrowers based on the given criteria.
1984
1985 =cut
1986
1987 sub GetBorrowersToExpunge {
1988     my $params = shift;
1989
1990     my $filterdate     = $params->{'not_borrowered_since'};
1991     my $filterexpiry   = $params->{'expired_before'};
1992     my $filtercategory = $params->{'category_code'};
1993     my $filterbranch   = $params->{'branchcode'} ||
1994                         ((C4::Context->preference('IndependentBranches')
1995                              && C4::Context->userenv 
1996                              && !C4::Context->IsSuperLibrarian()
1997                              && C4::Context->userenv->{branch})
1998                          ? C4::Context->userenv->{branch}
1999                          : "");  
2000
2001     my $dbh   = C4::Context->dbh;
2002     my $query = q|
2003         SELECT borrowers.borrowernumber,
2004                MAX(old_issues.timestamp) AS latestissue,
2005                MAX(issues.timestamp) AS currentissue
2006         FROM   borrowers
2007         JOIN   categories USING (categorycode)
2008         LEFT JOIN (
2009             SELECT guarantorid
2010             FROM borrowers
2011             WHERE guarantorid IS NOT NULL
2012                 AND guarantorid <> 0
2013         ) as tmp ON borrowers.borrowernumber=tmp.guarantorid
2014         LEFT JOIN old_issues USING (borrowernumber)
2015         LEFT JOIN issues USING (borrowernumber) 
2016         WHERE  category_type <> 'S'
2017         AND tmp.guarantorid IS NULL
2018    |;
2019
2020     my @query_params;
2021     if ( $filterbranch && $filterbranch ne "" ) {
2022         $query.= " AND borrowers.branchcode = ? ";
2023         push( @query_params, $filterbranch );
2024     }
2025     if ( $filterexpiry ) {
2026         $query .= " AND dateexpiry < ? ";
2027         push( @query_params, $filterexpiry );
2028     }
2029     if ( $filtercategory ) {
2030         $query .= " AND categorycode = ? ";
2031         push( @query_params, $filtercategory );
2032     }
2033     $query.=" GROUP BY borrowers.borrowernumber HAVING currentissue IS NULL ";
2034     if ( $filterdate ) {
2035         $query.=" AND ( latestissue < ? OR latestissue IS NULL ) ";
2036         push @query_params,$filterdate;
2037     }
2038     warn $query if $debug;
2039
2040     my $sth = $dbh->prepare($query);
2041     if (scalar(@query_params)>0){  
2042         $sth->execute(@query_params);
2043     } 
2044     else {
2045         $sth->execute;
2046     }      
2047     
2048     my @results;
2049     while ( my $data = $sth->fetchrow_hashref ) {
2050         push @results, $data;
2051     }
2052     return \@results;
2053 }
2054
2055 =head2 GetBorrowersWhoHaveNeverBorrowed
2056
2057   $results = &GetBorrowersWhoHaveNeverBorrowed
2058
2059 This function get all borrowers who have never borrowed.
2060
2061 I<$result> is a ref to an array which all elements are a hasref.
2062
2063 =cut
2064
2065 sub GetBorrowersWhoHaveNeverBorrowed {
2066     my $filterbranch = shift || 
2067                         ((C4::Context->preference('IndependentBranches')
2068                              && C4::Context->userenv 
2069                              && !C4::Context->IsSuperLibrarian()
2070                              && C4::Context->userenv->{branch})
2071                          ? C4::Context->userenv->{branch}
2072                          : "");  
2073     my $dbh   = C4::Context->dbh;
2074     my $query = "
2075         SELECT borrowers.borrowernumber,max(timestamp) as latestissue
2076         FROM   borrowers
2077           LEFT JOIN issues ON borrowers.borrowernumber = issues.borrowernumber
2078         WHERE issues.borrowernumber IS NULL
2079    ";
2080     my @query_params;
2081     if ($filterbranch && $filterbranch ne ""){ 
2082         $query.=" AND borrowers.branchcode= ?";
2083         push @query_params,$filterbranch;
2084     }
2085     warn $query if $debug;
2086   
2087     my $sth = $dbh->prepare($query);
2088     if (scalar(@query_params)>0){  
2089         $sth->execute(@query_params);
2090     } 
2091     else {
2092         $sth->execute;
2093     }      
2094     
2095     my @results;
2096     while ( my $data = $sth->fetchrow_hashref ) {
2097         push @results, $data;
2098     }
2099     return \@results;
2100 }
2101
2102 =head2 GetBorrowersWithIssuesHistoryOlderThan
2103
2104   $results = &GetBorrowersWithIssuesHistoryOlderThan($date)
2105
2106 this function get all borrowers who has an issue history older than I<$date> given on input arg.
2107
2108 I<$result> is a ref to an array which all elements are a hashref.
2109 This hashref is containt the number of time this borrowers has borrowed before I<$date> and the borrowernumber.
2110
2111 =cut
2112
2113 sub GetBorrowersWithIssuesHistoryOlderThan {
2114     my $dbh  = C4::Context->dbh;
2115     my $date = shift ||POSIX::strftime("%Y-%m-%d",localtime());
2116     my $filterbranch = shift || 
2117                         ((C4::Context->preference('IndependentBranches')
2118                              && C4::Context->userenv 
2119                              && !C4::Context->IsSuperLibrarian()
2120                              && C4::Context->userenv->{branch})
2121                          ? C4::Context->userenv->{branch}
2122                          : "");  
2123     my $query = "
2124        SELECT count(borrowernumber) as n,borrowernumber
2125        FROM old_issues
2126        WHERE returndate < ?
2127          AND borrowernumber IS NOT NULL 
2128     "; 
2129     my @query_params;
2130     push @query_params, $date;
2131     if ($filterbranch){
2132         $query.="   AND branchcode = ?";
2133         push @query_params, $filterbranch;
2134     }    
2135     $query.=" GROUP BY borrowernumber ";
2136     warn $query if $debug;
2137     my $sth = $dbh->prepare($query);
2138     $sth->execute(@query_params);
2139     my @results;
2140
2141     while ( my $data = $sth->fetchrow_hashref ) {
2142         push @results, $data;
2143     }
2144     return \@results;
2145 }
2146
2147 =head2 GetBorrowersNamesAndLatestIssue
2148
2149   $results = &GetBorrowersNamesAndLatestIssueList(@borrowernumbers)
2150
2151 this function get borrowers Names and surnames and Issue information.
2152
2153 I<@borrowernumbers> is an array which all elements are borrowernumbers.
2154 This hashref is containt the number of time this borrowers has borrowed before I<$date> and the borrowernumber.
2155
2156 =cut
2157
2158 sub GetBorrowersNamesAndLatestIssue {
2159     my $dbh  = C4::Context->dbh;
2160     my @borrowernumbers=@_;  
2161     my $query = "
2162        SELECT surname,lastname, phone, email,max(timestamp)
2163        FROM borrowers 
2164          LEFT JOIN issues ON borrowers.borrowernumber=issues.borrowernumber
2165        GROUP BY borrowernumber
2166    ";
2167     my $sth = $dbh->prepare($query);
2168     $sth->execute;
2169     my $results = $sth->fetchall_arrayref({});
2170     return $results;
2171 }
2172
2173 =head2 ModPrivacy
2174
2175   my $success = ModPrivacy( $borrowernumber, $privacy );
2176
2177 Update the privacy of a patron.
2178
2179 return :
2180 true on success, false on failure
2181
2182 =cut
2183
2184 sub ModPrivacy {
2185     my $borrowernumber = shift;
2186     my $privacy = shift;
2187     return unless defined $borrowernumber;
2188     return unless $borrowernumber =~ /^\d+$/;
2189
2190     return ModMember( borrowernumber => $borrowernumber,
2191                       privacy        => $privacy );
2192 }
2193
2194 =head2 AddMessage
2195
2196   AddMessage( $borrowernumber, $message_type, $message, $branchcode );
2197
2198 Adds a message to the messages table for the given borrower.
2199
2200 Returns:
2201   True on success
2202   False on failure
2203
2204 =cut
2205
2206 sub AddMessage {
2207     my ( $borrowernumber, $message_type, $message, $branchcode ) = @_;
2208
2209     my $dbh  = C4::Context->dbh;
2210
2211     if ( ! ( $borrowernumber && $message_type && $message && $branchcode ) ) {
2212       return;
2213     }
2214
2215     my $query = "INSERT INTO messages ( borrowernumber, branchcode, message_type, message ) VALUES ( ?, ?, ?, ? )";
2216     my $sth = $dbh->prepare($query);
2217     $sth->execute( $borrowernumber, $branchcode, $message_type, $message );
2218     logaction("MEMBERS", "ADDCIRCMESSAGE", $borrowernumber, $message) if C4::Context->preference("BorrowersLog");
2219     return 1;
2220 }
2221
2222 =head2 GetMessages
2223
2224   GetMessages( $borrowernumber, $type );
2225
2226 $type is message type, B for borrower, or L for Librarian.
2227 Empty type returns all messages of any type.
2228
2229 Returns all messages for the given borrowernumber
2230
2231 =cut
2232
2233 sub GetMessages {
2234     my ( $borrowernumber, $type, $branchcode ) = @_;
2235
2236     if ( ! $type ) {
2237       $type = '%';
2238     }
2239
2240     my $dbh  = C4::Context->dbh;
2241
2242     my $query = "SELECT
2243                   branches.branchname,
2244                   messages.*,
2245                   message_date,
2246                   messages.branchcode LIKE '$branchcode' AS can_delete
2247                   FROM messages, branches
2248                   WHERE borrowernumber = ?
2249                   AND message_type LIKE ?
2250                   AND messages.branchcode = branches.branchcode
2251                   ORDER BY message_date DESC";
2252     my $sth = $dbh->prepare($query);
2253     $sth->execute( $borrowernumber, $type ) ;
2254     my @results;
2255
2256     while ( my $data = $sth->fetchrow_hashref ) {
2257         my $d = C4::Dates->new( $data->{message_date}, 'iso' );
2258         $data->{message_date_formatted} = $d->output;
2259         push @results, $data;
2260     }
2261     return \@results;
2262
2263 }
2264
2265 =head2 GetMessages
2266
2267   GetMessagesCount( $borrowernumber, $type );
2268
2269 $type is message type, B for borrower, or L for Librarian.
2270 Empty type returns all messages of any type.
2271
2272 Returns the number of messages for the given borrowernumber
2273
2274 =cut
2275
2276 sub GetMessagesCount {
2277     my ( $borrowernumber, $type, $branchcode ) = @_;
2278
2279     if ( ! $type ) {
2280       $type = '%';
2281     }
2282
2283     my $dbh  = C4::Context->dbh;
2284
2285     my $query = "SELECT COUNT(*) as MsgCount FROM messages WHERE borrowernumber = ? AND message_type LIKE ?";
2286     my $sth = $dbh->prepare($query);
2287     $sth->execute( $borrowernumber, $type ) ;
2288     my @results;
2289
2290     my $data = $sth->fetchrow_hashref;
2291     my $count = $data->{'MsgCount'};
2292
2293     return $count;
2294 }
2295
2296
2297
2298 =head2 DeleteMessage
2299
2300   DeleteMessage( $message_id );
2301
2302 =cut
2303
2304 sub DeleteMessage {
2305     my ( $message_id ) = @_;
2306
2307     my $dbh = C4::Context->dbh;
2308     my $query = "SELECT * FROM messages WHERE message_id = ?";
2309     my $sth = $dbh->prepare($query);
2310     $sth->execute( $message_id );
2311     my $message = $sth->fetchrow_hashref();
2312
2313     $query = "DELETE FROM messages WHERE message_id = ?";
2314     $sth = $dbh->prepare($query);
2315     $sth->execute( $message_id );
2316     logaction("MEMBERS", "DELCIRCMESSAGE", $message->{'borrowernumber'}, $message->{'message'}) if C4::Context->preference("BorrowersLog");
2317 }
2318
2319 =head2 IssueSlip
2320
2321   IssueSlip($branchcode, $borrowernumber, $quickslip)
2322
2323   Returns letter hash ( see C4::Letters::GetPreparedLetter )
2324
2325   $quickslip is boolean, to indicate whether we want a quick slip
2326
2327   IssueSlip populates ISSUESLIP and ISSUEQSLIP, and will make the following expansions:
2328
2329   Both slips:
2330
2331       <<branches.*>>
2332       <<borrowers.*>>
2333
2334   ISSUESLIP:
2335
2336       <checkedout>
2337          <<biblio.*>>
2338          <<items.*>>
2339          <<biblioitems.*>>
2340          <<issues.*>>
2341       </checkedout>
2342
2343       <overdue>
2344          <<biblio.*>>
2345          <<items.*>>
2346          <<biblioitems.*>>
2347          <<issues.*>>
2348       </overdue>
2349
2350       <news>
2351          <<opac_news.*>>
2352       </news>
2353
2354   ISSUEQSLIP:
2355
2356       <checkedout>
2357          <<biblio.*>>
2358          <<items.*>>
2359          <<biblioitems.*>>
2360          <<issues.*>>
2361       </checkedout>
2362
2363   NOTE: Not all table fields are available, pleasee see GetPendingIssues for a list of available fields.
2364
2365 =cut
2366
2367 sub IssueSlip {
2368     my ($branch, $borrowernumber, $quickslip) = @_;
2369
2370     # FIXME Check callers before removing this statement
2371     #return unless $borrowernumber;
2372
2373     my @issues = @{ GetPendingIssues($borrowernumber) };
2374
2375     for my $issue (@issues) {
2376         $issue->{date_due} = $issue->{date_due_sql};
2377         if ($quickslip) {
2378             my $today = output_pref({ dt => dt_from_string, dateformat => 'iso', dateonly => 1 });
2379             if ( substr( $issue->{issuedate}, 0, 10 ) eq $today
2380                 or substr( $issue->{lastreneweddate}, 0, 10 ) eq $today ) {
2381                   $issue->{now} = 1;
2382             };
2383         }
2384     }
2385
2386     # Sort on timestamp then on issuedate (useful for tests and could be if modified in a batch
2387     @issues = sort {
2388         my $s = $b->{timestamp} <=> $a->{timestamp};
2389         $s == 0 ?
2390              $b->{issuedate} <=> $a->{issuedate} : $s;
2391     } @issues;
2392
2393     my ($letter_code, %repeat);
2394     if ( $quickslip ) {
2395         $letter_code = 'ISSUEQSLIP';
2396         %repeat =  (
2397             'checkedout' => [ map {
2398                 'biblio'       => $_,
2399                 'items'        => $_,
2400                 'biblioitems'  => $_,
2401                 'issues'       => $_,
2402             }, grep { $_->{'now'} } @issues ],
2403         );
2404     }
2405     else {
2406         $letter_code = 'ISSUESLIP';
2407         %repeat =  (
2408             'checkedout' => [ map {
2409                 'biblio'       => $_,
2410                 'items'        => $_,
2411                 'biblioitems'  => $_,
2412                 'issues'       => $_,
2413             }, grep { !$_->{'overdue'} } @issues ],
2414
2415             'overdue' => [ map {
2416                 'biblio'       => $_,
2417                 'items'        => $_,
2418                 'biblioitems'  => $_,
2419                 'issues'       => $_,
2420             }, grep { $_->{'overdue'} } @issues ],
2421
2422             'news' => [ map {
2423                 $_->{'timestamp'} = $_->{'newdate'};
2424                 { opac_news => $_ }
2425             } @{ GetNewsToDisplay("slip",$branch) } ],
2426         );
2427     }
2428
2429     return  C4::Letters::GetPreparedLetter (
2430         module => 'circulation',
2431         letter_code => $letter_code,
2432         branchcode => $branch,
2433         tables => {
2434             'branches'    => $branch,
2435             'borrowers'   => $borrowernumber,
2436         },
2437         repeat => \%repeat,
2438     );
2439 }
2440
2441 =head2 GetBorrowersWithEmail
2442
2443     ([$borrnum,$userid], ...) = GetBorrowersWithEmail('me@example.com');
2444
2445 This gets a list of users and their basic details from their email address.
2446 As it's possible for multiple user to have the same email address, it provides
2447 you with all of them. If there is no userid for the user, there will be an
2448 C<undef> there. An empty list will be returned if there are no matches.
2449
2450 =cut
2451
2452 sub GetBorrowersWithEmail {
2453     my $email = shift;
2454
2455     my $dbh = C4::Context->dbh;
2456
2457     my $query = "SELECT borrowernumber, userid FROM borrowers WHERE email=?";
2458     my $sth=$dbh->prepare($query);
2459     $sth->execute($email);
2460     my @result = ();
2461     while (my $ref = $sth->fetch) {
2462         push @result, $ref;
2463     }
2464     die "Failure searching for borrowers by email address: $sth->errstr" if $sth->err;
2465     return @result;
2466 }
2467
2468 =head2 AddMember_Opac
2469
2470 =cut
2471
2472 sub AddMember_Opac {
2473     my ( %borrower ) = @_;
2474
2475     $borrower{'categorycode'} = C4::Context->preference('PatronSelfRegistrationDefaultCategory');
2476
2477     my $sr = new String::Random;
2478     $sr->{'A'} = [ 'A'..'Z', 'a'..'z' ];
2479     my $password = $sr->randpattern("AAAAAAAAAA");
2480     $borrower{'password'} = $password;
2481
2482     $borrower{'cardnumber'} = fixup_cardnumber();
2483
2484     my $borrowernumber = AddMember(%borrower);
2485
2486     return ( $borrowernumber, $password );
2487 }
2488
2489 =head2 AddEnrolmentFeeIfNeeded
2490
2491     AddEnrolmentFeeIfNeeded( $borrower->{categorycode}, $borrower->{borrowernumber} );
2492
2493 Add enrolment fee for a patron if needed.
2494
2495 =cut
2496
2497 sub AddEnrolmentFeeIfNeeded {
2498     my ( $categorycode, $borrowernumber ) = @_;
2499     # check for enrollment fee & add it if needed
2500     my $dbh = C4::Context->dbh;
2501     my $sth = $dbh->prepare(q{
2502         SELECT enrolmentfee
2503         FROM categories
2504         WHERE categorycode=?
2505     });
2506     $sth->execute( $categorycode );
2507     if ( $sth->err ) {
2508         warn sprintf('Database returned the following error: %s', $sth->errstr);
2509         return;
2510     }
2511     my ($enrolmentfee) = $sth->fetchrow;
2512     if ($enrolmentfee && $enrolmentfee > 0) {
2513         # insert fee in patron debts
2514         C4::Accounts::manualinvoice( $borrowernumber, '', '', 'A', $enrolmentfee );
2515     }
2516 }
2517
2518 =head2 HasOverdues
2519
2520 =cut
2521
2522 sub HasOverdues {
2523     my ( $borrowernumber ) = @_;
2524
2525     my $sql = "SELECT COUNT(*) FROM issues WHERE date_due < NOW() AND borrowernumber = ?";
2526     my $sth = C4::Context->dbh->prepare( $sql );
2527     $sth->execute( $borrowernumber );
2528     my ( $count ) = $sth->fetchrow_array();
2529
2530     return $count;
2531 }
2532
2533 =head2 DeleteExpiredOpacRegistrations
2534
2535     Delete accounts that haven't been upgraded from the 'temporary' category
2536     Returns the number of removed patrons
2537
2538 =cut
2539
2540 sub DeleteExpiredOpacRegistrations {
2541
2542     my $delay = C4::Context->preference('PatronSelfRegistrationExpireTemporaryAccountsDelay');
2543     my $category_code = C4::Context->preference('PatronSelfRegistrationDefaultCategory');
2544
2545     return 0 if not $category_code or not defined $delay or $delay eq q||;
2546
2547     my $query = qq|
2548 SELECT borrowernumber
2549 FROM borrowers
2550 WHERE categorycode = ? AND DATEDIFF( NOW(), dateenrolled ) > ? |;
2551
2552     my $dbh = C4::Context->dbh;
2553     my $sth = $dbh->prepare($query);
2554     $sth->execute( $category_code, $delay );
2555     my $cnt=0;
2556     while ( my ($borrowernumber) = $sth->fetchrow_array() ) {
2557         DelMember($borrowernumber);
2558         $cnt++;
2559     }
2560     return $cnt;
2561 }
2562
2563 =head2 DeleteUnverifiedOpacRegistrations
2564
2565     Delete all unverified self registrations in borrower_modifications,
2566     older than the specified number of days.
2567
2568 =cut
2569
2570 sub DeleteUnverifiedOpacRegistrations {
2571     my ( $days ) = @_;
2572     my $dbh = C4::Context->dbh;
2573     my $sql=qq|
2574 DELETE FROM borrower_modifications
2575 WHERE borrowernumber = 0 AND DATEDIFF( NOW(), timestamp ) > ?|;
2576     my $cnt=$dbh->do($sql, undef, ($days) );
2577     return $cnt eq '0E0'? 0: $cnt;
2578 }
2579
2580 END { }    # module clean-up code here (global destructor)
2581
2582 1;
2583
2584 __END__
2585
2586 =head1 AUTHOR
2587
2588 Koha Team
2589
2590 =cut