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