Bug 7919 : Display of values depending on the connexion library
[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, $no_branch_limit ) = @_;
1378
1379     my $branch_limit = $no_branch_limit
1380         ? 0
1381         : C4::Context->userenv ? C4::Context->userenv->{"branch"} : "";
1382
1383     # FIXME - This API  seems both limited and dangerous.
1384     my $dbh     = C4::Context->dbh;
1385
1386     my $request = qq{
1387         SELECT categories.categorycode, categories.description
1388         FROM categories
1389     };
1390     $request .= qq{
1391         LEFT JOIN categories_branches ON categories.categorycode = categories_branches.categorycode
1392     } if $branch_limit;
1393     if($action) {
1394         $request .= " $action ";
1395         $request .= " AND (branchcode = ? OR branchcode IS NULL) GROUP BY description" if $branch_limit;
1396     } else {
1397         $request .= " WHERE branchcode = ? OR branchcode IS NULL GROUP BY description" if $branch_limit;
1398     }
1399     $request .= " ORDER BY categorycode";
1400
1401     my $sth = $dbh->prepare($request);
1402     $sth->execute(
1403         $action ? $category_type : (),
1404         $branch_limit ? $branch_limit : ()
1405     );
1406
1407     my %labels;
1408     my @codes;
1409
1410     while ( my $data = $sth->fetchrow_hashref ) {
1411         push @codes, $data->{'categorycode'};
1412         $labels{ $data->{'categorycode'} } = $data->{'description'};
1413     }
1414     $sth->finish;
1415     return ( \@codes, \%labels );
1416 }
1417
1418 =head2 GetBorrowercategory
1419
1420   $hashref = &GetBorrowercategory($categorycode);
1421
1422 Given the borrower's category code, the function returns the corresponding
1423 data hashref for a comprehensive information display.
1424
1425 =cut
1426
1427 sub GetBorrowercategory {
1428     my ($catcode) = @_;
1429     my $dbh       = C4::Context->dbh;
1430     if ($catcode){
1431         my $sth       =
1432         $dbh->prepare(
1433     "SELECT description,dateofbirthrequired,upperagelimit,category_type 
1434     FROM categories 
1435     WHERE categorycode = ?"
1436         );
1437         $sth->execute($catcode);
1438         my $data =
1439         $sth->fetchrow_hashref;
1440         return $data;
1441     } 
1442     return;  
1443 }    # sub getborrowercategory
1444
1445
1446 =head2 GetBorrowerCategorycode
1447
1448     $categorycode = &GetBorrowerCategoryCode( $borrowernumber );
1449
1450 Given the borrowernumber, the function returns the corresponding categorycode
1451 =cut
1452
1453 sub GetBorrowerCategorycode {
1454     my ( $borrowernumber ) = @_;
1455     my $dbh = C4::Context->dbh;
1456     my $sth = $dbh->prepare( qq{
1457         SELECT categorycode
1458         FROM borrowers
1459         WHERE borrowernumber = ?
1460     } );
1461     $sth->execute( $borrowernumber );
1462     return $sth->fetchrow;
1463 }
1464
1465 =head2 GetBorrowercategoryList
1466
1467   $arrayref_hashref = &GetBorrowercategoryList;
1468 If no category code provided, the function returns all the categories.
1469
1470 =cut
1471
1472 sub GetBorrowercategoryList {
1473     my $no_branch_limit = @_ ? shift : 0;
1474     my $branch_limit = $no_branch_limit
1475         ? 0
1476         : C4::Context->userenv ? C4::Context->userenv->{"branch"} : "";
1477     my $dbh       = C4::Context->dbh;
1478     my $query = "SELECT * FROM categories";
1479     $query .= qq{
1480         LEFT JOIN categories_branches ON categories.categorycode = categories_branches.categorycode
1481         WHERE branchcode = ? OR branchcode IS NULL GROUP BY description
1482     } if $branch_limit;
1483     $query .= " ORDER BY description";
1484     my $sth = $dbh->prepare( $query );
1485     $sth->execute( $branch_limit ? $branch_limit : () );
1486     my $data = $sth->fetchall_arrayref( {} );
1487     $sth->finish;
1488     return $data;
1489 }    # sub getborrowercategory
1490
1491 =head2 ethnicitycategories
1492
1493   ($codes_arrayref, $labels_hashref) = &ethnicitycategories();
1494
1495 Looks up the different ethnic types in the database. Returns two
1496 elements: a reference-to-array, which lists the ethnicity codes, and a
1497 reference-to-hash, which maps the ethnicity codes to ethnicity
1498 descriptions.
1499
1500 =cut
1501
1502 #'
1503
1504 sub ethnicitycategories {
1505     my $dbh = C4::Context->dbh;
1506     my $sth = $dbh->prepare("Select code,name from ethnicity order by name");
1507     $sth->execute;
1508     my %labels;
1509     my @codes;
1510     while ( my $data = $sth->fetchrow_hashref ) {
1511         push @codes, $data->{'code'};
1512         $labels{ $data->{'code'} } = $data->{'name'};
1513     }
1514     return ( \@codes, \%labels );
1515 }
1516
1517 =head2 fixEthnicity
1518
1519   $ethn_name = &fixEthnicity($ethn_code);
1520
1521 Takes an ethnicity code (e.g., "european" or "pi") and returns the
1522 corresponding descriptive name from the C<ethnicity> table in the
1523 Koha database ("European" or "Pacific Islander").
1524
1525 =cut
1526
1527 #'
1528
1529 sub fixEthnicity {
1530     my $ethnicity = shift;
1531     return unless $ethnicity;
1532     my $dbh       = C4::Context->dbh;
1533     my $sth       = $dbh->prepare("Select name from ethnicity where code = ?");
1534     $sth->execute($ethnicity);
1535     my $data = $sth->fetchrow_hashref;
1536     return $data->{'name'};
1537 }    # sub fixEthnicity
1538
1539 =head2 GetAge
1540
1541   $dateofbirth,$date = &GetAge($date);
1542
1543 this function return the borrowers age with the value of dateofbirth
1544
1545 =cut
1546
1547 #'
1548 sub GetAge{
1549     my ( $date, $date_ref ) = @_;
1550
1551     if ( not defined $date_ref ) {
1552         $date_ref = sprintf( '%04d-%02d-%02d', Today() );
1553     }
1554
1555     my ( $year1, $month1, $day1 ) = split /-/, $date;
1556     my ( $year2, $month2, $day2 ) = split /-/, $date_ref;
1557
1558     my $age = $year2 - $year1;
1559     if ( $month1 . $day1 > $month2 . $day2 ) {
1560         $age--;
1561     }
1562
1563     return $age;
1564 }    # sub get_age
1565
1566 =head2 get_institutions
1567
1568   $insitutions = get_institutions();
1569
1570 Just returns a list of all the borrowers of type I, borrownumber and name
1571
1572 =cut
1573
1574 #'
1575 sub get_institutions {
1576     my $dbh = C4::Context->dbh();
1577     my $sth =
1578       $dbh->prepare(
1579 "SELECT borrowernumber,surname FROM borrowers WHERE categorycode=? ORDER BY surname"
1580       );
1581     $sth->execute('I');
1582     my %orgs;
1583     while ( my $data = $sth->fetchrow_hashref() ) {
1584         $orgs{ $data->{'borrowernumber'} } = $data;
1585     }
1586     return ( \%orgs );
1587
1588 }    # sub get_institutions
1589
1590 =head2 add_member_orgs
1591
1592   add_member_orgs($borrowernumber,$borrowernumbers);
1593
1594 Takes a borrowernumber and a list of other borrowernumbers and inserts them into the borrowers_to_borrowers table
1595
1596 =cut
1597
1598 #'
1599 sub add_member_orgs {
1600     my ( $borrowernumber, $otherborrowers ) = @_;
1601     my $dbh   = C4::Context->dbh();
1602     my $query =
1603       "INSERT INTO borrowers_to_borrowers (borrower1,borrower2) VALUES (?,?)";
1604     my $sth = $dbh->prepare($query);
1605     foreach my $otherborrowernumber (@$otherborrowers) {
1606         $sth->execute( $borrowernumber, $otherborrowernumber );
1607     }
1608
1609 }    # sub add_member_orgs
1610
1611 =head2 GetCities
1612
1613   $cityarrayref = GetCities();
1614
1615   Returns an array_ref of the entries in the cities table
1616   If there are entries in the table an empty row is returned
1617   This is currently only used to populate a popup in memberentry
1618
1619 =cut
1620
1621 sub GetCities {
1622
1623     my $dbh   = C4::Context->dbh;
1624     my $city_arr = $dbh->selectall_arrayref(
1625         q|SELECT cityid,city_zipcode,city_name,city_state,city_country FROM cities ORDER BY city_name|,
1626         { Slice => {} });
1627     if ( @{$city_arr} ) {
1628         unshift @{$city_arr}, {
1629             city_zipcode => q{},
1630             city_name    => q{},
1631             cityid       => q{},
1632             city_state   => q{},
1633             city_country => q{},
1634         };
1635     }
1636
1637     return  $city_arr;
1638 }
1639
1640 =head2 GetSortDetails (OUEST-PROVENCE)
1641
1642   ($lib) = &GetSortDetails($category,$sortvalue);
1643
1644 Returns the authorized value  details
1645 C<&$lib>return value of authorized value details
1646 C<&$sortvalue>this is the value of authorized value 
1647 C<&$category>this is the value of authorized value category
1648
1649 =cut
1650
1651 sub GetSortDetails {
1652     my ( $category, $sortvalue ) = @_;
1653     my $dbh   = C4::Context->dbh;
1654     my $query = qq|SELECT lib 
1655         FROM authorised_values 
1656         WHERE category=?
1657         AND authorised_value=? |;
1658     my $sth = $dbh->prepare($query);
1659     $sth->execute( $category, $sortvalue );
1660     my $lib = $sth->fetchrow;
1661     return ($lib) if ($lib);
1662     return ($sortvalue) unless ($lib);
1663 }
1664
1665 =head2 MoveMemberToDeleted
1666
1667   $result = &MoveMemberToDeleted($borrowernumber);
1668
1669 Copy the record from borrowers to deletedborrowers table.
1670
1671 =cut
1672
1673 # FIXME: should do it in one SQL statement w/ subquery
1674 # Otherwise, we should return the @data on success
1675
1676 sub MoveMemberToDeleted {
1677     my ($member) = shift or return;
1678     my $dbh = C4::Context->dbh;
1679     my $query = qq|SELECT * 
1680           FROM borrowers 
1681           WHERE borrowernumber=?|;
1682     my $sth = $dbh->prepare($query);
1683     $sth->execute($member);
1684     my @data = $sth->fetchrow_array;
1685     (@data) or return;  # if we got a bad borrowernumber, there's nothing to insert
1686     $sth =
1687       $dbh->prepare( "INSERT INTO deletedborrowers VALUES ("
1688           . ( "?," x ( scalar(@data) - 1 ) )
1689           . "?)" );
1690     $sth->execute(@data);
1691 }
1692
1693 =head2 DelMember
1694
1695     DelMember($borrowernumber);
1696
1697 This function remove directly a borrower whitout writing it on deleteborrower.
1698 + Deletes reserves for the borrower
1699
1700 =cut
1701
1702 sub DelMember {
1703     my $dbh            = C4::Context->dbh;
1704     my $borrowernumber = shift;
1705     #warn "in delmember with $borrowernumber";
1706     return unless $borrowernumber;    # borrowernumber is mandatory.
1707
1708     my $query = qq|DELETE 
1709           FROM  reserves 
1710           WHERE borrowernumber=?|;
1711     my $sth = $dbh->prepare($query);
1712     $sth->execute($borrowernumber);
1713     $query = "
1714        DELETE
1715        FROM borrowers
1716        WHERE borrowernumber = ?
1717    ";
1718     $sth = $dbh->prepare($query);
1719     $sth->execute($borrowernumber);
1720     logaction("MEMBERS", "DELETE", $borrowernumber, "") if C4::Context->preference("BorrowersLog");
1721     return $sth->rows;
1722 }
1723
1724 =head2 ExtendMemberSubscriptionTo (OUEST-PROVENCE)
1725
1726     $date = ExtendMemberSubscriptionTo($borrowerid, $date);
1727
1728 Extending the subscription to a given date or to the expiry date calculated on ISO date.
1729 Returns ISO date.
1730
1731 =cut
1732
1733 sub ExtendMemberSubscriptionTo {
1734     my ( $borrowerid,$date) = @_;
1735     my $dbh = C4::Context->dbh;
1736     my $borrower = GetMember('borrowernumber'=>$borrowerid);
1737     unless ($date){
1738       $date = (C4::Context->preference('BorrowerRenewalPeriodBase') eq 'dateexpiry') ?
1739                                         C4::Dates->new($borrower->{'dateexpiry'}, 'iso')->output("iso") :
1740                                         C4::Dates->new()->output("iso");
1741       $date = GetExpiryDate( $borrower->{'categorycode'}, $date );
1742     }
1743     my $sth = $dbh->do(<<EOF);
1744 UPDATE borrowers 
1745 SET  dateexpiry='$date' 
1746 WHERE borrowernumber='$borrowerid'
1747 EOF
1748     # add enrolmentfee if needed
1749     $sth = $dbh->prepare("SELECT enrolmentfee FROM categories WHERE categorycode=?");
1750     $sth->execute($borrower->{'categorycode'});
1751     my ($enrolmentfee) = $sth->fetchrow;
1752     if ($enrolmentfee && $enrolmentfee > 0) {
1753         # insert fee in patron debts
1754         manualinvoice($borrower->{'borrowernumber'}, '', '', 'A', $enrolmentfee);
1755     }
1756      logaction("MEMBERS", "RENEW", $borrower->{'borrowernumber'}, "Membership renewed")if C4::Context->preference("BorrowersLog");
1757     return $date if ($sth);
1758     return 0;
1759 }
1760
1761 =head2 GetRoadTypes (OUEST-PROVENCE)
1762
1763   ($idroadtypearrayref, $roadttype_hashref) = &GetRoadTypes();
1764
1765 Looks up the different road type . Returns two
1766 elements: a reference-to-array, which lists the id_roadtype
1767 codes, and a reference-to-hash, which maps the road type of the road .
1768
1769 =cut
1770
1771 sub GetRoadTypes {
1772     my $dbh   = C4::Context->dbh;
1773     my $query = qq|
1774 SELECT roadtypeid,road_type 
1775 FROM roadtype 
1776 ORDER BY road_type|;
1777     my $sth = $dbh->prepare($query);
1778     $sth->execute();
1779     my %roadtype;
1780     my @id;
1781
1782     #    insert empty value to create a empty choice in cgi popup
1783
1784     while ( my $data = $sth->fetchrow_hashref ) {
1785
1786         push @id, $data->{'roadtypeid'};
1787         $roadtype{ $data->{'roadtypeid'} } = $data->{'road_type'};
1788     }
1789
1790 #test to know if the table contain some records if no the function return nothing
1791     my $id = @id;
1792     if ( $id eq 0 ) {
1793         return ();
1794     }
1795     else {
1796         unshift( @id, "" );
1797         return ( \@id, \%roadtype );
1798     }
1799 }
1800
1801
1802
1803 =head2 GetTitles (OUEST-PROVENCE)
1804
1805   ($borrowertitle)= &GetTitles();
1806
1807 Looks up the different title . Returns array  with all borrowers title
1808
1809 =cut
1810
1811 sub GetTitles {
1812     my @borrowerTitle = split (/,|\|/,C4::Context->preference('BorrowersTitles'));
1813     unshift( @borrowerTitle, "" );
1814     my $count=@borrowerTitle;
1815     if ($count == 1){
1816         return ();
1817     }
1818     else {
1819         return ( \@borrowerTitle);
1820     }
1821 }
1822
1823 =head2 GetPatronImage
1824
1825     my ($imagedata, $dberror) = GetPatronImage($cardnumber);
1826
1827 Returns the mimetype and binary image data of the image for the patron with the supplied cardnumber.
1828
1829 =cut
1830
1831 sub GetPatronImage {
1832     my ($cardnumber) = @_;
1833     warn "Cardnumber passed to GetPatronImage is $cardnumber" if $debug;
1834     my $dbh = C4::Context->dbh;
1835     my $query = 'SELECT mimetype, imagefile FROM patronimage WHERE cardnumber = ?';
1836     my $sth = $dbh->prepare($query);
1837     $sth->execute($cardnumber);
1838     my $imagedata = $sth->fetchrow_hashref;
1839     warn "Database error!" if $sth->errstr;
1840     return $imagedata, $sth->errstr;
1841 }
1842
1843 =head2 PutPatronImage
1844
1845     PutPatronImage($cardnumber, $mimetype, $imgfile);
1846
1847 Stores patron binary image data and mimetype in database.
1848 NOTE: This function is good for updating images as well as inserting new images in the database.
1849
1850 =cut
1851
1852 sub PutPatronImage {
1853     my ($cardnumber, $mimetype, $imgfile) = @_;
1854     warn "Parameters passed in: Cardnumber=$cardnumber, Mimetype=$mimetype, " . ($imgfile ? "Imagefile" : "No Imagefile") if $debug;
1855     my $dbh = C4::Context->dbh;
1856     my $query = "INSERT INTO patronimage (cardnumber, mimetype, imagefile) VALUES (?,?,?) ON DUPLICATE KEY UPDATE imagefile = ?;";
1857     my $sth = $dbh->prepare($query);
1858     $sth->execute($cardnumber,$mimetype,$imgfile,$imgfile);
1859     warn "Error returned inserting $cardnumber.$mimetype." if $sth->errstr;
1860     return $sth->errstr;
1861 }
1862
1863 =head2 RmPatronImage
1864
1865     my ($dberror) = RmPatronImage($cardnumber);
1866
1867 Removes the image for the patron with the supplied cardnumber.
1868
1869 =cut
1870
1871 sub RmPatronImage {
1872     my ($cardnumber) = @_;
1873     warn "Cardnumber passed to GetPatronImage is $cardnumber" if $debug;
1874     my $dbh = C4::Context->dbh;
1875     my $query = "DELETE FROM patronimage WHERE cardnumber = ?;";
1876     my $sth = $dbh->prepare($query);
1877     $sth->execute($cardnumber);
1878     my $dberror = $sth->errstr;
1879     warn "Database error!" if $sth->errstr;
1880     return $dberror;
1881 }
1882
1883 =head2 GetHideLostItemsPreference
1884
1885   $hidelostitemspref = &GetHideLostItemsPreference($borrowernumber);
1886
1887 Returns the HideLostItems preference for the patron category of the supplied borrowernumber
1888 C<&$hidelostitemspref>return value of function, 0 or 1
1889
1890 =cut
1891
1892 sub GetHideLostItemsPreference {
1893     my ($borrowernumber) = @_;
1894     my $dbh = C4::Context->dbh;
1895     my $query = "SELECT hidelostitems FROM borrowers,categories WHERE borrowers.categorycode = categories.categorycode AND borrowernumber = ?";
1896     my $sth = $dbh->prepare($query);
1897     $sth->execute($borrowernumber);
1898     my $hidelostitems = $sth->fetchrow;    
1899     return $hidelostitems;    
1900 }
1901
1902 =head2 GetRoadTypeDetails (OUEST-PROVENCE)
1903
1904   ($roadtype) = &GetRoadTypeDetails($roadtypeid);
1905
1906 Returns the description of roadtype
1907 C<&$roadtype>return description of road type
1908 C<&$roadtypeid>this is the value of roadtype s
1909
1910 =cut
1911
1912 sub GetRoadTypeDetails {
1913     my ($roadtypeid) = @_;
1914     my $dbh          = C4::Context->dbh;
1915     my $query        = qq|
1916 SELECT road_type 
1917 FROM roadtype 
1918 WHERE roadtypeid=?|;
1919     my $sth = $dbh->prepare($query);
1920     $sth->execute($roadtypeid);
1921     my $roadtype = $sth->fetchrow;
1922     return ($roadtype);
1923 }
1924
1925 =head2 GetBorrowersWhoHaveNotBorrowedSince
1926
1927   &GetBorrowersWhoHaveNotBorrowedSince($date)
1928
1929 this function get all borrowers who haven't borrowed since the date given on input arg.
1930
1931 =cut
1932
1933 sub GetBorrowersWhoHaveNotBorrowedSince {
1934     my $filterdate = shift||POSIX::strftime("%Y-%m-%d",localtime());
1935     my $filterexpiry = shift;
1936     my $filterbranch = shift || 
1937                         ((C4::Context->preference('IndependantBranches') 
1938                              && C4::Context->userenv 
1939                              && C4::Context->userenv->{flags} % 2 !=1 
1940                              && C4::Context->userenv->{branch})
1941                          ? C4::Context->userenv->{branch}
1942                          : "");  
1943     my $dbh   = C4::Context->dbh;
1944     my $query = "
1945         SELECT borrowers.borrowernumber,
1946                max(old_issues.timestamp) as latestissue,
1947                max(issues.timestamp) as currentissue
1948         FROM   borrowers
1949         JOIN   categories USING (categorycode)
1950         LEFT JOIN old_issues USING (borrowernumber)
1951         LEFT JOIN issues USING (borrowernumber) 
1952         WHERE  category_type <> 'S'
1953         AND borrowernumber NOT IN (SELECT guarantorid FROM borrowers WHERE guarantorid IS NOT NULL AND guarantorid <> 0) 
1954    ";
1955     my @query_params;
1956     if ($filterbranch && $filterbranch ne ""){ 
1957         $query.=" AND borrowers.branchcode= ?";
1958         push @query_params,$filterbranch;
1959     }
1960     if($filterexpiry){
1961         $query .= " AND dateexpiry < ? ";
1962         push @query_params,$filterdate;
1963     }
1964     $query.=" GROUP BY borrowers.borrowernumber";
1965     if ($filterdate){ 
1966         $query.=" HAVING (latestissue < ? OR latestissue IS NULL) 
1967                   AND currentissue IS NULL";
1968         push @query_params,$filterdate;
1969     }
1970     warn $query if $debug;
1971     my $sth = $dbh->prepare($query);
1972     if (scalar(@query_params)>0){  
1973         $sth->execute(@query_params);
1974     } 
1975     else {
1976         $sth->execute;
1977     }      
1978     
1979     my @results;
1980     while ( my $data = $sth->fetchrow_hashref ) {
1981         push @results, $data;
1982     }
1983     return \@results;
1984 }
1985
1986 =head2 GetBorrowersWhoHaveNeverBorrowed
1987
1988   $results = &GetBorrowersWhoHaveNeverBorrowed
1989
1990 This function get all borrowers who have never borrowed.
1991
1992 I<$result> is a ref to an array which all elements are a hasref.
1993
1994 =cut
1995
1996 sub GetBorrowersWhoHaveNeverBorrowed {
1997     my $filterbranch = shift || 
1998                         ((C4::Context->preference('IndependantBranches') 
1999                              && C4::Context->userenv 
2000                              && C4::Context->userenv->{flags} % 2 !=1 
2001                              && C4::Context->userenv->{branch})
2002                          ? C4::Context->userenv->{branch}
2003                          : "");  
2004     my $dbh   = C4::Context->dbh;
2005     my $query = "
2006         SELECT borrowers.borrowernumber,max(timestamp) as latestissue
2007         FROM   borrowers
2008           LEFT JOIN issues ON borrowers.borrowernumber = issues.borrowernumber
2009         WHERE issues.borrowernumber IS NULL
2010    ";
2011     my @query_params;
2012     if ($filterbranch && $filterbranch ne ""){ 
2013         $query.=" AND borrowers.branchcode= ?";
2014         push @query_params,$filterbranch;
2015     }
2016     warn $query if $debug;
2017   
2018     my $sth = $dbh->prepare($query);
2019     if (scalar(@query_params)>0){  
2020         $sth->execute(@query_params);
2021     } 
2022     else {
2023         $sth->execute;
2024     }      
2025     
2026     my @results;
2027     while ( my $data = $sth->fetchrow_hashref ) {
2028         push @results, $data;
2029     }
2030     return \@results;
2031 }
2032
2033 =head2 GetBorrowersWithIssuesHistoryOlderThan
2034
2035   $results = &GetBorrowersWithIssuesHistoryOlderThan($date)
2036
2037 this function get all borrowers who has an issue history older than I<$date> given on input arg.
2038
2039 I<$result> is a ref to an array which all elements are a hashref.
2040 This hashref is containt the number of time this borrowers has borrowed before I<$date> and the borrowernumber.
2041
2042 =cut
2043
2044 sub GetBorrowersWithIssuesHistoryOlderThan {
2045     my $dbh  = C4::Context->dbh;
2046     my $date = shift ||POSIX::strftime("%Y-%m-%d",localtime());
2047     my $filterbranch = shift || 
2048                         ((C4::Context->preference('IndependantBranches') 
2049                              && C4::Context->userenv 
2050                              && C4::Context->userenv->{flags} % 2 !=1 
2051                              && C4::Context->userenv->{branch})
2052                          ? C4::Context->userenv->{branch}
2053                          : "");  
2054     my $query = "
2055        SELECT count(borrowernumber) as n,borrowernumber
2056        FROM old_issues
2057        WHERE returndate < ?
2058          AND borrowernumber IS NOT NULL 
2059     "; 
2060     my @query_params;
2061     push @query_params, $date;
2062     if ($filterbranch){
2063         $query.="   AND branchcode = ?";
2064         push @query_params, $filterbranch;
2065     }    
2066     $query.=" GROUP BY borrowernumber ";
2067     warn $query if $debug;
2068     my $sth = $dbh->prepare($query);
2069     $sth->execute(@query_params);
2070     my @results;
2071
2072     while ( my $data = $sth->fetchrow_hashref ) {
2073         push @results, $data;
2074     }
2075     return \@results;
2076 }
2077
2078 =head2 GetBorrowersNamesAndLatestIssue
2079
2080   $results = &GetBorrowersNamesAndLatestIssueList(@borrowernumbers)
2081
2082 this function get borrowers Names and surnames and Issue information.
2083
2084 I<@borrowernumbers> is an array which all elements are borrowernumbers.
2085 This hashref is containt the number of time this borrowers has borrowed before I<$date> and the borrowernumber.
2086
2087 =cut
2088
2089 sub GetBorrowersNamesAndLatestIssue {
2090     my $dbh  = C4::Context->dbh;
2091     my @borrowernumbers=@_;  
2092     my $query = "
2093        SELECT surname,lastname, phone, email,max(timestamp)
2094        FROM borrowers 
2095          LEFT JOIN issues ON borrowers.borrowernumber=issues.borrowernumber
2096        GROUP BY borrowernumber
2097    ";
2098     my $sth = $dbh->prepare($query);
2099     $sth->execute;
2100     my $results = $sth->fetchall_arrayref({});
2101     return $results;
2102 }
2103
2104 =head2 DebarMember
2105
2106 my $success = DebarMember( $borrowernumber, $todate );
2107
2108 marks a Member as debarred, and therefore unable to checkout any more
2109 items.
2110
2111 return :
2112 true on success, false on failure
2113
2114 =cut
2115
2116 sub DebarMember {
2117     my $borrowernumber = shift;
2118     my $todate         = shift;
2119
2120     return unless defined $borrowernumber;
2121     return unless $borrowernumber =~ /^\d+$/;
2122
2123     return ModMember(
2124         borrowernumber => $borrowernumber,
2125         debarred       => $todate
2126     );
2127
2128 }
2129
2130 =head2 ModPrivacy
2131
2132 =over 4
2133
2134 my $success = ModPrivacy( $borrowernumber, $privacy );
2135
2136 Update the privacy of a patron.
2137
2138 return :
2139 true on success, false on failure
2140
2141 =back
2142
2143 =cut
2144
2145 sub ModPrivacy {
2146     my $borrowernumber = shift;
2147     my $privacy = shift;
2148     return unless defined $borrowernumber;
2149     return unless $borrowernumber =~ /^\d+$/;
2150
2151     return ModMember( borrowernumber => $borrowernumber,
2152                       privacy        => $privacy );
2153 }
2154
2155 =head2 AddMessage
2156
2157   AddMessage( $borrowernumber, $message_type, $message, $branchcode );
2158
2159 Adds a message to the messages table for the given borrower.
2160
2161 Returns:
2162   True on success
2163   False on failure
2164
2165 =cut
2166
2167 sub AddMessage {
2168     my ( $borrowernumber, $message_type, $message, $branchcode ) = @_;
2169
2170     my $dbh  = C4::Context->dbh;
2171
2172     if ( ! ( $borrowernumber && $message_type && $message && $branchcode ) ) {
2173       return;
2174     }
2175
2176     my $query = "INSERT INTO messages ( borrowernumber, branchcode, message_type, message ) VALUES ( ?, ?, ?, ? )";
2177     my $sth = $dbh->prepare($query);
2178     $sth->execute( $borrowernumber, $branchcode, $message_type, $message );
2179     logaction("MEMBERS", "ADDCIRCMESSAGE", $borrowernumber, $message) if C4::Context->preference("BorrowersLog");
2180     return 1;
2181 }
2182
2183 =head2 GetMessages
2184
2185   GetMessages( $borrowernumber, $type );
2186
2187 $type is message type, B for borrower, or L for Librarian.
2188 Empty type returns all messages of any type.
2189
2190 Returns all messages for the given borrowernumber
2191
2192 =cut
2193
2194 sub GetMessages {
2195     my ( $borrowernumber, $type, $branchcode ) = @_;
2196
2197     if ( ! $type ) {
2198       $type = '%';
2199     }
2200
2201     my $dbh  = C4::Context->dbh;
2202
2203     my $query = "SELECT
2204                   branches.branchname,
2205                   messages.*,
2206                   message_date,
2207                   messages.branchcode LIKE '$branchcode' AS can_delete
2208                   FROM messages, branches
2209                   WHERE borrowernumber = ?
2210                   AND message_type LIKE ?
2211                   AND messages.branchcode = branches.branchcode
2212                   ORDER BY message_date DESC";
2213     my $sth = $dbh->prepare($query);
2214     $sth->execute( $borrowernumber, $type ) ;
2215     my @results;
2216
2217     while ( my $data = $sth->fetchrow_hashref ) {
2218         my $d = C4::Dates->new( $data->{message_date}, 'iso' );
2219         $data->{message_date_formatted} = $d->output;
2220         push @results, $data;
2221     }
2222     return \@results;
2223
2224 }
2225
2226 =head2 GetMessages
2227
2228   GetMessagesCount( $borrowernumber, $type );
2229
2230 $type is message type, B for borrower, or L for Librarian.
2231 Empty type returns all messages of any type.
2232
2233 Returns the number of messages for the given borrowernumber
2234
2235 =cut
2236
2237 sub GetMessagesCount {
2238     my ( $borrowernumber, $type, $branchcode ) = @_;
2239
2240     if ( ! $type ) {
2241       $type = '%';
2242     }
2243
2244     my $dbh  = C4::Context->dbh;
2245
2246     my $query = "SELECT COUNT(*) as MsgCount FROM messages WHERE borrowernumber = ? AND message_type LIKE ?";
2247     my $sth = $dbh->prepare($query);
2248     $sth->execute( $borrowernumber, $type ) ;
2249     my @results;
2250
2251     my $data = $sth->fetchrow_hashref;
2252     my $count = $data->{'MsgCount'};
2253
2254     return $count;
2255 }
2256
2257
2258
2259 =head2 DeleteMessage
2260
2261   DeleteMessage( $message_id );
2262
2263 =cut
2264
2265 sub DeleteMessage {
2266     my ( $message_id ) = @_;
2267
2268     my $dbh = C4::Context->dbh;
2269     my $query = "SELECT * FROM messages WHERE message_id = ?";
2270     my $sth = $dbh->prepare($query);
2271     $sth->execute( $message_id );
2272     my $message = $sth->fetchrow_hashref();
2273
2274     $query = "DELETE FROM messages WHERE message_id = ?";
2275     $sth = $dbh->prepare($query);
2276     $sth->execute( $message_id );
2277     logaction("MEMBERS", "DELCIRCMESSAGE", $message->{'borrowernumber'}, $message->{'message'}) if C4::Context->preference("BorrowersLog");
2278 }
2279
2280 =head2 IssueSlip
2281
2282   IssueSlip($branchcode, $borrowernumber, $quickslip)
2283
2284   Returns letter hash ( see C4::Letters::GetPreparedLetter )
2285
2286   $quickslip is boolean, to indicate whether we want a quick slip
2287
2288 =cut
2289
2290 sub IssueSlip {
2291     my ($branch, $borrowernumber, $quickslip) = @_;
2292
2293 #   return unless ( C4::Context->boolean_preference('printcirculationslips') );
2294
2295     my $now       = POSIX::strftime("%Y-%m-%d", localtime);
2296
2297     my $issueslist = GetPendingIssues($borrowernumber);
2298     foreach my $it (@$issueslist){
2299         if ((substr $it->{'issuedate'}, 0, 10) eq $now) {
2300             $it->{'now'} = 1;
2301         }
2302         elsif ((substr $it->{'date_due'}, 0, 10) le $now) {
2303             $it->{'overdue'} = 1;
2304         }
2305
2306         $it->{'date_due'}=format_date($it->{'date_due'});
2307     }
2308     my @issues = sort { $b->{'timestamp'} <=> $a->{'timestamp'} } @$issueslist;
2309
2310     my ($letter_code, %repeat);
2311     if ( $quickslip ) {
2312         $letter_code = 'ISSUEQSLIP';
2313         %repeat =  (
2314             'checkedout' => [ map {
2315                 'biblio' => $_,
2316                 'items'  => $_,
2317                 'issues' => $_,
2318             }, grep { $_->{'now'} } @issues ],
2319         );
2320     }
2321     else {
2322         $letter_code = 'ISSUESLIP';
2323         %repeat =  (
2324             'checkedout' => [ map {
2325                 'biblio' => $_,
2326                 'items'  => $_,
2327                 'issues' => $_,
2328             }, grep { !$_->{'overdue'} } @issues ],
2329
2330             'overdue' => [ map {
2331                 'biblio' => $_,
2332                 'items'  => $_,
2333                 'issues' => $_,
2334             }, grep { $_->{'overdue'} } @issues ],
2335
2336             'news' => [ map {
2337                 $_->{'timestamp'} = $_->{'newdate'};
2338                 { opac_news => $_ }
2339             } @{ GetNewsToDisplay("slip") } ],
2340         );
2341     }
2342
2343     return  C4::Letters::GetPreparedLetter (
2344         module => 'circulation',
2345         letter_code => $letter_code,
2346         branchcode => $branch,
2347         tables => {
2348             'branches'    => $branch,
2349             'borrowers'   => $borrowernumber,
2350         },
2351         repeat => \%repeat,
2352     );
2353 }
2354
2355 =head2 GetBorrowersWithEmail
2356
2357     ([$borrnum,$userid], ...) = GetBorrowersWithEmail('me@example.com');
2358
2359 This gets a list of users and their basic details from their email address.
2360 As it's possible for multiple user to have the same email address, it provides
2361 you with all of them. If there is no userid for the user, there will be an
2362 C<undef> there. An empty list will be returned if there are no matches.
2363
2364 =cut
2365
2366 sub GetBorrowersWithEmail {
2367     my $email = shift;
2368
2369     my $dbh = C4::Context->dbh;
2370
2371     my $query = "SELECT borrowernumber, userid FROM borrowers WHERE email=?";
2372     my $sth=$dbh->prepare($query);
2373     $sth->execute($email);
2374     my @result = ();
2375     while (my $ref = $sth->fetch) {
2376         push @result, $ref;
2377     }
2378     die "Failure searching for borrowers by email address: $sth->errstr" if $sth->err;
2379     return @result;
2380 }
2381
2382
2383 END { }    # module clean-up code here (global destructor)
2384
2385 1;
2386
2387 __END__
2388
2389 =head1 AUTHOR
2390
2391 Koha Team
2392
2393 =cut