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