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