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