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