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