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