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