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