Merge remote-tracking branch 'origin/new/bug_8251'
[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 Date::Calc qw/Today Add_Delta_YM check_date Date_to_Days/;
29 use C4::Log; # logaction
30 use C4::Overdues;
31 use C4::Reserves;
32 use C4::Accounts;
33 use C4::Biblio;
34 use C4::Letters;
35 use C4::SQLHelper qw(InsertInTable UpdateInTable SearchInTable);
36 use C4::Members::Attributes qw(SearchIdMatchingAttribute);
37 use C4::NewsChannels; #get slip news
38 use DateTime;
39 use DateTime::Format::DateParse;
40 use Koha::DateUtils;
41 use Text::Unaccent qw( unac_string );
42
43 our ($VERSION,@ISA,@EXPORT,@EXPORT_OK,$debug);
44
45 BEGIN {
46     $VERSION = 3.07.00.049;
47     $debug = $ENV{DEBUG} || 0;
48     require Exporter;
49     @ISA = qw(Exporter);
50     #Get data
51     push @EXPORT, qw(
52         &Search
53         &GetMemberDetails
54         &GetMemberRelatives
55         &GetMember
56
57         &GetGuarantees
58
59         &GetMemberIssuesAndFines
60         &GetPendingIssues
61         &GetAllIssues
62
63         &get_institutions
64         &getzipnamecity
65         &getidcity
66
67         &GetFirstValidEmailAddress
68
69         &GetAge
70         &GetCities
71         &GetRoadTypes
72         &GetRoadTypeDetails
73         &GetSortDetails
74         &GetTitles
75
76         &GetPatronImage
77         &PutPatronImage
78         &RmPatronImage
79
80         &GetHideLostItemsPreference
81
82         &IsMemberBlocked
83         &GetMemberAccountRecords
84         &GetBorNotifyAcctRecord
85
86         &GetborCatFromCatType
87         &GetBorrowercategory
88         GetBorrowerCategorycode
89         &GetBorrowercategoryList
90
91         &GetBorrowersWhoHaveNotBorrowedSince
92         &GetBorrowersWhoHaveNeverBorrowed
93         &GetBorrowersWithIssuesHistoryOlderThan
94
95         &GetExpiryDate
96
97         &AddMessage
98         &DeleteMessage
99         &GetMessages
100         &GetMessagesCount
101
102         &IssueSlip
103         GetBorrowersWithEmail
104     );
105
106     #Modify data
107     push @EXPORT, qw(
108         &ModMember
109         &changepassword
110          &ModPrivacy
111     );
112
113     #Delete data
114     push @EXPORT, qw(
115         &DelMember
116     );
117
118     #Insert data
119     push @EXPORT, qw(
120         &AddMember
121         &add_member_orgs
122         &MoveMemberToDeleted
123         &ExtendMemberSubscriptionTo
124     );
125
126     #Check data
127     push @EXPORT, qw(
128         &checkuniquemember
129         &checkuserpassword
130         &Check_Userid
131         &Generate_Userid
132         &fixEthnicity
133         &ethnicitycategories
134         &fixup_cardnumber
135         &checkcardnumber
136     );
137 }
138
139 =head1 NAME
140
141 C4::Members - Perl Module containing convenience functions for member handling
142
143 =head1 SYNOPSIS
144
145 use C4::Members;
146
147 =head1 DESCRIPTION
148
149 This module contains routines for adding, modifying and deleting members/patrons/borrowers 
150
151 =head1 FUNCTIONS
152
153 =head2 Search
154
155   $borrowers_result_array_ref = &Search($filter,$orderby, $limit, 
156                        $columns_out, $search_on_fields,$searchtype);
157
158 Looks up patrons (borrowers) on filter. A wrapper for SearchInTable('borrowers').
159
160 For C<$filter>, C<$orderby>, C<$limit>, C<&columns_out>, C<&search_on_fields> and C<&searchtype>
161 refer to C4::SQLHelper:SearchInTable().
162
163 Special C<$filter> key '' is effectively expanded to search on surname firstname othernamescw
164 and cardnumber unless C<&search_on_fields> is defined
165
166 Examples:
167
168   $borrowers = Search('abcd', 'cardnumber');
169
170   $borrowers = Search({''=>'abcd', category_type=>'I'}, 'surname');
171
172 =cut
173
174 sub _express_member_find {
175     my ($filter) = @_;
176
177     # this is used by circulation everytime a new borrowers cardnumber is scanned
178     # so we can check an exact match first, if that works return, otherwise do the rest
179     my $dbh   = C4::Context->dbh;
180     my $query = "SELECT borrowernumber FROM borrowers WHERE cardnumber = ?";
181     if ( my $borrowernumber = $dbh->selectrow_array($query, undef, $filter) ) {
182         return( {"borrowernumber"=>$borrowernumber} );
183     }
184
185     my ($search_on_fields, $searchtype);
186     if ( length($filter) == 1 ) {
187         $search_on_fields = [ qw(surname) ];
188         $searchtype = 'start_with';
189     } else {
190         $search_on_fields = [ qw(surname firstname othernames cardnumber) ];
191         $searchtype = 'contain';
192     }
193
194     return (undef, $search_on_fields, $searchtype);
195 }
196
197 sub Search {
198     my ( $filter, $orderby, $limit, $columns_out, $search_on_fields, $searchtype ) = @_;
199
200     my $search_string;
201     my $found_borrower;
202
203     if ( my $fr = ref $filter ) {
204         if ( $fr eq "HASH" ) {
205             if ( my $search_string = $filter->{''} ) {
206                 my ($member_filter, $member_search_on_fields, $member_searchtype) = _express_member_find($search_string);
207                 if ($member_filter) {
208                     $filter = $member_filter;
209                     $found_borrower = 1;
210                 } else {
211                     $search_on_fields ||= $member_search_on_fields;
212                     $searchtype ||= $member_searchtype;
213                 }
214             }
215         }
216         else {
217             $search_string = $filter;
218         }
219     }
220     else {
221         $search_string = $filter;
222         my ($member_filter, $member_search_on_fields, $member_searchtype) = _express_member_find($search_string);
223         if ($member_filter) {
224             $filter = $member_filter;
225             $found_borrower = 1;
226         } else {
227             $search_on_fields ||= $member_search_on_fields;
228             $searchtype ||= $member_searchtype;
229         }
230     }
231
232     if ( !$found_borrower && C4::Context->preference('ExtendedPatronAttributes') && $search_string ) {
233         my $matching_records = C4::Members::Attributes::SearchIdMatchingAttribute($search_string);
234         if(scalar(@$matching_records)>0) {
235             if ( my $fr = ref $filter ) {
236                 if ( $fr eq "HASH" ) {
237                     my %f = %$filter;
238                     $filter = [ $filter ];
239                     delete $f{''};
240                     push @$filter, { %f, "borrowernumber"=>$$matching_records };
241                 }
242                 else {
243                     push @$filter, {"borrowernumber"=>$matching_records};
244                 }
245             }
246             else {
247                 $filter = [ $filter ];
248                 push @$filter, {"borrowernumber"=>$matching_records};
249             }
250                 }
251     }
252
253     # $showallbranches was not used at the time SearchMember() was mainstreamed into Search().
254     # Mentioning for the reference
255
256     if ( C4::Context->preference("IndependantBranches") ) { # && !$showallbranches){
257         if ( my $userenv = C4::Context->userenv ) {
258             my $branch =  $userenv->{'branch'};
259             if ( ($userenv->{flags} % 2 !=1) &&
260                  $branch && $branch ne "insecure" ){
261
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 ($amount) = GetMemberAccountRecords( $patroninformation->{'borrowernumber'});
434     if ( $amount > 0 ) {
435         my %flaginfo;
436         my $noissuescharge = C4::Context->preference("noissuescharge") || 5;
437         $flaginfo{'message'} = sprintf "Patron owes \$%.02f", $amount;
438         $flaginfo{'amount'}  = sprintf "%.02f", $amount;
439         if ( $amount > $noissuescharge && !C4::Context->preference("AllowFineOverride") ) {
440             $flaginfo{'noissues'} = 1;
441         }
442         $flags{'CHARGES'} = \%flaginfo;
443     }
444     elsif ( $amount < 0 ) {
445         my %flaginfo;
446         $flaginfo{'message'} = sprintf "Patron has credit of \$%.02f", -$amount;
447         $flaginfo{'amount'}  = sprintf "%.02f", $amount;
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         # generate a proper login if none provided
755         $data{'userid'} = Generate_Userid($data{'borrowernumber'}, $data{'firstname'}, $data{'surname'}) if $data{'userid'} eq '';
756         # create a disabled account if no password provided
757         $data{'password'} = ($data{'password'})? md5_base64($data{'password'}) : '!';
758         $data{'borrowernumber'}=InsertInTable("borrowers",\%data);      
759     # mysql_insertid is probably bad.  not necessarily accurate and mysql-specific at best.
760     logaction("MEMBERS", "CREATE", $data{'borrowernumber'}, "") if C4::Context->preference("BorrowersLog");
761     
762     # check for enrollment fee & add it if needed
763     my $sth = $dbh->prepare("SELECT enrolmentfee FROM categories WHERE categorycode=?");
764     $sth->execute($data{'categorycode'});
765     my ($enrolmentfee) = $sth->fetchrow;
766     if ($sth->err) {
767         warn sprintf('Database returned the following error: %s', $sth->errstr);
768         return;
769     }
770     if ($enrolmentfee && $enrolmentfee > 0) {
771         # insert fee in patron debts
772         manualinvoice($data{'borrowernumber'}, '', '', 'A', $enrolmentfee);
773     }
774
775     return $data{'borrowernumber'};
776 }
777
778
779 sub Check_Userid {
780     my ($uid,$member) = @_;
781     my $dbh = C4::Context->dbh;
782     # Make sure the userid chosen is unique and not theirs if non-empty. If it is not,
783     # Then we need to tell the user and have them create a new one.
784     my $sth =
785       $dbh->prepare(
786         "SELECT * FROM borrowers WHERE userid=? AND borrowernumber != ?");
787     $sth->execute( $uid, $member );
788     if ( ( $uid ne '' ) && ( my $row = $sth->fetchrow_hashref ) ) {
789         return 0;
790     }
791     else {
792         return 1;
793     }
794 }
795
796 sub Generate_Userid {
797   my ($borrowernumber, $firstname, $surname) = @_;
798   my $newuid;
799   my $offset = 0;
800   do {
801     $firstname =~ s/[[:digit:][:space:][:blank:][:punct:][:cntrl:]]//g;
802     $surname =~ s/[[:digit:][:space:][:blank:][:punct:][:cntrl:]]//g;
803     $newuid = lc(($firstname)? "$firstname.$surname" : $surname);
804     $newuid = unac_string('utf-8',$newuid);
805     $newuid .= $offset unless $offset == 0;
806     $offset++;
807
808    } while (!Check_Userid($newuid,$borrowernumber));
809
810    return $newuid;
811 }
812
813 sub changepassword {
814     my ( $uid, $member, $digest ) = @_;
815     my $dbh = C4::Context->dbh;
816
817 #Make sure the userid chosen is unique and not theirs if non-empty. If it is not,
818 #Then we need to tell the user and have them create a new one.
819     my $resultcode;
820     my $sth =
821       $dbh->prepare(
822         "SELECT * FROM borrowers WHERE userid=? AND borrowernumber != ?");
823     $sth->execute( $uid, $member );
824     if ( ( $uid ne '' ) && ( my $row = $sth->fetchrow_hashref ) ) {
825         $resultcode=0;
826     }
827     else {
828         #Everything is good so we can update the information.
829         $sth =
830           $dbh->prepare(
831             "update borrowers set userid=?, password=? where borrowernumber=?");
832         $sth->execute( $uid, $digest, $member );
833         $resultcode=1;
834     }
835     
836     logaction("MEMBERS", "CHANGE PASS", $member, "") if C4::Context->preference("BorrowersLog");
837     return $resultcode;    
838 }
839
840
841
842 =head2 fixup_cardnumber
843
844 Warning: The caller is responsible for locking the members table in write
845 mode, to avoid database corruption.
846
847 =cut
848
849 use vars qw( @weightings );
850 my @weightings = ( 8, 4, 6, 3, 5, 2, 1 );
851
852 sub fixup_cardnumber {
853     my ($cardnumber) = @_;
854     my $autonumber_members = C4::Context->boolean_preference('autoMemberNum') || 0;
855
856     # Find out whether member numbers should be generated
857     # automatically. Should be either "1" or something else.
858     # Defaults to "0", which is interpreted as "no".
859
860     #     if ($cardnumber !~ /\S/ && $autonumber_members) {
861     ($autonumber_members) or return $cardnumber;
862     my $checkdigit = C4::Context->preference('checkdigit');
863     my $dbh = C4::Context->dbh;
864     if ( $checkdigit and $checkdigit eq 'katipo' ) {
865
866         # if checkdigit is selected, calculate katipo-style cardnumber.
867         # otherwise, just use the max()
868         # purpose: generate checksum'd member numbers.
869         # We'll assume we just got the max value of digits 2-8 of member #'s
870         # from the database and our job is to increment that by one,
871         # determine the 1st and 9th digits and return the full string.
872         my $sth = $dbh->prepare(
873             "select max(substring(borrowers.cardnumber,2,7)) as new_num from borrowers"
874         );
875         $sth->execute;
876         my $data = $sth->fetchrow_hashref;
877         $cardnumber = $data->{new_num};
878         if ( !$cardnumber ) {    # If DB has no values,
879             $cardnumber = 1000000;    # start at 1000000
880         } else {
881             $cardnumber += 1;
882         }
883
884         my $sum = 0;
885         for ( my $i = 0 ; $i < 8 ; $i += 1 ) {
886             # read weightings, left to right, 1 char at a time
887             my $temp1 = $weightings[$i];
888
889             # sequence left to right, 1 char at a time
890             my $temp2 = substr( $cardnumber, $i, 1 );
891
892             # mult each char 1-7 by its corresponding weighting
893             $sum += $temp1 * $temp2;
894         }
895
896         my $rem = ( $sum % 11 );
897         $rem = 'X' if $rem == 10;
898
899         return "V$cardnumber$rem";
900      } else {
901
902         my $sth = $dbh->prepare(
903             'SELECT MAX( CAST( cardnumber AS SIGNED ) ) FROM borrowers WHERE cardnumber REGEXP "^-?[0-9]+$"'
904         );
905         $sth->execute;
906         my ($result) = $sth->fetchrow;
907         return $result + 1;
908     }
909     return $cardnumber;     # just here as a fallback/reminder 
910 }
911
912 =head2 GetGuarantees
913
914   ($num_children, $children_arrayref) = &GetGuarantees($parent_borrno);
915   $child0_cardno = $children_arrayref->[0]{"cardnumber"};
916   $child0_borrno = $children_arrayref->[0]{"borrowernumber"};
917
918 C<&GetGuarantees> takes a borrower number (e.g., that of a patron
919 with children) and looks up the borrowers who are guaranteed by that
920 borrower (i.e., the patron's children).
921
922 C<&GetGuarantees> returns two values: an integer giving the number of
923 borrowers guaranteed by C<$parent_borrno>, and a reference to an array
924 of references to hash, which gives the actual results.
925
926 =cut
927
928 #'
929 sub GetGuarantees {
930     my ($borrowernumber) = @_;
931     my $dbh              = C4::Context->dbh;
932     my $sth              =
933       $dbh->prepare(
934 "select cardnumber,borrowernumber, firstname, surname from borrowers where guarantorid=?"
935       );
936     $sth->execute($borrowernumber);
937
938     my @dat;
939     my $data = $sth->fetchall_arrayref({}); 
940     return ( scalar(@$data), $data );
941 }
942
943 =head2 UpdateGuarantees
944
945   &UpdateGuarantees($parent_borrno);
946   
947
948 C<&UpdateGuarantees> borrower data for an adult and updates all the guarantees
949 with the modified information
950
951 =cut
952
953 #'
954 sub UpdateGuarantees {
955     my %data = shift;
956     my $dbh = C4::Context->dbh;
957     my ( $count, $guarantees ) = GetGuarantees( $data{'borrowernumber'} );
958     foreach my $guarantee (@$guarantees){
959         my $guaquery = qq|UPDATE borrowers 
960               SET address=?,fax=?,B_city=?,mobile=?,city=?,phone=?
961               WHERE borrowernumber=?
962         |;
963         my $sth = $dbh->prepare($guaquery);
964         $sth->execute($data{'address'},$data{'fax'},$data{'B_city'},$data{'mobile'},$data{'city'},$data{'phone'},$guarantee->{'borrowernumber'});
965     }
966 }
967 =head2 GetPendingIssues
968
969   my $issues = &GetPendingIssues(@borrowernumber);
970
971 Looks up what the patron with the given borrowernumber has borrowed.
972
973 C<&GetPendingIssues> returns a
974 reference-to-array where each element is a reference-to-hash; the
975 keys are the fields from the C<issues>, C<biblio>, and C<items> tables.
976 The keys include C<biblioitems> fields except marc and marcxml.
977
978 =cut
979
980 #'
981 sub GetPendingIssues {
982     my @borrowernumbers = @_;
983
984     unless (@borrowernumbers ) { # return a ref_to_array
985         return \@borrowernumbers; # to not cause surprise to caller
986     }
987
988     # Borrowers part of the query
989     my $bquery = '';
990     for (my $i = 0; $i < @borrowernumbers; $i++) {
991         $bquery .= ' issues.borrowernumber = ?';
992         if ($i < $#borrowernumbers ) {
993             $bquery .= ' OR';
994         }
995     }
996
997     # must avoid biblioitems.* to prevent large marc and marcxml fields from killing performance
998     # FIXME: namespace collision: each table has "timestamp" fields.  Which one is "timestamp" ?
999     # FIXME: circ/ciculation.pl tries to sort by timestamp!
1000     # FIXME: namespace collision: other collisions possible.
1001     # FIXME: most of this data isn't really being used by callers.
1002     my $query =
1003    "SELECT issues.*,
1004             items.*,
1005            biblio.*,
1006            biblioitems.volume,
1007            biblioitems.number,
1008            biblioitems.itemtype,
1009            biblioitems.isbn,
1010            biblioitems.issn,
1011            biblioitems.publicationyear,
1012            biblioitems.publishercode,
1013            biblioitems.volumedate,
1014            biblioitems.volumedesc,
1015            biblioitems.lccn,
1016            biblioitems.url,
1017            borrowers.firstname,
1018            borrowers.surname,
1019            borrowers.cardnumber,
1020            issues.timestamp AS timestamp,
1021            issues.renewals  AS renewals,
1022            issues.borrowernumber AS borrowernumber,
1023             items.renewals  AS totalrenewals
1024     FROM   issues
1025     LEFT JOIN items       ON items.itemnumber       =      issues.itemnumber
1026     LEFT JOIN biblio      ON items.biblionumber     =      biblio.biblionumber
1027     LEFT JOIN biblioitems ON items.biblioitemnumber = biblioitems.biblioitemnumber
1028     LEFT JOIN borrowers ON issues.borrowernumber = borrowers.borrowernumber
1029     WHERE
1030       $bquery
1031     ORDER BY issues.issuedate"
1032     ;
1033
1034     my $sth = C4::Context->dbh->prepare($query);
1035     $sth->execute(@borrowernumbers);
1036     my $data = $sth->fetchall_arrayref({});
1037     my $tz = C4::Context->tz();
1038     my $today = DateTime->now( time_zone => $tz);
1039     foreach (@{$data}) {
1040         if ($_->{issuedate}) {
1041             $_->{issuedate} = dt_from_string($_->{issuedate}, 'sql');
1042         }
1043         $_->{date_due} or next;
1044         $_->{date_due} = DateTime::Format::DateParse->parse_datetime($_->{date_due}, $tz->name());
1045         if ( DateTime->compare($_->{date_due}, $today) == -1 ) {
1046             $_->{overdue} = 1;
1047         }
1048     }
1049     return $data;
1050 }
1051
1052 =head2 GetAllIssues
1053
1054   $issues = &GetAllIssues($borrowernumber, $sortkey, $limit);
1055
1056 Looks up what the patron with the given borrowernumber has borrowed,
1057 and sorts the results.
1058
1059 C<$sortkey> is the name of a field on which to sort the results. This
1060 should be the name of a field in the C<issues>, C<biblio>,
1061 C<biblioitems>, or C<items> table in the Koha database.
1062
1063 C<$limit> is the maximum number of results to return.
1064
1065 C<&GetAllIssues> an arrayref, C<$issues>, of hashrefs, the keys of which
1066 are the fields from the C<issues>, C<biblio>, C<biblioitems>, and
1067 C<items> tables of the Koha database.
1068
1069 =cut
1070
1071 #'
1072 sub GetAllIssues {
1073     my ( $borrowernumber, $order, $limit ) = @_;
1074
1075     #FIXME: sanity-check order and limit
1076     my $dbh   = C4::Context->dbh;
1077     my $query =
1078   "SELECT *, issues.timestamp as issuestimestamp, issues.renewals AS renewals,items.renewals AS totalrenewals,items.timestamp AS itemstimestamp 
1079   FROM issues 
1080   LEFT JOIN items on items.itemnumber=issues.itemnumber
1081   LEFT JOIN biblio ON items.biblionumber=biblio.biblionumber
1082   LEFT JOIN biblioitems ON items.biblioitemnumber=biblioitems.biblioitemnumber
1083   WHERE borrowernumber=? 
1084   UNION ALL
1085   SELECT *, old_issues.timestamp as issuestimestamp, old_issues.renewals AS renewals,items.renewals AS totalrenewals,items.timestamp AS itemstimestamp 
1086   FROM old_issues 
1087   LEFT JOIN items on items.itemnumber=old_issues.itemnumber
1088   LEFT JOIN biblio ON items.biblionumber=biblio.biblionumber
1089   LEFT JOIN biblioitems ON items.biblioitemnumber=biblioitems.biblioitemnumber
1090   WHERE borrowernumber=? AND old_issues.itemnumber IS NOT NULL
1091   order by $order";
1092     if ( $limit != 0 ) {
1093         $query .= " limit $limit";
1094     }
1095
1096     my $sth = $dbh->prepare($query);
1097     $sth->execute($borrowernumber, $borrowernumber);
1098     my @result;
1099     my $i = 0;
1100     while ( my $data = $sth->fetchrow_hashref ) {
1101         push @result, $data;
1102     }
1103
1104     return \@result;
1105 }
1106
1107
1108 =head2 GetMemberAccountRecords
1109
1110   ($total, $acctlines, $count) = &GetMemberAccountRecords($borrowernumber);
1111
1112 Looks up accounting data for the patron with the given borrowernumber.
1113
1114 C<&GetMemberAccountRecords> returns a three-element array. C<$acctlines> is a
1115 reference-to-array, where each element is a reference-to-hash; the
1116 keys are the fields of the C<accountlines> table in the Koha database.
1117 C<$count> is the number of elements in C<$acctlines>. C<$total> is the
1118 total amount outstanding for all of the account lines.
1119
1120 =cut
1121
1122 #'
1123 sub GetMemberAccountRecords {
1124     my ($borrowernumber,$date) = @_;
1125     my $dbh = C4::Context->dbh;
1126     my @acctlines;
1127     my $numlines = 0;
1128     my $strsth      = qq(
1129                         SELECT * 
1130                         FROM accountlines 
1131                         WHERE borrowernumber=?);
1132     my @bind = ($borrowernumber);
1133     if ($date && $date ne ''){
1134             $strsth.=" AND date < ? ";
1135             push(@bind,$date);
1136     }
1137     $strsth.=" ORDER BY date desc,timestamp DESC";
1138     my $sth= $dbh->prepare( $strsth );
1139     $sth->execute( @bind );
1140     my $total = 0;
1141     while ( my $data = $sth->fetchrow_hashref ) {
1142         if ( $data->{itemnumber} ) {
1143             my $biblio = GetBiblioFromItemNumber( $data->{itemnumber} );
1144             $data->{biblionumber} = $biblio->{biblionumber};
1145             $data->{title}        = $biblio->{title};
1146         }
1147         $acctlines[$numlines] = $data;
1148         $numlines++;
1149         $total += int(1000 * $data->{'amountoutstanding'}); # convert float to integer to avoid round-off errors
1150     }
1151     $total /= 1000;
1152     return ( $total, \@acctlines,$numlines);
1153 }
1154
1155 =head2 GetBorNotifyAcctRecord
1156
1157   ($total, $acctlines, $count) = &GetBorNotifyAcctRecord($params,$notifyid);
1158
1159 Looks up accounting data for the patron with the given borrowernumber per file number.
1160
1161 C<&GetBorNotifyAcctRecord> returns a three-element array. C<$acctlines> is a
1162 reference-to-array, where each element is a reference-to-hash; the
1163 keys are the fields of the C<accountlines> table in the Koha database.
1164 C<$count> is the number of elements in C<$acctlines>. C<$total> is the
1165 total amount outstanding for all of the account lines.
1166
1167 =cut
1168
1169 sub GetBorNotifyAcctRecord {
1170     my ( $borrowernumber, $notifyid ) = @_;
1171     my $dbh = C4::Context->dbh;
1172     my @acctlines;
1173     my $numlines = 0;
1174     my $sth = $dbh->prepare(
1175             "SELECT * 
1176                 FROM accountlines 
1177                 WHERE borrowernumber=? 
1178                     AND notify_id=? 
1179                     AND amountoutstanding != '0' 
1180                 ORDER BY notify_id,accounttype
1181                 ");
1182
1183     $sth->execute( $borrowernumber, $notifyid );
1184     my $total = 0;
1185     while ( my $data = $sth->fetchrow_hashref ) {
1186         if ( $data->{itemnumber} ) {
1187             my $biblio = GetBiblioFromItemNumber( $data->{itemnumber} );
1188             $data->{biblionumber} = $biblio->{biblionumber};
1189             $data->{title}        = $biblio->{title};
1190         }
1191         $acctlines[$numlines] = $data;
1192         $numlines++;
1193         $total += int(100 * $data->{'amountoutstanding'});
1194     }
1195     $total /= 100;
1196     return ( $total, \@acctlines, $numlines );
1197 }
1198
1199 =head2 checkuniquemember (OUEST-PROVENCE)
1200
1201   ($result,$categorycode)  = &checkuniquemember($collectivity,$surname,$firstname,$dateofbirth);
1202
1203 Checks that a member exists or not in the database.
1204
1205 C<&result> is nonzero (=exist) or 0 (=does not exist)
1206 C<&categorycode> is from categorycode table
1207 C<&collectivity> is 1 (= we add a collectivity) or 0 (= we add a physical member)
1208 C<&surname> is the surname
1209 C<&firstname> is the firstname (only if collectivity=0)
1210 C<&dateofbirth> is the date of birth in ISO format (only if collectivity=0)
1211
1212 =cut
1213
1214 # FIXME: This function is not legitimate.  Multiple patrons might have the same first/last name and birthdate.
1215 # This is especially true since first name is not even a required field.
1216
1217 sub checkuniquemember {
1218     my ( $collectivity, $surname, $firstname, $dateofbirth ) = @_;
1219     my $dbh = C4::Context->dbh;
1220     my $request = ($collectivity) ?
1221         "SELECT borrowernumber,categorycode FROM borrowers WHERE surname=? " :
1222             ($dateofbirth) ?
1223             "SELECT borrowernumber,categorycode FROM borrowers WHERE surname=? and firstname=?  and dateofbirth=?" :
1224             "SELECT borrowernumber,categorycode FROM borrowers WHERE surname=? and firstname=?";
1225     my $sth = $dbh->prepare($request);
1226     if ($collectivity) {
1227         $sth->execute( uc($surname) );
1228     } elsif($dateofbirth){
1229         $sth->execute( uc($surname), ucfirst($firstname), $dateofbirth );
1230     }else{
1231         $sth->execute( uc($surname), ucfirst($firstname));
1232     }
1233     my @data = $sth->fetchrow;
1234     ( $data[0] ) and return $data[0], $data[1];
1235     return 0;
1236 }
1237
1238 sub checkcardnumber {
1239     my ($cardnumber,$borrowernumber) = @_;
1240     # If cardnumber is null, we assume they're allowed.
1241     return 0 if !defined($cardnumber);
1242     my $dbh = C4::Context->dbh;
1243     my $query = "SELECT * FROM borrowers WHERE cardnumber=?";
1244     $query .= " AND borrowernumber <> ?" if ($borrowernumber);
1245   my $sth = $dbh->prepare($query);
1246   if ($borrowernumber) {
1247    $sth->execute($cardnumber,$borrowernumber);
1248   } else { 
1249      $sth->execute($cardnumber);
1250   } 
1251     if (my $data= $sth->fetchrow_hashref()){
1252         return 1;
1253     }
1254     else {
1255         return 0;
1256     }
1257 }  
1258
1259
1260 =head2 getzipnamecity (OUEST-PROVENCE)
1261
1262 take all info from table city for the fields city and  zip
1263 check for the name and the zip code of the city selected
1264
1265 =cut
1266
1267 sub getzipnamecity {
1268     my ($cityid) = @_;
1269     my $dbh      = C4::Context->dbh;
1270     my $sth      =
1271       $dbh->prepare(
1272         "select city_name,city_state,city_zipcode,city_country from cities where cityid=? ");
1273     $sth->execute($cityid);
1274     my @data = $sth->fetchrow;
1275     return $data[0], $data[1], $data[2], $data[3];
1276 }
1277
1278
1279 =head2 getdcity (OUEST-PROVENCE)
1280
1281 recover cityid  with city_name condition
1282
1283 =cut
1284
1285 sub getidcity {
1286     my ($city_name) = @_;
1287     my $dbh = C4::Context->dbh;
1288     my $sth = $dbh->prepare("select cityid from cities where city_name=? ");
1289     $sth->execute($city_name);
1290     my $data = $sth->fetchrow;
1291     return $data;
1292 }
1293
1294 =head2 GetFirstValidEmailAddress
1295
1296   $email = GetFirstValidEmailAddress($borrowernumber);
1297
1298 Return the first valid email address for a borrower, given the borrowernumber.  For now, the order 
1299 is defined as email, emailpro, B_email.  Returns the empty string if the borrower has no email 
1300 addresses.
1301
1302 =cut
1303
1304 sub GetFirstValidEmailAddress {
1305     my $borrowernumber = shift;
1306     my $dbh = C4::Context->dbh;
1307     my $sth = $dbh->prepare( "SELECT email, emailpro, B_email FROM borrowers where borrowernumber = ? ");
1308     $sth->execute( $borrowernumber );
1309     my $data = $sth->fetchrow_hashref;
1310
1311     if ($data->{'email'}) {
1312        return $data->{'email'};
1313     } elsif ($data->{'emailpro'}) {
1314        return $data->{'emailpro'};
1315     } elsif ($data->{'B_email'}) {
1316        return $data->{'B_email'};
1317     } else {
1318        return '';
1319     }
1320 }
1321
1322 =head2 GetExpiryDate 
1323
1324   $expirydate = GetExpiryDate($categorycode, $dateenrolled);
1325
1326 Calculate expiry date given a categorycode and starting date.  Date argument must be in ISO format.
1327 Return date is also in ISO format.
1328
1329 =cut
1330
1331 sub GetExpiryDate {
1332     my ( $categorycode, $dateenrolled ) = @_;
1333     my $enrolments;
1334     if ($categorycode) {
1335         my $dbh = C4::Context->dbh;
1336         my $sth = $dbh->prepare("SELECT enrolmentperiod,enrolmentperioddate FROM categories WHERE categorycode=?");
1337         $sth->execute($categorycode);
1338         $enrolments = $sth->fetchrow_hashref;
1339     }
1340     # die "GetExpiryDate: for enrollmentperiod $enrolmentperiod (category '$categorycode') starting $dateenrolled.\n";
1341     my @date = split (/-/,$dateenrolled);
1342     if($enrolments->{enrolmentperiod}){
1343         return sprintf("%04d-%02d-%02d", Add_Delta_YM(@date,0,$enrolments->{enrolmentperiod}));
1344     }else{
1345         return $enrolments->{enrolmentperioddate};
1346     }
1347 }
1348
1349 =head2 checkuserpassword (OUEST-PROVENCE)
1350
1351 check for the password and login are not used
1352 return the number of record 
1353 0=> NOT USED 1=> USED
1354
1355 =cut
1356
1357 sub checkuserpassword {
1358     my ( $borrowernumber, $userid, $password ) = @_;
1359     $password = md5_base64($password);
1360     my $dbh = C4::Context->dbh;
1361     my $sth =
1362       $dbh->prepare(
1363 "Select count(*) from borrowers where borrowernumber !=? and userid =? and password=? "
1364       );
1365     $sth->execute( $borrowernumber, $userid, $password );
1366     my $number_rows = $sth->fetchrow;
1367     return $number_rows;
1368
1369 }
1370
1371 =head2 GetborCatFromCatType
1372
1373   ($codes_arrayref, $labels_hashref) = &GetborCatFromCatType();
1374
1375 Looks up the different types of borrowers in the database. Returns two
1376 elements: a reference-to-array, which lists the borrower category
1377 codes, and a reference-to-hash, which maps the borrower category codes
1378 to category descriptions.
1379
1380 =cut
1381
1382 #'
1383 sub GetborCatFromCatType {
1384     my ( $category_type, $action ) = @_;
1385         # FIXME - This API  seems both limited and dangerous. 
1386     my $dbh     = C4::Context->dbh;
1387     my $request = qq|   SELECT categorycode,description 
1388             FROM categories 
1389             $action
1390             ORDER BY categorycode|;
1391     my $sth = $dbh->prepare($request);
1392         if ($action) {
1393         $sth->execute($category_type);
1394     }
1395     else {
1396         $sth->execute();
1397     }
1398
1399     my %labels;
1400     my @codes;
1401
1402     while ( my $data = $sth->fetchrow_hashref ) {
1403         push @codes, $data->{'categorycode'};
1404         $labels{ $data->{'categorycode'} } = $data->{'description'};
1405     }
1406     return ( \@codes, \%labels );
1407 }
1408
1409 =head2 GetBorrowercategory
1410
1411   $hashref = &GetBorrowercategory($categorycode);
1412
1413 Given the borrower's category code, the function returns the corresponding
1414 data hashref for a comprehensive information display.
1415
1416 =cut
1417
1418 sub GetBorrowercategory {
1419     my ($catcode) = @_;
1420     my $dbh       = C4::Context->dbh;
1421     if ($catcode){
1422         my $sth       =
1423         $dbh->prepare(
1424     "SELECT description,dateofbirthrequired,upperagelimit,category_type 
1425     FROM categories 
1426     WHERE categorycode = ?"
1427         );
1428         $sth->execute($catcode);
1429         my $data =
1430         $sth->fetchrow_hashref;
1431         return $data;
1432     } 
1433     return;  
1434 }    # sub getborrowercategory
1435
1436
1437 =head2 GetBorrowerCategorycode
1438
1439     $categorycode = &GetBorrowerCategoryCode( $borrowernumber );
1440
1441 Given the borrowernumber, the function returns the corresponding categorycode
1442 =cut
1443
1444 sub GetBorrowerCategorycode {
1445     my ( $borrowernumber ) = @_;
1446     my $dbh = C4::Context->dbh;
1447     my $sth = $dbh->prepare( qq{
1448         SELECT categorycode
1449         FROM borrowers
1450         WHERE borrowernumber = ?
1451     } );
1452     $sth->execute( $borrowernumber );
1453     return $sth->fetchrow;
1454 }
1455
1456 =head2 GetBorrowercategoryList
1457
1458   $arrayref_hashref = &GetBorrowercategoryList;
1459 If no category code provided, the function returns all the categories.
1460
1461 =cut
1462
1463 sub GetBorrowercategoryList {
1464     my $dbh       = C4::Context->dbh;
1465     my $sth       =
1466     $dbh->prepare(
1467     "SELECT * 
1468     FROM categories 
1469     ORDER BY description"
1470         );
1471     $sth->execute;
1472     my $data =
1473     $sth->fetchall_arrayref({});
1474     return $data;
1475 }    # sub getborrowercategory
1476
1477 =head2 ethnicitycategories
1478
1479   ($codes_arrayref, $labels_hashref) = &ethnicitycategories();
1480
1481 Looks up the different ethnic types in the database. Returns two
1482 elements: a reference-to-array, which lists the ethnicity codes, and a
1483 reference-to-hash, which maps the ethnicity codes to ethnicity
1484 descriptions.
1485
1486 =cut
1487
1488 #'
1489
1490 sub ethnicitycategories {
1491     my $dbh = C4::Context->dbh;
1492     my $sth = $dbh->prepare("Select code,name from ethnicity order by name");
1493     $sth->execute;
1494     my %labels;
1495     my @codes;
1496     while ( my $data = $sth->fetchrow_hashref ) {
1497         push @codes, $data->{'code'};
1498         $labels{ $data->{'code'} } = $data->{'name'};
1499     }
1500     return ( \@codes, \%labels );
1501 }
1502
1503 =head2 fixEthnicity
1504
1505   $ethn_name = &fixEthnicity($ethn_code);
1506
1507 Takes an ethnicity code (e.g., "european" or "pi") and returns the
1508 corresponding descriptive name from the C<ethnicity> table in the
1509 Koha database ("European" or "Pacific Islander").
1510
1511 =cut
1512
1513 #'
1514
1515 sub fixEthnicity {
1516     my $ethnicity = shift;
1517     return unless $ethnicity;
1518     my $dbh       = C4::Context->dbh;
1519     my $sth       = $dbh->prepare("Select name from ethnicity where code = ?");
1520     $sth->execute($ethnicity);
1521     my $data = $sth->fetchrow_hashref;
1522     return $data->{'name'};
1523 }    # sub fixEthnicity
1524
1525 =head2 GetAge
1526
1527   $dateofbirth,$date = &GetAge($date);
1528
1529 this function return the borrowers age with the value of dateofbirth
1530
1531 =cut
1532
1533 #'
1534 sub GetAge{
1535     my ( $date, $date_ref ) = @_;
1536
1537     if ( not defined $date_ref ) {
1538         $date_ref = sprintf( '%04d-%02d-%02d', Today() );
1539     }
1540
1541     my ( $year1, $month1, $day1 ) = split /-/, $date;
1542     my ( $year2, $month2, $day2 ) = split /-/, $date_ref;
1543
1544     my $age = $year2 - $year1;
1545     if ( $month1 . $day1 > $month2 . $day2 ) {
1546         $age--;
1547     }
1548
1549     return $age;
1550 }    # sub get_age
1551
1552 =head2 get_institutions
1553
1554   $insitutions = get_institutions();
1555
1556 Just returns a list of all the borrowers of type I, borrownumber and name
1557
1558 =cut
1559
1560 #'
1561 sub get_institutions {
1562     my $dbh = C4::Context->dbh();
1563     my $sth =
1564       $dbh->prepare(
1565 "SELECT borrowernumber,surname FROM borrowers WHERE categorycode=? ORDER BY surname"
1566       );
1567     $sth->execute('I');
1568     my %orgs;
1569     while ( my $data = $sth->fetchrow_hashref() ) {
1570         $orgs{ $data->{'borrowernumber'} } = $data;
1571     }
1572     return ( \%orgs );
1573
1574 }    # sub get_institutions
1575
1576 =head2 add_member_orgs
1577
1578   add_member_orgs($borrowernumber,$borrowernumbers);
1579
1580 Takes a borrowernumber and a list of other borrowernumbers and inserts them into the borrowers_to_borrowers table
1581
1582 =cut
1583
1584 #'
1585 sub add_member_orgs {
1586     my ( $borrowernumber, $otherborrowers ) = @_;
1587     my $dbh   = C4::Context->dbh();
1588     my $query =
1589       "INSERT INTO borrowers_to_borrowers (borrower1,borrower2) VALUES (?,?)";
1590     my $sth = $dbh->prepare($query);
1591     foreach my $otherborrowernumber (@$otherborrowers) {
1592         $sth->execute( $borrowernumber, $otherborrowernumber );
1593     }
1594
1595 }    # sub add_member_orgs
1596
1597 =head2 GetCities
1598
1599   $cityarrayref = GetCities();
1600
1601   Returns an array_ref of the entries in the cities table
1602   If there are entries in the table an empty row is returned
1603   This is currently only used to populate a popup in memberentry
1604
1605 =cut
1606
1607 sub GetCities {
1608
1609     my $dbh   = C4::Context->dbh;
1610     my $city_arr = $dbh->selectall_arrayref(
1611         q|SELECT cityid,city_zipcode,city_name,city_state,city_country FROM cities ORDER BY city_name|,
1612         { Slice => {} });
1613     if ( @{$city_arr} ) {
1614         unshift @{$city_arr}, {
1615             city_zipcode => q{},
1616             city_name    => q{},
1617             cityid       => q{},
1618             city_state   => q{},
1619             city_country => q{},
1620         };
1621     }
1622
1623     return  $city_arr;
1624 }
1625
1626 =head2 GetSortDetails (OUEST-PROVENCE)
1627
1628   ($lib) = &GetSortDetails($category,$sortvalue);
1629
1630 Returns the authorized value  details
1631 C<&$lib>return value of authorized value details
1632 C<&$sortvalue>this is the value of authorized value 
1633 C<&$category>this is the value of authorized value category
1634
1635 =cut
1636
1637 sub GetSortDetails {
1638     my ( $category, $sortvalue ) = @_;
1639     my $dbh   = C4::Context->dbh;
1640     my $query = qq|SELECT lib 
1641         FROM authorised_values 
1642         WHERE category=?
1643         AND authorised_value=? |;
1644     my $sth = $dbh->prepare($query);
1645     $sth->execute( $category, $sortvalue );
1646     my $lib = $sth->fetchrow;
1647     return ($lib) if ($lib);
1648     return ($sortvalue) unless ($lib);
1649 }
1650
1651 =head2 MoveMemberToDeleted
1652
1653   $result = &MoveMemberToDeleted($borrowernumber);
1654
1655 Copy the record from borrowers to deletedborrowers table.
1656
1657 =cut
1658
1659 # FIXME: should do it in one SQL statement w/ subquery
1660 # Otherwise, we should return the @data on success
1661
1662 sub MoveMemberToDeleted {
1663     my ($member) = shift or return;
1664     my $dbh = C4::Context->dbh;
1665     my $query = qq|SELECT * 
1666           FROM borrowers 
1667           WHERE borrowernumber=?|;
1668     my $sth = $dbh->prepare($query);
1669     $sth->execute($member);
1670     my @data = $sth->fetchrow_array;
1671     (@data) or return;  # if we got a bad borrowernumber, there's nothing to insert
1672     $sth =
1673       $dbh->prepare( "INSERT INTO deletedborrowers VALUES ("
1674           . ( "?," x ( scalar(@data) - 1 ) )
1675           . "?)" );
1676     $sth->execute(@data);
1677 }
1678
1679 =head2 DelMember
1680
1681     DelMember($borrowernumber);
1682
1683 This function remove directly a borrower whitout writing it on deleteborrower.
1684 + Deletes reserves for the borrower
1685
1686 =cut
1687
1688 sub DelMember {
1689     my $dbh            = C4::Context->dbh;
1690     my $borrowernumber = shift;
1691     #warn "in delmember with $borrowernumber";
1692     return unless $borrowernumber;    # borrowernumber is mandatory.
1693
1694     my $query = qq|DELETE 
1695           FROM  reserves 
1696           WHERE borrowernumber=?|;
1697     my $sth = $dbh->prepare($query);
1698     $sth->execute($borrowernumber);
1699     $query = "
1700        DELETE
1701        FROM borrowers
1702        WHERE borrowernumber = ?
1703    ";
1704     $sth = $dbh->prepare($query);
1705     $sth->execute($borrowernumber);
1706     logaction("MEMBERS", "DELETE", $borrowernumber, "") if C4::Context->preference("BorrowersLog");
1707     return $sth->rows;
1708 }
1709
1710 =head2 ExtendMemberSubscriptionTo (OUEST-PROVENCE)
1711
1712     $date = ExtendMemberSubscriptionTo($borrowerid, $date);
1713
1714 Extending the subscription to a given date or to the expiry date calculated on ISO date.
1715 Returns ISO date.
1716
1717 =cut
1718
1719 sub ExtendMemberSubscriptionTo {
1720     my ( $borrowerid,$date) = @_;
1721     my $dbh = C4::Context->dbh;
1722     my $borrower = GetMember('borrowernumber'=>$borrowerid);
1723     unless ($date){
1724       $date = (C4::Context->preference('BorrowerRenewalPeriodBase') eq 'dateexpiry') ?
1725                                         C4::Dates->new($borrower->{'dateexpiry'}, 'iso')->output("iso") :
1726                                         C4::Dates->new()->output("iso");
1727       $date = GetExpiryDate( $borrower->{'categorycode'}, $date );
1728     }
1729     my $sth = $dbh->do(<<EOF);
1730 UPDATE borrowers 
1731 SET  dateexpiry='$date' 
1732 WHERE borrowernumber='$borrowerid'
1733 EOF
1734     # add enrolmentfee if needed
1735     $sth = $dbh->prepare("SELECT enrolmentfee FROM categories WHERE categorycode=?");
1736     $sth->execute($borrower->{'categorycode'});
1737     my ($enrolmentfee) = $sth->fetchrow;
1738     if ($enrolmentfee && $enrolmentfee > 0) {
1739         # insert fee in patron debts
1740         manualinvoice($borrower->{'borrowernumber'}, '', '', 'A', $enrolmentfee);
1741     }
1742      logaction("MEMBERS", "RENEW", $borrower->{'borrowernumber'}, "Membership renewed")if C4::Context->preference("BorrowersLog");
1743     return $date if ($sth);
1744     return 0;
1745 }
1746
1747 =head2 GetRoadTypes (OUEST-PROVENCE)
1748
1749   ($idroadtypearrayref, $roadttype_hashref) = &GetRoadTypes();
1750
1751 Looks up the different road type . Returns two
1752 elements: a reference-to-array, which lists the id_roadtype
1753 codes, and a reference-to-hash, which maps the road type of the road .
1754
1755 =cut
1756
1757 sub GetRoadTypes {
1758     my $dbh   = C4::Context->dbh;
1759     my $query = qq|
1760 SELECT roadtypeid,road_type 
1761 FROM roadtype 
1762 ORDER BY road_type|;
1763     my $sth = $dbh->prepare($query);
1764     $sth->execute();
1765     my %roadtype;
1766     my @id;
1767
1768     #    insert empty value to create a empty choice in cgi popup
1769
1770     while ( my $data = $sth->fetchrow_hashref ) {
1771
1772         push @id, $data->{'roadtypeid'};
1773         $roadtype{ $data->{'roadtypeid'} } = $data->{'road_type'};
1774     }
1775
1776 #test to know if the table contain some records if no the function return nothing
1777     my $id = @id;
1778     if ( $id eq 0 ) {
1779         return ();
1780     }
1781     else {
1782         unshift( @id, "" );
1783         return ( \@id, \%roadtype );
1784     }
1785 }
1786
1787
1788
1789 =head2 GetTitles (OUEST-PROVENCE)
1790
1791   ($borrowertitle)= &GetTitles();
1792
1793 Looks up the different title . Returns array  with all borrowers title
1794
1795 =cut
1796
1797 sub GetTitles {
1798     my @borrowerTitle = split (/,|\|/,C4::Context->preference('BorrowersTitles'));
1799     unshift( @borrowerTitle, "" );
1800     my $count=@borrowerTitle;
1801     if ($count == 1){
1802         return ();
1803     }
1804     else {
1805         return ( \@borrowerTitle);
1806     }
1807 }
1808
1809 =head2 GetPatronImage
1810
1811     my ($imagedata, $dberror) = GetPatronImage($cardnumber);
1812
1813 Returns the mimetype and binary image data of the image for the patron with the supplied cardnumber.
1814
1815 =cut
1816
1817 sub GetPatronImage {
1818     my ($cardnumber) = @_;
1819     warn "Cardnumber passed to GetPatronImage is $cardnumber" if $debug;
1820     my $dbh = C4::Context->dbh;
1821     my $query = 'SELECT mimetype, imagefile FROM patronimage WHERE cardnumber = ?';
1822     my $sth = $dbh->prepare($query);
1823     $sth->execute($cardnumber);
1824     my $imagedata = $sth->fetchrow_hashref;
1825     warn "Database error!" if $sth->errstr;
1826     return $imagedata, $sth->errstr;
1827 }
1828
1829 =head2 PutPatronImage
1830
1831     PutPatronImage($cardnumber, $mimetype, $imgfile);
1832
1833 Stores patron binary image data and mimetype in database.
1834 NOTE: This function is good for updating images as well as inserting new images in the database.
1835
1836 =cut
1837
1838 sub PutPatronImage {
1839     my ($cardnumber, $mimetype, $imgfile) = @_;
1840     warn "Parameters passed in: Cardnumber=$cardnumber, Mimetype=$mimetype, " . ($imgfile ? "Imagefile" : "No Imagefile") if $debug;
1841     my $dbh = C4::Context->dbh;
1842     my $query = "INSERT INTO patronimage (cardnumber, mimetype, imagefile) VALUES (?,?,?) ON DUPLICATE KEY UPDATE imagefile = ?;";
1843     my $sth = $dbh->prepare($query);
1844     $sth->execute($cardnumber,$mimetype,$imgfile,$imgfile);
1845     warn "Error returned inserting $cardnumber.$mimetype." if $sth->errstr;
1846     return $sth->errstr;
1847 }
1848
1849 =head2 RmPatronImage
1850
1851     my ($dberror) = RmPatronImage($cardnumber);
1852
1853 Removes the image for the patron with the supplied cardnumber.
1854
1855 =cut
1856
1857 sub RmPatronImage {
1858     my ($cardnumber) = @_;
1859     warn "Cardnumber passed to GetPatronImage is $cardnumber" if $debug;
1860     my $dbh = C4::Context->dbh;
1861     my $query = "DELETE FROM patronimage WHERE cardnumber = ?;";
1862     my $sth = $dbh->prepare($query);
1863     $sth->execute($cardnumber);
1864     my $dberror = $sth->errstr;
1865     warn "Database error!" if $sth->errstr;
1866     return $dberror;
1867 }
1868
1869 =head2 GetHideLostItemsPreference
1870
1871   $hidelostitemspref = &GetHideLostItemsPreference($borrowernumber);
1872
1873 Returns the HideLostItems preference for the patron category of the supplied borrowernumber
1874 C<&$hidelostitemspref>return value of function, 0 or 1
1875
1876 =cut
1877
1878 sub GetHideLostItemsPreference {
1879     my ($borrowernumber) = @_;
1880     my $dbh = C4::Context->dbh;
1881     my $query = "SELECT hidelostitems FROM borrowers,categories WHERE borrowers.categorycode = categories.categorycode AND borrowernumber = ?";
1882     my $sth = $dbh->prepare($query);
1883     $sth->execute($borrowernumber);
1884     my $hidelostitems = $sth->fetchrow;    
1885     return $hidelostitems;    
1886 }
1887
1888 =head2 GetRoadTypeDetails (OUEST-PROVENCE)
1889
1890   ($roadtype) = &GetRoadTypeDetails($roadtypeid);
1891
1892 Returns the description of roadtype
1893 C<&$roadtype>return description of road type
1894 C<&$roadtypeid>this is the value of roadtype s
1895
1896 =cut
1897
1898 sub GetRoadTypeDetails {
1899     my ($roadtypeid) = @_;
1900     my $dbh          = C4::Context->dbh;
1901     my $query        = qq|
1902 SELECT road_type 
1903 FROM roadtype 
1904 WHERE roadtypeid=?|;
1905     my $sth = $dbh->prepare($query);
1906     $sth->execute($roadtypeid);
1907     my $roadtype = $sth->fetchrow;
1908     return ($roadtype);
1909 }
1910
1911 =head2 GetBorrowersWhoHaveNotBorrowedSince
1912
1913   &GetBorrowersWhoHaveNotBorrowedSince($date)
1914
1915 this function get all borrowers who haven't borrowed since the date given on input arg.
1916
1917 =cut
1918
1919 sub GetBorrowersWhoHaveNotBorrowedSince {
1920     my $filterdate = shift||POSIX::strftime("%Y-%m-%d",localtime());
1921     my $filterexpiry = shift;
1922     my $filterbranch = shift || 
1923                         ((C4::Context->preference('IndependantBranches') 
1924                              && C4::Context->userenv 
1925                              && C4::Context->userenv->{flags} % 2 !=1 
1926                              && C4::Context->userenv->{branch})
1927                          ? C4::Context->userenv->{branch}
1928                          : "");  
1929     my $dbh   = C4::Context->dbh;
1930     my $query = "
1931         SELECT borrowers.borrowernumber,
1932                max(old_issues.timestamp) as latestissue,
1933                max(issues.timestamp) as currentissue
1934         FROM   borrowers
1935         JOIN   categories USING (categorycode)
1936         LEFT JOIN old_issues USING (borrowernumber)
1937         LEFT JOIN issues USING (borrowernumber) 
1938         WHERE  category_type <> 'S'
1939         AND borrowernumber NOT IN (SELECT guarantorid FROM borrowers WHERE guarantorid IS NOT NULL AND guarantorid <> 0) 
1940    ";
1941     my @query_params;
1942     if ($filterbranch && $filterbranch ne ""){ 
1943         $query.=" AND borrowers.branchcode= ?";
1944         push @query_params,$filterbranch;
1945     }
1946     if($filterexpiry){
1947         $query .= " AND dateexpiry < ? ";
1948         push @query_params,$filterdate;
1949     }
1950     $query.=" GROUP BY borrowers.borrowernumber";
1951     if ($filterdate){ 
1952         $query.=" HAVING (latestissue < ? OR latestissue IS NULL) 
1953                   AND currentissue IS NULL";
1954         push @query_params,$filterdate;
1955     }
1956     warn $query if $debug;
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('IndependantBranches') 
1985                              && C4::Context->userenv 
1986                              && C4::Context->userenv->{flags} % 2 !=1 
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('IndependantBranches') 
2035                              && C4::Context->userenv 
2036                              && C4::Context->userenv->{flags} % 2 !=1 
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 DebarMember
2091
2092 my $success = DebarMember( $borrowernumber, $todate );
2093
2094 marks a Member as debarred, and therefore unable to checkout any more
2095 items.
2096
2097 return :
2098 true on success, false on failure
2099
2100 =cut
2101
2102 sub DebarMember {
2103     my $borrowernumber = shift;
2104     my $todate         = shift;
2105
2106     return unless defined $borrowernumber;
2107     return unless $borrowernumber =~ /^\d+$/;
2108
2109     return ModMember(
2110         borrowernumber => $borrowernumber,
2111         debarred       => $todate
2112     );
2113
2114 }
2115
2116 =head2 ModPrivacy
2117
2118 =over 4
2119
2120 my $success = ModPrivacy( $borrowernumber, $privacy );
2121
2122 Update the privacy of a patron.
2123
2124 return :
2125 true on success, false on failure
2126
2127 =back
2128
2129 =cut
2130
2131 sub ModPrivacy {
2132     my $borrowernumber = shift;
2133     my $privacy = shift;
2134     return unless defined $borrowernumber;
2135     return unless $borrowernumber =~ /^\d+$/;
2136
2137     return ModMember( borrowernumber => $borrowernumber,
2138                       privacy        => $privacy );
2139 }
2140
2141 =head2 AddMessage
2142
2143   AddMessage( $borrowernumber, $message_type, $message, $branchcode );
2144
2145 Adds a message to the messages table for the given borrower.
2146
2147 Returns:
2148   True on success
2149   False on failure
2150
2151 =cut
2152
2153 sub AddMessage {
2154     my ( $borrowernumber, $message_type, $message, $branchcode ) = @_;
2155
2156     my $dbh  = C4::Context->dbh;
2157
2158     if ( ! ( $borrowernumber && $message_type && $message && $branchcode ) ) {
2159       return;
2160     }
2161
2162     my $query = "INSERT INTO messages ( borrowernumber, branchcode, message_type, message ) VALUES ( ?, ?, ?, ? )";
2163     my $sth = $dbh->prepare($query);
2164     $sth->execute( $borrowernumber, $branchcode, $message_type, $message );
2165     logaction("MEMBERS", "ADDCIRCMESSAGE", $borrowernumber, $message) if C4::Context->preference("BorrowersLog");
2166     return 1;
2167 }
2168
2169 =head2 GetMessages
2170
2171   GetMessages( $borrowernumber, $type );
2172
2173 $type is message type, B for borrower, or L for Librarian.
2174 Empty type returns all messages of any type.
2175
2176 Returns all messages for the given borrowernumber
2177
2178 =cut
2179
2180 sub GetMessages {
2181     my ( $borrowernumber, $type, $branchcode ) = @_;
2182
2183     if ( ! $type ) {
2184       $type = '%';
2185     }
2186
2187     my $dbh  = C4::Context->dbh;
2188
2189     my $query = "SELECT
2190                   branches.branchname,
2191                   messages.*,
2192                   message_date,
2193                   messages.branchcode LIKE '$branchcode' AS can_delete
2194                   FROM messages, branches
2195                   WHERE borrowernumber = ?
2196                   AND message_type LIKE ?
2197                   AND messages.branchcode = branches.branchcode
2198                   ORDER BY message_date DESC";
2199     my $sth = $dbh->prepare($query);
2200     $sth->execute( $borrowernumber, $type ) ;
2201     my @results;
2202
2203     while ( my $data = $sth->fetchrow_hashref ) {
2204         my $d = C4::Dates->new( $data->{message_date}, 'iso' );
2205         $data->{message_date_formatted} = $d->output;
2206         push @results, $data;
2207     }
2208     return \@results;
2209
2210 }
2211
2212 =head2 GetMessages
2213
2214   GetMessagesCount( $borrowernumber, $type );
2215
2216 $type is message type, B for borrower, or L for Librarian.
2217 Empty type returns all messages of any type.
2218
2219 Returns the number of messages for the given borrowernumber
2220
2221 =cut
2222
2223 sub GetMessagesCount {
2224     my ( $borrowernumber, $type, $branchcode ) = @_;
2225
2226     if ( ! $type ) {
2227       $type = '%';
2228     }
2229
2230     my $dbh  = C4::Context->dbh;
2231
2232     my $query = "SELECT COUNT(*) as MsgCount FROM messages WHERE borrowernumber = ? AND message_type LIKE ?";
2233     my $sth = $dbh->prepare($query);
2234     $sth->execute( $borrowernumber, $type ) ;
2235     my @results;
2236
2237     my $data = $sth->fetchrow_hashref;
2238     my $count = $data->{'MsgCount'};
2239
2240     return $count;
2241 }
2242
2243
2244
2245 =head2 DeleteMessage
2246
2247   DeleteMessage( $message_id );
2248
2249 =cut
2250
2251 sub DeleteMessage {
2252     my ( $message_id ) = @_;
2253
2254     my $dbh = C4::Context->dbh;
2255     my $query = "SELECT * FROM messages WHERE message_id = ?";
2256     my $sth = $dbh->prepare($query);
2257     $sth->execute( $message_id );
2258     my $message = $sth->fetchrow_hashref();
2259
2260     $query = "DELETE FROM messages WHERE message_id = ?";
2261     $sth = $dbh->prepare($query);
2262     $sth->execute( $message_id );
2263     logaction("MEMBERS", "DELCIRCMESSAGE", $message->{'borrowernumber'}, $message->{'message'}) if C4::Context->preference("BorrowersLog");
2264 }
2265
2266 =head2 IssueSlip
2267
2268   IssueSlip($branchcode, $borrowernumber, $quickslip)
2269
2270   Returns letter hash ( see C4::Letters::GetPreparedLetter )
2271
2272   $quickslip is boolean, to indicate whether we want a quick slip
2273
2274 =cut
2275
2276 sub IssueSlip {
2277     my ($branch, $borrowernumber, $quickslip) = @_;
2278
2279 #   return unless ( C4::Context->boolean_preference('printcirculationslips') );
2280
2281     my $now       = POSIX::strftime("%Y-%m-%d", localtime);
2282
2283     my $issueslist = GetPendingIssues($borrowernumber);
2284     foreach my $it (@$issueslist){
2285         if ((substr $it->{'issuedate'}, 0, 10) eq $now) {
2286             $it->{'now'} = 1;
2287         }
2288         elsif ((substr $it->{'date_due'}, 0, 10) le $now) {
2289             $it->{'overdue'} = 1;
2290         }
2291
2292         $it->{'date_due'}=format_date($it->{'date_due'});
2293     }
2294     my @issues = sort { $b->{'timestamp'} <=> $a->{'timestamp'} } @$issueslist;
2295
2296     my ($letter_code, %repeat);
2297     if ( $quickslip ) {
2298         $letter_code = 'ISSUEQSLIP';
2299         %repeat =  (
2300             'checkedout' => [ map {
2301                 'biblio' => $_,
2302                 'items'  => $_,
2303                 'issues' => $_,
2304             }, grep { $_->{'now'} } @issues ],
2305         );
2306     }
2307     else {
2308         $letter_code = 'ISSUESLIP';
2309         %repeat =  (
2310             'checkedout' => [ map {
2311                 'biblio' => $_,
2312                 'items'  => $_,
2313                 'issues' => $_,
2314             }, grep { !$_->{'overdue'} } @issues ],
2315
2316             'overdue' => [ map {
2317                 'biblio' => $_,
2318                 'items'  => $_,
2319                 'issues' => $_,
2320             }, grep { $_->{'overdue'} } @issues ],
2321
2322             'news' => [ map {
2323                 $_->{'timestamp'} = $_->{'newdate'};
2324                 { opac_news => $_ }
2325             } @{ GetNewsToDisplay("slip") } ],
2326         );
2327     }
2328
2329     return  C4::Letters::GetPreparedLetter (
2330         module => 'circulation',
2331         letter_code => $letter_code,
2332         branchcode => $branch,
2333         tables => {
2334             'branches'    => $branch,
2335             'borrowers'   => $borrowernumber,
2336         },
2337         repeat => \%repeat,
2338     );
2339 }
2340
2341 =head2 GetBorrowersWithEmail
2342
2343     ([$borrnum,$userid], ...) = GetBorrowersWithEmail('me@example.com');
2344
2345 This gets a list of users and their basic details from their email address.
2346 As it's possible for multiple user to have the same email address, it provides
2347 you with all of them. If there is no userid for the user, there will be an
2348 C<undef> there. An empty list will be returned if there are no matches.
2349
2350 =cut
2351
2352 sub GetBorrowersWithEmail {
2353     my $email = shift;
2354
2355     my $dbh = C4::Context->dbh;
2356
2357     my $query = "SELECT borrowernumber, userid FROM borrowers WHERE email=?";
2358     my $sth=$dbh->prepare($query);
2359     $sth->execute($email);
2360     my @result = ();
2361     while (my $ref = $sth->fetch) {
2362         push @result, $ref;
2363     }
2364     die "Failure searching for borrowers by email address: $sth->errstr" if $sth->err;
2365     return @result;
2366 }
2367
2368
2369 END { }    # module clean-up code here (global destructor)
2370
2371 1;
2372
2373 __END__
2374
2375 =head1 AUTHOR
2376
2377 Koha Team
2378
2379 =cut