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