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