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