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