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