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