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