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