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