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