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