Revert "fix for bug 1468, but not sure if this is the best"
[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 #     warn Data::Dumper::Dumper(%data);
595     #   warn "num user".$data{'borrowernumber'};
596     my $qborrower=$dbh->prepare("SHOW columns from borrowers");
597     $qborrower->execute;
598     my %hashborrowerfields;  
599     while (my ($field)=$qborrower->fetchrow){
600       $hashborrowerfields{$field}=1;
601     }  
602     my $query;
603     my $sth;
604     $data{'userid'} = '' if ( $data{'password'} eq '' );  
605     my @parameters;  
606     
607     # test to know if u must update or not the borrower password
608     if ( $data{'password'} eq '****' ) {
609         delete $data{'password'};
610         foreach (keys %data)
611         {push @parameters,"$_ = ".$dbh->quote($data{$_}) if ($_ ne "borrowernumber" and $hashborrowerfields{$_}) } ;
612         $query = "UPDATE borrowers SET ".join (",",@parameters)
613     ." WHERE borrowernumber=$data{'borrowernumber'}";
614 #         warn "$query";
615         $sth = $dbh->prepare($query);
616         $sth->execute;
617     }
618     else {
619         $data{'password'} = md5_base64( $data{'password'} )   if ( $data{'password'} ne '' );
620         delete $data{'password'} if ($data{password} eq "");
621         foreach (keys %data)
622         {push @parameters,"$_ = ".$dbh->quote($data{$_}) if ($_ ne "borrowernumber" and $hashborrowerfields{$_})} ;
623         
624         $query = "UPDATE borrowers SET ".join (",",@parameters)." WHERE borrowernumber=$data{'borrowernumber'}";
625 #         warn "$query";
626         $sth = $dbh->prepare($query);
627         $sth->execute;
628     }
629     $sth->finish;
630
631 # ok if its an adult (type) it may have borrowers that depend on it as a guarantor
632 # so when we update information for an adult we should check for guarantees and update the relevant part
633 # of their records, ie addresses and phone numbers
634     my $borrowercategory= GetBorrowercategory( $data{'category_type'} );
635     if ( $borrowercategory->{'category_type'} eq 'A' ) {
636         # is adult check guarantees;
637         UpdateGuarantees(%data);
638
639     }
640     &logaction(C4::Context->userenv->{'number'},"MEMBERS","MODIFY",$data{'borrowernumber'},"") 
641         if C4::Context->preference("BorrowersLog");
642 }
643
644
645 =head2
646
647 =item AddMember
648
649   $borrowernumber = &AddMember(%borrower);
650
651 insert new borrower into table
652 Returns the borrowernumber
653
654 =cut
655
656 #'
657 sub AddMember {
658     my (%data) = @_;
659     my $dbh = C4::Context->dbh;
660     $data{'userid'} = '' unless $data{'password'};
661     $data{'password'} = md5_base64( $data{'password'} ) if $data{'password'};
662     $data{'dateofbirth'} = format_date_in_iso( $data{'dateofbirth'} );
663     $data{'dateenrolled'} = format_date_in_iso( $data{'dateenrolled'} );
664     $data{'dateexpiry'}   = format_date_in_iso( $data{'dateexpiry'} );
665     my $query =
666         "insert into borrowers set cardnumber="
667       . $dbh->quote( $data{'cardnumber'} )
668       . ",surname="
669       . $dbh->quote( $data{'surname'} )
670       . ",firstname="
671       . $dbh->quote( $data{'firstname'} )
672       . ",title="
673       . $dbh->quote( $data{'title'} )
674       . ",othernames="
675       . $dbh->quote( $data{'othernames'} )
676       . ",initials="
677       . $dbh->quote( $data{'initials'} )
678       . ",streetnumber="
679       . $dbh->quote( $data{'streetnumber'} )
680       . ",streettype="
681       . $dbh->quote( $data{'streettype'} )
682       . ",address="
683       . $dbh->quote( $data{'address'} )
684       . ",address2="
685       . $dbh->quote( $data{'address2'} )
686       . ",zipcode="
687       . $dbh->quote( $data{'zipcode'} )
688       . ",city="
689       . $dbh->quote( $data{'city'} )
690       . ",phone="
691       . $dbh->quote( $data{'phone'} )
692       . ",email="
693       . $dbh->quote( $data{'email'} )
694       . ",mobile="
695       . $dbh->quote( $data{'mobile'} )
696       . ",phonepro="
697       . $dbh->quote( $data{'phonepro'} )
698       . ",opacnote="
699       . $dbh->quote( $data{'opacnote'} )
700       . ",guarantorid="
701       . $dbh->quote( $data{'guarantorid'} )
702       . ",dateofbirth="
703       . $dbh->quote( $data{'dateofbirth'} )
704       . ",branchcode="
705       . $dbh->quote( $data{'branchcode'} )
706       . ",categorycode="
707       . $dbh->quote( $data{'categorycode'} )
708       . ",dateenrolled="
709       . $dbh->quote( $data{'dateenrolled'} )
710       . ",contactname="
711       . $dbh->quote( $data{'contactname'} )
712       . ",borrowernotes="
713       . $dbh->quote( $data{'borrowernotes'} )
714       . ",dateexpiry="
715       . $dbh->quote( $data{'dateexpiry'} )
716       . ",contactnote="
717       . $dbh->quote( $data{'contactnote'} )
718       . ",B_address="
719       . $dbh->quote( $data{'B_address'} )
720       . ",B_zipcode="
721       . $dbh->quote( $data{'B_zipcode'} )
722       . ",B_city="
723       . $dbh->quote( $data{'B_city'} )
724       . ",B_phone="
725       . $dbh->quote( $data{'B_phone'} )
726       . ",B_email="
727       . $dbh->quote( $data{'B_email'}, )
728       . ",password="
729       . $dbh->quote( $data{'password'} )
730       . ",userid="
731       . $dbh->quote( $data{'userid'} )
732       . ",sort1="
733       . $dbh->quote( $data{'sort1'} )
734       . ",sort2="
735       . $dbh->quote( $data{'sort2'} )
736       . ",contacttitle="
737       . $dbh->quote( $data{'contacttitle'} )
738       . ",emailpro="
739       . $dbh->quote( $data{'emailpro'} )
740       . ",contactfirstname="
741       . $dbh->quote( $data{'contactfirstname'} ) . ",sex="
742       . $dbh->quote( $data{'sex'} ) . ",fax="
743       . $dbh->quote( $data{'fax'} )
744       . ",relationship="
745       . $dbh->quote( $data{'relationship'} )
746       . ",B_streetnumber="
747       . $dbh->quote( $data{'B_streetnumber'} )
748       . ",B_streettype="
749       . $dbh->quote( $data{'B_streettype'} )
750       . ",gonenoaddress="
751       . $dbh->quote( $data{'gonenoaddress'} )
752       . ",lost="
753       . $dbh->quote( $data{'lost'} )
754       . ",debarred="
755       . $dbh->quote( $data{'debarred'} )
756       . ",ethnicity="
757       . $dbh->quote( $data{'ethnicity'} )
758       . ",ethnotes="
759       . $dbh->quote( $data{'ethnotes'} );
760
761     my $sth = $dbh->prepare($query);
762     $sth->execute;
763     $sth->finish;
764     $data{'borrowernumber'} = $dbh->{'mysql_insertid'};
765     
766     &logaction(C4::Context->userenv->{'number'},"MEMBERS","CREATE",$data{'borrowernumber'},"") 
767         if C4::Context->preference("BorrowersLog");
768         
769     return $data{'borrowernumber'};
770 }
771
772 sub Check_Userid {
773         my ($uid,$member) = @_;
774         my $dbh = C4::Context->dbh;
775     # Make sure the userid chosen is unique and not theirs if non-empty. If it is not,
776     # Then we need to tell the user and have them create a new one.
777     my $sth =
778       $dbh->prepare(
779         "SELECT * FROM borrowers WHERE userid=? AND borrowernumber != ?");
780     $sth->execute( $uid, $member );
781     if ( ( $uid ne '' ) && ( my $row = $sth->fetchrow_hashref ) ) {
782         return 0;
783     }
784         else {
785                 return 1;
786         }
787 }
788
789
790 sub changepassword {
791     my ( $uid, $member, $digest ) = @_;
792     my $dbh = C4::Context->dbh;
793
794 #Make sure the userid chosen is unique and not theirs if non-empty. If it is not,
795 #Then we need to tell the user and have them create a new one.
796     my $sth =
797       $dbh->prepare(
798         "SELECT * FROM borrowers WHERE userid=? AND borrowernumber != ?");
799     $sth->execute( $uid, $member );
800     if ( ( $uid ne '' ) && ( my $row = $sth->fetchrow_hashref ) ) {
801         return 0;
802     }
803     else {
804         #Everything is good so we can update the information.
805         $sth =
806           $dbh->prepare(
807             "update borrowers set userid=?, password=? where borrowernumber=?");
808         $sth->execute( $uid, $digest, $member );
809         return 1;
810     }
811     
812     &logaction(C4::Context->userenv->{'number'},"MEMBERS","CHANGE PASS",$member,"") 
813         if C4::Context->preference("BorrowersLog");
814 }
815
816
817
818 =item fixup_cardnumber
819
820 Warning: The caller is responsible for locking the members table in write
821 mode, to avoid database corruption.
822
823 =cut
824
825 use vars qw( @weightings );
826 my @weightings = ( 8, 4, 6, 3, 5, 2, 1 );
827
828 sub fixup_cardnumber ($) {
829     my ($cardnumber) = @_;
830     my $autonumber_members = C4::Context->boolean_preference('autoMemberNum');
831     $autonumber_members = 0 unless defined $autonumber_members;
832
833     # Find out whether member numbers should be generated
834     # automatically. Should be either "1" or something else.
835     # Defaults to "0", which is interpreted as "no".
836
837     #     if ($cardnumber !~ /\S/ && $autonumber_members) {
838     if ($autonumber_members) {
839         my $dbh = C4::Context->dbh;
840         if ( C4::Context->preference('checkdigit') eq 'katipo' ) {
841
842             # if checkdigit is selected, calculate katipo-style cardnumber.
843             # otherwise, just use the max()
844             # purpose: generate checksum'd member numbers.
845             # We'll assume we just got the max value of digits 2-8 of member #'s
846             # from the database and our job is to increment that by one,
847             # determine the 1st and 9th digits and return the full string.
848             my $sth =
849               $dbh->prepare(
850                 "select max(substring(borrowers.cardnumber,2,7)) from borrowers"
851               );
852             $sth->execute;
853
854             my $data = $sth->fetchrow_hashref;
855             $cardnumber = $data->{'max(substring(borrowers.cardnumber,2,7))'};
856             $sth->finish;
857             if ( !$cardnumber ) {    # If DB has no values,
858                 $cardnumber = 1000000;    # start at 1000000
859             }
860             else {
861                 $cardnumber += 1;
862             }
863
864             my $sum = 0;
865             for ( my $i = 0 ; $i < 8 ; $i += 1 ) {
866
867                 # read weightings, left to right, 1 char at a time
868                 my $temp1 = $weightings[$i];
869
870                 # sequence left to right, 1 char at a time
871                 my $temp2 = substr( $cardnumber, $i, 1 );
872
873                 # mult each char 1-7 by its corresponding weighting
874                 $sum += $temp1 * $temp2;
875             }
876
877             my $rem = ( $sum % 11 );
878             $rem = 'X' if $rem == 10;
879
880             $cardnumber = "V$cardnumber$rem";
881         }
882         else {
883
884      # MODIFIED BY JF: mysql4.1 allows casting as an integer, which is probably
885      # better. I'll leave the original in in case it needs to be changed for you
886             my $sth =
887               $dbh->prepare(
888                 "select max(cast(cardnumber as signed)) from borrowers");
889
890       #my $sth=$dbh->prepare("select max(borrowers.cardnumber) from borrowers");
891
892             $sth->execute;
893
894             my ($result) = $sth->fetchrow;
895             $sth->finish;
896             $cardnumber = $result + 1;
897         }
898     }
899     return $cardnumber;
900 }
901
902 =head2 GetGuarantees
903
904   ($num_children, $children_arrayref) = &GetGuarantees($parent_borrno);
905   $child0_cardno = $children_arrayref->[0]{"cardnumber"};
906   $child0_borrno = $children_arrayref->[0]{"borrowernumber"};
907
908 C<&GetGuarantees> takes a borrower number (e.g., that of a patron
909 with children) and looks up the borrowers who are guaranteed by that
910 borrower (i.e., the patron's children).
911
912 C<&GetGuarantees> returns two values: an integer giving the number of
913 borrowers guaranteed by C<$parent_borrno>, and a reference to an array
914 of references to hash, which gives the actual results.
915
916 =cut
917
918 #'
919 sub GetGuarantees {
920     my ($borrowernumber) = @_;
921     my $dbh              = C4::Context->dbh;
922     my $sth              =
923       $dbh->prepare(
924 "select cardnumber,borrowernumber, firstname, surname from borrowers where guarantorid=?"
925       );
926     $sth->execute($borrowernumber);
927
928     my @dat;
929     my $data = $sth->fetchall_arrayref({}); 
930     $sth->finish;
931     return ( scalar(@$data), $data );
932 }
933
934 =head2 UpdateGuarantees
935
936   &UpdateGuarantees($parent_borrno);
937   
938
939 C<&UpdateGuarantees> borrower data for an adulte and updates all the guarantees
940 with the modified information
941
942 =cut
943
944 #'
945 sub UpdateGuarantees {
946     my (%data) = @_;
947     my $dbh = C4::Context->dbh;
948     my ( $count, $guarantees ) = GetGuarantees( $data{'borrowernumber'} );
949     for ( my $i = 0 ; $i < $count ; $i++ ) {
950
951         # FIXME
952         # It looks like the $i is only being returned to handle walking through
953         # the array, which is probably better done as a foreach loop.
954         #
955         my $guaquery = qq|UPDATE borrowers 
956                           SET address='$data{'address'}',fax='$data{'fax'}',
957                               B_city='$data{'B_city'}',mobile='$data{'mobile'}',city='$data{'city'}',phone='$data{'phone'}'
958                           WHERE borrowernumber='$guarantees->[$i]->{'borrowernumber'}'
959                 |;
960         my $sth3 = $dbh->prepare($guaquery);
961         $sth3->execute;
962         $sth3->finish;
963     }
964 }
965 =head2 GetPendingIssues
966
967   ($count, $issues) = &GetPendingIssues($borrowernumber);
968
969 Looks up what the patron with the given borrowernumber has borrowed.
970
971 C<&GetPendingIssues> returns a two-element array. C<$issues> is a
972 reference-to-array, where each element is a reference-to-hash; the
973 keys are the fields from the C<issues>, C<biblio>, and C<items> tables
974 in the Koha database. C<$count> is the number of elements in
975 C<$issues>.
976
977 =cut
978
979 #'
980 sub GetPendingIssues {
981     my ($borrowernumber) = @_;
982     my $dbh              = C4::Context->dbh;
983
984     my $sth              = $dbh->prepare(
985    "SELECT * FROM issues 
986       LEFT JOIN items ON issues.itemnumber=items.itemnumber
987       LEFT JOIN biblio ON     items.biblionumber=biblio.biblionumber 
988       LEFT JOIN biblioitems ON items.biblioitemnumber=biblioitems.biblioitemnumber
989     WHERE
990       borrowernumber=? 
991       AND returndate IS NULL
992     ORDER BY issues.issuedate"
993     );
994     $sth->execute($borrowernumber);
995     my $data = $sth->fetchall_arrayref({});
996     my $today = POSIX::strftime("%Y%m%d", localtime);
997     foreach( @$data ) {
998         my $datedue = $_->{'date_due'};
999         $datedue =~ s/-//g;
1000         if ( $datedue < $today ) {
1001             $_->{'overdue'} = 1;
1002         }
1003     }
1004     $sth->finish;
1005     return ( scalar(@$data), $data );
1006 }
1007
1008 =head2 GetAllIssues
1009
1010   ($count, $issues) = &GetAllIssues($borrowernumber, $sortkey, $limit);
1011
1012 Looks up what the patron with the given borrowernumber has borrowed,
1013 and sorts the results.
1014
1015 C<$sortkey> is the name of a field on which to sort the results. This
1016 should be the name of a field in the C<issues>, C<biblio>,
1017 C<biblioitems>, or C<items> table in the Koha database.
1018
1019 C<$limit> is the maximum number of results to return.
1020
1021 C<&GetAllIssues> returns a two-element array. C<$issues> is a
1022 reference-to-array, where each element is a reference-to-hash; the
1023 keys are the fields from the C<issues>, C<biblio>, C<biblioitems>, and
1024 C<items> tables of the Koha database. C<$count> is the number of
1025 elements in C<$issues>
1026
1027 =cut
1028
1029 #'
1030 sub GetAllIssues {
1031     my ( $borrowernumber, $order, $limit ) = @_;
1032
1033     #FIXME: sanity-check order and limit
1034     my $dbh   = C4::Context->dbh;
1035     my $count = 0;
1036     my $query =
1037   "Select *,items.timestamp AS itemstimestamp from 
1038   issues 
1039   LEFT JOIN items on items.itemnumber=issues.itemnumber
1040   LEFT JOIN biblio ON items.biblionumber=biblio.biblionumber
1041   LEFT JOIN biblioitems ON items.biblioitemnumber=biblioitems.biblioitemnumber
1042   where borrowernumber=? 
1043   order by $order";
1044     if ( $limit != 0 ) {
1045         $query .= " limit $limit";
1046     }
1047
1048     #print $query;
1049     my $sth = $dbh->prepare($query);
1050     $sth->execute($borrowernumber);
1051     my @result;
1052     my $i = 0;
1053     while ( my $data = $sth->fetchrow_hashref ) {
1054         $result[$i] = $data;
1055         $i++;
1056         $count++;
1057     }
1058
1059     # get all issued items for borrowernumber from oldissues table
1060     # large chunk of older issues data put into table oldissues
1061     # to speed up db calls for issuing items
1062     if ( C4::Context->preference("ReadingHistory") ) {
1063         my $query2 = "SELECT * FROM oldissues
1064                       LEFT JOIN items ON items.itemnumber=oldissues.itemnumber
1065                       LEFT JOIN biblio ON items.biblionumber=biblio.biblionumber
1066                       LEFT JOIN biblioitems ON items.biblioitemnumber=biblioitems.biblioitemnumber
1067                       WHERE borrowernumber=? 
1068                       ORDER BY $order";
1069         if ( $limit != 0 ) {
1070             $limit = $limit - $count;
1071             $query2 .= " limit $limit";
1072         }
1073
1074         my $sth2 = $dbh->prepare($query2);
1075         $sth2->execute($borrowernumber);
1076
1077         while ( my $data2 = $sth2->fetchrow_hashref ) {
1078             $result[$i] = $data2;
1079             $i++;
1080         }
1081         $sth2->finish;
1082     }
1083     $sth->finish;
1084
1085     return ( $i, \@result );
1086 }
1087
1088
1089 =head2 GetMemberAccountRecords
1090
1091   ($total, $acctlines, $count) = &GetMemberAccountRecords($borrowernumber);
1092
1093 Looks up accounting data for the patron with the given borrowernumber.
1094
1095 C<&GetMemberAccountRecords> returns a three-element array. C<$acctlines> is a
1096 reference-to-array, where each element is a reference-to-hash; the
1097 keys are the fields of the C<accountlines> table in the Koha database.
1098 C<$count> is the number of elements in C<$acctlines>. C<$total> is the
1099 total amount outstanding for all of the account lines.
1100
1101 =cut
1102
1103 #'
1104 sub GetMemberAccountRecords {
1105     my ($borrowernumber,$date) = @_;
1106     my $dbh = C4::Context->dbh;
1107     my @acctlines;
1108     my $numlines = 0;
1109     my $strsth      = qq(
1110 SELECT * 
1111 FROM accountlines 
1112 WHERE borrowernumber=?);
1113     my @bind = ($borrowernumber);
1114     if ($date && $date ne ''){
1115     $strsth.="
1116 AND date < ? ";
1117     push(@bind,$date);
1118     }
1119     $strsth.="
1120 ORDER BY date desc,timestamp DESC";
1121     my $sth= $dbh->prepare( $strsth );
1122     $sth->execute( @bind );
1123     my $total = 0;
1124     while ( my $data = $sth->fetchrow_hashref ) {
1125         $acctlines[$numlines] = $data;
1126         $numlines++;
1127         $total += $data->{'amountoutstanding'};
1128     }
1129     $sth->finish;
1130     return ( $total, \@acctlines,$numlines);
1131 }
1132
1133 =head2 GetBorNotifyAcctRecord
1134
1135   ($count, $acctlines, $total) = &GetBorNotifyAcctRecord($params,$notifyid);
1136
1137 Looks up accounting data for the patron with the given borrowernumber per file number.
1138
1139 (FIXME - I'm not at all sure what this is about.)
1140
1141 C<&GetBorNotifyAcctRecord> returns a three-element array. C<$acctlines> is a
1142 reference-to-array, where each element is a reference-to-hash; the
1143 keys are the fields of the C<accountlines> table in the Koha database.
1144 C<$count> is the number of elements in C<$acctlines>. C<$total> is the
1145 total amount outstanding for all of the account lines.
1146
1147 =cut
1148
1149 sub GetBorNotifyAcctRecord {
1150     my ( $borrowernumber, $notifyid ) = @_;
1151     my $dbh = C4::Context->dbh;
1152     my @acctlines;
1153     my $numlines = 0;
1154     my $query    = qq|  SELECT * 
1155                         FROM accountlines 
1156                         WHERE borrowernumber=? 
1157                         AND notify_id=? 
1158                         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')
1159                         AND amountoutstanding != '0' 
1160                         ORDER BY notify_id,accounttype
1161                 |;
1162     my $sth = $dbh->prepare($query);
1163
1164     $sth->execute( $borrowernumber, $notifyid );
1165     my $total = 0;
1166     while ( my $data = $sth->fetchrow_hashref ) {
1167         $acctlines[$numlines] = $data;
1168         $numlines++;
1169         $total += $data->{'amountoutstanding'};
1170     }
1171     $sth->finish;
1172     return ( $total, \@acctlines, $numlines );
1173 }
1174
1175 =head2 checkuniquemember (OUEST-PROVENCE)
1176
1177   $result = &checkuniquemember($collectivity,$surname,$categorycode,$firstname,$dateofbirth);
1178
1179 Checks that a member exists or not in the database.
1180
1181 C<&result> is 1 (=exist) or 0 (=does not exist)
1182 C<&collectivity> is 1 (= we add a collectivity) or 0 (= we add a physical member)
1183 C<&surname> is the surname
1184 C<&categorycode> is from categorycode table
1185 C<&firstname> is the firstname (only if collectivity=0)
1186 C<&dateofbirth> is the date of birth (only if collectivity=0)
1187
1188 =cut
1189
1190 sub checkuniquemember {
1191     my ( $collectivity, $surname, $firstname, $dateofbirth ) = @_;
1192     my $dbh = C4::Context->dbh;
1193     my $request;
1194     if ($collectivity) {
1195
1196 #                               $request="select count(*) from borrowers where surname=? and categorycode=?";
1197         $request =
1198           "select borrowernumber,categorycode from borrowers where surname=? ";
1199     }
1200     else {
1201
1202 #                               $request="select count(*) from borrowers where surname=? and categorycode=? and firstname=? and dateofbirth=?";
1203         $request =
1204 "select borrowernumber,categorycode from borrowers where surname=?  and firstname=? and dateofbirth=?";
1205     }
1206     my $sth = $dbh->prepare($request);
1207     if ($collectivity) {
1208         $sth->execute( uc($surname) );
1209     }
1210     else {
1211         $sth->execute( uc($surname), ucfirst($firstname), $dateofbirth );
1212     }
1213     my @data = $sth->fetchrow;
1214     if ( $data[0] ) {
1215         $sth->finish;
1216         return $data[0], $data[1];
1217
1218         #
1219     }
1220     else {
1221         $sth->finish;
1222         return 0;
1223     }
1224 }
1225
1226 sub checkcardnumber {
1227         my ($cardnumber) = @_;
1228         my $dbh = C4::Context->dbh;
1229         my $query = "SELECT * FROM borrowers WHERE cardnumber=?";
1230         my $sth = $dbh->prepare($query);
1231         $sth->execute($cardnumber);
1232         if (my $data= $sth->fetchrow_hashref()){
1233                 return 1;
1234         }
1235         else {
1236                 return 0;
1237         }
1238         $sth->finish();
1239 }  
1240
1241
1242 =head2 getzipnamecity (OUEST-PROVENCE)
1243
1244 take all info from table city for the fields city and  zip
1245 check for the name and the zip code of the city selected
1246
1247 =cut
1248
1249 sub getzipnamecity {
1250     my ($cityid) = @_;
1251     my $dbh      = C4::Context->dbh;
1252     my $sth      =
1253       $dbh->prepare(
1254         "select city_name,city_zipcode from cities where cityid=? ");
1255     $sth->execute($cityid);
1256     my @data = $sth->fetchrow;
1257     return $data[0], $data[1];
1258 }
1259
1260
1261 =head2 getdcity (OUEST-PROVENCE)
1262
1263 recover cityid  with city_name condition
1264
1265 =cut
1266
1267 sub getidcity {
1268     my ($city_name) = @_;
1269     my $dbh = C4::Context->dbh;
1270     my $sth = $dbh->prepare("select cityid from cities where city_name=? ");
1271     $sth->execute($city_name);
1272     my $data = $sth->fetchrow;
1273     return $data;
1274 }
1275
1276
1277 =head2 GetExpiryDate 
1278
1279   $expirydate = GetExpiryDate($categorycode, $dateenrolled);
1280 process expiry date given a date and a categorycode
1281
1282 =cut
1283 sub GetExpiryDate {
1284     my ( $categorycode, $dateenrolled ) = @_;
1285     my $dbh = C4::Context->dbh;
1286     my $sth =
1287       $dbh->prepare(
1288         "select enrolmentperiod from categories where categorycode=?");
1289     $sth->execute($categorycode);
1290     my ($enrolmentperiod) = $sth->fetchrow;
1291     $enrolmentperiod = 12 unless ($enrolmentperiod);
1292     my @date=split /-/,format_date_in_iso($dateenrolled);
1293     @date=Add_Delta_YM($date[0],$date[1],$date[2],0,$enrolmentperiod);
1294     return sprintf("%04d-%02d-%02d",$date[0],$date[1],$date[2]);
1295 }
1296
1297 =head2 checkuserpassword (OUEST-PROVENCE)
1298
1299 check for the password and login are not used
1300 return the number of record 
1301 0=> NOT USED 1=> USED
1302
1303 =cut
1304
1305 sub checkuserpassword {
1306     my ( $borrowernumber, $userid, $password ) = @_;
1307     $password = md5_base64($password);
1308     my $dbh = C4::Context->dbh;
1309     my $sth =
1310       $dbh->prepare(
1311 "Select count(*) from borrowers where borrowernumber !=? and userid =? and password=? "
1312       );
1313     $sth->execute( $borrowernumber, $userid, $password );
1314     my $number_rows = $sth->fetchrow;
1315     return $number_rows;
1316
1317 }
1318
1319 =head2 GetborCatFromCatType
1320
1321   ($codes_arrayref, $labels_hashref) = &GetborCatFromCatType();
1322
1323 Looks up the different types of borrowers in the database. Returns two
1324 elements: a reference-to-array, which lists the borrower category
1325 codes, and a reference-to-hash, which maps the borrower category codes
1326 to category descriptions.
1327
1328 =cut
1329
1330 #'
1331 sub GetborCatFromCatType {
1332     my ( $category_type, $action ) = @_;
1333     my $dbh     = C4::Context->dbh;
1334     my $request = qq|   SELECT categorycode,description 
1335                         FROM categories 
1336                         $action
1337                         ORDER BY categorycode|;
1338     my $sth = $dbh->prepare($request);
1339     if ($action) {
1340         $sth->execute($category_type);
1341     }
1342     else {
1343         $sth->execute();
1344     }
1345
1346     my %labels;
1347     my @codes;
1348
1349     while ( my $data = $sth->fetchrow_hashref ) {
1350         push @codes, $data->{'categorycode'};
1351         $labels{ $data->{'categorycode'} } = $data->{'description'};
1352     }
1353     $sth->finish;
1354     return ( \@codes, \%labels );
1355 }
1356
1357 =head2 GetBorrowercategory
1358
1359   $hashref = &GetBorrowercategory($categorycode);
1360
1361 Given the borrower's category code, the function returns the corresponding
1362 data hashref for a comprehensive information display.
1363
1364 =cut
1365
1366 sub GetBorrowercategory {
1367     my ($catcode) = @_;
1368     my $dbh       = C4::Context->dbh;
1369     my $sth       =
1370       $dbh->prepare(
1371 "SELECT description,dateofbirthrequired,upperagelimit,category_type 
1372  FROM categories 
1373  WHERE categorycode = ?"
1374       );
1375     $sth->execute($catcode);
1376     my $data =
1377       $sth->fetchrow_hashref;
1378     $sth->finish();
1379     return $data;
1380 }    # sub getborrowercategory
1381
1382 =head2 ethnicitycategories
1383
1384   ($codes_arrayref, $labels_hashref) = &ethnicitycategories();
1385
1386 Looks up the different ethnic types in the database. Returns two
1387 elements: a reference-to-array, which lists the ethnicity codes, and a
1388 reference-to-hash, which maps the ethnicity codes to ethnicity
1389 descriptions.
1390
1391 =cut
1392
1393 #'
1394
1395 sub ethnicitycategories {
1396     my $dbh = C4::Context->dbh;
1397     my $sth = $dbh->prepare("Select code,name from ethnicity order by name");
1398     $sth->execute;
1399     my %labels;
1400     my @codes;
1401     while ( my $data = $sth->fetchrow_hashref ) {
1402         push @codes, $data->{'code'};
1403         $labels{ $data->{'code'} } = $data->{'name'};
1404     }
1405     $sth->finish;
1406     return ( \@codes, \%labels );
1407 }
1408
1409 =head2 fixEthnicity
1410
1411   $ethn_name = &fixEthnicity($ethn_code);
1412
1413 Takes an ethnicity code (e.g., "european" or "pi") and returns the
1414 corresponding descriptive name from the C<ethnicity> table in the
1415 Koha database ("European" or "Pacific Islander").
1416
1417 =cut
1418
1419 #'
1420
1421 sub fixEthnicity {
1422     my $ethnicity = shift;
1423     return unless $ethnicity;
1424     my $dbh       = C4::Context->dbh;
1425     my $sth       = $dbh->prepare("Select name from ethnicity where code = ?");
1426     $sth->execute($ethnicity);
1427     my $data = $sth->fetchrow_hashref;
1428     $sth->finish;
1429     return $data->{'name'};
1430 }    # sub fixEthnicity
1431
1432 =head2 GetAge
1433
1434   $dateofbirth,$date = &GetAge($date);
1435
1436 this function return the borrowers age with the value of dateofbirth
1437
1438 =cut
1439
1440 #'
1441 sub GetAge{
1442     my ( $date, $date_ref ) = @_;
1443
1444     if ( not defined $date_ref ) {
1445         $date_ref = sprintf( '%04d-%02d-%02d', Today() );
1446     }
1447
1448     my ( $year1, $month1, $day1 ) = split /-/, $date;
1449     my ( $year2, $month2, $day2 ) = split /-/, $date_ref;
1450
1451     my $age = $year2 - $year1;
1452     if ( $month1 . $day1 > $month2 . $day2 ) {
1453         $age--;
1454     }
1455
1456     return $age;
1457 }    # sub get_age
1458
1459 =head2 get_institutions
1460   $insitutions = get_institutions();
1461
1462 Just returns a list of all the borrowers of type I, borrownumber and name
1463
1464 =cut
1465
1466 #'
1467 sub get_institutions {
1468     my $dbh = C4::Context->dbh();
1469     my $sth =
1470       $dbh->prepare(
1471 "SELECT borrowernumber,surname FROM borrowers WHERE categorycode=? ORDER BY surname"
1472       );
1473     $sth->execute('I');
1474     my %orgs;
1475     while ( my $data = $sth->fetchrow_hashref() ) {
1476         $orgs{ $data->{'borrowernumber'} } = $data;
1477     }
1478     $sth->finish();
1479     return ( \%orgs );
1480
1481 }    # sub get_institutions
1482
1483 =head2 add_member_orgs
1484
1485   add_member_orgs($borrowernumber,$borrowernumbers);
1486
1487 Takes a borrowernumber and a list of other borrowernumbers and inserts them into the borrowers_to_borrowers table
1488
1489 =cut
1490
1491 #'
1492 sub add_member_orgs {
1493     my ( $borrowernumber, $otherborrowers ) = @_;
1494     my $dbh   = C4::Context->dbh();
1495     my $query =
1496       "INSERT INTO borrowers_to_borrowers (borrower1,borrower2) VALUES (?,?)";
1497     my $sth = $dbh->prepare($query);
1498     foreach my $otherborrowernumber (@$otherborrowers) {
1499         $sth->execute( $borrowernumber, $otherborrowernumber );
1500     }
1501     $sth->finish();
1502
1503 }    # sub add_member_orgs
1504
1505 =head2 GetCities (OUEST-PROVENCE)
1506
1507   ($id_cityarrayref, $city_hashref) = &GetCities();
1508
1509 Looks up the different city and zip in the database. Returns two
1510 elements: a reference-to-array, which lists the zip city
1511 codes, and a reference-to-hash, which maps the name of the city.
1512 WHERE =>OUEST PROVENCE OR EXTERIEUR
1513
1514 =cut
1515
1516 sub GetCities {
1517
1518     #my ($type_city) = @_;
1519     my $dbh   = C4::Context->dbh;
1520     my $query = qq|SELECT cityid,city_name 
1521                 FROM cities 
1522                 ORDER BY city_name|;
1523     my $sth = $dbh->prepare($query);
1524
1525     #$sth->execute($type_city);
1526     $sth->execute();
1527     my %city;
1528     my @id;
1529
1530     #    insert empty value to create a empty choice in cgi popup
1531
1532     while ( my $data = $sth->fetchrow_hashref ) {
1533
1534         push @id, $data->{'cityid'};
1535         $city{ $data->{'cityid'} } = $data->{'city_name'};
1536     }
1537
1538 #test to know if the table contain some records if no the function return nothing
1539     my $id = @id;
1540     $sth->finish;
1541     if ( $id eq 0 ) {
1542         return ();
1543     }
1544     else {
1545         unshift( @id, "" );
1546         return ( \@id, \%city );
1547     }
1548 }
1549
1550 =head2 GetSortDetails (OUEST-PROVENCE)
1551
1552   ($lib) = &GetSortDetails($category,$sortvalue);
1553
1554 Returns the authorized value  details
1555 C<&$lib>return value of authorized value details
1556 C<&$sortvalue>this is the value of authorized value 
1557 C<&$category>this is the value of authorized value category
1558
1559 =cut
1560
1561 sub GetSortDetails {
1562     my ( $category, $sortvalue ) = @_;
1563     my $dbh   = C4::Context->dbh;
1564     my $query = qq|SELECT lib 
1565                 FROM authorised_values 
1566                 WHERE category=?
1567                 AND authorised_value=? |;
1568     my $sth = $dbh->prepare($query);
1569     $sth->execute( $category, $sortvalue );
1570     my $lib = $sth->fetchrow;
1571     return ($lib);
1572 }
1573
1574 =head2 DeleteBorrower 
1575
1576   () = &DeleteBorrower($member);
1577
1578 delete all data fo borrowers and add record to deletedborrowers table
1579 C<&$member>this is the borrowernumber
1580
1581 =cut
1582
1583 sub MoveMemberToDeleted {
1584     my ($member) = @_;
1585     my $dbh = C4::Context->dbh;
1586     my $query;
1587     $query = qq|SELECT * 
1588                   FROM borrowers 
1589                   WHERE borrowernumber=?|;
1590     my $sth = $dbh->prepare($query);
1591     $sth->execute($member);
1592     my @data = $sth->fetchrow_array;
1593     $sth->finish;
1594     $sth =
1595       $dbh->prepare( "INSERT INTO deletedborrowers VALUES ("
1596           . ( "?," x ( scalar(@data) - 1 ) )
1597           . "?)" );
1598     $sth->execute(@data);
1599     $sth->finish;
1600 }
1601
1602 =head2 DelMember
1603
1604 DelMember($borrowernumber);
1605
1606 This function remove directly a borrower whitout writing it on deleteborrower.
1607 + Deletes reserves for the borrower
1608
1609 =cut
1610
1611 sub DelMember {
1612     my $dbh            = C4::Context->dbh;
1613     my $borrowernumber = shift;
1614         warn "in delmember with $borrowernumber";
1615     return unless $borrowernumber;    # borrowernumber is mandatory.
1616
1617     my $query = qq|DELETE 
1618                   FROM  reserves 
1619                   WHERE borrowernumber=?|;
1620     my $sth = $dbh->prepare($query);
1621     $sth->execute($borrowernumber);
1622     $sth->finish;
1623     $query = "
1624        DELETE
1625        FROM borrowers
1626        WHERE borrowernumber = ?
1627    ";
1628     $sth = $dbh->prepare($query);
1629     $sth->execute($borrowernumber);
1630     $sth->finish;
1631     &logaction(C4::Context->userenv->{'number'},"MEMBERS","DELETE",$borrowernumber,"") 
1632         if C4::Context->preference("BorrowersLog");
1633     return $sth->rows;
1634 }
1635
1636 =head2 ExtendMemberSubscriptionTo (OUEST-PROVENCE)
1637
1638 $date= ExtendMemberSubscriptionTo($borrowerid, $date);
1639 Extending the subscription to a given date or to the expiry date calculated on local date.
1640 returns date 
1641 =cut
1642
1643 sub ExtendMemberSubscriptionTo {
1644     my ( $borrowerid,$date) = @_;
1645     my $dbh = C4::Context->dbh;
1646     unless ($date){
1647       $date=POSIX::strftime("%Y-%m-%d",localtime(time));
1648       my $borrower = GetMember($borrowerid,'borrowernumber');
1649       $date = GetExpiryDate( $borrower->{'categorycode'}, $date );
1650     }
1651     my $sth = $dbh->do(<<EOF);
1652 UPDATE borrowers 
1653 SET  dateexpiry='$date' 
1654 WHERE borrowernumber='$borrowerid'
1655 EOF
1656     return $date if ($sth);
1657     return 0;
1658 }
1659
1660 =head2 GetRoadTypes (OUEST-PROVENCE)
1661
1662   ($idroadtypearrayref, $roadttype_hashref) = &GetRoadTypes();
1663
1664 Looks up the different road type . Returns two
1665 elements: a reference-to-array, which lists the id_roadtype
1666 codes, and a reference-to-hash, which maps the road type of the road .
1667
1668
1669 =cut
1670
1671 sub GetRoadTypes {
1672     my $dbh   = C4::Context->dbh;
1673     my $query = qq|
1674 SELECT roadtypeid,road_type 
1675 FROM roadtype 
1676 ORDER BY road_type|;
1677     my $sth = $dbh->prepare($query);
1678     $sth->execute();
1679     my %roadtype;
1680     my @id;
1681
1682     #    insert empty value to create a empty choice in cgi popup
1683
1684     while ( my $data = $sth->fetchrow_hashref ) {
1685
1686         push @id, $data->{'roadtypeid'};
1687         $roadtype{ $data->{'roadtypeid'} } = $data->{'road_type'};
1688     }
1689
1690 #test to know if the table contain some records if no the function return nothing
1691     my $id = @id;
1692     $sth->finish;
1693     if ( $id eq 0 ) {
1694         return ();
1695     }
1696     else {
1697         unshift( @id, "" );
1698         return ( \@id, \%roadtype );
1699     }
1700 }
1701
1702
1703
1704 =head2 GetTitles (OUEST-PROVENCE)
1705
1706   ($borrowertitle)= &GetTitles();
1707
1708 Looks up the different title . Returns array  with all borrowers title
1709
1710 =cut
1711
1712 sub GetTitles {
1713     my @borrowerTitle = split /,|\|/,C4::Context->preference('BorrowersTitles');
1714     unshift( @borrowerTitle, "" );
1715     return ( \@borrowerTitle);
1716     }
1717
1718
1719
1720 =head2 GetRoadTypeDetails (OUEST-PROVENCE)
1721
1722   ($roadtype) = &GetRoadTypeDetails($roadtypeid);
1723
1724 Returns the description of roadtype
1725 C<&$roadtype>return description of road type
1726 C<&$roadtypeid>this is the value of roadtype s
1727
1728 =cut
1729
1730 sub GetRoadTypeDetails {
1731     my ($roadtypeid) = @_;
1732     my $dbh          = C4::Context->dbh;
1733     my $query        = qq|
1734 SELECT road_type 
1735 FROM roadtype 
1736 WHERE roadtypeid=?|;
1737     my $sth = $dbh->prepare($query);
1738     $sth->execute($roadtypeid);
1739     my $roadtype = $sth->fetchrow;
1740     return ($roadtype);
1741 }
1742
1743 =head2 GetBorrowersWhoHaveNotBorrowedSince
1744
1745 &GetBorrowersWhoHaveNotBorrowedSince($date)
1746
1747 this function get all borrowers who haven't borrowed since the date given on input arg.
1748
1749 =cut
1750
1751 sub GetBorrowersWhoHaveNotBorrowedSince {
1752     my $date = shift;
1753     return unless $date;    # date is mandatory.
1754     my $dbh   = C4::Context->dbh;
1755     my $query = "
1756         SELECT borrowers.borrowernumber,max(timestamp)
1757         FROM   borrowers
1758           LEFT JOIN issues ON borrowers.borrowernumber = issues.borrowernumber
1759         WHERE issues.borrowernumber IS NOT NULL
1760         GROUP BY borrowers.borrowernumber
1761    ";
1762     my $sth = $dbh->prepare($query);
1763     $sth->execute;
1764     my @results;
1765
1766     while ( my $data = $sth->fetchrow_hashref ) {
1767         push @results, $data;
1768     }
1769     return \@results;
1770 }
1771
1772 =head2 GetBorrowersWhoHaveNeverBorrowed
1773
1774 $results = &GetBorrowersWhoHaveNeverBorrowed
1775
1776 this function get all borrowers who have never borrowed.
1777
1778 I<$result> is a ref to an array which all elements are a hasref.
1779
1780 =cut
1781
1782 sub GetBorrowersWhoHaveNeverBorrowed {
1783     my $dbh   = C4::Context->dbh;
1784     my $query = "
1785         SELECT borrowers.borrowernumber,max(timestamp)
1786         FROM   borrowers
1787           LEFT JOIN issues ON borrowers.borrowernumber = issues.borrowernumber
1788         WHERE issues.borrowernumber IS NULL
1789    ";
1790     my $sth = $dbh->prepare($query);
1791     $sth->execute;
1792     my @results;
1793     while ( my $data = $sth->fetchrow_hashref ) {
1794         push @results, $data;
1795     }
1796     return \@results;
1797 }
1798
1799 =head2 GetBorrowersWithIssuesHistoryOlderThan
1800
1801 $results = &GetBorrowersWithIssuesHistoryOlderThan($date)
1802
1803 this function get all borrowers who has an issue history older than I<$date> given on input arg.
1804
1805 I<$result> is a ref to an array which all elements are a hashref.
1806 This hashref is containt the number of time this borrowers has borrowed before I<$date> and the borrowernumber.
1807
1808 =cut
1809
1810 sub GetBorrowersWithIssuesHistoryOlderThan {
1811     my $dbh  = C4::Context->dbh;
1812     my $date = shift;
1813     return unless $date;    # date is mandatory.
1814     my $query = "
1815        SELECT count(borrowernumber) as n,borrowernumber
1816        FROM issues
1817        WHERE returndate < ?
1818          AND borrowernumber IS NOT NULL 
1819        GROUP BY borrowernumber
1820    ";
1821     my $sth = $dbh->prepare($query);
1822     $sth->execute($date);
1823     my @results;
1824
1825     while ( my $data = $sth->fetchrow_hashref ) {
1826         push @results, $data;
1827     }
1828     return \@results;
1829 }
1830
1831 END { }    # module clean-up code here (global destructor)
1832
1833 1;
1834
1835 __END__
1836
1837 =back
1838
1839 =head1 AUTHOR
1840
1841 Koha Team
1842
1843 =cut