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