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