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