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