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