Merge remote-tracking branch 'origin/new/bug_8233'
[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     my $dbh = C4::Context->dbh;
1076     my $query =
1077 'SELECT *, issues.timestamp as issuestimestamp, issues.renewals AS renewals,items.renewals AS totalrenewals,items.timestamp AS itemstimestamp
1078   FROM issues 
1079   LEFT JOIN items on items.itemnumber=issues.itemnumber
1080   LEFT JOIN biblio ON items.biblionumber=biblio.biblionumber
1081   LEFT JOIN biblioitems ON items.biblioitemnumber=biblioitems.biblioitemnumber
1082   WHERE borrowernumber=? 
1083   UNION ALL
1084   SELECT *, old_issues.timestamp as issuestimestamp, old_issues.renewals AS renewals,items.renewals AS totalrenewals,items.timestamp AS itemstimestamp 
1085   FROM old_issues 
1086   LEFT JOIN items on items.itemnumber=old_issues.itemnumber
1087   LEFT JOIN biblio ON items.biblionumber=biblio.biblionumber
1088   LEFT JOIN biblioitems ON items.biblioitemnumber=biblioitems.biblioitemnumber
1089   WHERE borrowernumber=? AND old_issues.itemnumber IS NOT NULL
1090   order by ' . $order;
1091     if ($limit) {
1092         $query .= " limit $limit";
1093     }
1094
1095     my $sth = $dbh->prepare($query);
1096     $sth->execute( $borrowernumber, $borrowernumber );
1097     return $sth->fetchall_arrayref( {} );
1098 }
1099
1100
1101 =head2 GetMemberAccountRecords
1102
1103   ($total, $acctlines, $count) = &GetMemberAccountRecords($borrowernumber);
1104
1105 Looks up accounting data for the patron with the given borrowernumber.
1106
1107 C<&GetMemberAccountRecords> returns a three-element array. C<$acctlines> is a
1108 reference-to-array, where each element is a reference-to-hash; the
1109 keys are the fields of the C<accountlines> table in the Koha database.
1110 C<$count> is the number of elements in C<$acctlines>. C<$total> is the
1111 total amount outstanding for all of the account lines.
1112
1113 =cut
1114
1115 #'
1116 sub GetMemberAccountRecords {
1117     my ($borrowernumber,$date) = @_;
1118     my $dbh = C4::Context->dbh;
1119     my @acctlines;
1120     my $numlines = 0;
1121     my $strsth      = qq(
1122                         SELECT * 
1123                         FROM accountlines 
1124                         WHERE borrowernumber=?);
1125     my @bind = ($borrowernumber);
1126     if ($date && $date ne ''){
1127             $strsth.=" AND date < ? ";
1128             push(@bind,$date);
1129     }
1130     $strsth.=" ORDER BY date desc,timestamp DESC";
1131     my $sth= $dbh->prepare( $strsth );
1132     $sth->execute( @bind );
1133     my $total = 0;
1134     while ( my $data = $sth->fetchrow_hashref ) {
1135         if ( $data->{itemnumber} ) {
1136             my $biblio = GetBiblioFromItemNumber( $data->{itemnumber} );
1137             $data->{biblionumber} = $biblio->{biblionumber};
1138             $data->{title}        = $biblio->{title};
1139         }
1140         $acctlines[$numlines] = $data;
1141         $numlines++;
1142         $total += int(1000 * $data->{'amountoutstanding'}); # convert float to integer to avoid round-off errors
1143     }
1144     $total /= 1000;
1145     return ( $total, \@acctlines,$numlines);
1146 }
1147
1148 =head2 GetBorNotifyAcctRecord
1149
1150   ($total, $acctlines, $count) = &GetBorNotifyAcctRecord($params,$notifyid);
1151
1152 Looks up accounting data for the patron with the given borrowernumber per file number.
1153
1154 C<&GetBorNotifyAcctRecord> returns a three-element array. C<$acctlines> is a
1155 reference-to-array, where each element is a reference-to-hash; the
1156 keys are the fields of the C<accountlines> table in the Koha database.
1157 C<$count> is the number of elements in C<$acctlines>. C<$total> is the
1158 total amount outstanding for all of the account lines.
1159
1160 =cut
1161
1162 sub GetBorNotifyAcctRecord {
1163     my ( $borrowernumber, $notifyid ) = @_;
1164     my $dbh = C4::Context->dbh;
1165     my @acctlines;
1166     my $numlines = 0;
1167     my $sth = $dbh->prepare(
1168             "SELECT * 
1169                 FROM accountlines 
1170                 WHERE borrowernumber=? 
1171                     AND notify_id=? 
1172                     AND amountoutstanding != '0' 
1173                 ORDER BY notify_id,accounttype
1174                 ");
1175
1176     $sth->execute( $borrowernumber, $notifyid );
1177     my $total = 0;
1178     while ( my $data = $sth->fetchrow_hashref ) {
1179         if ( $data->{itemnumber} ) {
1180             my $biblio = GetBiblioFromItemNumber( $data->{itemnumber} );
1181             $data->{biblionumber} = $biblio->{biblionumber};
1182             $data->{title}        = $biblio->{title};
1183         }
1184         $acctlines[$numlines] = $data;
1185         $numlines++;
1186         $total += int(100 * $data->{'amountoutstanding'});
1187     }
1188     $total /= 100;
1189     return ( $total, \@acctlines, $numlines );
1190 }
1191
1192 =head2 checkuniquemember (OUEST-PROVENCE)
1193
1194   ($result,$categorycode)  = &checkuniquemember($collectivity,$surname,$firstname,$dateofbirth);
1195
1196 Checks that a member exists or not in the database.
1197
1198 C<&result> is nonzero (=exist) or 0 (=does not exist)
1199 C<&categorycode> is from categorycode table
1200 C<&collectivity> is 1 (= we add a collectivity) or 0 (= we add a physical member)
1201 C<&surname> is the surname
1202 C<&firstname> is the firstname (only if collectivity=0)
1203 C<&dateofbirth> is the date of birth in ISO format (only if collectivity=0)
1204
1205 =cut
1206
1207 # FIXME: This function is not legitimate.  Multiple patrons might have the same first/last name and birthdate.
1208 # This is especially true since first name is not even a required field.
1209
1210 sub checkuniquemember {
1211     my ( $collectivity, $surname, $firstname, $dateofbirth ) = @_;
1212     my $dbh = C4::Context->dbh;
1213     my $request = ($collectivity) ?
1214         "SELECT borrowernumber,categorycode FROM borrowers WHERE surname=? " :
1215             ($dateofbirth) ?
1216             "SELECT borrowernumber,categorycode FROM borrowers WHERE surname=? and firstname=?  and dateofbirth=?" :
1217             "SELECT borrowernumber,categorycode FROM borrowers WHERE surname=? and firstname=?";
1218     my $sth = $dbh->prepare($request);
1219     if ($collectivity) {
1220         $sth->execute( uc($surname) );
1221     } elsif($dateofbirth){
1222         $sth->execute( uc($surname), ucfirst($firstname), $dateofbirth );
1223     }else{
1224         $sth->execute( uc($surname), ucfirst($firstname));
1225     }
1226     my @data = $sth->fetchrow;
1227     ( $data[0] ) and return $data[0], $data[1];
1228     return 0;
1229 }
1230
1231 sub checkcardnumber {
1232     my ($cardnumber,$borrowernumber) = @_;
1233     # If cardnumber is null, we assume they're allowed.
1234     return 0 if !defined($cardnumber);
1235     my $dbh = C4::Context->dbh;
1236     my $query = "SELECT * FROM borrowers WHERE cardnumber=?";
1237     $query .= " AND borrowernumber <> ?" if ($borrowernumber);
1238   my $sth = $dbh->prepare($query);
1239   if ($borrowernumber) {
1240    $sth->execute($cardnumber,$borrowernumber);
1241   } else { 
1242      $sth->execute($cardnumber);
1243   } 
1244     if (my $data= $sth->fetchrow_hashref()){
1245         return 1;
1246     }
1247     else {
1248         return 0;
1249     }
1250 }  
1251
1252
1253 =head2 getzipnamecity (OUEST-PROVENCE)
1254
1255 take all info from table city for the fields city and  zip
1256 check for the name and the zip code of the city selected
1257
1258 =cut
1259
1260 sub getzipnamecity {
1261     my ($cityid) = @_;
1262     my $dbh      = C4::Context->dbh;
1263     my $sth      =
1264       $dbh->prepare(
1265         "select city_name,city_state,city_zipcode,city_country from cities where cityid=? ");
1266     $sth->execute($cityid);
1267     my @data = $sth->fetchrow;
1268     return $data[0], $data[1], $data[2], $data[3];
1269 }
1270
1271
1272 =head2 getdcity (OUEST-PROVENCE)
1273
1274 recover cityid  with city_name condition
1275
1276 =cut
1277
1278 sub getidcity {
1279     my ($city_name) = @_;
1280     my $dbh = C4::Context->dbh;
1281     my $sth = $dbh->prepare("select cityid from cities where city_name=? ");
1282     $sth->execute($city_name);
1283     my $data = $sth->fetchrow;
1284     return $data;
1285 }
1286
1287 =head2 GetFirstValidEmailAddress
1288
1289   $email = GetFirstValidEmailAddress($borrowernumber);
1290
1291 Return the first valid email address for a borrower, given the borrowernumber.  For now, the order 
1292 is defined as email, emailpro, B_email.  Returns the empty string if the borrower has no email 
1293 addresses.
1294
1295 =cut
1296
1297 sub GetFirstValidEmailAddress {
1298     my $borrowernumber = shift;
1299     my $dbh = C4::Context->dbh;
1300     my $sth = $dbh->prepare( "SELECT email, emailpro, B_email FROM borrowers where borrowernumber = ? ");
1301     $sth->execute( $borrowernumber );
1302     my $data = $sth->fetchrow_hashref;
1303
1304     if ($data->{'email'}) {
1305        return $data->{'email'};
1306     } elsif ($data->{'emailpro'}) {
1307        return $data->{'emailpro'};
1308     } elsif ($data->{'B_email'}) {
1309        return $data->{'B_email'};
1310     } else {
1311        return '';
1312     }
1313 }
1314
1315 =head2 GetExpiryDate 
1316
1317   $expirydate = GetExpiryDate($categorycode, $dateenrolled);
1318
1319 Calculate expiry date given a categorycode and starting date.  Date argument must be in ISO format.
1320 Return date is also in ISO format.
1321
1322 =cut
1323
1324 sub GetExpiryDate {
1325     my ( $categorycode, $dateenrolled ) = @_;
1326     my $enrolments;
1327     if ($categorycode) {
1328         my $dbh = C4::Context->dbh;
1329         my $sth = $dbh->prepare("SELECT enrolmentperiod,enrolmentperioddate FROM categories WHERE categorycode=?");
1330         $sth->execute($categorycode);
1331         $enrolments = $sth->fetchrow_hashref;
1332     }
1333     # die "GetExpiryDate: for enrollmentperiod $enrolmentperiod (category '$categorycode') starting $dateenrolled.\n";
1334     my @date = split (/-/,$dateenrolled);
1335     if($enrolments->{enrolmentperiod}){
1336         return sprintf("%04d-%02d-%02d", Add_Delta_YM(@date,0,$enrolments->{enrolmentperiod}));
1337     }else{
1338         return $enrolments->{enrolmentperioddate};
1339     }
1340 }
1341
1342 =head2 checkuserpassword (OUEST-PROVENCE)
1343
1344 check for the password and login are not used
1345 return the number of record 
1346 0=> NOT USED 1=> USED
1347
1348 =cut
1349
1350 sub checkuserpassword {
1351     my ( $borrowernumber, $userid, $password ) = @_;
1352     $password = md5_base64($password);
1353     my $dbh = C4::Context->dbh;
1354     my $sth =
1355       $dbh->prepare(
1356 "Select count(*) from borrowers where borrowernumber !=? and userid =? and password=? "
1357       );
1358     $sth->execute( $borrowernumber, $userid, $password );
1359     my $number_rows = $sth->fetchrow;
1360     return $number_rows;
1361
1362 }
1363
1364 =head2 GetborCatFromCatType
1365
1366   ($codes_arrayref, $labels_hashref) = &GetborCatFromCatType();
1367
1368 Looks up the different types of borrowers in the database. Returns two
1369 elements: a reference-to-array, which lists the borrower category
1370 codes, and a reference-to-hash, which maps the borrower category codes
1371 to category descriptions.
1372
1373 =cut
1374
1375 #'
1376 sub GetborCatFromCatType {
1377     my ( $category_type, $action ) = @_;
1378         # FIXME - This API  seems both limited and dangerous. 
1379     my $dbh     = C4::Context->dbh;
1380     my $request = qq|   SELECT categorycode,description 
1381             FROM categories 
1382             $action
1383             ORDER BY categorycode|;
1384     my $sth = $dbh->prepare($request);
1385         if ($action) {
1386         $sth->execute($category_type);
1387     }
1388     else {
1389         $sth->execute();
1390     }
1391
1392     my %labels;
1393     my @codes;
1394
1395     while ( my $data = $sth->fetchrow_hashref ) {
1396         push @codes, $data->{'categorycode'};
1397         $labels{ $data->{'categorycode'} } = $data->{'description'};
1398     }
1399     return ( \@codes, \%labels );
1400 }
1401
1402 =head2 GetBorrowercategory
1403
1404   $hashref = &GetBorrowercategory($categorycode);
1405
1406 Given the borrower's category code, the function returns the corresponding
1407 data hashref for a comprehensive information display.
1408
1409 =cut
1410
1411 sub GetBorrowercategory {
1412     my ($catcode) = @_;
1413     my $dbh       = C4::Context->dbh;
1414     if ($catcode){
1415         my $sth       =
1416         $dbh->prepare(
1417     "SELECT description,dateofbirthrequired,upperagelimit,category_type 
1418     FROM categories 
1419     WHERE categorycode = ?"
1420         );
1421         $sth->execute($catcode);
1422         my $data =
1423         $sth->fetchrow_hashref;
1424         return $data;
1425     } 
1426     return;  
1427 }    # sub getborrowercategory
1428
1429
1430 =head2 GetBorrowerCategorycode
1431
1432     $categorycode = &GetBorrowerCategoryCode( $borrowernumber );
1433
1434 Given the borrowernumber, the function returns the corresponding categorycode
1435 =cut
1436
1437 sub GetBorrowerCategorycode {
1438     my ( $borrowernumber ) = @_;
1439     my $dbh = C4::Context->dbh;
1440     my $sth = $dbh->prepare( qq{
1441         SELECT categorycode
1442         FROM borrowers
1443         WHERE borrowernumber = ?
1444     } );
1445     $sth->execute( $borrowernumber );
1446     return $sth->fetchrow;
1447 }
1448
1449 =head2 GetBorrowercategoryList
1450
1451   $arrayref_hashref = &GetBorrowercategoryList;
1452 If no category code provided, the function returns all the categories.
1453
1454 =cut
1455
1456 sub GetBorrowercategoryList {
1457     my $dbh       = C4::Context->dbh;
1458     my $sth       =
1459     $dbh->prepare(
1460     "SELECT * 
1461     FROM categories 
1462     ORDER BY description"
1463         );
1464     $sth->execute;
1465     my $data =
1466     $sth->fetchall_arrayref({});
1467     return $data;
1468 }    # sub getborrowercategory
1469
1470 =head2 ethnicitycategories
1471
1472   ($codes_arrayref, $labels_hashref) = &ethnicitycategories();
1473
1474 Looks up the different ethnic types in the database. Returns two
1475 elements: a reference-to-array, which lists the ethnicity codes, and a
1476 reference-to-hash, which maps the ethnicity codes to ethnicity
1477 descriptions.
1478
1479 =cut
1480
1481 #'
1482
1483 sub ethnicitycategories {
1484     my $dbh = C4::Context->dbh;
1485     my $sth = $dbh->prepare("Select code,name from ethnicity order by name");
1486     $sth->execute;
1487     my %labels;
1488     my @codes;
1489     while ( my $data = $sth->fetchrow_hashref ) {
1490         push @codes, $data->{'code'};
1491         $labels{ $data->{'code'} } = $data->{'name'};
1492     }
1493     return ( \@codes, \%labels );
1494 }
1495
1496 =head2 fixEthnicity
1497
1498   $ethn_name = &fixEthnicity($ethn_code);
1499
1500 Takes an ethnicity code (e.g., "european" or "pi") and returns the
1501 corresponding descriptive name from the C<ethnicity> table in the
1502 Koha database ("European" or "Pacific Islander").
1503
1504 =cut
1505
1506 #'
1507
1508 sub fixEthnicity {
1509     my $ethnicity = shift;
1510     return unless $ethnicity;
1511     my $dbh       = C4::Context->dbh;
1512     my $sth       = $dbh->prepare("Select name from ethnicity where code = ?");
1513     $sth->execute($ethnicity);
1514     my $data = $sth->fetchrow_hashref;
1515     return $data->{'name'};
1516 }    # sub fixEthnicity
1517
1518 =head2 GetAge
1519
1520   $dateofbirth,$date = &GetAge($date);
1521
1522 this function return the borrowers age with the value of dateofbirth
1523
1524 =cut
1525
1526 #'
1527 sub GetAge{
1528     my ( $date, $date_ref ) = @_;
1529
1530     if ( not defined $date_ref ) {
1531         $date_ref = sprintf( '%04d-%02d-%02d', Today() );
1532     }
1533
1534     my ( $year1, $month1, $day1 ) = split /-/, $date;
1535     my ( $year2, $month2, $day2 ) = split /-/, $date_ref;
1536
1537     my $age = $year2 - $year1;
1538     if ( $month1 . $day1 > $month2 . $day2 ) {
1539         $age--;
1540     }
1541
1542     return $age;
1543 }    # sub get_age
1544
1545 =head2 get_institutions
1546
1547   $insitutions = get_institutions();
1548
1549 Just returns a list of all the borrowers of type I, borrownumber and name
1550
1551 =cut
1552
1553 #'
1554 sub get_institutions {
1555     my $dbh = C4::Context->dbh();
1556     my $sth =
1557       $dbh->prepare(
1558 "SELECT borrowernumber,surname FROM borrowers WHERE categorycode=? ORDER BY surname"
1559       );
1560     $sth->execute('I');
1561     my %orgs;
1562     while ( my $data = $sth->fetchrow_hashref() ) {
1563         $orgs{ $data->{'borrowernumber'} } = $data;
1564     }
1565     return ( \%orgs );
1566
1567 }    # sub get_institutions
1568
1569 =head2 add_member_orgs
1570
1571   add_member_orgs($borrowernumber,$borrowernumbers);
1572
1573 Takes a borrowernumber and a list of other borrowernumbers and inserts them into the borrowers_to_borrowers table
1574
1575 =cut
1576
1577 #'
1578 sub add_member_orgs {
1579     my ( $borrowernumber, $otherborrowers ) = @_;
1580     my $dbh   = C4::Context->dbh();
1581     my $query =
1582       "INSERT INTO borrowers_to_borrowers (borrower1,borrower2) VALUES (?,?)";
1583     my $sth = $dbh->prepare($query);
1584     foreach my $otherborrowernumber (@$otherborrowers) {
1585         $sth->execute( $borrowernumber, $otherborrowernumber );
1586     }
1587
1588 }    # sub add_member_orgs
1589
1590 =head2 GetCities
1591
1592   $cityarrayref = GetCities();
1593
1594   Returns an array_ref of the entries in the cities table
1595   If there are entries in the table an empty row is returned
1596   This is currently only used to populate a popup in memberentry
1597
1598 =cut
1599
1600 sub GetCities {
1601
1602     my $dbh   = C4::Context->dbh;
1603     my $city_arr = $dbh->selectall_arrayref(
1604         q|SELECT cityid,city_zipcode,city_name,city_state,city_country FROM cities ORDER BY city_name|,
1605         { Slice => {} });
1606     if ( @{$city_arr} ) {
1607         unshift @{$city_arr}, {
1608             city_zipcode => q{},
1609             city_name    => q{},
1610             cityid       => q{},
1611             city_state   => q{},
1612             city_country => q{},
1613         };
1614     }
1615
1616     return  $city_arr;
1617 }
1618
1619 =head2 GetSortDetails (OUEST-PROVENCE)
1620
1621   ($lib) = &GetSortDetails($category,$sortvalue);
1622
1623 Returns the authorized value  details
1624 C<&$lib>return value of authorized value details
1625 C<&$sortvalue>this is the value of authorized value 
1626 C<&$category>this is the value of authorized value category
1627
1628 =cut
1629
1630 sub GetSortDetails {
1631     my ( $category, $sortvalue ) = @_;
1632     my $dbh   = C4::Context->dbh;
1633     my $query = qq|SELECT lib 
1634         FROM authorised_values 
1635         WHERE category=?
1636         AND authorised_value=? |;
1637     my $sth = $dbh->prepare($query);
1638     $sth->execute( $category, $sortvalue );
1639     my $lib = $sth->fetchrow;
1640     return ($lib) if ($lib);
1641     return ($sortvalue) unless ($lib);
1642 }
1643
1644 =head2 MoveMemberToDeleted
1645
1646   $result = &MoveMemberToDeleted($borrowernumber);
1647
1648 Copy the record from borrowers to deletedborrowers table.
1649
1650 =cut
1651
1652 # FIXME: should do it in one SQL statement w/ subquery
1653 # Otherwise, we should return the @data on success
1654
1655 sub MoveMemberToDeleted {
1656     my ($member) = shift or return;
1657     my $dbh = C4::Context->dbh;
1658     my $query = qq|SELECT * 
1659           FROM borrowers 
1660           WHERE borrowernumber=?|;
1661     my $sth = $dbh->prepare($query);
1662     $sth->execute($member);
1663     my @data = $sth->fetchrow_array;
1664     (@data) or return;  # if we got a bad borrowernumber, there's nothing to insert
1665     $sth =
1666       $dbh->prepare( "INSERT INTO deletedborrowers VALUES ("
1667           . ( "?," x ( scalar(@data) - 1 ) )
1668           . "?)" );
1669     $sth->execute(@data);
1670 }
1671
1672 =head2 DelMember
1673
1674     DelMember($borrowernumber);
1675
1676 This function remove directly a borrower whitout writing it on deleteborrower.
1677 + Deletes reserves for the borrower
1678
1679 =cut
1680
1681 sub DelMember {
1682     my $dbh            = C4::Context->dbh;
1683     my $borrowernumber = shift;
1684     #warn "in delmember with $borrowernumber";
1685     return unless $borrowernumber;    # borrowernumber is mandatory.
1686
1687     my $query = qq|DELETE 
1688           FROM  reserves 
1689           WHERE borrowernumber=?|;
1690     my $sth = $dbh->prepare($query);
1691     $sth->execute($borrowernumber);
1692     $query = "
1693        DELETE
1694        FROM borrowers
1695        WHERE borrowernumber = ?
1696    ";
1697     $sth = $dbh->prepare($query);
1698     $sth->execute($borrowernumber);
1699     logaction("MEMBERS", "DELETE", $borrowernumber, "") if C4::Context->preference("BorrowersLog");
1700     return $sth->rows;
1701 }
1702
1703 =head2 ExtendMemberSubscriptionTo (OUEST-PROVENCE)
1704
1705     $date = ExtendMemberSubscriptionTo($borrowerid, $date);
1706
1707 Extending the subscription to a given date or to the expiry date calculated on ISO date.
1708 Returns ISO date.
1709
1710 =cut
1711
1712 sub ExtendMemberSubscriptionTo {
1713     my ( $borrowerid,$date) = @_;
1714     my $dbh = C4::Context->dbh;
1715     my $borrower = GetMember('borrowernumber'=>$borrowerid);
1716     unless ($date){
1717       $date = (C4::Context->preference('BorrowerRenewalPeriodBase') eq 'dateexpiry') ?
1718                                         C4::Dates->new($borrower->{'dateexpiry'}, 'iso')->output("iso") :
1719                                         C4::Dates->new()->output("iso");
1720       $date = GetExpiryDate( $borrower->{'categorycode'}, $date );
1721     }
1722     my $sth = $dbh->do(<<EOF);
1723 UPDATE borrowers 
1724 SET  dateexpiry='$date' 
1725 WHERE borrowernumber='$borrowerid'
1726 EOF
1727     # add enrolmentfee if needed
1728     $sth = $dbh->prepare("SELECT enrolmentfee FROM categories WHERE categorycode=?");
1729     $sth->execute($borrower->{'categorycode'});
1730     my ($enrolmentfee) = $sth->fetchrow;
1731     if ($enrolmentfee && $enrolmentfee > 0) {
1732         # insert fee in patron debts
1733         manualinvoice($borrower->{'borrowernumber'}, '', '', 'A', $enrolmentfee);
1734     }
1735      logaction("MEMBERS", "RENEW", $borrower->{'borrowernumber'}, "Membership renewed")if C4::Context->preference("BorrowersLog");
1736     return $date if ($sth);
1737     return 0;
1738 }
1739
1740 =head2 GetRoadTypes (OUEST-PROVENCE)
1741
1742   ($idroadtypearrayref, $roadttype_hashref) = &GetRoadTypes();
1743
1744 Looks up the different road type . Returns two
1745 elements: a reference-to-array, which lists the id_roadtype
1746 codes, and a reference-to-hash, which maps the road type of the road .
1747
1748 =cut
1749
1750 sub GetRoadTypes {
1751     my $dbh   = C4::Context->dbh;
1752     my $query = qq|
1753 SELECT roadtypeid,road_type 
1754 FROM roadtype 
1755 ORDER BY road_type|;
1756     my $sth = $dbh->prepare($query);
1757     $sth->execute();
1758     my %roadtype;
1759     my @id;
1760
1761     #    insert empty value to create a empty choice in cgi popup
1762
1763     while ( my $data = $sth->fetchrow_hashref ) {
1764
1765         push @id, $data->{'roadtypeid'};
1766         $roadtype{ $data->{'roadtypeid'} } = $data->{'road_type'};
1767     }
1768
1769 #test to know if the table contain some records if no the function return nothing
1770     my $id = @id;
1771     if ( $id eq 0 ) {
1772         return ();
1773     }
1774     else {
1775         unshift( @id, "" );
1776         return ( \@id, \%roadtype );
1777     }
1778 }
1779
1780
1781
1782 =head2 GetTitles (OUEST-PROVENCE)
1783
1784   ($borrowertitle)= &GetTitles();
1785
1786 Looks up the different title . Returns array  with all borrowers title
1787
1788 =cut
1789
1790 sub GetTitles {
1791     my @borrowerTitle = split (/,|\|/,C4::Context->preference('BorrowersTitles'));
1792     unshift( @borrowerTitle, "" );
1793     my $count=@borrowerTitle;
1794     if ($count == 1){
1795         return ();
1796     }
1797     else {
1798         return ( \@borrowerTitle);
1799     }
1800 }
1801
1802 =head2 GetPatronImage
1803
1804     my ($imagedata, $dberror) = GetPatronImage($cardnumber);
1805
1806 Returns the mimetype and binary image data of the image for the patron with the supplied cardnumber.
1807
1808 =cut
1809
1810 sub GetPatronImage {
1811     my ($cardnumber) = @_;
1812     warn "Cardnumber passed to GetPatronImage is $cardnumber" if $debug;
1813     my $dbh = C4::Context->dbh;
1814     my $query = 'SELECT mimetype, imagefile FROM patronimage WHERE cardnumber = ?';
1815     my $sth = $dbh->prepare($query);
1816     $sth->execute($cardnumber);
1817     my $imagedata = $sth->fetchrow_hashref;
1818     warn "Database error!" if $sth->errstr;
1819     return $imagedata, $sth->errstr;
1820 }
1821
1822 =head2 PutPatronImage
1823
1824     PutPatronImage($cardnumber, $mimetype, $imgfile);
1825
1826 Stores patron binary image data and mimetype in database.
1827 NOTE: This function is good for updating images as well as inserting new images in the database.
1828
1829 =cut
1830
1831 sub PutPatronImage {
1832     my ($cardnumber, $mimetype, $imgfile) = @_;
1833     warn "Parameters passed in: Cardnumber=$cardnumber, Mimetype=$mimetype, " . ($imgfile ? "Imagefile" : "No Imagefile") if $debug;
1834     my $dbh = C4::Context->dbh;
1835     my $query = "INSERT INTO patronimage (cardnumber, mimetype, imagefile) VALUES (?,?,?) ON DUPLICATE KEY UPDATE imagefile = ?;";
1836     my $sth = $dbh->prepare($query);
1837     $sth->execute($cardnumber,$mimetype,$imgfile,$imgfile);
1838     warn "Error returned inserting $cardnumber.$mimetype." if $sth->errstr;
1839     return $sth->errstr;
1840 }
1841
1842 =head2 RmPatronImage
1843
1844     my ($dberror) = RmPatronImage($cardnumber);
1845
1846 Removes the image for the patron with the supplied cardnumber.
1847
1848 =cut
1849
1850 sub RmPatronImage {
1851     my ($cardnumber) = @_;
1852     warn "Cardnumber passed to GetPatronImage is $cardnumber" if $debug;
1853     my $dbh = C4::Context->dbh;
1854     my $query = "DELETE FROM patronimage WHERE cardnumber = ?;";
1855     my $sth = $dbh->prepare($query);
1856     $sth->execute($cardnumber);
1857     my $dberror = $sth->errstr;
1858     warn "Database error!" if $sth->errstr;
1859     return $dberror;
1860 }
1861
1862 =head2 GetHideLostItemsPreference
1863
1864   $hidelostitemspref = &GetHideLostItemsPreference($borrowernumber);
1865
1866 Returns the HideLostItems preference for the patron category of the supplied borrowernumber
1867 C<&$hidelostitemspref>return value of function, 0 or 1
1868
1869 =cut
1870
1871 sub GetHideLostItemsPreference {
1872     my ($borrowernumber) = @_;
1873     my $dbh = C4::Context->dbh;
1874     my $query = "SELECT hidelostitems FROM borrowers,categories WHERE borrowers.categorycode = categories.categorycode AND borrowernumber = ?";
1875     my $sth = $dbh->prepare($query);
1876     $sth->execute($borrowernumber);
1877     my $hidelostitems = $sth->fetchrow;    
1878     return $hidelostitems;    
1879 }
1880
1881 =head2 GetRoadTypeDetails (OUEST-PROVENCE)
1882
1883   ($roadtype) = &GetRoadTypeDetails($roadtypeid);
1884
1885 Returns the description of roadtype
1886 C<&$roadtype>return description of road type
1887 C<&$roadtypeid>this is the value of roadtype s
1888
1889 =cut
1890
1891 sub GetRoadTypeDetails {
1892     my ($roadtypeid) = @_;
1893     my $dbh          = C4::Context->dbh;
1894     my $query        = qq|
1895 SELECT road_type 
1896 FROM roadtype 
1897 WHERE roadtypeid=?|;
1898     my $sth = $dbh->prepare($query);
1899     $sth->execute($roadtypeid);
1900     my $roadtype = $sth->fetchrow;
1901     return ($roadtype);
1902 }
1903
1904 =head2 GetBorrowersWhoHaveNotBorrowedSince
1905
1906   &GetBorrowersWhoHaveNotBorrowedSince($date)
1907
1908 this function get all borrowers who haven't borrowed since the date given on input arg.
1909
1910 =cut
1911
1912 sub GetBorrowersWhoHaveNotBorrowedSince {
1913     my $filterdate = shift||POSIX::strftime("%Y-%m-%d",localtime());
1914     my $filterexpiry = shift;
1915     my $filterbranch = shift || 
1916                         ((C4::Context->preference('IndependantBranches') 
1917                              && C4::Context->userenv 
1918                              && C4::Context->userenv->{flags} % 2 !=1 
1919                              && C4::Context->userenv->{branch})
1920                          ? C4::Context->userenv->{branch}
1921                          : "");  
1922     my $dbh   = C4::Context->dbh;
1923     my $query = "
1924         SELECT borrowers.borrowernumber,
1925                max(old_issues.timestamp) as latestissue,
1926                max(issues.timestamp) as currentissue
1927         FROM   borrowers
1928         JOIN   categories USING (categorycode)
1929         LEFT JOIN old_issues USING (borrowernumber)
1930         LEFT JOIN issues USING (borrowernumber) 
1931         WHERE  category_type <> 'S'
1932         AND borrowernumber NOT IN (SELECT guarantorid FROM borrowers WHERE guarantorid IS NOT NULL AND guarantorid <> 0) 
1933    ";
1934     my @query_params;
1935     if ($filterbranch && $filterbranch ne ""){ 
1936         $query.=" AND borrowers.branchcode= ?";
1937         push @query_params,$filterbranch;
1938     }
1939     if($filterexpiry){
1940         $query .= " AND dateexpiry < ? ";
1941         push @query_params,$filterdate;
1942     }
1943     $query.=" GROUP BY borrowers.borrowernumber";
1944     if ($filterdate){ 
1945         $query.=" HAVING (latestissue < ? OR latestissue IS NULL) 
1946                   AND currentissue IS NULL";
1947         push @query_params,$filterdate;
1948     }
1949     warn $query if $debug;
1950     my $sth = $dbh->prepare($query);
1951     if (scalar(@query_params)>0){  
1952         $sth->execute(@query_params);
1953     } 
1954     else {
1955         $sth->execute;
1956     }      
1957     
1958     my @results;
1959     while ( my $data = $sth->fetchrow_hashref ) {
1960         push @results, $data;
1961     }
1962     return \@results;
1963 }
1964
1965 =head2 GetBorrowersWhoHaveNeverBorrowed
1966
1967   $results = &GetBorrowersWhoHaveNeverBorrowed
1968
1969 This function get all borrowers who have never borrowed.
1970
1971 I<$result> is a ref to an array which all elements are a hasref.
1972
1973 =cut
1974
1975 sub GetBorrowersWhoHaveNeverBorrowed {
1976     my $filterbranch = shift || 
1977                         ((C4::Context->preference('IndependantBranches') 
1978                              && C4::Context->userenv 
1979                              && C4::Context->userenv->{flags} % 2 !=1 
1980                              && C4::Context->userenv->{branch})
1981                          ? C4::Context->userenv->{branch}
1982                          : "");  
1983     my $dbh   = C4::Context->dbh;
1984     my $query = "
1985         SELECT borrowers.borrowernumber,max(timestamp) as latestissue
1986         FROM   borrowers
1987           LEFT JOIN issues ON borrowers.borrowernumber = issues.borrowernumber
1988         WHERE issues.borrowernumber IS NULL
1989    ";
1990     my @query_params;
1991     if ($filterbranch && $filterbranch ne ""){ 
1992         $query.=" AND borrowers.branchcode= ?";
1993         push @query_params,$filterbranch;
1994     }
1995     warn $query if $debug;
1996   
1997     my $sth = $dbh->prepare($query);
1998     if (scalar(@query_params)>0){  
1999         $sth->execute(@query_params);
2000     } 
2001     else {
2002         $sth->execute;
2003     }      
2004     
2005     my @results;
2006     while ( my $data = $sth->fetchrow_hashref ) {
2007         push @results, $data;
2008     }
2009     return \@results;
2010 }
2011
2012 =head2 GetBorrowersWithIssuesHistoryOlderThan
2013
2014   $results = &GetBorrowersWithIssuesHistoryOlderThan($date)
2015
2016 this function get all borrowers who has an issue history older than I<$date> given on input arg.
2017
2018 I<$result> is a ref to an array which all elements are a hashref.
2019 This hashref is containt the number of time this borrowers has borrowed before I<$date> and the borrowernumber.
2020
2021 =cut
2022
2023 sub GetBorrowersWithIssuesHistoryOlderThan {
2024     my $dbh  = C4::Context->dbh;
2025     my $date = shift ||POSIX::strftime("%Y-%m-%d",localtime());
2026     my $filterbranch = shift || 
2027                         ((C4::Context->preference('IndependantBranches') 
2028                              && C4::Context->userenv 
2029                              && C4::Context->userenv->{flags} % 2 !=1 
2030                              && C4::Context->userenv->{branch})
2031                          ? C4::Context->userenv->{branch}
2032                          : "");  
2033     my $query = "
2034        SELECT count(borrowernumber) as n,borrowernumber
2035        FROM old_issues
2036        WHERE returndate < ?
2037          AND borrowernumber IS NOT NULL 
2038     "; 
2039     my @query_params;
2040     push @query_params, $date;
2041     if ($filterbranch){
2042         $query.="   AND branchcode = ?";
2043         push @query_params, $filterbranch;
2044     }    
2045     $query.=" GROUP BY borrowernumber ";
2046     warn $query if $debug;
2047     my $sth = $dbh->prepare($query);
2048     $sth->execute(@query_params);
2049     my @results;
2050
2051     while ( my $data = $sth->fetchrow_hashref ) {
2052         push @results, $data;
2053     }
2054     return \@results;
2055 }
2056
2057 =head2 GetBorrowersNamesAndLatestIssue
2058
2059   $results = &GetBorrowersNamesAndLatestIssueList(@borrowernumbers)
2060
2061 this function get borrowers Names and surnames and Issue information.
2062
2063 I<@borrowernumbers> is an array which all elements are borrowernumbers.
2064 This hashref is containt the number of time this borrowers has borrowed before I<$date> and the borrowernumber.
2065
2066 =cut
2067
2068 sub GetBorrowersNamesAndLatestIssue {
2069     my $dbh  = C4::Context->dbh;
2070     my @borrowernumbers=@_;  
2071     my $query = "
2072        SELECT surname,lastname, phone, email,max(timestamp)
2073        FROM borrowers 
2074          LEFT JOIN issues ON borrowers.borrowernumber=issues.borrowernumber
2075        GROUP BY borrowernumber
2076    ";
2077     my $sth = $dbh->prepare($query);
2078     $sth->execute;
2079     my $results = $sth->fetchall_arrayref({});
2080     return $results;
2081 }
2082
2083 =head2 DebarMember
2084
2085 my $success = DebarMember( $borrowernumber, $todate );
2086
2087 marks a Member as debarred, and therefore unable to checkout any more
2088 items.
2089
2090 return :
2091 true on success, false on failure
2092
2093 =cut
2094
2095 sub DebarMember {
2096     my $borrowernumber = shift;
2097     my $todate         = shift;
2098
2099     return unless defined $borrowernumber;
2100     return unless $borrowernumber =~ /^\d+$/;
2101
2102     return ModMember(
2103         borrowernumber => $borrowernumber,
2104         debarred       => $todate
2105     );
2106
2107 }
2108
2109 =head2 ModPrivacy
2110
2111 =over 4
2112
2113 my $success = ModPrivacy( $borrowernumber, $privacy );
2114
2115 Update the privacy of a patron.
2116
2117 return :
2118 true on success, false on failure
2119
2120 =back
2121
2122 =cut
2123
2124 sub ModPrivacy {
2125     my $borrowernumber = shift;
2126     my $privacy = shift;
2127     return unless defined $borrowernumber;
2128     return unless $borrowernumber =~ /^\d+$/;
2129
2130     return ModMember( borrowernumber => $borrowernumber,
2131                       privacy        => $privacy );
2132 }
2133
2134 =head2 AddMessage
2135
2136   AddMessage( $borrowernumber, $message_type, $message, $branchcode );
2137
2138 Adds a message to the messages table for the given borrower.
2139
2140 Returns:
2141   True on success
2142   False on failure
2143
2144 =cut
2145
2146 sub AddMessage {
2147     my ( $borrowernumber, $message_type, $message, $branchcode ) = @_;
2148
2149     my $dbh  = C4::Context->dbh;
2150
2151     if ( ! ( $borrowernumber && $message_type && $message && $branchcode ) ) {
2152       return;
2153     }
2154
2155     my $query = "INSERT INTO messages ( borrowernumber, branchcode, message_type, message ) VALUES ( ?, ?, ?, ? )";
2156     my $sth = $dbh->prepare($query);
2157     $sth->execute( $borrowernumber, $branchcode, $message_type, $message );
2158     logaction("MEMBERS", "ADDCIRCMESSAGE", $borrowernumber, $message) if C4::Context->preference("BorrowersLog");
2159     return 1;
2160 }
2161
2162 =head2 GetMessages
2163
2164   GetMessages( $borrowernumber, $type );
2165
2166 $type is message type, B for borrower, or L for Librarian.
2167 Empty type returns all messages of any type.
2168
2169 Returns all messages for the given borrowernumber
2170
2171 =cut
2172
2173 sub GetMessages {
2174     my ( $borrowernumber, $type, $branchcode ) = @_;
2175
2176     if ( ! $type ) {
2177       $type = '%';
2178     }
2179
2180     my $dbh  = C4::Context->dbh;
2181
2182     my $query = "SELECT
2183                   branches.branchname,
2184                   messages.*,
2185                   message_date,
2186                   messages.branchcode LIKE '$branchcode' AS can_delete
2187                   FROM messages, branches
2188                   WHERE borrowernumber = ?
2189                   AND message_type LIKE ?
2190                   AND messages.branchcode = branches.branchcode
2191                   ORDER BY message_date DESC";
2192     my $sth = $dbh->prepare($query);
2193     $sth->execute( $borrowernumber, $type ) ;
2194     my @results;
2195
2196     while ( my $data = $sth->fetchrow_hashref ) {
2197         my $d = C4::Dates->new( $data->{message_date}, 'iso' );
2198         $data->{message_date_formatted} = $d->output;
2199         push @results, $data;
2200     }
2201     return \@results;
2202
2203 }
2204
2205 =head2 GetMessages
2206
2207   GetMessagesCount( $borrowernumber, $type );
2208
2209 $type is message type, B for borrower, or L for Librarian.
2210 Empty type returns all messages of any type.
2211
2212 Returns the number of messages for the given borrowernumber
2213
2214 =cut
2215
2216 sub GetMessagesCount {
2217     my ( $borrowernumber, $type, $branchcode ) = @_;
2218
2219     if ( ! $type ) {
2220       $type = '%';
2221     }
2222
2223     my $dbh  = C4::Context->dbh;
2224
2225     my $query = "SELECT COUNT(*) as MsgCount FROM messages WHERE borrowernumber = ? AND message_type LIKE ?";
2226     my $sth = $dbh->prepare($query);
2227     $sth->execute( $borrowernumber, $type ) ;
2228     my @results;
2229
2230     my $data = $sth->fetchrow_hashref;
2231     my $count = $data->{'MsgCount'};
2232
2233     return $count;
2234 }
2235
2236
2237
2238 =head2 DeleteMessage
2239
2240   DeleteMessage( $message_id );
2241
2242 =cut
2243
2244 sub DeleteMessage {
2245     my ( $message_id ) = @_;
2246
2247     my $dbh = C4::Context->dbh;
2248     my $query = "SELECT * FROM messages WHERE message_id = ?";
2249     my $sth = $dbh->prepare($query);
2250     $sth->execute( $message_id );
2251     my $message = $sth->fetchrow_hashref();
2252
2253     $query = "DELETE FROM messages WHERE message_id = ?";
2254     $sth = $dbh->prepare($query);
2255     $sth->execute( $message_id );
2256     logaction("MEMBERS", "DELCIRCMESSAGE", $message->{'borrowernumber'}, $message->{'message'}) if C4::Context->preference("BorrowersLog");
2257 }
2258
2259 =head2 IssueSlip
2260
2261   IssueSlip($branchcode, $borrowernumber, $quickslip)
2262
2263   Returns letter hash ( see C4::Letters::GetPreparedLetter )
2264
2265   $quickslip is boolean, to indicate whether we want a quick slip
2266
2267 =cut
2268
2269 sub IssueSlip {
2270     my ($branch, $borrowernumber, $quickslip) = @_;
2271
2272 #   return unless ( C4::Context->boolean_preference('printcirculationslips') );
2273
2274     my $now       = POSIX::strftime("%Y-%m-%d", localtime);
2275
2276     my $issueslist = GetPendingIssues($borrowernumber);
2277     foreach my $it (@$issueslist){
2278         if ((substr $it->{'issuedate'}, 0, 10) eq $now) {
2279             $it->{'now'} = 1;
2280         }
2281         elsif ((substr $it->{'date_due'}, 0, 10) le $now) {
2282             $it->{'overdue'} = 1;
2283         }
2284
2285         $it->{'date_due'}=format_date($it->{'date_due'});
2286     }
2287     my @issues = sort { $b->{'timestamp'} <=> $a->{'timestamp'} } @$issueslist;
2288
2289     my ($letter_code, %repeat);
2290     if ( $quickslip ) {
2291         $letter_code = 'ISSUEQSLIP';
2292         %repeat =  (
2293             'checkedout' => [ map {
2294                 'biblio' => $_,
2295                 'items'  => $_,
2296                 'issues' => $_,
2297             }, grep { $_->{'now'} } @issues ],
2298         );
2299     }
2300     else {
2301         $letter_code = 'ISSUESLIP';
2302         %repeat =  (
2303             'checkedout' => [ map {
2304                 'biblio' => $_,
2305                 'items'  => $_,
2306                 'issues' => $_,
2307             }, grep { !$_->{'overdue'} } @issues ],
2308
2309             'overdue' => [ map {
2310                 'biblio' => $_,
2311                 'items'  => $_,
2312                 'issues' => $_,
2313             }, grep { $_->{'overdue'} } @issues ],
2314
2315             'news' => [ map {
2316                 $_->{'timestamp'} = $_->{'newdate'};
2317                 { opac_news => $_ }
2318             } @{ GetNewsToDisplay("slip") } ],
2319         );
2320     }
2321
2322     return  C4::Letters::GetPreparedLetter (
2323         module => 'circulation',
2324         letter_code => $letter_code,
2325         branchcode => $branch,
2326         tables => {
2327             'branches'    => $branch,
2328             'borrowers'   => $borrowernumber,
2329         },
2330         repeat => \%repeat,
2331     );
2332 }
2333
2334 =head2 GetBorrowersWithEmail
2335
2336     ([$borrnum,$userid], ...) = GetBorrowersWithEmail('me@example.com');
2337
2338 This gets a list of users and their basic details from their email address.
2339 As it's possible for multiple user to have the same email address, it provides
2340 you with all of them. If there is no userid for the user, there will be an
2341 C<undef> there. An empty list will be returned if there are no matches.
2342
2343 =cut
2344
2345 sub GetBorrowersWithEmail {
2346     my $email = shift;
2347
2348     my $dbh = C4::Context->dbh;
2349
2350     my $query = "SELECT borrowernumber, userid FROM borrowers WHERE email=?";
2351     my $sth=$dbh->prepare($query);
2352     $sth->execute($email);
2353     my @result = ();
2354     while (my $ref = $sth->fetch) {
2355         push @result, $ref;
2356     }
2357     die "Failure searching for borrowers by email address: $sth->errstr" if $sth->err;
2358     return @result;
2359 }
2360
2361
2362 END { }    # module clean-up code here (global destructor)
2363
2364 1;
2365
2366 __END__
2367
2368 =head1 AUTHOR
2369
2370 Koha Team
2371
2372 =cut