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