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