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