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