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