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