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