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