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