patches for members and resultlists.
[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.="
1113 AND date < ? ";
1114     push(@bind,$date);
1115     }
1116     $strsth.="
1117 ORDER BY date desc,timestamp DESC";
1118     my $sth= $dbh->prepare( $strsth );
1119     $sth->execute( @bind );
1120     my $total = 0;
1121     while ( my $data = $sth->fetchrow_hashref ) {
1122         $acctlines[$numlines] = $data;
1123         $numlines++;
1124         $total += $data->{'amountoutstanding'};
1125     }
1126     $sth->finish;
1127     return ( $total, \@acctlines,$numlines);
1128 }
1129
1130 =head2 GetBorNotifyAcctRecord
1131
1132   ($count, $acctlines, $total) = &GetBorNotifyAcctRecord($params,$notifyid);
1133
1134 Looks up accounting data for the patron with the given borrowernumber per file number.
1135
1136 (FIXME - I'm not at all sure what this is about.)
1137
1138 C<&GetBorNotifyAcctRecord> returns a three-element array. C<$acctlines> is a
1139 reference-to-array, where each element is a reference-to-hash; the
1140 keys are the fields of the C<accountlines> table in the Koha database.
1141 C<$count> is the number of elements in C<$acctlines>. C<$total> is the
1142 total amount outstanding for all of the account lines.
1143
1144 =cut
1145
1146 sub GetBorNotifyAcctRecord {
1147     my ( $borrowernumber, $notifyid ) = @_;
1148     my $dbh = C4::Context->dbh;
1149     my @acctlines;
1150     my $numlines = 0;
1151     my $query    = qq|  SELECT * 
1152                         FROM accountlines 
1153                         WHERE borrowernumber=? 
1154                         AND notify_id=? 
1155                         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')
1156                         AND amountoutstanding != '0' 
1157                         ORDER BY notify_id,accounttype
1158                 |;
1159     my $sth = $dbh->prepare($query);
1160
1161     $sth->execute( $borrowernumber, $notifyid );
1162     my $total = 0;
1163     while ( my $data = $sth->fetchrow_hashref ) {
1164         $acctlines[$numlines] = $data;
1165         $numlines++;
1166         $total += $data->{'amountoutstanding'};
1167     }
1168     $sth->finish;
1169     return ( $total, \@acctlines, $numlines );
1170 }
1171
1172 =head2 checkuniquemember (OUEST-PROVENCE)
1173
1174   $result = &checkuniquemember($collectivity,$surname,$categorycode,$firstname,$dateofbirth);
1175
1176 Checks that a member exists or not in the database.
1177
1178 C<&result> is 1 (=exist) or 0 (=does not exist)
1179 C<&collectivity> is 1 (= we add a collectivity) or 0 (= we add a physical member)
1180 C<&surname> is the surname
1181 C<&categorycode> is from categorycode table
1182 C<&firstname> is the firstname (only if collectivity=0)
1183 C<&dateofbirth> is the date of birth (only if collectivity=0)
1184
1185 =cut
1186
1187 sub checkuniquemember {
1188     my ( $collectivity, $surname, $firstname, $dateofbirth ) = @_;
1189     my $dbh = C4::Context->dbh;
1190     my $request;
1191     if ($collectivity) {
1192
1193 #                               $request="select count(*) from borrowers where surname=? and categorycode=?";
1194         $request =
1195           "select borrowernumber,categorycode from borrowers where surname=? ";
1196     }
1197     else {
1198
1199 #                               $request="select count(*) from borrowers where surname=? and categorycode=? and firstname=? and dateofbirth=?";
1200         $request =
1201 "select borrowernumber,categorycode from borrowers where surname=?  and firstname=? and dateofbirth=?";
1202     }
1203     my $sth = $dbh->prepare($request);
1204     if ($collectivity) {
1205         $sth->execute( uc($surname) );
1206     }
1207     else {
1208         $sth->execute( uc($surname), ucfirst($firstname), $dateofbirth );
1209     }
1210     my @data = $sth->fetchrow;
1211     if ( $data[0] ) {
1212         $sth->finish;
1213         return $data[0], $data[1];
1214
1215         #
1216     }
1217     else {
1218         $sth->finish;
1219         return 0;
1220     }
1221 }
1222
1223 sub checkcardnumber {
1224         my ($cardnumber,$borrowernumber) = @_;
1225         my $dbh = C4::Context->dbh;
1226         my $query = "SELECT * FROM borrowers WHERE cardnumber=?";
1227         $query .= " AND borrowernumber <> ?" if ($borrowernumber);
1228   my $sth = $dbh->prepare($query);
1229   if ($borrowernumber) {
1230    $sth->execute($cardnumber,$borrowernumber);
1231   } else { 
1232          $sth->execute($cardnumber);
1233   } 
1234         if (my $data= $sth->fetchrow_hashref()){
1235                 return 1;
1236         }
1237         else {
1238                 return 0;
1239         }
1240         $sth->finish();
1241 }  
1242
1243
1244 =head2 getzipnamecity (OUEST-PROVENCE)
1245
1246 take all info from table city for the fields city and  zip
1247 check for the name and the zip code of the city selected
1248
1249 =cut
1250
1251 sub getzipnamecity {
1252     my ($cityid) = @_;
1253     my $dbh      = C4::Context->dbh;
1254     my $sth      =
1255       $dbh->prepare(
1256         "select city_name,city_zipcode from cities where cityid=? ");
1257     $sth->execute($cityid);
1258     my @data = $sth->fetchrow;
1259     return $data[0], $data[1];
1260 }
1261
1262
1263 =head2 getdcity (OUEST-PROVENCE)
1264
1265 recover cityid  with city_name condition
1266
1267 =cut
1268
1269 sub getidcity {
1270     my ($city_name) = @_;
1271     my $dbh = C4::Context->dbh;
1272     my $sth = $dbh->prepare("select cityid from cities where city_name=? ");
1273     $sth->execute($city_name);
1274     my $data = $sth->fetchrow;
1275     return $data;
1276 }
1277
1278
1279 =head2 GetExpiryDate 
1280
1281   $expirydate = GetExpiryDate($categorycode, $dateenrolled);
1282 process expiry date given a date and a categorycode
1283
1284 =cut
1285 sub GetExpiryDate {
1286     my ( $categorycode, $dateenrolled ) = @_;
1287     my $dbh = C4::Context->dbh;
1288     my $sth =
1289       $dbh->prepare(
1290         "select enrolmentperiod from categories where categorycode=?");
1291     $sth->execute($categorycode);
1292     my ($enrolmentperiod) = $sth->fetchrow;
1293     $enrolmentperiod = 12 unless ($enrolmentperiod);
1294     my @date=split /-/,format_date_in_iso($dateenrolled);
1295     @date=Add_Delta_YM($date[0],$date[1],$date[2],0,$enrolmentperiod);
1296     return sprintf("%04d-%02d-%02d",$date[0],$date[1],$date[2]);
1297 }
1298
1299 =head2 checkuserpassword (OUEST-PROVENCE)
1300
1301 check for the password and login are not used
1302 return the number of record 
1303 0=> NOT USED 1=> USED
1304
1305 =cut
1306
1307 sub checkuserpassword {
1308     my ( $borrowernumber, $userid, $password ) = @_;
1309     $password = md5_base64($password);
1310     my $dbh = C4::Context->dbh;
1311     my $sth =
1312       $dbh->prepare(
1313 "Select count(*) from borrowers where borrowernumber !=? and userid =? and password=? "
1314       );
1315     $sth->execute( $borrowernumber, $userid, $password );
1316     my $number_rows = $sth->fetchrow;
1317     return $number_rows;
1318
1319 }
1320
1321 =head2 GetborCatFromCatType
1322
1323   ($codes_arrayref, $labels_hashref) = &GetborCatFromCatType();
1324
1325 Looks up the different types of borrowers in the database. Returns two
1326 elements: a reference-to-array, which lists the borrower category
1327 codes, and a reference-to-hash, which maps the borrower category codes
1328 to category descriptions.
1329
1330 =cut
1331
1332 #'
1333 sub GetborCatFromCatType {
1334     my ( $category_type, $action ) = @_;
1335     my $dbh     = C4::Context->dbh;
1336     my $request = qq|   SELECT categorycode,description 
1337                         FROM categories 
1338                         $action
1339                         ORDER BY categorycode|;
1340     my $sth = $dbh->prepare($request);
1341     if ($action) {
1342         $sth->execute($category_type);
1343     }
1344     else {
1345         $sth->execute();
1346     }
1347
1348     my %labels;
1349     my @codes;
1350
1351     while ( my $data = $sth->fetchrow_hashref ) {
1352         push @codes, $data->{'categorycode'};
1353         $labels{ $data->{'categorycode'} } = $data->{'description'};
1354     }
1355     $sth->finish;
1356     return ( \@codes, \%labels );
1357 }
1358
1359 =head2 GetBorrowercategory
1360
1361   $hashref = &GetBorrowercategory($categorycode);
1362
1363 Given the borrower's category code, the function returns the corresponding
1364 data hashref for a comprehensive information display.
1365
1366 =cut
1367
1368 sub GetBorrowercategory {
1369     my ($catcode) = @_;
1370     my $dbh       = C4::Context->dbh;
1371     my $sth       =
1372       $dbh->prepare(
1373 "SELECT description,dateofbirthrequired,upperagelimit,category_type 
1374  FROM categories 
1375  WHERE categorycode = ?"
1376       );
1377     $sth->execute($catcode);
1378     my $data =
1379       $sth->fetchrow_hashref;
1380     $sth->finish();
1381     return $data;
1382 }    # sub getborrowercategory
1383
1384 =head2 ethnicitycategories
1385
1386   ($codes_arrayref, $labels_hashref) = &ethnicitycategories();
1387
1388 Looks up the different ethnic types in the database. Returns two
1389 elements: a reference-to-array, which lists the ethnicity codes, and a
1390 reference-to-hash, which maps the ethnicity codes to ethnicity
1391 descriptions.
1392
1393 =cut
1394
1395 #'
1396
1397 sub ethnicitycategories {
1398     my $dbh = C4::Context->dbh;
1399     my $sth = $dbh->prepare("Select code,name from ethnicity order by name");
1400     $sth->execute;
1401     my %labels;
1402     my @codes;
1403     while ( my $data = $sth->fetchrow_hashref ) {
1404         push @codes, $data->{'code'};
1405         $labels{ $data->{'code'} } = $data->{'name'};
1406     }
1407     $sth->finish;
1408     return ( \@codes, \%labels );
1409 }
1410
1411 =head2 fixEthnicity
1412
1413   $ethn_name = &fixEthnicity($ethn_code);
1414
1415 Takes an ethnicity code (e.g., "european" or "pi") and returns the
1416 corresponding descriptive name from the C<ethnicity> table in the
1417 Koha database ("European" or "Pacific Islander").
1418
1419 =cut
1420
1421 #'
1422
1423 sub fixEthnicity {
1424     my $ethnicity = shift;
1425     return unless $ethnicity;
1426     my $dbh       = C4::Context->dbh;
1427     my $sth       = $dbh->prepare("Select name from ethnicity where code = ?");
1428     $sth->execute($ethnicity);
1429     my $data = $sth->fetchrow_hashref;
1430     $sth->finish;
1431     return $data->{'name'};
1432 }    # sub fixEthnicity
1433
1434 =head2 GetAge
1435
1436   $dateofbirth,$date = &GetAge($date);
1437
1438 this function return the borrowers age with the value of dateofbirth
1439
1440 =cut
1441
1442 #'
1443 sub GetAge{
1444     my ( $date, $date_ref ) = @_;
1445
1446     if ( not defined $date_ref ) {
1447         $date_ref = sprintf( '%04d-%02d-%02d', Today() );
1448     }
1449
1450     my ( $year1, $month1, $day1 ) = split /-/, $date;
1451     my ( $year2, $month2, $day2 ) = split /-/, $date_ref;
1452
1453     my $age = $year2 - $year1;
1454     if ( $month1 . $day1 > $month2 . $day2 ) {
1455         $age--;
1456     }
1457
1458     return $age;
1459 }    # sub get_age
1460
1461 =head2 get_institutions
1462   $insitutions = get_institutions();
1463
1464 Just returns a list of all the borrowers of type I, borrownumber and name
1465
1466 =cut
1467
1468 #'
1469 sub get_institutions {
1470     my $dbh = C4::Context->dbh();
1471     my $sth =
1472       $dbh->prepare(
1473 "SELECT borrowernumber,surname FROM borrowers WHERE categorycode=? ORDER BY surname"
1474       );
1475     $sth->execute('I');
1476     my %orgs;
1477     while ( my $data = $sth->fetchrow_hashref() ) {
1478         $orgs{ $data->{'borrowernumber'} } = $data;
1479     }
1480     $sth->finish();
1481     return ( \%orgs );
1482
1483 }    # sub get_institutions
1484
1485 =head2 add_member_orgs
1486
1487   add_member_orgs($borrowernumber,$borrowernumbers);
1488
1489 Takes a borrowernumber and a list of other borrowernumbers and inserts them into the borrowers_to_borrowers table
1490
1491 =cut
1492
1493 #'
1494 sub add_member_orgs {
1495     my ( $borrowernumber, $otherborrowers ) = @_;
1496     my $dbh   = C4::Context->dbh();
1497     my $query =
1498       "INSERT INTO borrowers_to_borrowers (borrower1,borrower2) VALUES (?,?)";
1499     my $sth = $dbh->prepare($query);
1500     foreach my $otherborrowernumber (@$otherborrowers) {
1501         $sth->execute( $borrowernumber, $otherborrowernumber );
1502     }
1503     $sth->finish();
1504
1505 }    # sub add_member_orgs
1506
1507 =head2 GetCities (OUEST-PROVENCE)
1508
1509   ($id_cityarrayref, $city_hashref) = &GetCities();
1510
1511 Looks up the different city and zip in the database. Returns two
1512 elements: a reference-to-array, which lists the zip city
1513 codes, and a reference-to-hash, which maps the name of the city.
1514 WHERE =>OUEST PROVENCE OR EXTERIEUR
1515
1516 =cut
1517
1518 sub GetCities {
1519
1520     #my ($type_city) = @_;
1521     my $dbh   = C4::Context->dbh;
1522     my $query = qq|SELECT cityid,city_name 
1523                 FROM cities 
1524                 ORDER BY city_name|;
1525     my $sth = $dbh->prepare($query);
1526
1527     #$sth->execute($type_city);
1528     $sth->execute();
1529     my %city;
1530     my @id;
1531
1532     #    insert empty value to create a empty choice in cgi popup
1533
1534     while ( my $data = $sth->fetchrow_hashref ) {
1535
1536         push @id, $data->{'cityid'};
1537         $city{ $data->{'cityid'} } = $data->{'city_name'};
1538     }
1539
1540 #test to know if the table contain some records if no the function return nothing
1541     my $id = @id;
1542     $sth->finish;
1543     if ( $id eq 0 ) {
1544         return ();
1545     }
1546     else {
1547         unshift( @id, "" );
1548         return ( \@id, \%city );
1549     }
1550 }
1551
1552 =head2 GetSortDetails (OUEST-PROVENCE)
1553
1554   ($lib) = &GetSortDetails($category,$sortvalue);
1555
1556 Returns the authorized value  details
1557 C<&$lib>return value of authorized value details
1558 C<&$sortvalue>this is the value of authorized value 
1559 C<&$category>this is the value of authorized value category
1560
1561 =cut
1562
1563 sub GetSortDetails {
1564     my ( $category, $sortvalue ) = @_;
1565     my $dbh   = C4::Context->dbh;
1566     my $query = qq|SELECT lib 
1567                 FROM authorised_values 
1568                 WHERE category=?
1569                 AND authorised_value=? |;
1570     my $sth = $dbh->prepare($query);
1571     $sth->execute( $category, $sortvalue );
1572     my $lib = $sth->fetchrow;
1573     return ($lib);
1574 }
1575
1576 =head2 DeleteBorrower 
1577
1578   () = &DeleteBorrower($member);
1579
1580 delete all data fo borrowers and add record to deletedborrowers table
1581 C<&$member>this is the borrowernumber
1582
1583 =cut
1584
1585 sub MoveMemberToDeleted {
1586     my ($member) = @_;
1587     my $dbh = C4::Context->dbh;
1588     my $query;
1589     $query = qq|SELECT * 
1590                   FROM borrowers 
1591                   WHERE borrowernumber=?|;
1592     my $sth = $dbh->prepare($query);
1593     $sth->execute($member);
1594     my @data = $sth->fetchrow_array;
1595     $sth->finish;
1596     $sth =
1597       $dbh->prepare( "INSERT INTO deletedborrowers VALUES ("
1598           . ( "?," x ( scalar(@data) - 1 ) )
1599           . "?)" );
1600     $sth->execute(@data);
1601     $sth->finish;
1602 }
1603
1604 =head2 DelMember
1605
1606 DelMember($borrowernumber);
1607
1608 This function remove directly a borrower whitout writing it on deleteborrower.
1609 + Deletes reserves for the borrower
1610
1611 =cut
1612
1613 sub DelMember {
1614     my $dbh            = C4::Context->dbh;
1615     my $borrowernumber = shift;
1616         warn "in delmember with $borrowernumber";
1617     return unless $borrowernumber;    # borrowernumber is mandatory.
1618
1619     my $query = qq|DELETE 
1620                   FROM  reserves 
1621                   WHERE borrowernumber=?|;
1622     my $sth = $dbh->prepare($query);
1623     $sth->execute($borrowernumber);
1624     $sth->finish;
1625     $query = "
1626        DELETE
1627        FROM borrowers
1628        WHERE borrowernumber = ?
1629    ";
1630     $sth = $dbh->prepare($query);
1631     $sth->execute($borrowernumber);
1632     $sth->finish;
1633     &logaction(C4::Context->userenv->{'number'},"MEMBERS","DELETE",$borrowernumber,"") 
1634         if C4::Context->preference("BorrowersLog");
1635     return $sth->rows;
1636 }
1637
1638 =head2 ExtendMemberSubscriptionTo (OUEST-PROVENCE)
1639
1640 $date= ExtendMemberSubscriptionTo($borrowerid, $date);
1641 Extending the subscription to a given date or to the expiry date calculated on local date.
1642 returns date 
1643 =cut
1644
1645 sub ExtendMemberSubscriptionTo {
1646     my ( $borrowerid,$date) = @_;
1647     my $dbh = C4::Context->dbh;
1648     unless ($date){
1649       $date=POSIX::strftime("%Y-%m-%d",localtime(time));
1650       my $borrower = GetMember($borrowerid,'borrowernumber');
1651       $date = GetExpiryDate( $borrower->{'categorycode'}, $date );
1652     }
1653     my $sth = $dbh->do(<<EOF);
1654 UPDATE borrowers 
1655 SET  dateexpiry='$date' 
1656 WHERE borrowernumber='$borrowerid'
1657 EOF
1658     return $date if ($sth);
1659     return 0;
1660 }
1661
1662 =head2 GetRoadTypes (OUEST-PROVENCE)
1663
1664   ($idroadtypearrayref, $roadttype_hashref) = &GetRoadTypes();
1665
1666 Looks up the different road type . Returns two
1667 elements: a reference-to-array, which lists the id_roadtype
1668 codes, and a reference-to-hash, which maps the road type of the road .
1669
1670
1671 =cut
1672
1673 sub GetRoadTypes {
1674     my $dbh   = C4::Context->dbh;
1675     my $query = qq|
1676 SELECT roadtypeid,road_type 
1677 FROM roadtype 
1678 ORDER BY road_type|;
1679     my $sth = $dbh->prepare($query);
1680     $sth->execute();
1681     my %roadtype;
1682     my @id;
1683
1684     #    insert empty value to create a empty choice in cgi popup
1685
1686     while ( my $data = $sth->fetchrow_hashref ) {
1687
1688         push @id, $data->{'roadtypeid'};
1689         $roadtype{ $data->{'roadtypeid'} } = $data->{'road_type'};
1690     }
1691
1692 #test to know if the table contain some records if no the function return nothing
1693     my $id = @id;
1694     $sth->finish;
1695     if ( $id eq 0 ) {
1696         return ();
1697     }
1698     else {
1699         unshift( @id, "" );
1700         return ( \@id, \%roadtype );
1701     }
1702 }
1703
1704
1705
1706 =head2 GetTitles (OUEST-PROVENCE)
1707
1708   ($borrowertitle)= &GetTitles();
1709
1710 Looks up the different title . Returns array  with all borrowers title
1711
1712 =cut
1713
1714 sub GetTitles {
1715     my @borrowerTitle = split /,|\|/,C4::Context->preference('BorrowersTitles');
1716     unshift( @borrowerTitle, "" );
1717     return ( \@borrowerTitle);
1718     }
1719
1720
1721
1722 =head2 GetRoadTypeDetails (OUEST-PROVENCE)
1723
1724   ($roadtype) = &GetRoadTypeDetails($roadtypeid);
1725
1726 Returns the description of roadtype
1727 C<&$roadtype>return description of road type
1728 C<&$roadtypeid>this is the value of roadtype s
1729
1730 =cut
1731
1732 sub GetRoadTypeDetails {
1733     my ($roadtypeid) = @_;
1734     my $dbh          = C4::Context->dbh;
1735     my $query        = qq|
1736 SELECT road_type 
1737 FROM roadtype 
1738 WHERE roadtypeid=?|;
1739     my $sth = $dbh->prepare($query);
1740     $sth->execute($roadtypeid);
1741     my $roadtype = $sth->fetchrow;
1742     return ($roadtype);
1743 }
1744
1745 =head2 GetBorrowersWhoHaveNotBorrowedSince
1746
1747 &GetBorrowersWhoHaveNotBorrowedSince($date)
1748
1749 this function get all borrowers who haven't borrowed since the date given on input arg.
1750
1751 =cut
1752
1753 sub GetBorrowersWhoHaveNotBorrowedSince {
1754     my $date = shift;
1755     return unless $date;    # date is mandatory.
1756     my $dbh   = C4::Context->dbh;
1757     my $query = "
1758         SELECT borrowers.borrowernumber,max(timestamp)
1759         FROM   borrowers
1760           LEFT JOIN issues ON borrowers.borrowernumber = issues.borrowernumber
1761         WHERE issues.borrowernumber IS NOT NULL
1762         GROUP BY borrowers.borrowernumber
1763    ";
1764     my $sth = $dbh->prepare($query);
1765     $sth->execute;
1766     my @results;
1767
1768     while ( my $data = $sth->fetchrow_hashref ) {
1769         push @results, $data;
1770     }
1771     return \@results;
1772 }
1773
1774 =head2 GetBorrowersWhoHaveNeverBorrowed
1775
1776 $results = &GetBorrowersWhoHaveNeverBorrowed
1777
1778 this function get all borrowers who have never borrowed.
1779
1780 I<$result> is a ref to an array which all elements are a hasref.
1781
1782 =cut
1783
1784 sub GetBorrowersWhoHaveNeverBorrowed {
1785     my $dbh   = C4::Context->dbh;
1786     my $query = "
1787         SELECT borrowers.borrowernumber,max(timestamp)
1788         FROM   borrowers
1789           LEFT JOIN issues ON borrowers.borrowernumber = issues.borrowernumber
1790         WHERE issues.borrowernumber IS NULL
1791    ";
1792     my $sth = $dbh->prepare($query);
1793     $sth->execute;
1794     my @results;
1795     while ( my $data = $sth->fetchrow_hashref ) {
1796         push @results, $data;
1797     }
1798     return \@results;
1799 }
1800
1801 =head2 GetBorrowersWithIssuesHistoryOlderThan
1802
1803 $results = &GetBorrowersWithIssuesHistoryOlderThan($date)
1804
1805 this function get all borrowers who has an issue history older than I<$date> given on input arg.
1806
1807 I<$result> is a ref to an array which all elements are a hashref.
1808 This hashref is containt the number of time this borrowers has borrowed before I<$date> and the borrowernumber.
1809
1810 =cut
1811
1812 sub GetBorrowersWithIssuesHistoryOlderThan {
1813     my $dbh  = C4::Context->dbh;
1814     my $date = shift;
1815     return unless $date;    # date is mandatory.
1816     my $query = "
1817        SELECT count(borrowernumber) as n,borrowernumber
1818        FROM issues
1819        WHERE returndate < ?
1820          AND borrowernumber IS NOT NULL 
1821        GROUP BY borrowernumber
1822    ";
1823     my $sth = $dbh->prepare($query);
1824     $sth->execute($date);
1825     my @results;
1826
1827     while ( my $data = $sth->fetchrow_hashref ) {
1828         push @results, $data;
1829     }
1830     return \@results;
1831 }
1832
1833 END { }    # module clean-up code here (global destructor)
1834
1835 1;
1836
1837 __END__
1838
1839 =back
1840
1841 =head1 AUTHOR
1842
1843 Koha Team
1844
1845 =cut