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