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