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