Bug 16850: Remove C4::Members::IsMemberBlocked
[koha.git] / C4 / Members.pm
1 package C4::Members;
2
3 # Copyright 2000-2003 Katipo Communications
4 # Copyright 2010 BibLibre
5 # Parts Copyright 2010 Catalyst IT
6 #
7 # This file is part of Koha.
8 #
9 # Koha is free software; you can redistribute it and/or modify it
10 # under the terms of the GNU General Public License as published by
11 # the Free Software Foundation; either version 3 of the License, or
12 # (at your option) any later version.
13 #
14 # Koha is distributed in the hope that it will be useful, but
15 # WITHOUT ANY WARRANTY; without even the implied warranty of
16 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 # GNU General Public License for more details.
18 #
19 # You should have received a copy of the GNU General Public License
20 # along with Koha; if not, see <http://www.gnu.org/licenses>.
21
22
23 use strict;
24 #use warnings; FIXME - Bug 2505
25 use C4::Context;
26 use String::Random qw( random_string );
27 use Scalar::Util qw( looks_like_number );
28 use Date::Calc qw/Today 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 Text::Unaccent qw( unac_string );
41 use Koha::AuthUtils qw(hash_password);
42 use Koha::Database;
43 use Koha::Holds;
44 use Koha::List::Patron;
45 use Koha::Patrons;
46 use Koha::Patron::Categories;
47
48 our (@ISA,@EXPORT,@EXPORT_OK,$debug);
49
50 use Module::Load::Conditional qw( can_load );
51 if ( ! can_load( modules => { 'Koha::NorwegianPatronDB' => undef } ) ) {
52    $debug && warn "Unable to load Koha::NorwegianPatronDB";
53 }
54
55
56 BEGIN {
57     $debug = $ENV{DEBUG} || 0;
58     require Exporter;
59     @ISA = qw(Exporter);
60     #Get data
61     push @EXPORT, qw(
62         &Search
63         &GetMemberDetails
64         &GetMember
65
66         &GetMemberIssuesAndFines
67         &GetPendingIssues
68         &GetAllIssues
69
70         &GetFirstValidEmailAddress
71         &GetNoticeEmailAddress
72
73         &GetAge
74         &GetTitles
75
76         &GetHideLostItemsPreference
77
78         &GetMemberAccountRecords
79         &GetBorNotifyAcctRecord
80
81         GetBorrowerCategorycode
82
83         &GetBorrowersToExpunge
84         &GetBorrowersWhoHaveNeverBorrowed
85         &GetBorrowersWithIssuesHistoryOlderThan
86
87         &GetUpcomingMembershipExpires
88
89         &IssueSlip
90         GetBorrowersWithEmail
91
92         GetOverduesForPatron
93     );
94
95     #Modify data
96     push @EXPORT, qw(
97         &ModMember
98         &changepassword
99     );
100
101     #Delete data
102     push @EXPORT, qw(
103         &DelMember
104     );
105
106     #Insert data
107     push @EXPORT, qw(
108         &AddMember
109         &AddMember_Opac
110         &MoveMemberToDeleted
111     );
112
113     #Check data
114     push @EXPORT, qw(
115         &checkuniquemember
116         &checkuserpassword
117         &Check_Userid
118         &Generate_Userid
119         &fixup_cardnumber
120         &checkcardnumber
121     );
122 }
123
124 =head1 NAME
125
126 C4::Members - Perl Module containing convenience functions for member handling
127
128 =head1 SYNOPSIS
129
130 use C4::Members;
131
132 =head1 DESCRIPTION
133
134 This module contains routines for adding, modifying and deleting members/patrons/borrowers 
135
136 =head1 FUNCTIONS
137
138 =head2 GetMemberDetails
139
140 ($borrower) = &GetMemberDetails($borrowernumber, $cardnumber);
141
142 Looks up a patron and returns information about him or her. If
143 C<$borrowernumber> is true (nonzero), C<&GetMemberDetails> looks
144 up the borrower by number; otherwise, it looks up the borrower by card
145 number.
146
147 C<$borrower> is a reference-to-hash whose keys are the fields of the
148 borrowers table in the Koha database. In addition,
149 C<$borrower-E<gt>{flags}> is a hash giving more detailed information
150 about the patron. Its keys act as flags :
151
152     if $borrower->{flags}->{LOST} {
153         # Patron's card was reported lost
154     }
155
156 If the state of a flag means that the patron should not be
157 allowed to borrow any more books, then it will have a C<noissues> key
158 with a true value.
159
160 See patronflags for more details.
161
162 C<$borrower-E<gt>{authflags}> is a hash giving more detailed information
163 about the top-level permissions flags set for the borrower.  For example,
164 if a user has the "editcatalogue" permission,
165 C<$borrower-E<gt>{authflags}-E<gt>{editcatalogue}> will exist and have
166 the value "1".
167
168 =cut
169
170 sub GetMemberDetails {
171     my ( $borrowernumber, $cardnumber ) = @_;
172     my $dbh = C4::Context->dbh;
173     my $query;
174     my $sth;
175     if ($borrowernumber) {
176         $sth = $dbh->prepare("
177             SELECT borrowers.*,
178                    category_type,
179                    categories.description,
180                    categories.BlockExpiredPatronOpacActions,
181                    reservefee,
182                    enrolmentperiod
183             FROM borrowers
184             LEFT JOIN categories ON borrowers.categorycode=categories.categorycode
185             WHERE borrowernumber = ?
186         ");
187         $sth->execute($borrowernumber);
188     }
189     elsif ($cardnumber) {
190         $sth = $dbh->prepare("
191             SELECT borrowers.*,
192                    category_type,
193                    categories.description,
194                    categories.BlockExpiredPatronOpacActions,
195                    reservefee,
196                    enrolmentperiod
197             FROM borrowers
198             LEFT JOIN categories ON borrowers.categorycode = categories.categorycode
199             WHERE cardnumber = ?
200         ");
201         $sth->execute($cardnumber);
202     }
203     else {
204         return;
205     }
206     my $borrower = $sth->fetchrow_hashref;
207     return unless $borrower;
208     my ($amount) = GetMemberAccountRecords($borrower->{borrowernumber});
209     $borrower->{'amountoutstanding'} = $amount;
210     # FIXME - patronflags calls GetMemberAccountRecords... just have patronflags return $amount
211     my $flags = patronflags( $borrower);
212     my $accessflagshash;
213
214     $sth = $dbh->prepare("select bit,flag from userflags");
215     $sth->execute;
216     while ( my ( $bit, $flag ) = $sth->fetchrow ) {
217         if ( $borrower->{'flags'} && $borrower->{'flags'} & 2**$bit ) {
218             $accessflagshash->{$flag} = 1;
219         }
220     }
221     $borrower->{'flags'}     = $flags;
222     $borrower->{'authflags'} = $accessflagshash;
223
224     # Handle setting the true behavior for BlockExpiredPatronOpacActions
225     $borrower->{'BlockExpiredPatronOpacActions'} =
226       C4::Context->preference('BlockExpiredPatronOpacActions')
227       if ( $borrower->{'BlockExpiredPatronOpacActions'} == -1 );
228
229     $borrower->{'is_expired'} = 0;
230     $borrower->{'is_expired'} = 1 if
231       defined($borrower->{dateexpiry}) &&
232       $borrower->{'dateexpiry'} ne '0000-00-00' &&
233       Date_to_Days( Today() ) >
234       Date_to_Days( split /-/, $borrower->{'dateexpiry'} );
235
236     return ($borrower);    #, $flags, $accessflagshash);
237 }
238
239 =head2 patronflags
240
241  $flags = &patronflags($patron);
242
243 This function is not exported.
244
245 The following will be set where applicable:
246  $flags->{CHARGES}->{amount}        Amount of debt
247  $flags->{CHARGES}->{noissues}      Set if debt amount >$5.00 (or syspref noissuescharge)
248  $flags->{CHARGES}->{message}       Message -- deprecated
249
250  $flags->{CREDITS}->{amount}        Amount of credit
251  $flags->{CREDITS}->{message}       Message -- deprecated
252
253  $flags->{  GNA  }                  Patron has no valid address
254  $flags->{  GNA  }->{noissues}      Set for each GNA
255  $flags->{  GNA  }->{message}       "Borrower has no valid address" -- deprecated
256
257  $flags->{ LOST  }                  Patron's card reported lost
258  $flags->{ LOST  }->{noissues}      Set for each LOST
259  $flags->{ LOST  }->{message}       Message -- deprecated
260
261  $flags->{DBARRED}                  Set if patron debarred, no access
262  $flags->{DBARRED}->{noissues}      Set for each DBARRED
263  $flags->{DBARRED}->{message}       Message -- deprecated
264
265  $flags->{ NOTES }
266  $flags->{ NOTES }->{message}       The note itself.  NOT deprecated
267
268  $flags->{ ODUES }                  Set if patron has overdue books.
269  $flags->{ ODUES }->{message}       "Yes"  -- deprecated
270  $flags->{ ODUES }->{itemlist}      ref-to-array: list of overdue books
271  $flags->{ ODUES }->{itemlisttext}  Text list of overdue items -- deprecated
272
273  $flags->{WAITING}                  Set if any of patron's reserves are available
274  $flags->{WAITING}->{message}       Message -- deprecated
275  $flags->{WAITING}->{itemlist}      ref-to-array: list of available items
276
277 =over 
278
279 =item C<$flags-E<gt>{ODUES}-E<gt>{itemlist}> is a reference-to-array listing the
280 overdue items. Its elements are references-to-hash, each describing an
281 overdue item. The keys are selected fields from the issues, biblio,
282 biblioitems, and items tables of the Koha database.
283
284 =item C<$flags-E<gt>{ODUES}-E<gt>{itemlisttext}> is a string giving a text listing of
285 the overdue items, one per line.  Deprecated.
286
287 =item C<$flags-E<gt>{WAITING}-E<gt>{itemlist}> is a reference-to-array listing the
288 available items. Each element is a reference-to-hash whose keys are
289 fields from the reserves table of the Koha database.
290
291 =back
292
293 All the "message" fields that include language generated in this function are deprecated, 
294 because such strings belong properly in the display layer.
295
296 The "message" field that comes from the DB is OK.
297
298 =cut
299
300 # TODO: use {anonymous => hashes} instead of a dozen %flaginfo
301 # FIXME rename this function.
302 sub patronflags {
303     my %flags;
304     my ( $patroninformation) = @_;
305     my $dbh=C4::Context->dbh;
306     my ($balance, $owing) = GetMemberAccountBalance( $patroninformation->{'borrowernumber'});
307     if ( $owing > 0 ) {
308         my %flaginfo;
309         my $noissuescharge = C4::Context->preference("noissuescharge") || 5;
310         $flaginfo{'message'} = sprintf 'Patron owes %.02f', $owing;
311         $flaginfo{'amount'}  = sprintf "%.02f", $owing;
312         if ( $owing > $noissuescharge && !C4::Context->preference("AllowFineOverride") ) {
313             $flaginfo{'noissues'} = 1;
314         }
315         $flags{'CHARGES'} = \%flaginfo;
316     }
317     elsif ( $balance < 0 ) {
318         my %flaginfo;
319         $flaginfo{'message'} = sprintf 'Patron has credit of %.02f', -$balance;
320         $flaginfo{'amount'}  = sprintf "%.02f", $balance;
321         $flags{'CREDITS'} = \%flaginfo;
322     }
323
324     # Check the debt of the guarntees of this patron
325     my $no_issues_charge_guarantees = C4::Context->preference("NoIssuesChargeGuarantees");
326     $no_issues_charge_guarantees = undef unless looks_like_number( $no_issues_charge_guarantees );
327     if ( defined $no_issues_charge_guarantees ) {
328         my $p = Koha::Patrons->find( $patroninformation->{borrowernumber} );
329         my @guarantees = $p->guarantees();
330         my $guarantees_non_issues_charges;
331         foreach my $g ( @guarantees ) {
332             my ( $b, $n, $o ) = C4::Members::GetMemberAccountBalance( $g->id );
333             $guarantees_non_issues_charges += $n;
334         }
335
336         if ( $guarantees_non_issues_charges > $no_issues_charge_guarantees ) {
337             my %flaginfo;
338             $flaginfo{'message'} = sprintf 'patron guarantees owe %.02f', $guarantees_non_issues_charges;
339             $flaginfo{'amount'}  = $guarantees_non_issues_charges;
340             $flaginfo{'noissues'} = 1 unless C4::Context->preference("allowfineoverride");
341             $flags{'CHARGES_GUARANTEES'} = \%flaginfo;
342         }
343     }
344
345     if (   $patroninformation->{'gonenoaddress'}
346         && $patroninformation->{'gonenoaddress'} == 1 )
347     {
348         my %flaginfo;
349         $flaginfo{'message'}  = 'Borrower has no valid address.';
350         $flaginfo{'noissues'} = 1;
351         $flags{'GNA'}         = \%flaginfo;
352     }
353     if ( $patroninformation->{'lost'} && $patroninformation->{'lost'} == 1 ) {
354         my %flaginfo;
355         $flaginfo{'message'}  = 'Borrower\'s card reported lost.';
356         $flaginfo{'noissues'} = 1;
357         $flags{'LOST'}        = \%flaginfo;
358     }
359     if ( $patroninformation->{'debarred'} && check_date( split( /-/, $patroninformation->{'debarred'} ) ) ) {
360         if ( Date_to_Days(Date::Calc::Today) < Date_to_Days( split( /-/, $patroninformation->{'debarred'} ) ) ) {
361             my %flaginfo;
362             $flaginfo{'debarredcomment'} = $patroninformation->{'debarredcomment'};
363             $flaginfo{'message'}         = $patroninformation->{'debarredcomment'};
364             $flaginfo{'noissues'}        = 1;
365             $flaginfo{'dateend'}         = $patroninformation->{'debarred'};
366             $flags{'DBARRED'}           = \%flaginfo;
367         }
368     }
369     if (   $patroninformation->{'borrowernotes'}
370         && $patroninformation->{'borrowernotes'} )
371     {
372         my %flaginfo;
373         $flaginfo{'message'} = $patroninformation->{'borrowernotes'};
374         $flags{'NOTES'}      = \%flaginfo;
375     }
376     my ( $odues, $itemsoverdue ) = C4::Overdues::checkoverdues($patroninformation->{'borrowernumber'});
377     if ( $odues && $odues > 0 ) {
378         my %flaginfo;
379         $flaginfo{'message'}  = "Yes";
380         $flaginfo{'itemlist'} = $itemsoverdue;
381         foreach ( sort { $a->{'date_due'} cmp $b->{'date_due'} }
382             @$itemsoverdue )
383         {
384             $flaginfo{'itemlisttext'} .=
385               "$_->{'date_due'} $_->{'barcode'} $_->{'title'} \n";  # newline is display layer
386         }
387         $flags{'ODUES'} = \%flaginfo;
388     }
389     my @itemswaiting = C4::Reserves::GetReservesFromBorrowernumber( $patroninformation->{'borrowernumber'},'W' );
390     my $nowaiting = scalar @itemswaiting;
391     if ( $nowaiting > 0 ) {
392         my %flaginfo;
393         $flaginfo{'message'}  = "Reserved items available";
394         $flaginfo{'itemlist'} = \@itemswaiting;
395         $flags{'WAITING'}     = \%flaginfo;
396     }
397     return ( \%flags );
398 }
399
400
401 =head2 GetMember
402
403   $borrower = &GetMember(%information);
404
405 Retrieve the first patron record meeting on criteria listed in the
406 C<%information> hash, which should contain one or more
407 pairs of borrowers column names and values, e.g.,
408
409    $borrower = GetMember(borrowernumber => id);
410
411 C<&GetBorrower> returns a reference-to-hash whose keys are the fields of
412 the C<borrowers> table in the Koha database.
413
414 FIXME: GetMember() is used throughout the code as a lookup
415 on a unique key such as the borrowernumber, but this meaning is not
416 enforced in the routine itself.
417
418 =cut
419
420 #'
421 sub GetMember {
422     my ( %information ) = @_;
423     if (exists $information{borrowernumber} && !defined $information{borrowernumber}) {
424         #passing mysql's kohaadmin?? Makes no sense as a query
425         return;
426     }
427     my $dbh = C4::Context->dbh;
428     my $select =
429     q{SELECT borrowers.*, categories.category_type, categories.description
430     FROM borrowers 
431     LEFT JOIN categories on borrowers.categorycode=categories.categorycode WHERE };
432     my $more_p = 0;
433     my @values = ();
434     for (keys %information ) {
435         if ($more_p) {
436             $select .= ' AND ';
437         }
438         else {
439             $more_p++;
440         }
441
442         if (defined $information{$_}) {
443             $select .= "$_ = ?";
444             push @values, $information{$_};
445         }
446         else {
447             $select .= "$_ IS NULL";
448         }
449     }
450     $debug && warn $select, " ",values %information;
451     my $sth = $dbh->prepare("$select");
452     $sth->execute(@values);
453     my $data = $sth->fetchall_arrayref({});
454     #FIXME interface to this routine now allows generation of a result set
455     #so whole array should be returned but bowhere in the current code expects this
456     if (@{$data} ) {
457         return $data->[0];
458     }
459
460     return;
461 }
462
463 =head2 GetMemberIssuesAndFines
464
465   ($overdue_count, $issue_count, $total_fines) = &GetMemberIssuesAndFines($borrowernumber);
466
467 Returns aggregate data about items borrowed by the patron with the
468 given borrowernumber.
469
470 C<&GetMemberIssuesAndFines> returns a three-element array.  C<$overdue_count> is the
471 number of overdue items the patron currently has borrowed. C<$issue_count> is the
472 number of books the patron currently has borrowed.  C<$total_fines> is
473 the total fine currently due by the borrower.
474
475 =cut
476
477 #'
478 sub GetMemberIssuesAndFines {
479     my ( $borrowernumber ) = @_;
480     my $dbh   = C4::Context->dbh;
481     my $query = "SELECT COUNT(*) FROM issues WHERE borrowernumber = ?";
482
483     $debug and warn $query."\n";
484     my $sth = $dbh->prepare($query);
485     $sth->execute($borrowernumber);
486     my $issue_count = $sth->fetchrow_arrayref->[0];
487
488     $sth = $dbh->prepare(
489         "SELECT COUNT(*) FROM issues 
490          WHERE borrowernumber = ? 
491          AND date_due < now()"
492     );
493     $sth->execute($borrowernumber);
494     my $overdue_count = $sth->fetchrow_arrayref->[0];
495
496     $sth = $dbh->prepare("SELECT SUM(amountoutstanding) FROM accountlines WHERE borrowernumber = ?");
497     $sth->execute($borrowernumber);
498     my $total_fines = $sth->fetchrow_arrayref->[0];
499
500     return ($overdue_count, $issue_count, $total_fines);
501 }
502
503
504 =head2 ModMember
505
506   my $success = ModMember(borrowernumber => $borrowernumber,
507                                             [ field => value ]... );
508
509 Modify borrower's data.  All date fields should ALREADY be in ISO format.
510
511 return :
512 true on success, or false on failure
513
514 =cut
515
516 sub ModMember {
517     my (%data) = @_;
518     # test to know if you must update or not the borrower password
519     if (exists $data{password}) {
520         if ($data{password} eq '****' or $data{password} eq '') {
521             delete $data{password};
522         } else {
523             if ( C4::Context->preference('NorwegianPatronDBEnable') && C4::Context->preference('NorwegianPatronDBEnable') == 1 ) {
524                 # Update the hashed PIN in borrower_sync.hashed_pin, before Koha hashes it
525                 Koha::NorwegianPatronDB::NLUpdateHashedPIN( $data{'borrowernumber'}, $data{password} );
526             }
527             $data{password} = hash_password($data{password});
528         }
529     }
530
531     my $old_categorycode = GetBorrowerCategorycode( $data{borrowernumber} );
532
533     # get only the columns of a borrower
534     my $schema = Koha::Database->new()->schema;
535     my @columns = $schema->source('Borrower')->columns;
536     my $new_borrower = { map { join(' ', @columns) =~ /$_/ ? ( $_ => $data{$_} ) : () } keys(%data) };
537     delete $new_borrower->{flags};
538
539     $new_borrower->{dateofbirth}     ||= undef if exists $new_borrower->{dateofbirth};
540     $new_borrower->{dateenrolled}    ||= undef if exists $new_borrower->{dateenrolled};
541     $new_borrower->{dateexpiry}      ||= undef if exists $new_borrower->{dateexpiry};
542     $new_borrower->{debarred}        ||= undef if exists $new_borrower->{debarred};
543     $new_borrower->{sms_provider_id} ||= undef if exists $new_borrower->{sms_provider_id};
544
545     my $rs = $schema->resultset('Borrower')->search({
546         borrowernumber => $new_borrower->{borrowernumber},
547      });
548
549     delete $new_borrower->{userid} if exists $new_borrower->{userid} and not $new_borrower->{userid};
550
551     my $execute_success = $rs->update($new_borrower);
552     if ($execute_success ne '0E0') { # only proceed if the update was a success
553         # If the patron changes to a category with enrollment fee, we add a fee
554         if ( $data{categorycode} and $data{categorycode} ne $old_categorycode ) {
555             if ( C4::Context->preference('FeeOnChangePatronCategory') ) {
556                 AddEnrolmentFeeIfNeeded( $data{categorycode}, $data{borrowernumber} );
557             }
558         }
559
560         # If NorwegianPatronDBEnable is enabled, we set syncstatus to something that a
561         # cronjob will use for syncing with NL
562         if ( C4::Context->preference('NorwegianPatronDBEnable') && C4::Context->preference('NorwegianPatronDBEnable') == 1 ) {
563             my $borrowersync = Koha::Database->new->schema->resultset('BorrowerSync')->find({
564                 'synctype'       => 'norwegianpatrondb',
565                 'borrowernumber' => $data{'borrowernumber'}
566             });
567             # Do not set to "edited" if syncstatus is "new". We need to sync as new before
568             # we can sync as changed. And the "new sync" will pick up all changes since
569             # the patron was created anyway.
570             if ( $borrowersync->syncstatus ne 'new' && $borrowersync->syncstatus ne 'delete' ) {
571                 $borrowersync->update( { 'syncstatus' => 'edited' } );
572             }
573             # Set the value of 'sync'
574             $borrowersync->update( { 'sync' => $data{'sync'} } );
575             # Try to do the live sync
576             Koha::NorwegianPatronDB::NLSync({ 'borrowernumber' => $data{'borrowernumber'} });
577         }
578
579         logaction("MEMBERS", "MODIFY", $data{'borrowernumber'}, "UPDATE (executed w/ arg: $data{'borrowernumber'})") if C4::Context->preference("BorrowersLog");
580     }
581     return $execute_success;
582 }
583
584 =head2 AddMember
585
586   $borrowernumber = &AddMember(%borrower);
587
588 insert new borrower into table
589
590 (%borrower keys are database columns. Database columns could be
591 different in different versions. Please look into database for correct
592 column names.)
593
594 Returns the borrowernumber upon success
595
596 Returns as undef upon any db error without further processing
597
598 =cut
599
600 #'
601 sub AddMember {
602     my (%data) = @_;
603     my $dbh = C4::Context->dbh;
604     my $schema = Koha::Database->new()->schema;
605
606     # generate a proper login if none provided
607     $data{'userid'} = Generate_Userid( $data{'borrowernumber'}, $data{'firstname'}, $data{'surname'} )
608       if ( $data{'userid'} eq '' || !Check_Userid( $data{'userid'} ) );
609
610     # add expiration date if it isn't already there
611     $data{dateexpiry} ||= Koha::Patron::Categories->find( $data{categorycode} )->get_expiry_date;
612
613     # add enrollment date if it isn't already there
614     unless ( $data{'dateenrolled'} ) {
615         $data{'dateenrolled'} = output_pref( { dt => dt_from_string, dateonly => 1, dateformat => 'iso' } );
616     }
617
618     my $patron_category = $schema->resultset('Category')->find( $data{'categorycode'} );
619     $data{'privacy'} =
620         $patron_category->default_privacy() eq 'default' ? 1
621       : $patron_category->default_privacy() eq 'never'   ? 2
622       : $patron_category->default_privacy() eq 'forever' ? 0
623       :                                                    undef;
624
625     $data{'privacy_guarantor_checkouts'} = 0 unless defined( $data{'privacy_guarantor_checkouts'} );
626
627     # Make a copy of the plain text password for later use
628     my $plain_text_password = $data{'password'};
629
630     # create a disabled account if no password provided
631     $data{'password'} = ($data{'password'})? hash_password($data{'password'}) : '!';
632
633     # we don't want invalid dates in the db (mysql has a bad habit of inserting 0000-00-00
634     $data{'dateofbirth'}     = undef if ( not $data{'dateofbirth'} );
635     $data{'debarred'}        = undef if ( not $data{'debarred'} );
636     $data{'sms_provider_id'} = undef if ( not $data{'sms_provider_id'} );
637
638     # get only the columns of Borrower
639     my @columns = $schema->source('Borrower')->columns;
640     my $new_member = { map { join(' ',@columns) =~ /$_/ ? ( $_ => $data{$_} )  : () } keys(%data) } ;
641     $new_member->{checkprevcheckout} ||= 'inherit';
642     delete $new_member->{borrowernumber};
643
644     my $rs = $schema->resultset('Borrower');
645     $data{borrowernumber} = $rs->create($new_member)->id;
646
647     # If NorwegianPatronDBEnable is enabled, we set syncstatus to something that a
648     # cronjob will use for syncing with NL
649     if ( exists $data{'borrowernumber'} && C4::Context->preference('NorwegianPatronDBEnable') && C4::Context->preference('NorwegianPatronDBEnable') == 1 ) {
650         Koha::Database->new->schema->resultset('BorrowerSync')->create({
651             'borrowernumber' => $data{'borrowernumber'},
652             'synctype'       => 'norwegianpatrondb',
653             'sync'           => 1,
654             'syncstatus'     => 'new',
655             'hashed_pin'     => Koha::NorwegianPatronDB::NLEncryptPIN( $plain_text_password ),
656         });
657     }
658
659     # mysql_insertid is probably bad.  not necessarily accurate and mysql-specific at best.
660     logaction("MEMBERS", "CREATE", $data{'borrowernumber'}, "") if C4::Context->preference("BorrowersLog");
661
662     AddEnrolmentFeeIfNeeded( $data{categorycode}, $data{borrowernumber} );
663
664     return $data{borrowernumber};
665 }
666
667 =head2 Check_Userid
668
669     my $uniqueness = Check_Userid($userid,$borrowernumber);
670
671     $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 != '').
672
673     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.
674
675     return :
676         0 for not unique (i.e. this $userid already exists)
677         1 for unique (i.e. this $userid does not exist, or this $userid/$borrowernumber combination already exists)
678
679 =cut
680
681 sub Check_Userid {
682     my ( $uid, $borrowernumber ) = @_;
683
684     return 0 unless ($uid); # userid is a unique column, we should assume NULL is not unique
685
686     return 0 if ( $uid eq C4::Context->config('user') );
687
688     my $rs = Koha::Database->new()->schema()->resultset('Borrower');
689
690     my $params;
691     $params->{userid} = $uid;
692     $params->{borrowernumber} = { '!=' => $borrowernumber } if ($borrowernumber);
693
694     my $count = $rs->count( $params );
695
696     return $count ? 0 : 1;
697 }
698
699 =head2 Generate_Userid
700
701     my $newuid = Generate_Userid($borrowernumber, $firstname, $surname);
702
703     Generate a userid using the $surname and the $firstname (if there is a value in $firstname).
704
705     $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.
706
707     return :
708         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).
709
710 =cut
711
712 sub Generate_Userid {
713   my ($borrowernumber, $firstname, $surname) = @_;
714   my $newuid;
715   my $offset = 0;
716   #The script will "do" the following code and increment the $offset until Check_Userid = 1 (i.e. until $newuid comes back as unique)
717   do {
718     $firstname =~ s/[[:digit:][:space:][:blank:][:punct:][:cntrl:]]//g;
719     $surname =~ s/[[:digit:][:space:][:blank:][:punct:][:cntrl:]]//g;
720     $newuid = lc(($firstname)? "$firstname.$surname" : $surname);
721     $newuid = unac_string('utf-8',$newuid);
722     $newuid .= $offset unless $offset == 0;
723     $offset++;
724
725    } while (!Check_Userid($newuid,$borrowernumber));
726
727    return $newuid;
728 }
729
730 =head2 fixup_cardnumber
731
732 Warning: The caller is responsible for locking the members table in write
733 mode, to avoid database corruption.
734
735 =cut
736
737 use vars qw( @weightings );
738 my @weightings = ( 8, 4, 6, 3, 5, 2, 1 );
739
740 sub fixup_cardnumber {
741     my ($cardnumber) = @_;
742     my $autonumber_members = C4::Context->boolean_preference('autoMemberNum') || 0;
743
744     # Find out whether member numbers should be generated
745     # automatically. Should be either "1" or something else.
746     # Defaults to "0", which is interpreted as "no".
747
748     #     if ($cardnumber !~ /\S/ && $autonumber_members) {
749     ($autonumber_members) or return $cardnumber;
750     my $checkdigit = C4::Context->preference('checkdigit');
751     my $dbh = C4::Context->dbh;
752     if ( $checkdigit and $checkdigit eq 'katipo' ) {
753
754         # if checkdigit is selected, calculate katipo-style cardnumber.
755         # otherwise, just use the max()
756         # purpose: generate checksum'd member numbers.
757         # We'll assume we just got the max value of digits 2-8 of member #'s
758         # from the database and our job is to increment that by one,
759         # determine the 1st and 9th digits and return the full string.
760         my $sth = $dbh->prepare(
761             "select max(substring(borrowers.cardnumber,2,7)) as new_num from borrowers"
762         );
763         $sth->execute;
764         my $data = $sth->fetchrow_hashref;
765         $cardnumber = $data->{new_num};
766         if ( !$cardnumber ) {    # If DB has no values,
767             $cardnumber = 1000000;    # start at 1000000
768         } else {
769             $cardnumber += 1;
770         }
771
772         my $sum = 0;
773         for ( my $i = 0 ; $i < 8 ; $i += 1 ) {
774             # read weightings, left to right, 1 char at a time
775             my $temp1 = $weightings[$i];
776
777             # sequence left to right, 1 char at a time
778             my $temp2 = substr( $cardnumber, $i, 1 );
779
780             # mult each char 1-7 by its corresponding weighting
781             $sum += $temp1 * $temp2;
782         }
783
784         my $rem = ( $sum % 11 );
785         $rem = 'X' if $rem == 10;
786
787         return "V$cardnumber$rem";
788      } else {
789
790         my $sth = $dbh->prepare(
791             'SELECT MAX( CAST( cardnumber AS SIGNED ) ) FROM borrowers WHERE cardnumber REGEXP "^-?[0-9]+$"'
792         );
793         $sth->execute;
794         my ($result) = $sth->fetchrow;
795         return $result + 1;
796     }
797     return $cardnumber;     # just here as a fallback/reminder 
798 }
799
800 =head2 GetPendingIssues
801
802   my $issues = &GetPendingIssues(@borrowernumber);
803
804 Looks up what the patron with the given borrowernumber has borrowed.
805
806 C<&GetPendingIssues> returns a
807 reference-to-array where each element is a reference-to-hash; the
808 keys are the fields from the C<issues>, C<biblio>, and C<items> tables.
809 The keys include C<biblioitems> fields except marc and marcxml.
810
811 =cut
812
813 sub GetPendingIssues {
814     my @borrowernumbers = @_;
815
816     unless (@borrowernumbers ) { # return a ref_to_array
817         return \@borrowernumbers; # to not cause surprise to caller
818     }
819
820     # Borrowers part of the query
821     my $bquery = '';
822     for (my $i = 0; $i < @borrowernumbers; $i++) {
823         $bquery .= ' issues.borrowernumber = ?';
824         if ($i < $#borrowernumbers ) {
825             $bquery .= ' OR';
826         }
827     }
828
829     # must avoid biblioitems.* to prevent large marc and marcxml fields from killing performance
830     # FIXME: namespace collision: each table has "timestamp" fields.  Which one is "timestamp" ?
831     # FIXME: circ/ciculation.pl tries to sort by timestamp!
832     # FIXME: namespace collision: other collisions possible.
833     # FIXME: most of this data isn't really being used by callers.
834     my $query =
835    "SELECT issues.*,
836             items.*,
837            biblio.*,
838            biblioitems.volume,
839            biblioitems.number,
840            biblioitems.itemtype,
841            biblioitems.isbn,
842            biblioitems.issn,
843            biblioitems.publicationyear,
844            biblioitems.publishercode,
845            biblioitems.volumedate,
846            biblioitems.volumedesc,
847            biblioitems.lccn,
848            biblioitems.url,
849            borrowers.firstname,
850            borrowers.surname,
851            borrowers.cardnumber,
852            issues.timestamp AS timestamp,
853            issues.renewals  AS renewals,
854            issues.borrowernumber AS borrowernumber,
855             items.renewals  AS totalrenewals
856     FROM   issues
857     LEFT JOIN items       ON items.itemnumber       =      issues.itemnumber
858     LEFT JOIN biblio      ON items.biblionumber     =      biblio.biblionumber
859     LEFT JOIN biblioitems ON items.biblioitemnumber = biblioitems.biblioitemnumber
860     LEFT JOIN borrowers ON issues.borrowernumber = borrowers.borrowernumber
861     WHERE
862       $bquery
863     ORDER BY issues.issuedate"
864     ;
865
866     my $sth = C4::Context->dbh->prepare($query);
867     $sth->execute(@borrowernumbers);
868     my $data = $sth->fetchall_arrayref({});
869     my $today = dt_from_string;
870     foreach (@{$data}) {
871         if ($_->{issuedate}) {
872             $_->{issuedate} = dt_from_string($_->{issuedate}, 'sql');
873         }
874         $_->{date_due_sql} = $_->{date_due};
875         # FIXME no need to have this value
876         $_->{date_due} or next;
877         $_->{date_due_sql} = $_->{date_due};
878         # FIXME no need to have this value
879         $_->{date_due} = dt_from_string($_->{date_due}, 'sql');
880         if ( DateTime->compare($_->{date_due}, $today) == -1 ) {
881             $_->{overdue} = 1;
882         }
883     }
884     return $data;
885 }
886
887 =head2 GetAllIssues
888
889   $issues = &GetAllIssues($borrowernumber, $sortkey, $limit);
890
891 Looks up what the patron with the given borrowernumber has borrowed,
892 and sorts the results.
893
894 C<$sortkey> is the name of a field on which to sort the results. This
895 should be the name of a field in the C<issues>, C<biblio>,
896 C<biblioitems>, or C<items> table in the Koha database.
897
898 C<$limit> is the maximum number of results to return.
899
900 C<&GetAllIssues> an arrayref, C<$issues>, of hashrefs, the keys of which
901 are the fields from the C<issues>, C<biblio>, C<biblioitems>, and
902 C<items> tables of the Koha database.
903
904 =cut
905
906 #'
907 sub GetAllIssues {
908     my ( $borrowernumber, $order, $limit ) = @_;
909
910     return unless $borrowernumber;
911     $order = 'date_due desc' unless $order;
912
913     my $dbh = C4::Context->dbh;
914     my $query =
915 'SELECT *, issues.timestamp as issuestimestamp, issues.renewals AS renewals,items.renewals AS totalrenewals,items.timestamp AS itemstimestamp
916   FROM issues 
917   LEFT JOIN items on items.itemnumber=issues.itemnumber
918   LEFT JOIN biblio ON items.biblionumber=biblio.biblionumber
919   LEFT JOIN biblioitems ON items.biblioitemnumber=biblioitems.biblioitemnumber
920   WHERE borrowernumber=? 
921   UNION ALL
922   SELECT *, old_issues.timestamp as issuestimestamp, old_issues.renewals AS renewals,items.renewals AS totalrenewals,items.timestamp AS itemstimestamp 
923   FROM old_issues 
924   LEFT JOIN items on items.itemnumber=old_issues.itemnumber
925   LEFT JOIN biblio ON items.biblionumber=biblio.biblionumber
926   LEFT JOIN biblioitems ON items.biblioitemnumber=biblioitems.biblioitemnumber
927   WHERE borrowernumber=? AND old_issues.itemnumber IS NOT NULL
928   order by ' . $order;
929     if ($limit) {
930         $query .= " limit $limit";
931     }
932
933     my $sth = $dbh->prepare($query);
934     $sth->execute( $borrowernumber, $borrowernumber );
935     return $sth->fetchall_arrayref( {} );
936 }
937
938
939 =head2 GetMemberAccountRecords
940
941   ($total, $acctlines, $count) = &GetMemberAccountRecords($borrowernumber);
942
943 Looks up accounting data for the patron with the given borrowernumber.
944
945 C<&GetMemberAccountRecords> returns a three-element array. C<$acctlines> is a
946 reference-to-array, where each element is a reference-to-hash; the
947 keys are the fields of the C<accountlines> table in the Koha database.
948 C<$count> is the number of elements in C<$acctlines>. C<$total> is the
949 total amount outstanding for all of the account lines.
950
951 =cut
952
953 sub GetMemberAccountRecords {
954     my ($borrowernumber) = @_;
955     my $dbh = C4::Context->dbh;
956     my @acctlines;
957     my $numlines = 0;
958     my $strsth      = qq(
959                         SELECT * 
960                         FROM accountlines 
961                         WHERE borrowernumber=?);
962     $strsth.=" ORDER BY accountlines_id desc";
963     my $sth= $dbh->prepare( $strsth );
964     $sth->execute( $borrowernumber );
965
966     my $total = 0;
967     while ( my $data = $sth->fetchrow_hashref ) {
968         if ( $data->{itemnumber} ) {
969             my $biblio = GetBiblioFromItemNumber( $data->{itemnumber} );
970             $data->{biblionumber} = $biblio->{biblionumber};
971             $data->{title}        = $biblio->{title};
972         }
973         $acctlines[$numlines] = $data;
974         $numlines++;
975         $total += sprintf "%.0f", 1000*$data->{amountoutstanding}; # convert float to integer to avoid round-off errors
976     }
977     $total /= 1000;
978     return ( $total, \@acctlines,$numlines);
979 }
980
981 =head2 GetMemberAccountBalance
982
983   ($total_balance, $non_issue_balance, $other_charges) = &GetMemberAccountBalance($borrowernumber);
984
985 Calculates amount immediately owing by the patron - non-issue charges.
986 Based on GetMemberAccountRecords.
987 Charges exempt from non-issue are:
988 * Res (reserves)
989 * Rent (rental) if RentalsInNoissuesCharge syspref is set to false
990 * Manual invoices if ManInvInNoissuesCharge syspref is set to false
991
992 =cut
993
994 sub GetMemberAccountBalance {
995     my ($borrowernumber) = @_;
996
997     my $ACCOUNT_TYPE_LENGTH = 5; # this is plain ridiculous...
998
999     my @not_fines;
1000     push @not_fines, 'Res' unless C4::Context->preference('HoldsInNoissuesCharge');
1001     push @not_fines, 'Rent' unless C4::Context->preference('RentalsInNoissuesCharge');
1002     unless ( C4::Context->preference('ManInvInNoissuesCharge') ) {
1003         my $dbh = C4::Context->dbh;
1004         my $man_inv_types = $dbh->selectcol_arrayref(qq{SELECT authorised_value FROM authorised_values WHERE category = 'MANUAL_INV'});
1005         push @not_fines, map substr($_, 0, $ACCOUNT_TYPE_LENGTH), @$man_inv_types;
1006     }
1007     my %not_fine = map {$_ => 1} @not_fines;
1008
1009     my ($total, $acctlines) = GetMemberAccountRecords($borrowernumber);
1010     my $other_charges = 0;
1011     foreach (@$acctlines) {
1012         $other_charges += $_->{amountoutstanding} if $not_fine{ substr($_->{accounttype}, 0, $ACCOUNT_TYPE_LENGTH) };
1013     }
1014
1015     return ( $total, $total - $other_charges, $other_charges);
1016 }
1017
1018 =head2 GetBorNotifyAcctRecord
1019
1020   ($total, $acctlines, $count) = &GetBorNotifyAcctRecord($params,$notifyid);
1021
1022 Looks up accounting data for the patron with the given borrowernumber per file number.
1023
1024 C<&GetBorNotifyAcctRecord> returns a three-element array. C<$acctlines> is a
1025 reference-to-array, where each element is a reference-to-hash; the
1026 keys are the fields of the C<accountlines> table in the Koha database.
1027 C<$count> is the number of elements in C<$acctlines>. C<$total> is the
1028 total amount outstanding for all of the account lines.
1029
1030 =cut
1031
1032 sub GetBorNotifyAcctRecord {
1033     my ( $borrowernumber, $notifyid ) = @_;
1034     my $dbh = C4::Context->dbh;
1035     my @acctlines;
1036     my $numlines = 0;
1037     my $sth = $dbh->prepare(
1038             "SELECT * 
1039                 FROM accountlines 
1040                 WHERE borrowernumber=? 
1041                     AND notify_id=? 
1042                     AND amountoutstanding != '0' 
1043                 ORDER BY notify_id,accounttype
1044                 ");
1045
1046     $sth->execute( $borrowernumber, $notifyid );
1047     my $total = 0;
1048     while ( my $data = $sth->fetchrow_hashref ) {
1049         if ( $data->{itemnumber} ) {
1050             my $biblio = GetBiblioFromItemNumber( $data->{itemnumber} );
1051             $data->{biblionumber} = $biblio->{biblionumber};
1052             $data->{title}        = $biblio->{title};
1053         }
1054         $acctlines[$numlines] = $data;
1055         $numlines++;
1056         $total += int(100 * $data->{'amountoutstanding'});
1057     }
1058     $total /= 100;
1059     return ( $total, \@acctlines, $numlines );
1060 }
1061
1062 sub checkcardnumber {
1063     my ( $cardnumber, $borrowernumber ) = @_;
1064
1065     # If cardnumber is null, we assume they're allowed.
1066     return 0 unless defined $cardnumber;
1067
1068     my $dbh = C4::Context->dbh;
1069     my $query = "SELECT * FROM borrowers WHERE cardnumber=?";
1070     $query .= " AND borrowernumber <> ?" if ($borrowernumber);
1071     my $sth = $dbh->prepare($query);
1072     $sth->execute(
1073         $cardnumber,
1074         ( $borrowernumber ? $borrowernumber : () )
1075     );
1076
1077     return 1 if $sth->fetchrow_hashref;
1078
1079     my ( $min_length, $max_length ) = get_cardnumber_length();
1080     return 2
1081         if length $cardnumber > $max_length
1082         or length $cardnumber < $min_length;
1083
1084     return 0;
1085 }
1086
1087 =head2 get_cardnumber_length
1088
1089     my ($min, $max) = C4::Members::get_cardnumber_length()
1090
1091 Returns the minimum and maximum length for patron cardnumbers as
1092 determined by the CardnumberLength system preference, the
1093 BorrowerMandatoryField system preference, and the width of the
1094 database column.
1095
1096 =cut
1097
1098 sub get_cardnumber_length {
1099     my ( $min, $max ) = ( 0, 16 ); # borrowers.cardnumber is a nullable varchar(16)
1100     $min = 1 if C4::Context->preference('BorrowerMandatoryField') =~ /cardnumber/;
1101     if ( my $cardnumber_length = C4::Context->preference('CardnumberLength') ) {
1102         # Is integer and length match
1103         if ( $cardnumber_length =~ m|^\d+$| ) {
1104             $min = $max = $cardnumber_length
1105                 if $cardnumber_length >= $min
1106                     and $cardnumber_length <= $max;
1107         }
1108         # Else assuming it is a range
1109         elsif ( $cardnumber_length =~ m|(\d*),(\d*)| ) {
1110             $min = $1 if $1 and $min < $1;
1111             $max = $2 if $2 and $max > $2;
1112         }
1113
1114     }
1115     return ( $min, $max );
1116 }
1117
1118 =head2 GetFirstValidEmailAddress
1119
1120   $email = GetFirstValidEmailAddress($borrowernumber);
1121
1122 Return the first valid email address for a borrower, given the borrowernumber.  For now, the order 
1123 is defined as email, emailpro, B_email.  Returns the empty string if the borrower has no email 
1124 addresses.
1125
1126 =cut
1127
1128 sub GetFirstValidEmailAddress {
1129     my $borrowernumber = shift;
1130     my $dbh = C4::Context->dbh;
1131     my $sth = $dbh->prepare( "SELECT email, emailpro, B_email FROM borrowers where borrowernumber = ? ");
1132     $sth->execute( $borrowernumber );
1133     my $data = $sth->fetchrow_hashref;
1134
1135     if ($data->{'email'}) {
1136        return $data->{'email'};
1137     } elsif ($data->{'emailpro'}) {
1138        return $data->{'emailpro'};
1139     } elsif ($data->{'B_email'}) {
1140        return $data->{'B_email'};
1141     } else {
1142        return '';
1143     }
1144 }
1145
1146 =head2 GetNoticeEmailAddress
1147
1148   $email = GetNoticeEmailAddress($borrowernumber);
1149
1150 Return the email address of borrower used for notices, given the borrowernumber.
1151 Returns the empty string if no email address.
1152
1153 =cut
1154
1155 sub GetNoticeEmailAddress {
1156     my $borrowernumber = shift;
1157
1158     my $which_address = C4::Context->preference("AutoEmailPrimaryAddress");
1159     # if syspref is set to 'first valid' (value == OFF), look up email address
1160     if ( $which_address eq 'OFF' ) {
1161         return GetFirstValidEmailAddress($borrowernumber);
1162     }
1163     # specified email address field
1164     my $dbh = C4::Context->dbh;
1165     my $sth = $dbh->prepare( qq{
1166         SELECT $which_address AS primaryemail
1167         FROM borrowers
1168         WHERE borrowernumber=?
1169     } );
1170     $sth->execute($borrowernumber);
1171     my $data = $sth->fetchrow_hashref;
1172     return $data->{'primaryemail'} || '';
1173 }
1174
1175 =head2 GetUpcomingMembershipExpires
1176
1177     my $expires = GetUpcomingMembershipExpires({
1178         branch => $branch, before => $before, after => $after,
1179     });
1180
1181     $branch is an optional branch code.
1182     $before/$after is an optional number of days before/after the date that
1183     is set by the preference MembershipExpiryDaysNotice.
1184     If the pref would be 14, before 2 and after 3, you will get all expires
1185     from 12 to 17 days.
1186
1187 =cut
1188
1189 sub GetUpcomingMembershipExpires {
1190     my ( $params ) = @_;
1191     my $before = $params->{before} || 0;
1192     my $after  = $params->{after} || 0;
1193     my $branch = $params->{branch};
1194
1195     my $dbh = C4::Context->dbh;
1196     my $days = C4::Context->preference("MembershipExpiryDaysNotice") || 0;
1197     my $date1 = dt_from_string->add( days => $days - $before );
1198     my $date2 = dt_from_string->add( days => $days + $after );
1199     $date1= output_pref({ dt => $date1, dateformat => 'iso', dateonly => 1 });
1200     $date2= output_pref({ dt => $date2, dateformat => 'iso', dateonly => 1 });
1201
1202     my $query = q|
1203         SELECT borrowers.*, categories.description,
1204         branches.branchname, branches.branchemail FROM borrowers
1205         LEFT JOIN branches USING (branchcode)
1206         LEFT JOIN categories USING (categorycode)
1207     |;
1208     if( $branch ) {
1209         $query.= 'WHERE branchcode=? AND dateexpiry BETWEEN ? AND ?';
1210     } else {
1211         $query.= 'WHERE dateexpiry BETWEEN ? AND ?';
1212     }
1213
1214     my $sth = $dbh->prepare( $query );
1215     my @pars = $branch? ( $branch ): ();
1216     push @pars, $date1, $date2;
1217     $sth->execute( @pars );
1218     my $results = $sth->fetchall_arrayref( {} );
1219     return $results;
1220 }
1221
1222 =head2 GetBorrowerCategorycode
1223
1224     $categorycode = &GetBorrowerCategoryCode( $borrowernumber );
1225
1226 Given the borrowernumber, the function returns the corresponding categorycode
1227
1228 =cut
1229
1230 sub GetBorrowerCategorycode {
1231     my ( $borrowernumber ) = @_;
1232     my $dbh = C4::Context->dbh;
1233     my $sth = $dbh->prepare( qq{
1234         SELECT categorycode
1235         FROM borrowers
1236         WHERE borrowernumber = ?
1237     } );
1238     $sth->execute( $borrowernumber );
1239     return $sth->fetchrow;
1240 }
1241
1242 =head2 GetAge
1243
1244   $dateofbirth,$date = &GetAge($date);
1245
1246 this function return the borrowers age with the value of dateofbirth
1247
1248 =cut
1249
1250 #'
1251 sub GetAge{
1252     my ( $date, $date_ref ) = @_;
1253
1254     if ( not defined $date_ref ) {
1255         $date_ref = sprintf( '%04d-%02d-%02d', Today() );
1256     }
1257
1258     my ( $year1, $month1, $day1 ) = split /-/, $date;
1259     my ( $year2, $month2, $day2 ) = split /-/, $date_ref;
1260
1261     my $age = $year2 - $year1;
1262     if ( $month1 . $day1 > $month2 . $day2 ) {
1263         $age--;
1264     }
1265
1266     return $age;
1267 }    # sub get_age
1268
1269 =head2 SetAge
1270
1271   $borrower = C4::Members::SetAge($borrower, $datetimeduration);
1272   $borrower = C4::Members::SetAge($borrower, '0015-12-10');
1273   $borrower = C4::Members::SetAge($borrower, $datetimeduration, $datetime_reference);
1274
1275   eval { $borrower = C4::Members::SetAge($borrower, '015-1-10'); };
1276   if ($@) {print $@;} #Catch a bad ISO Date or kill your script!
1277
1278 This function sets the borrower's dateofbirth to match the given age.
1279 Optionally relative to the given $datetime_reference.
1280
1281 @PARAM1 koha.borrowers-object
1282 @PARAM2 DateTime::Duration-object as the desired age
1283         OR a ISO 8601 Date. (To make the API more pleasant)
1284 @PARAM3 DateTime-object as the relative date, defaults to now().
1285 RETURNS The given borrower reference @PARAM1.
1286 DIES    If there was an error with the ISO Date handling.
1287
1288 =cut
1289
1290 #'
1291 sub SetAge{
1292     my ( $borrower, $datetimeduration, $datetime_ref ) = @_;
1293     $datetime_ref = DateTime->now() unless $datetime_ref;
1294
1295     if ($datetimeduration && ref $datetimeduration ne 'DateTime::Duration') {
1296         if ($datetimeduration =~ /^(\d{4})-(\d{2})-(\d{2})/) {
1297             $datetimeduration = DateTime::Duration->new(years => $1, months => $2, days => $3);
1298         }
1299         else {
1300             die "C4::Members::SetAge($borrower, $datetimeduration), datetimeduration not a valid ISO 8601 Date!\n";
1301         }
1302     }
1303
1304     my $new_datetime_ref = $datetime_ref->clone();
1305     $new_datetime_ref->subtract_duration( $datetimeduration );
1306
1307     $borrower->{dateofbirth} = $new_datetime_ref->ymd();
1308
1309     return $borrower;
1310 }    # sub SetAge
1311
1312 =head2 MoveMemberToDeleted
1313
1314   $result = &MoveMemberToDeleted($borrowernumber);
1315
1316 Copy the record from borrowers to deletedborrowers table.
1317 The routine returns 1 for success, undef for failure.
1318
1319 =cut
1320
1321 sub MoveMemberToDeleted {
1322     my ($member) = shift or return;
1323
1324     my $schema       = Koha::Database->new()->schema();
1325     my $borrowers_rs = $schema->resultset('Borrower');
1326     $borrowers_rs->result_class('DBIx::Class::ResultClass::HashRefInflator');
1327     my $borrower = $borrowers_rs->find($member);
1328     return unless $borrower;
1329
1330     my $deleted = $schema->resultset('Deletedborrower')->create($borrower);
1331
1332     return $deleted ? 1 : undef;
1333 }
1334
1335 =head2 DelMember
1336
1337     DelMember($borrowernumber);
1338
1339 This function remove directly a borrower whitout writing it on deleteborrower.
1340 + Deletes reserves for the borrower
1341
1342 =cut
1343
1344 sub DelMember {
1345     my $dbh            = C4::Context->dbh;
1346     my $borrowernumber = shift;
1347     #warn "in delmember with $borrowernumber";
1348     return unless $borrowernumber;    # borrowernumber is mandatory.
1349     # Delete Patron's holds
1350     my @holds = Koha::Holds->search({ borrowernumber => $borrowernumber });
1351     $_->delete for @holds;
1352
1353     my $query = "
1354        DELETE
1355        FROM borrowers
1356        WHERE borrowernumber = ?
1357    ";
1358     my $sth = $dbh->prepare($query);
1359     $sth->execute($borrowernumber);
1360     logaction("MEMBERS", "DELETE", $borrowernumber, "") if C4::Context->preference("BorrowersLog");
1361     return $sth->rows;
1362 }
1363
1364 =head2 HandleDelBorrower
1365
1366      HandleDelBorrower($borrower);
1367
1368 When a member is deleted (DelMember in Members.pm), you should call me first.
1369 This routine deletes/moves lists and entries for the deleted member/borrower.
1370 Lists owned by the borrower are deleted, but entries from the borrower to
1371 other lists are kept.
1372
1373 =cut
1374
1375 sub HandleDelBorrower {
1376     my ($borrower)= @_;
1377     my $query;
1378     my $dbh = C4::Context->dbh;
1379
1380     #Delete all lists and all shares of this borrower
1381     #Consistent with the approach Koha uses on deleting individual lists
1382     #Note that entries in virtualshelfcontents added by this borrower to
1383     #lists of others will be handled by a table constraint: the borrower
1384     #is set to NULL in those entries.
1385     $query="DELETE FROM virtualshelves WHERE owner=?";
1386     $dbh->do($query,undef,($borrower));
1387
1388     #NOTE:
1389     #We could handle the above deletes via a constraint too.
1390     #But a new BZ report 11889 has been opened to discuss another approach.
1391     #Instead of deleting we could also disown lists (based on a pref).
1392     #In that way we could save shared and public lists.
1393     #The current table constraints support that idea now.
1394     #This pref should then govern the results of other routines/methods such as
1395     #Koha::Virtualshelf->new->delete too.
1396 }
1397
1398 =head2 GetHideLostItemsPreference
1399
1400   $hidelostitemspref = &GetHideLostItemsPreference($borrowernumber);
1401
1402 Returns the HideLostItems preference for the patron category of the supplied borrowernumber
1403 C<&$hidelostitemspref>return value of function, 0 or 1
1404
1405 =cut
1406
1407 sub GetHideLostItemsPreference {
1408     my ($borrowernumber) = @_;
1409     my $dbh = C4::Context->dbh;
1410     my $query = "SELECT hidelostitems FROM borrowers,categories WHERE borrowers.categorycode = categories.categorycode AND borrowernumber = ?";
1411     my $sth = $dbh->prepare($query);
1412     $sth->execute($borrowernumber);
1413     my $hidelostitems = $sth->fetchrow;    
1414     return $hidelostitems;    
1415 }
1416
1417 =head2 GetBorrowersToExpunge
1418
1419   $borrowers = &GetBorrowersToExpunge(
1420       not_borrowed_since => $not_borrowed_since,
1421       expired_before       => $expired_before,
1422       category_code        => $category_code,
1423       patron_list_id       => $patron_list_id,
1424       branchcode           => $branchcode
1425   );
1426
1427   This function get all borrowers based on the given criteria.
1428
1429 =cut
1430
1431 sub GetBorrowersToExpunge {
1432
1433     my $params = shift;
1434     my $filterdate       = $params->{'not_borrowed_since'};
1435     my $filterexpiry     = $params->{'expired_before'};
1436     my $filterlastseen   = $params->{'last_seen'};
1437     my $filtercategory   = $params->{'category_code'};
1438     my $filterbranch     = $params->{'branchcode'} ||
1439                         ((C4::Context->preference('IndependentBranches')
1440                              && C4::Context->userenv 
1441                              && !C4::Context->IsSuperLibrarian()
1442                              && C4::Context->userenv->{branch})
1443                          ? C4::Context->userenv->{branch}
1444                          : "");  
1445     my $filterpatronlist = $params->{'patron_list_id'};
1446
1447     my $dbh   = C4::Context->dbh;
1448     my $query = q|
1449         SELECT borrowers.borrowernumber,
1450                MAX(old_issues.timestamp) AS latestissue,
1451                MAX(issues.timestamp) AS currentissue
1452         FROM   borrowers
1453         JOIN   categories USING (categorycode)
1454         LEFT JOIN (
1455             SELECT guarantorid
1456             FROM borrowers
1457             WHERE guarantorid IS NOT NULL
1458                 AND guarantorid <> 0
1459         ) as tmp ON borrowers.borrowernumber=tmp.guarantorid
1460         LEFT JOIN old_issues USING (borrowernumber)
1461         LEFT JOIN issues USING (borrowernumber)|;
1462     if ( $filterpatronlist  ){
1463         $query .= q| LEFT JOIN patron_list_patrons USING (borrowernumber)|;
1464     }
1465     $query .= q| WHERE  category_type <> 'S'
1466         AND tmp.guarantorid IS NULL
1467    |;
1468     my @query_params;
1469     if ( $filterbranch && $filterbranch ne "" ) {
1470         $query.= " AND borrowers.branchcode = ? ";
1471         push( @query_params, $filterbranch );
1472     }
1473     if ( $filterexpiry ) {
1474         $query .= " AND dateexpiry < ? ";
1475         push( @query_params, $filterexpiry );
1476     }
1477     if ( $filterlastseen ) {
1478         $query .= ' AND lastseen < ? ';
1479         push @query_params, $filterlastseen;
1480     }
1481     if ( $filtercategory ) {
1482         $query .= " AND categorycode = ? ";
1483         push( @query_params, $filtercategory );
1484     }
1485     if ( $filterpatronlist ){
1486         $query.=" AND patron_list_id = ? ";
1487         push( @query_params, $filterpatronlist );
1488     }
1489     $query.=" GROUP BY borrowers.borrowernumber HAVING currentissue IS NULL ";
1490     if ( $filterdate ) {
1491         $query.=" AND ( latestissue < ? OR latestissue IS NULL ) ";
1492         push @query_params,$filterdate;
1493     }
1494     warn $query if $debug;
1495
1496     my $sth = $dbh->prepare($query);
1497     if (scalar(@query_params)>0){  
1498         $sth->execute(@query_params);
1499     }
1500     else {
1501         $sth->execute;
1502     }
1503     
1504     my @results;
1505     while ( my $data = $sth->fetchrow_hashref ) {
1506         push @results, $data;
1507     }
1508     return \@results;
1509 }
1510
1511 =head2 GetBorrowersWhoHaveNeverBorrowed
1512
1513   $results = &GetBorrowersWhoHaveNeverBorrowed
1514
1515 This function get all borrowers who have never borrowed.
1516
1517 I<$result> is a ref to an array which all elements are a hasref.
1518
1519 =cut
1520
1521 sub GetBorrowersWhoHaveNeverBorrowed {
1522     my $filterbranch = shift || 
1523                         ((C4::Context->preference('IndependentBranches')
1524                              && C4::Context->userenv 
1525                              && !C4::Context->IsSuperLibrarian()
1526                              && C4::Context->userenv->{branch})
1527                          ? C4::Context->userenv->{branch}
1528                          : "");  
1529     my $dbh   = C4::Context->dbh;
1530     my $query = "
1531         SELECT borrowers.borrowernumber,max(timestamp) as latestissue
1532         FROM   borrowers
1533           LEFT JOIN issues ON borrowers.borrowernumber = issues.borrowernumber
1534         WHERE issues.borrowernumber IS NULL
1535    ";
1536     my @query_params;
1537     if ($filterbranch && $filterbranch ne ""){ 
1538         $query.=" AND borrowers.branchcode= ?";
1539         push @query_params,$filterbranch;
1540     }
1541     warn $query if $debug;
1542   
1543     my $sth = $dbh->prepare($query);
1544     if (scalar(@query_params)>0){  
1545         $sth->execute(@query_params);
1546     } 
1547     else {
1548         $sth->execute;
1549     }      
1550     
1551     my @results;
1552     while ( my $data = $sth->fetchrow_hashref ) {
1553         push @results, $data;
1554     }
1555     return \@results;
1556 }
1557
1558 =head2 GetBorrowersWithIssuesHistoryOlderThan
1559
1560   $results = &GetBorrowersWithIssuesHistoryOlderThan($date)
1561
1562 this function get all borrowers who has an issue history older than I<$date> given on input arg.
1563
1564 I<$result> is a ref to an array which all elements are a hashref.
1565 This hashref is containt the number of time this borrowers has borrowed before I<$date> and the borrowernumber.
1566
1567 =cut
1568
1569 sub GetBorrowersWithIssuesHistoryOlderThan {
1570     my $dbh  = C4::Context->dbh;
1571     my $date = shift ||POSIX::strftime("%Y-%m-%d",localtime());
1572     my $filterbranch = shift || 
1573                         ((C4::Context->preference('IndependentBranches')
1574                              && C4::Context->userenv 
1575                              && !C4::Context->IsSuperLibrarian()
1576                              && C4::Context->userenv->{branch})
1577                          ? C4::Context->userenv->{branch}
1578                          : "");  
1579     my $query = "
1580        SELECT count(borrowernumber) as n,borrowernumber
1581        FROM old_issues
1582        WHERE returndate < ?
1583          AND borrowernumber IS NOT NULL 
1584     "; 
1585     my @query_params;
1586     push @query_params, $date;
1587     if ($filterbranch){
1588         $query.="   AND branchcode = ?";
1589         push @query_params, $filterbranch;
1590     }    
1591     $query.=" GROUP BY borrowernumber ";
1592     warn $query if $debug;
1593     my $sth = $dbh->prepare($query);
1594     $sth->execute(@query_params);
1595     my @results;
1596
1597     while ( my $data = $sth->fetchrow_hashref ) {
1598         push @results, $data;
1599     }
1600     return \@results;
1601 }
1602
1603 =head2 IssueSlip
1604
1605   IssueSlip($branchcode, $borrowernumber, $quickslip)
1606
1607   Returns letter hash ( see C4::Letters::GetPreparedLetter )
1608
1609   $quickslip is boolean, to indicate whether we want a quick slip
1610
1611   IssueSlip populates ISSUESLIP and ISSUEQSLIP, and will make the following expansions:
1612
1613   Both slips:
1614
1615       <<branches.*>>
1616       <<borrowers.*>>
1617
1618   ISSUESLIP:
1619
1620       <checkedout>
1621          <<biblio.*>>
1622          <<items.*>>
1623          <<biblioitems.*>>
1624          <<issues.*>>
1625       </checkedout>
1626
1627       <overdue>
1628          <<biblio.*>>
1629          <<items.*>>
1630          <<biblioitems.*>>
1631          <<issues.*>>
1632       </overdue>
1633
1634       <news>
1635          <<opac_news.*>>
1636       </news>
1637
1638   ISSUEQSLIP:
1639
1640       <checkedout>
1641          <<biblio.*>>
1642          <<items.*>>
1643          <<biblioitems.*>>
1644          <<issues.*>>
1645       </checkedout>
1646
1647   NOTE: Not all table fields are available, pleasee see GetPendingIssues for a list of available fields.
1648
1649 =cut
1650
1651 sub IssueSlip {
1652     my ($branch, $borrowernumber, $quickslip) = @_;
1653
1654     # FIXME Check callers before removing this statement
1655     #return unless $borrowernumber;
1656
1657     my @issues = @{ GetPendingIssues($borrowernumber) };
1658
1659     for my $issue (@issues) {
1660         $issue->{date_due} = $issue->{date_due_sql};
1661         if ($quickslip) {
1662             my $today = output_pref({ dt => dt_from_string, dateformat => 'iso', dateonly => 1 });
1663             if ( substr( $issue->{issuedate}, 0, 10 ) eq $today
1664                 or substr( $issue->{lastreneweddate}, 0, 10 ) eq $today ) {
1665                   $issue->{now} = 1;
1666             };
1667         }
1668     }
1669
1670     # Sort on timestamp then on issuedate (useful for tests and could be if modified in a batch
1671     @issues = sort {
1672         my $s = $b->{timestamp} <=> $a->{timestamp};
1673         $s == 0 ?
1674              $b->{issuedate} <=> $a->{issuedate} : $s;
1675     } @issues;
1676
1677     my ($letter_code, %repeat);
1678     if ( $quickslip ) {
1679         $letter_code = 'ISSUEQSLIP';
1680         %repeat =  (
1681             'checkedout' => [ map {
1682                 'biblio'       => $_,
1683                 'items'        => $_,
1684                 'biblioitems'  => $_,
1685                 'issues'       => $_,
1686             }, grep { $_->{'now'} } @issues ],
1687         );
1688     }
1689     else {
1690         $letter_code = 'ISSUESLIP';
1691         %repeat =  (
1692             'checkedout' => [ map {
1693                 'biblio'       => $_,
1694                 'items'        => $_,
1695                 'biblioitems'  => $_,
1696                 'issues'       => $_,
1697             }, grep { !$_->{'overdue'} } @issues ],
1698
1699             'overdue' => [ map {
1700                 'biblio'       => $_,
1701                 'items'        => $_,
1702                 'biblioitems'  => $_,
1703                 'issues'       => $_,
1704             }, grep { $_->{'overdue'} } @issues ],
1705
1706             'news' => [ map {
1707                 $_->{'timestamp'} = $_->{'newdate'};
1708                 { opac_news => $_ }
1709             } @{ GetNewsToDisplay("slip",$branch) } ],
1710         );
1711     }
1712
1713     return  C4::Letters::GetPreparedLetter (
1714         module => 'circulation',
1715         letter_code => $letter_code,
1716         branchcode => $branch,
1717         tables => {
1718             'branches'    => $branch,
1719             'borrowers'   => $borrowernumber,
1720         },
1721         repeat => \%repeat,
1722     );
1723 }
1724
1725 =head2 GetBorrowersWithEmail
1726
1727     ([$borrnum,$userid], ...) = GetBorrowersWithEmail('me@example.com');
1728
1729 This gets a list of users and their basic details from their email address.
1730 As it's possible for multiple user to have the same email address, it provides
1731 you with all of them. If there is no userid for the user, there will be an
1732 C<undef> there. An empty list will be returned if there are no matches.
1733
1734 =cut
1735
1736 sub GetBorrowersWithEmail {
1737     my $email = shift;
1738
1739     my $dbh = C4::Context->dbh;
1740
1741     my $query = "SELECT borrowernumber, userid FROM borrowers WHERE email=?";
1742     my $sth=$dbh->prepare($query);
1743     $sth->execute($email);
1744     my @result = ();
1745     while (my $ref = $sth->fetch) {
1746         push @result, $ref;
1747     }
1748     die "Failure searching for borrowers by email address: $sth->errstr" if $sth->err;
1749     return @result;
1750 }
1751
1752 =head2 AddMember_Opac
1753
1754 =cut
1755
1756 sub AddMember_Opac {
1757     my ( %borrower ) = @_;
1758
1759     $borrower{'categorycode'} //= C4::Context->preference('PatronSelfRegistrationDefaultCategory');
1760     if (not defined $borrower{'password'}){
1761         my $sr = new String::Random;
1762         $sr->{'A'} = [ 'A'..'Z', 'a'..'z' ];
1763         my $password = $sr->randpattern("AAAAAAAAAA");
1764         $borrower{'password'} = $password;
1765     }
1766
1767     $borrower{'cardnumber'} = fixup_cardnumber( $borrower{'cardnumber'} );
1768
1769     my $borrowernumber = AddMember(%borrower);
1770
1771     return ( $borrowernumber, $borrower{'password'} );
1772 }
1773
1774 =head2 AddEnrolmentFeeIfNeeded
1775
1776     AddEnrolmentFeeIfNeeded( $borrower->{categorycode}, $borrower->{borrowernumber} );
1777
1778 Add enrolment fee for a patron if needed.
1779
1780 =cut
1781
1782 sub AddEnrolmentFeeIfNeeded {
1783     my ( $categorycode, $borrowernumber ) = @_;
1784     # check for enrollment fee & add it if needed
1785     my $dbh = C4::Context->dbh;
1786     my $sth = $dbh->prepare(q{
1787         SELECT enrolmentfee
1788         FROM categories
1789         WHERE categorycode=?
1790     });
1791     $sth->execute( $categorycode );
1792     if ( $sth->err ) {
1793         warn sprintf('Database returned the following error: %s', $sth->errstr);
1794         return;
1795     }
1796     my ($enrolmentfee) = $sth->fetchrow;
1797     if ($enrolmentfee && $enrolmentfee > 0) {
1798         # insert fee in patron debts
1799         C4::Accounts::manualinvoice( $borrowernumber, '', '', 'A', $enrolmentfee );
1800     }
1801 }
1802
1803 =head2 DeleteExpiredOpacRegistrations
1804
1805     Delete accounts that haven't been upgraded from the 'temporary' category
1806     Returns the number of removed patrons
1807
1808 =cut
1809
1810 sub DeleteExpiredOpacRegistrations {
1811
1812     my $delay = C4::Context->preference('PatronSelfRegistrationExpireTemporaryAccountsDelay');
1813     my $category_code = C4::Context->preference('PatronSelfRegistrationDefaultCategory');
1814
1815     return 0 if not $category_code or not defined $delay or $delay eq q||;
1816
1817     my $query = qq|
1818 SELECT borrowernumber
1819 FROM borrowers
1820 WHERE categorycode = ? AND DATEDIFF( NOW(), dateenrolled ) > ? |;
1821
1822     my $dbh = C4::Context->dbh;
1823     my $sth = $dbh->prepare($query);
1824     $sth->execute( $category_code, $delay );
1825     my $cnt=0;
1826     while ( my ($borrowernumber) = $sth->fetchrow_array() ) {
1827         DelMember($borrowernumber);
1828         $cnt++;
1829     }
1830     return $cnt;
1831 }
1832
1833 =head2 DeleteUnverifiedOpacRegistrations
1834
1835     Delete all unverified self registrations in borrower_modifications,
1836     older than the specified number of days.
1837
1838 =cut
1839
1840 sub DeleteUnverifiedOpacRegistrations {
1841     my ( $days ) = @_;
1842     my $dbh = C4::Context->dbh;
1843     my $sql=qq|
1844 DELETE FROM borrower_modifications
1845 WHERE borrowernumber = 0 AND DATEDIFF( NOW(), timestamp ) > ?|;
1846     my $cnt=$dbh->do($sql, undef, ($days) );
1847     return $cnt eq '0E0'? 0: $cnt;
1848 }
1849
1850 sub GetOverduesForPatron {
1851     my ( $borrowernumber ) = @_;
1852
1853     my $sql = "
1854         SELECT *
1855         FROM issues, items, biblio, biblioitems
1856         WHERE items.itemnumber=issues.itemnumber
1857           AND biblio.biblionumber   = items.biblionumber
1858           AND biblio.biblionumber   = biblioitems.biblionumber
1859           AND issues.borrowernumber = ?
1860           AND date_due < NOW()
1861     ";
1862
1863     my $sth = C4::Context->dbh->prepare( $sql );
1864     $sth->execute( $borrowernumber );
1865
1866     return $sth->fetchall_arrayref({});
1867 }
1868
1869 END { }    # module clean-up code here (global destructor)
1870
1871 1;
1872
1873 __END__
1874
1875 =head1 AUTHOR
1876
1877 Koha Team
1878
1879 =cut