Assigning bug 1835 : change password would never log password change.
[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 use C4::Context;
23 use C4::Dates qw(format_date_in_iso);
24 use Digest::MD5 qw(md5_base64);
25 use Date::Calc qw/Today Add_Delta_YM/;
26 use C4::Log; # logaction
27 use C4::Overdues;
28 use C4::Reserves;
29 use C4::Accounts;
30
31 our ($VERSION,@ISA,@EXPORT,@EXPORT_OK,$debug);
32
33 BEGIN {
34         $VERSION = 3.02;
35         $debug = $ENV{DEBUG} || 0;
36         require Exporter;
37         @ISA = qw(Exporter);
38         #Get data
39         push @EXPORT, qw(
40                 &SearchMember 
41                 &GetMemberDetails
42                 &GetMember
43
44                 &GetGuarantees 
45
46                 &GetMemberIssuesAndFines
47                 &GetPendingIssues
48                 &GetAllIssues
49
50                 &get_institutions 
51                 &getzipnamecity 
52                 &getidcity
53
54                 &GetAge 
55                 &GetCities 
56                 &GetRoadTypes 
57                 &GetRoadTypeDetails 
58                 &GetSortDetails
59                 &GetTitles
60
61     &GetPatronImage
62     &PutPatronImage
63     &RmPatronImage
64
65                 &GetMemberAccountRecords
66                 &GetBorNotifyAcctRecord
67
68                 &GetborCatFromCatType 
69                 &GetBorrowercategory
70
71                 &GetBorrowersWhoHaveNotBorrowedSince
72                 &GetBorrowersWhoHaveNeverBorrowed
73                 &GetBorrowersWithIssuesHistoryOlderThan
74
75                 &GetExpiryDate
76         );
77
78         #Modify data
79         push @EXPORT, qw(
80                 &ModMember
81                 &changepassword
82         );
83
84         #Delete data
85         push @EXPORT, qw(
86                 &DelMember
87         );
88
89         #Insert data
90         push @EXPORT, qw(
91                 &AddMember
92                 &add_member_orgs
93                 &MoveMemberToDeleted
94                 &ExtendMemberSubscriptionTo 
95         );
96
97         #Check data
98         push @EXPORT, qw(
99                 &checkuniquemember 
100                 &checkuserpassword
101                 &Check_Userid
102                 &fixEthnicity
103                 &ethnicitycategories 
104                 &fixup_cardnumber
105                 &checkcardnumber
106         );
107 }
108
109 =head1 NAME
110
111 C4::Members - Perl Module containing convenience functions for member handling
112
113 =head1 SYNOPSIS
114
115 use C4::Members;
116
117 =head1 DESCRIPTION
118
119 This module contains routines for adding, modifying and deleting members/patrons/borrowers 
120
121 =head1 FUNCTIONS
122
123 =over 2
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{'CREDITS'} = \%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         ($data) and return ($data);
527     }
528     return undef;        
529 }
530
531 =item GetMemberIssuesAndFines
532
533   ($overdue_count, $issue_count, $total_fines) = &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<$overdue_count> is the
539 number of overdue items the patron currently has borrowed. C<$issue_count> is the
540 number of books the patron currently has borrowed.  C<$total_fines> 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 = "SELECT COUNT(*) FROM issues WHERE borrowernumber = ?";
550
551     $debug and warn $query."\n";
552     my $sth = $dbh->prepare($query);
553     $sth->execute($borrowernumber);
554     my $issue_count = $sth->fetchrow_arrayref->[0];
555     $sth->finish;
556
557     $sth = $dbh->prepare(
558         "SELECT COUNT(*) FROM issues 
559          WHERE borrowernumber = ? 
560          AND date_due < now()"
561     );
562     $sth->execute($borrowernumber);
563     my $overdue_count = $sth->fetchrow_arrayref->[0];
564     $sth->finish;
565
566     $sth = $dbh->prepare("SELECT SUM(amountoutstanding) FROM accountlines WHERE borrowernumber = ?");
567     $sth->execute($borrowernumber);
568     my $total_fines = $sth->fetchrow_arrayref->[0];
569     $sth->finish;
570
571     return ($overdue_count, $issue_count, $total_fines);
572 }
573
574 =head2
575
576 =item ModMember
577
578   &ModMember($borrowernumber);
579
580 Modify borrower's data.  All date fields should ALREADY be in ISO format.
581
582 =cut
583
584 #'
585 sub ModMember {
586     my (%data) = @_;
587     my $dbh = C4::Context->dbh;
588     my $iso_re = C4::Dates->new()->regexp('iso');
589     foreach (qw(dateofbirth dateexpiry dateenrolled)) {
590         if (my $tempdate = $data{$_}) {                                 # assignment, not comparison
591             ($tempdate =~ /$iso_re/) and next;                          # Congatulations, you sent a valid ISO date.
592             warn "ModMember given $_ not in ISO format ($tempdate)";
593             if (my $tempdate2 = format_date_in_iso($tempdate)) {        # assignment, not comparison
594                 $data{$_} = $tempdate2;
595             } else {
596                 warn "ModMember cannot convert '$tempdate' (from syspref)";
597             }
598         }
599     }
600     if (!$data{'dateofbirth'}){
601         undef $data{'dateofbirth'};
602     }
603     my $qborrower=$dbh->prepare("SHOW columns from borrowers");
604     $qborrower->execute;
605     my %hashborrowerfields;  
606     while (my ($field)=$qborrower->fetchrow){
607       $hashborrowerfields{$field}=1;
608     }  
609     my $query = "UPDATE borrowers SET \n";
610     my $sth;
611     my @parameters;  
612     
613     # test to know if you must update or not the borrower password
614     if ( $data{'password'} eq '****' ) {
615         delete $data{'password'};
616     } else {
617         $data{'password'} = md5_base64( $data{'password'} )  if ($data{'password'} ne "");
618         delete $data{'password'} if ($data{password} eq "");
619     }
620     foreach (keys %data)
621     { push @parameters,"$_ = ".$dbh->quote($data{$_}) if ($_ ne 'borrowernumber' and $_ ne 'flags' and $hashborrowerfields{$_}); }
622     $query .= join (',',@parameters) . "\n WHERE borrowernumber=? \n";
623     $debug and print STDERR "$query (executed w/ arg: $data{'borrowernumber'})";
624     $sth = $dbh->prepare($query);
625     $sth->execute($data{'borrowernumber'});
626     $sth->finish;
627
628 # ok if its an adult (type) it may have borrowers that depend on it as a guarantor
629 # so when we update information for an adult we should check for guarantees and update the relevant part
630 # of their records, ie addresses and phone numbers
631     my $borrowercategory= GetBorrowercategory( $data{'category_type'} );
632     if ( $borrowercategory->{'category_type'} eq ('A' || 'S') ) {
633         # is adult check guarantees;
634         UpdateGuarantees(%data);
635     }
636     logaction("MEMBERS", "MODIFY", $data{'borrowernumber'}, "$query (executed w/ arg: $data{'borrowernumber'})") 
637         if C4::Context->preference("BorrowersLog");
638 }
639
640
641 =head2
642
643 =item AddMember
644
645   $borrowernumber = &AddMember(%borrower);
646
647 insert new borrower into table
648 Returns the borrowernumber
649
650 =cut
651
652 #'
653 sub AddMember {
654     my (%data) = @_;
655     my $dbh = C4::Context->dbh;
656     $data{'userid'} = '' unless $data{'password'};
657     $data{'password'} = md5_base64( $data{'password'} ) if $data{'password'};
658     
659     # WE SHOULD NEVER PASS THIS SUBROUTINE ANYTHING OTHER THAN ISO DATES
660     # IF YOU UNCOMMENT THESE LINES YOU BETTER HAVE A DARN COMPELLING REASON
661 #    $data{'dateofbirth'}  = format_date_in_iso( $data{'dateofbirth'} );
662 #    $data{'dateenrolled'} = format_date_in_iso( $data{'dateenrolled'});
663 #    $data{'dateexpiry'}   = format_date_in_iso( $data{'dateexpiry'}  );
664     # This query should be rewritten to use "?" at execute.
665     if (!$data{'dateofbirth'}){
666         undef ($data{'dateofbirth'});
667     }
668     my $query =
669         "insert into borrowers set cardnumber=" . $dbh->quote( $data{'cardnumber'} )
670       . ",surname="     . $dbh->quote( $data{'surname'} )
671       . ",firstname="   . $dbh->quote( $data{'firstname'} )
672       . ",title="       . $dbh->quote( $data{'title'} )
673       . ",othernames="  . $dbh->quote( $data{'othernames'} )
674       . ",initials="    . $dbh->quote( $data{'initials'} )
675       . ",streetnumber=". $dbh->quote( $data{'streetnumber'} )
676       . ",streettype="  . $dbh->quote( $data{'streettype'} )
677       . ",address="     . $dbh->quote( $data{'address'} )
678       . ",address2="    . $dbh->quote( $data{'address2'} )
679       . ",zipcode="     . $dbh->quote( $data{'zipcode'} )
680       . ",city="        . $dbh->quote( $data{'city'} )
681       . ",phone="       . $dbh->quote( $data{'phone'} )
682       . ",email="       . $dbh->quote( $data{'email'} )
683       . ",mobile="      . $dbh->quote( $data{'mobile'} )
684       . ",phonepro="    . $dbh->quote( $data{'phonepro'} )
685       . ",opacnote="    . $dbh->quote( $data{'opacnote'} )
686       . ",guarantorid=" . $dbh->quote( $data{'guarantorid'} )
687       . ",dateofbirth=" . $dbh->quote( $data{'dateofbirth'} )
688       . ",branchcode="  . $dbh->quote( $data{'branchcode'} )
689       . ",categorycode=" . $dbh->quote( $data{'categorycode'} )
690       . ",dateenrolled=" . $dbh->quote( $data{'dateenrolled'} )
691       . ",contactname=" . $dbh->quote( $data{'contactname'} )
692       . ",borrowernotes=" . $dbh->quote( $data{'borrowernotes'} )
693       . ",dateexpiry="  . $dbh->quote( $data{'dateexpiry'} )
694       . ",contactnote=" . $dbh->quote( $data{'contactnote'} )
695       . ",B_address="   . $dbh->quote( $data{'B_address'} )
696       . ",B_zipcode="   . $dbh->quote( $data{'B_zipcode'} )
697       . ",B_city="      . $dbh->quote( $data{'B_city'} )
698       . ",B_phone="     . $dbh->quote( $data{'B_phone'} )
699       . ",B_email="     . $dbh->quote( $data{'B_email'} )
700       . ",password="    . $dbh->quote( $data{'password'} )
701       . ",userid="      . $dbh->quote( $data{'userid'} )
702       . ",sort1="       . $dbh->quote( $data{'sort1'} )
703       . ",sort2="       . $dbh->quote( $data{'sort2'} )
704       . ",contacttitle=" . $dbh->quote( $data{'contacttitle'} )
705       . ",emailpro="    . $dbh->quote( $data{'emailpro'} )
706       . ",contactfirstname=" . $dbh->quote( $data{'contactfirstname'} )
707       . ",sex="         . $dbh->quote( $data{'sex'} )
708       . ",fax="         . $dbh->quote( $data{'fax'} )
709       . ",relationship=" . $dbh->quote( $data{'relationship'} )
710       . ",B_streetnumber=" . $dbh->quote( $data{'B_streetnumber'} )
711       . ",B_streettype=" . $dbh->quote( $data{'B_streettype'} )
712       . ",gonenoaddress=" . $dbh->quote( $data{'gonenoaddress'} )
713       . ",lost="        . $dbh->quote( $data{'lost'} )
714       . ",debarred="    . $dbh->quote( $data{'debarred'} )
715       . ",ethnicity="   . $dbh->quote( $data{'ethnicity'} )
716       . ",ethnotes="    . $dbh->quote( $data{'ethnotes'} ) 
717       . ",altcontactsurname="   . $dbh->quote( $data{'altcontactsurname'} ) 
718       . ",altcontactfirstname="     . $dbh->quote( $data{'altcontactfirstname'} ) 
719       . ",altcontactaddress1="  . $dbh->quote( $data{'altcontactaddress1'} ) 
720       . ",altcontactaddress2="  . $dbh->quote( $data{'altcontactaddress2'} ) 
721       . ",altcontactaddress3="  . $dbh->quote( $data{'altcontactaddress3'} ) 
722       . ",altcontactzipcode="   . $dbh->quote( $data{'altcontactzipcode'} ) 
723       . ",altcontactphone="     . $dbh->quote( $data{'altcontactphone'} ) ;
724     $debug and print STDERR "AddMember SQL: ($query)\n";
725     my $sth = $dbh->prepare($query);
726     #   print "Executing SQL: $query\n";
727     $sth->execute();
728     $sth->finish;
729     $data{'borrowernumber'} = $dbh->{'mysql_insertid'};     # unneeded w/ autoincrement ?  
730     # mysql_insertid is probably bad.  not necessarily accurate and mysql-specific at best.
731     
732     logaction("MEMBERS", "CREATE", $data{'borrowernumber'}, "") if C4::Context->preference("BorrowersLog");
733     
734     # check for enrollment fee & add it if needed
735     $sth = $dbh->prepare("SELECT enrolmentfee FROM categories WHERE categorycode=?");
736     $sth->execute($data{'categorycode'});
737     my ($enrolmentfee) = $sth->fetchrow;
738     if ($enrolmentfee) {
739         # insert fee in patron debts
740         manualinvoice($data{'borrowernumber'}, '', '', 'A', $enrolmentfee);
741     }
742     return $data{'borrowernumber'};
743 }
744
745 sub Check_Userid {
746     my ($uid,$member) = @_;
747     my $dbh = C4::Context->dbh;
748     # Make sure the userid chosen is unique and not theirs if non-empty. If it is not,
749     # Then we need to tell the user and have them create a new one.
750     my $sth =
751       $dbh->prepare(
752         "SELECT * FROM borrowers WHERE userid=? AND borrowernumber != ?");
753     $sth->execute( $uid, $member );
754     if ( ( $uid ne '' ) && ( my $row = $sth->fetchrow_hashref ) ) {
755         return 0;
756     }
757     else {
758         return 1;
759     }
760 }
761
762
763 sub changepassword {
764     my ( $uid, $member, $digest ) = @_;
765     my $dbh = C4::Context->dbh;
766
767 #Make sure the userid chosen is unique and not theirs if non-empty. If it is not,
768 #Then we need to tell the user and have them create a new one.
769     my $resultcode;
770     my $sth =
771       $dbh->prepare(
772         "SELECT * FROM borrowers WHERE userid=? AND borrowernumber != ?");
773     $sth->execute( $uid, $member );
774     if ( ( $uid ne '' ) && ( my $row = $sth->fetchrow_hashref ) ) {
775         $resultcode=0;
776     }
777     else {
778         #Everything is good so we can update the information.
779         $sth =
780           $dbh->prepare(
781             "update borrowers set userid=?, password=? where borrowernumber=?");
782         $sth->execute( $uid, $digest, $member );
783         $resultcode=1;
784     }
785     
786     logaction("MEMBERS", "CHANGE PASS", $member, "") if C4::Context->preference("BorrowersLog");
787     return $resultcode;    
788 }
789
790
791
792 =item fixup_cardnumber
793
794 Warning: The caller is responsible for locking the members table in write
795 mode, to avoid database corruption.
796
797 =cut
798
799 use vars qw( @weightings );
800 my @weightings = ( 8, 4, 6, 3, 5, 2, 1 );
801
802 sub fixup_cardnumber ($) {
803     my ($cardnumber) = @_;
804     my $autonumber_members = C4::Context->boolean_preference('autoMemberNum');
805     $autonumber_members = 0 unless defined $autonumber_members;
806
807     # Find out whether member numbers should be generated
808     # automatically. Should be either "1" or something else.
809     # Defaults to "0", which is interpreted as "no".
810
811     #     if ($cardnumber !~ /\S/ && $autonumber_members) {
812     if ($autonumber_members) {
813         my $dbh = C4::Context->dbh;
814         if ( C4::Context->preference('checkdigit') eq 'katipo' ) {
815
816             # if checkdigit is selected, calculate katipo-style cardnumber.
817             # otherwise, just use the max()
818             # purpose: generate checksum'd member numbers.
819             # We'll assume we just got the max value of digits 2-8 of member #'s
820             # from the database and our job is to increment that by one,
821             # determine the 1st and 9th digits and return the full string.
822             my $sth =
823               $dbh->prepare(
824                 "select max(substring(borrowers.cardnumber,2,7)) from borrowers"
825               );
826             $sth->execute;
827
828             my $data = $sth->fetchrow_hashref;
829             $cardnumber = $data->{'max(substring(borrowers.cardnumber,2,7))'};
830             $sth->finish;
831             if ( !$cardnumber ) {    # If DB has no values,
832                 $cardnumber = 1000000;    # start at 1000000
833             }
834             else {
835                 $cardnumber += 1;
836             }
837
838             my $sum = 0;
839             for ( my $i = 0 ; $i < 8 ; $i += 1 ) {
840
841                 # read weightings, left to right, 1 char at a time
842                 my $temp1 = $weightings[$i];
843
844                 # sequence left to right, 1 char at a time
845                 my $temp2 = substr( $cardnumber, $i, 1 );
846
847                 # mult each char 1-7 by its corresponding weighting
848                 $sum += $temp1 * $temp2;
849             }
850
851             my $rem = ( $sum % 11 );
852             $rem = 'X' if $rem == 10;
853
854             $cardnumber = "V$cardnumber$rem";
855         }
856         else {
857
858      # MODIFIED BY JF: mysql4.1 allows casting as an integer, which is probably
859      # better. I'll leave the original in in case it needs to be changed for you
860             my $sth =
861               $dbh->prepare(
862                 "select max(cast(cardnumber as signed)) from borrowers");
863
864       #my $sth=$dbh->prepare("select max(borrowers.cardnumber) from borrowers");
865
866             $sth->execute;
867
868             my ($result) = $sth->fetchrow;
869             $sth->finish;
870             $cardnumber = $result + 1;
871         }
872     }
873     return $cardnumber;
874 }
875
876 =head2 GetGuarantees
877
878   ($num_children, $children_arrayref) = &GetGuarantees($parent_borrno);
879   $child0_cardno = $children_arrayref->[0]{"cardnumber"};
880   $child0_borrno = $children_arrayref->[0]{"borrowernumber"};
881
882 C<&GetGuarantees> takes a borrower number (e.g., that of a patron
883 with children) and looks up the borrowers who are guaranteed by that
884 borrower (i.e., the patron's children).
885
886 C<&GetGuarantees> returns two values: an integer giving the number of
887 borrowers guaranteed by C<$parent_borrno>, and a reference to an array
888 of references to hash, which gives the actual results.
889
890 =cut
891
892 #'
893 sub GetGuarantees {
894     my ($borrowernumber) = @_;
895     my $dbh              = C4::Context->dbh;
896     my $sth              =
897       $dbh->prepare(
898 "select cardnumber,borrowernumber, firstname, surname from borrowers where guarantorid=?"
899       );
900     $sth->execute($borrowernumber);
901
902     my @dat;
903     my $data = $sth->fetchall_arrayref({}); 
904     $sth->finish;
905     return ( scalar(@$data), $data );
906 }
907
908 =head2 UpdateGuarantees
909
910   &UpdateGuarantees($parent_borrno);
911   
912
913 C<&UpdateGuarantees> borrower data for an adulte and updates all the guarantees
914 with the modified information
915
916 =cut
917
918 #'
919 sub UpdateGuarantees {
920     my (%data) = @_;
921     my $dbh = C4::Context->dbh;
922     my ( $count, $guarantees ) = GetGuarantees( $data{'borrowernumber'} );
923     for ( my $i = 0 ; $i < $count ; $i++ ) {
924
925         # FIXME
926         # It looks like the $i is only being returned to handle walking through
927         # the array, which is probably better done as a foreach loop.
928         #
929         my $guaquery = qq|UPDATE borrowers 
930               SET address='$data{'address'}',fax='$data{'fax'}',
931                   B_city='$data{'B_city'}',mobile='$data{'mobile'}',city='$data{'city'}',phone='$data{'phone'}'
932               WHERE borrowernumber='$guarantees->[$i]->{'borrowernumber'}'
933         |;
934         my $sth3 = $dbh->prepare($guaquery);
935         $sth3->execute;
936         $sth3->finish;
937     }
938 }
939 =head2 GetPendingIssues
940
941   ($count, $issues) = &GetPendingIssues($borrowernumber);
942
943 Looks up what the patron with the given borrowernumber has borrowed.
944
945 C<&GetPendingIssues> returns a two-element array. C<$issues> is a
946 reference-to-array, where each element is a reference-to-hash; the
947 keys are the fields from the C<issues>, C<biblio>, and C<items> tables
948 in the Koha database. C<$count> is the number of elements in
949 C<$issues>.
950
951 =cut
952
953 #'
954 sub GetPendingIssues {
955     my ($borrowernumber) = @_;
956     my $dbh              = C4::Context->dbh;
957
958     my $sth              = $dbh->prepare(
959    "SELECT * FROM issues 
960       LEFT JOIN items ON issues.itemnumber=items.itemnumber
961       LEFT JOIN biblio ON     items.biblionumber=biblio.biblionumber 
962       LEFT JOIN biblioitems ON items.biblioitemnumber=biblioitems.biblioitemnumber
963     WHERE
964       borrowernumber=? 
965     ORDER BY issues.issuedate"
966     );
967     $sth->execute($borrowernumber);
968     my $data = $sth->fetchall_arrayref({});
969     my $today = POSIX::strftime("%Y%m%d", localtime);
970     foreach( @$data ) {
971         my $datedue = $_->{'date_due'};
972         $datedue =~ s/-//g;
973         if ( $datedue < $today ) {
974             $_->{'overdue'} = 1;
975         }
976     }
977     $sth->finish;
978     return ( scalar(@$data), $data );
979 }
980
981 =head2 GetAllIssues
982
983   ($count, $issues) = &GetAllIssues($borrowernumber, $sortkey, $limit);
984
985 Looks up what the patron with the given borrowernumber has borrowed,
986 and sorts the results.
987
988 C<$sortkey> is the name of a field on which to sort the results. This
989 should be the name of a field in the C<issues>, C<biblio>,
990 C<biblioitems>, or C<items> table in the Koha database.
991
992 C<$limit> is the maximum number of results to return.
993
994 C<&GetAllIssues> returns a two-element array. C<$issues> is a
995 reference-to-array, where each element is a reference-to-hash; the
996 keys are the fields from the C<issues>, C<biblio>, C<biblioitems>, and
997 C<items> tables of the Koha database. C<$count> is the number of
998 elements in C<$issues>
999
1000 =cut
1001
1002 #'
1003 sub GetAllIssues {
1004     my ( $borrowernumber, $order, $limit ) = @_;
1005
1006     #FIXME: sanity-check order and limit
1007     my $dbh   = C4::Context->dbh;
1008     my $count = 0;
1009     my $query =
1010   "SELECT *,items.timestamp AS itemstimestamp 
1011   FROM issues 
1012   LEFT JOIN items on items.itemnumber=issues.itemnumber
1013   LEFT JOIN biblio ON items.biblionumber=biblio.biblionumber
1014   LEFT JOIN biblioitems ON items.biblioitemnumber=biblioitems.biblioitemnumber
1015   WHERE borrowernumber=? 
1016   UNION ALL
1017   SELECT *,items.timestamp AS itemstimestamp 
1018   FROM old_issues 
1019   LEFT JOIN items on items.itemnumber=old_issues.itemnumber
1020   LEFT JOIN biblio ON items.biblionumber=biblio.biblionumber
1021   LEFT JOIN biblioitems ON items.biblioitemnumber=biblioitems.biblioitemnumber
1022   WHERE borrowernumber=? 
1023   order by $order";
1024     if ( $limit != 0 ) {
1025         $query .= " limit $limit";
1026     }
1027
1028     #print $query;
1029     my $sth = $dbh->prepare($query);
1030     $sth->execute($borrowernumber, $borrowernumber);
1031     my @result;
1032     my $i = 0;
1033     while ( my $data = $sth->fetchrow_hashref ) {
1034         $result[$i] = $data;
1035         $i++;
1036         $count++;
1037     }
1038
1039     # get all issued items for borrowernumber from oldissues table
1040     # large chunk of older issues data put into table oldissues
1041     # to speed up db calls for issuing items
1042     if ( C4::Context->preference("ReadingHistory") ) {
1043         # FIXME oldissues (not to be confused with old_issues) is
1044         # apparently specific to HLT.  Not sure if the ReadingHistory
1045         # syspref is still required, as old_issues by design
1046         # is no longer checked with each loan.
1047         my $query2 = "SELECT * FROM oldissues
1048                       LEFT JOIN items ON items.itemnumber=oldissues.itemnumber
1049                       LEFT JOIN biblio ON items.biblionumber=biblio.biblionumber
1050                       LEFT JOIN biblioitems ON items.biblioitemnumber=biblioitems.biblioitemnumber
1051                       WHERE borrowernumber=? 
1052                       ORDER BY $order";
1053         if ( $limit != 0 ) {
1054             $limit = $limit - $count;
1055             $query2 .= " limit $limit";
1056         }
1057
1058         my $sth2 = $dbh->prepare($query2);
1059         $sth2->execute($borrowernumber);
1060
1061         while ( my $data2 = $sth2->fetchrow_hashref ) {
1062             $result[$i] = $data2;
1063             $i++;
1064         }
1065         $sth2->finish;
1066     }
1067     $sth->finish;
1068
1069     return ( $i, \@result );
1070 }
1071
1072
1073 =head2 GetMemberAccountRecords
1074
1075   ($total, $acctlines, $count) = &GetMemberAccountRecords($borrowernumber);
1076
1077 Looks up accounting data for the patron with the given borrowernumber.
1078
1079 C<&GetMemberAccountRecords> returns a three-element array. C<$acctlines> is a
1080 reference-to-array, where each element is a reference-to-hash; the
1081 keys are the fields of the C<accountlines> table in the Koha database.
1082 C<$count> is the number of elements in C<$acctlines>. C<$total> is the
1083 total amount outstanding for all of the account lines.
1084
1085 =cut
1086
1087 #'
1088 sub GetMemberAccountRecords {
1089     my ($borrowernumber,$date) = @_;
1090     my $dbh = C4::Context->dbh;
1091     my @acctlines;
1092     my $numlines = 0;
1093     my $strsth      = qq(
1094                         SELECT * 
1095                         FROM accountlines 
1096                         WHERE borrowernumber=?);
1097     my @bind = ($borrowernumber);
1098     if ($date && $date ne ''){
1099             $strsth.=" AND date < ? ";
1100             push(@bind,$date);
1101     }
1102     $strsth.=" ORDER BY date desc,timestamp DESC";
1103     my $sth= $dbh->prepare( $strsth );
1104     $sth->execute( @bind );
1105     my $total = 0;
1106     while ( my $data = $sth->fetchrow_hashref ) {
1107         $acctlines[$numlines] = $data;
1108         $numlines++;
1109         $total += $data->{'amountoutstanding'};
1110     }
1111     $sth->finish;
1112     return ( $total, \@acctlines,$numlines);
1113 }
1114
1115 =head2 GetBorNotifyAcctRecord
1116
1117   ($count, $acctlines, $total) = &GetBorNotifyAcctRecord($params,$notifyid);
1118
1119 Looks up accounting data for the patron with the given borrowernumber per file number.
1120
1121 (FIXME - I'm not at all sure what this is about.)
1122
1123 C<&GetBorNotifyAcctRecord> returns a three-element array. C<$acctlines> is a
1124 reference-to-array, where each element is a reference-to-hash; the
1125 keys are the fields of the C<accountlines> table in the Koha database.
1126 C<$count> is the number of elements in C<$acctlines>. C<$total> is the
1127 total amount outstanding for all of the account lines.
1128
1129 =cut
1130
1131 sub GetBorNotifyAcctRecord {
1132     my ( $borrowernumber, $notifyid ) = @_;
1133     my $dbh = C4::Context->dbh;
1134     my @acctlines;
1135     my $numlines = 0;
1136     my $sth = $dbh->prepare(
1137             "SELECT * 
1138                 FROM accountlines 
1139                 WHERE borrowernumber=? 
1140                     AND notify_id=? 
1141                     AND amountoutstanding != '0' 
1142                 ORDER BY notify_id,accounttype
1143                 ");
1144 #                    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')
1145
1146     $sth->execute( $borrowernumber, $notifyid );
1147     my $total = 0;
1148     while ( my $data = $sth->fetchrow_hashref ) {
1149         $acctlines[$numlines] = $data;
1150         $numlines++;
1151         $total += $data->{'amountoutstanding'};
1152     }
1153     $sth->finish;
1154     return ( $total, \@acctlines, $numlines );
1155 }
1156
1157 =head2 checkuniquemember (OUEST-PROVENCE)
1158
1159   ($result,$categorycode)  = &checkuniquemember($collectivity,$surname,$firstname,$dateofbirth);
1160
1161 Checks that a member exists or not in the database.
1162
1163 C<&result> is nonzero (=exist) or 0 (=does not exist)
1164 C<&categorycode> is from categorycode table
1165 C<&collectivity> is 1 (= we add a collectivity) or 0 (= we add a physical member)
1166 C<&surname> is the surname
1167 C<&firstname> is the firstname (only if collectivity=0)
1168 C<&dateofbirth> is the date of birth in ISO format (only if collectivity=0)
1169
1170 =cut
1171
1172 # FIXME: This function is not legitimate.  Multiple patrons might have the same first/last name and birthdate.
1173 # This is especially true since first name is not even a required field.
1174
1175 sub checkuniquemember {
1176     my ( $collectivity, $surname, $firstname, $dateofbirth ) = @_;
1177     my $dbh = C4::Context->dbh;
1178     my $request = ($collectivity) ?
1179         "SELECT borrowernumber,categorycode FROM borrowers WHERE surname=? " :
1180         "SELECT borrowernumber,categorycode FROM borrowers WHERE surname=? and firstname=? and dateofbirth=? ";
1181     my $sth = $dbh->prepare($request);
1182     if ($collectivity) {
1183         $sth->execute( uc($surname) );
1184     } else {
1185         $sth->execute( uc($surname), ucfirst($firstname), $dateofbirth );
1186     }
1187     my @data = $sth->fetchrow;
1188     $sth->finish;
1189     ( $data[0] ) and return $data[0], $data[1];
1190     return 0;
1191 }
1192
1193 sub checkcardnumber {
1194     my ($cardnumber,$borrowernumber) = @_;
1195     my $dbh = C4::Context->dbh;
1196     my $query = "SELECT * FROM borrowers WHERE cardnumber=?";
1197     $query .= " AND borrowernumber <> ?" if ($borrowernumber);
1198   my $sth = $dbh->prepare($query);
1199   if ($borrowernumber) {
1200    $sth->execute($cardnumber,$borrowernumber);
1201   } else { 
1202      $sth->execute($cardnumber);
1203   } 
1204     if (my $data= $sth->fetchrow_hashref()){
1205         return 1;
1206     }
1207     else {
1208         return 0;
1209     }
1210     $sth->finish();
1211 }  
1212
1213
1214 =head2 getzipnamecity (OUEST-PROVENCE)
1215
1216 take all info from table city for the fields city and  zip
1217 check for the name and the zip code of the city selected
1218
1219 =cut
1220
1221 sub getzipnamecity {
1222     my ($cityid) = @_;
1223     my $dbh      = C4::Context->dbh;
1224     my $sth      =
1225       $dbh->prepare(
1226         "select city_name,city_zipcode from cities where cityid=? ");
1227     $sth->execute($cityid);
1228     my @data = $sth->fetchrow;
1229     return $data[0], $data[1];
1230 }
1231
1232
1233 =head2 getdcity (OUEST-PROVENCE)
1234
1235 recover cityid  with city_name condition
1236
1237 =cut
1238
1239 sub getidcity {
1240     my ($city_name) = @_;
1241     my $dbh = C4::Context->dbh;
1242     my $sth = $dbh->prepare("select cityid from cities where city_name=? ");
1243     $sth->execute($city_name);
1244     my $data = $sth->fetchrow;
1245     return $data;
1246 }
1247
1248
1249 =head2 GetExpiryDate 
1250
1251   $expirydate = GetExpiryDate($categorycode, $dateenrolled);
1252
1253 Calculate expiry date given a categorycode and starting date.  Date argument must be in ISO format.
1254 Return date is also in ISO format.
1255
1256 =cut
1257
1258 sub GetExpiryDate {
1259     my ( $categorycode, $dateenrolled ) = @_;
1260     my $enrolmentperiod = 12;   # reasonable default
1261     if ($categorycode) {
1262         my $dbh = C4::Context->dbh;
1263         my $sth = $dbh->prepare("select enrolmentperiod from categories where categorycode=?");
1264         $sth->execute($categorycode);
1265         $enrolmentperiod = $sth->fetchrow;
1266     }
1267     # die "GetExpiryDate: for enrollmentperiod $enrolmentperiod (category '$categorycode') starting $dateenrolled.\n";
1268     my @date = split /-/,$dateenrolled;
1269     return sprintf("%04d-%02d-%02d", Add_Delta_YM(@date,0,$enrolmentperiod));
1270 }
1271
1272 =head2 checkuserpassword (OUEST-PROVENCE)
1273
1274 check for the password and login are not used
1275 return the number of record 
1276 0=> NOT USED 1=> USED
1277
1278 =cut
1279
1280 sub checkuserpassword {
1281     my ( $borrowernumber, $userid, $password ) = @_;
1282     $password = md5_base64($password);
1283     my $dbh = C4::Context->dbh;
1284     my $sth =
1285       $dbh->prepare(
1286 "Select count(*) from borrowers where borrowernumber !=? and userid =? and password=? "
1287       );
1288     $sth->execute( $borrowernumber, $userid, $password );
1289     my $number_rows = $sth->fetchrow;
1290     return $number_rows;
1291
1292 }
1293
1294 =head2 GetborCatFromCatType
1295
1296   ($codes_arrayref, $labels_hashref) = &GetborCatFromCatType();
1297
1298 Looks up the different types of borrowers in the database. Returns two
1299 elements: a reference-to-array, which lists the borrower category
1300 codes, and a reference-to-hash, which maps the borrower category codes
1301 to category descriptions.
1302
1303 =cut
1304
1305 #'
1306 sub GetborCatFromCatType {
1307     my ( $category_type, $action ) = @_;
1308     my $dbh     = C4::Context->dbh;
1309     my $request = qq|   SELECT categorycode,description 
1310             FROM categories 
1311             $action
1312             ORDER BY categorycode|;
1313     my $sth = $dbh->prepare($request);
1314     if ($action) {
1315         $sth->execute($category_type);
1316     }
1317     else {
1318         $sth->execute();
1319     }
1320
1321     my %labels;
1322     my @codes;
1323
1324     while ( my $data = $sth->fetchrow_hashref ) {
1325         push @codes, $data->{'categorycode'};
1326         $labels{ $data->{'categorycode'} } = $data->{'description'};
1327     }
1328     $sth->finish;
1329     return ( \@codes, \%labels );
1330 }
1331
1332 =head2 GetBorrowercategory
1333
1334   $hashref = &GetBorrowercategory($categorycode);
1335
1336 Given the borrower's category code, the function returns the corresponding
1337 data hashref for a comprehensive information display.
1338
1339 =cut
1340
1341 sub GetBorrowercategory {
1342     my ($catcode) = @_;
1343     my $dbh       = C4::Context->dbh;
1344     my $sth       =
1345       $dbh->prepare(
1346 "SELECT description,dateofbirthrequired,upperagelimit,category_type 
1347  FROM categories 
1348  WHERE categorycode = ?"
1349       );
1350     $sth->execute($catcode);
1351     my $data =
1352       $sth->fetchrow_hashref;
1353     $sth->finish();
1354     return $data;
1355 }    # sub getborrowercategory
1356
1357 =head2 ethnicitycategories
1358
1359   ($codes_arrayref, $labels_hashref) = &ethnicitycategories();
1360
1361 Looks up the different ethnic types in the database. Returns two
1362 elements: a reference-to-array, which lists the ethnicity codes, and a
1363 reference-to-hash, which maps the ethnicity codes to ethnicity
1364 descriptions.
1365
1366 =cut
1367
1368 #'
1369
1370 sub ethnicitycategories {
1371     my $dbh = C4::Context->dbh;
1372     my $sth = $dbh->prepare("Select code,name from ethnicity order by name");
1373     $sth->execute;
1374     my %labels;
1375     my @codes;
1376     while ( my $data = $sth->fetchrow_hashref ) {
1377         push @codes, $data->{'code'};
1378         $labels{ $data->{'code'} } = $data->{'name'};
1379     }
1380     $sth->finish;
1381     return ( \@codes, \%labels );
1382 }
1383
1384 =head2 fixEthnicity
1385
1386   $ethn_name = &fixEthnicity($ethn_code);
1387
1388 Takes an ethnicity code (e.g., "european" or "pi") and returns the
1389 corresponding descriptive name from the C<ethnicity> table in the
1390 Koha database ("European" or "Pacific Islander").
1391
1392 =cut
1393
1394 #'
1395
1396 sub fixEthnicity {
1397     my $ethnicity = shift;
1398     return unless $ethnicity;
1399     my $dbh       = C4::Context->dbh;
1400     my $sth       = $dbh->prepare("Select name from ethnicity where code = ?");
1401     $sth->execute($ethnicity);
1402     my $data = $sth->fetchrow_hashref;
1403     $sth->finish;
1404     return $data->{'name'};
1405 }    # sub fixEthnicity
1406
1407 =head2 GetAge
1408
1409   $dateofbirth,$date = &GetAge($date);
1410
1411 this function return the borrowers age with the value of dateofbirth
1412
1413 =cut
1414
1415 #'
1416 sub GetAge{
1417     my ( $date, $date_ref ) = @_;
1418
1419     if ( not defined $date_ref ) {
1420         $date_ref = sprintf( '%04d-%02d-%02d', Today() );
1421     }
1422
1423     my ( $year1, $month1, $day1 ) = split /-/, $date;
1424     my ( $year2, $month2, $day2 ) = split /-/, $date_ref;
1425
1426     my $age = $year2 - $year1;
1427     if ( $month1 . $day1 > $month2 . $day2 ) {
1428         $age--;
1429     }
1430
1431     return $age;
1432 }    # sub get_age
1433
1434 =head2 get_institutions
1435   $insitutions = get_institutions();
1436
1437 Just returns a list of all the borrowers of type I, borrownumber and name
1438
1439 =cut
1440
1441 #'
1442 sub get_institutions {
1443     my $dbh = C4::Context->dbh();
1444     my $sth =
1445       $dbh->prepare(
1446 "SELECT borrowernumber,surname FROM borrowers WHERE categorycode=? ORDER BY surname"
1447       );
1448     $sth->execute('I');
1449     my %orgs;
1450     while ( my $data = $sth->fetchrow_hashref() ) {
1451         $orgs{ $data->{'borrowernumber'} } = $data;
1452     }
1453     $sth->finish();
1454     return ( \%orgs );
1455
1456 }    # sub get_institutions
1457
1458 =head2 add_member_orgs
1459
1460   add_member_orgs($borrowernumber,$borrowernumbers);
1461
1462 Takes a borrowernumber and a list of other borrowernumbers and inserts them into the borrowers_to_borrowers table
1463
1464 =cut
1465
1466 #'
1467 sub add_member_orgs {
1468     my ( $borrowernumber, $otherborrowers ) = @_;
1469     my $dbh   = C4::Context->dbh();
1470     my $query =
1471       "INSERT INTO borrowers_to_borrowers (borrower1,borrower2) VALUES (?,?)";
1472     my $sth = $dbh->prepare($query);
1473     foreach my $otherborrowernumber (@$otherborrowers) {
1474         $sth->execute( $borrowernumber, $otherborrowernumber );
1475     }
1476     $sth->finish();
1477
1478 }    # sub add_member_orgs
1479
1480 =head2 GetCities (OUEST-PROVENCE)
1481
1482   ($id_cityarrayref, $city_hashref) = &GetCities();
1483
1484 Looks up the different city and zip in the database. Returns two
1485 elements: a reference-to-array, which lists the zip city
1486 codes, and a reference-to-hash, which maps the name of the city.
1487 WHERE =>OUEST PROVENCE OR EXTERIEUR
1488
1489 =cut
1490
1491 sub GetCities {
1492
1493     #my ($type_city) = @_;
1494     my $dbh   = C4::Context->dbh;
1495     my $query = qq|SELECT cityid,city_zipcode,city_name 
1496         FROM cities 
1497         ORDER BY city_name|;
1498     my $sth = $dbh->prepare($query);
1499
1500     #$sth->execute($type_city);
1501     $sth->execute();
1502     my %city;
1503     my @id;
1504     #    insert empty value to create a empty choice in cgi popup
1505     push @id, " ";
1506     $city{""} = "";
1507     while ( my $data = $sth->fetchrow_hashref ) {
1508         push @id, $data->{'city_zipcode'}."|".$data->{'city_name'};
1509         $city{ $data->{'city_zipcode'}."|".$data->{'city_name'} } = $data->{'city_name'};
1510     }
1511
1512 #test to know if the table contain some records if no the function return nothing
1513     my $id = @id;
1514     $sth->finish;
1515     if ( $id == 1 ) {
1516         # all we have is the one blank row
1517         return ();
1518     }
1519     else {
1520         unshift( @id, "" );
1521         return ( \@id, \%city );
1522     }
1523 }
1524
1525 =head2 GetSortDetails (OUEST-PROVENCE)
1526
1527   ($lib) = &GetSortDetails($category,$sortvalue);
1528
1529 Returns the authorized value  details
1530 C<&$lib>return value of authorized value details
1531 C<&$sortvalue>this is the value of authorized value 
1532 C<&$category>this is the value of authorized value category
1533
1534 =cut
1535
1536 sub GetSortDetails {
1537     my ( $category, $sortvalue ) = @_;
1538     my $dbh   = C4::Context->dbh;
1539     my $query = qq|SELECT lib 
1540         FROM authorised_values 
1541         WHERE category=?
1542         AND authorised_value=? |;
1543     my $sth = $dbh->prepare($query);
1544     $sth->execute( $category, $sortvalue );
1545     my $lib = $sth->fetchrow;
1546     return ($lib) if ($lib);
1547     return ($sortvalue) unless ($lib);
1548 }
1549
1550 =head2 DeleteBorrower 
1551
1552   () = &DeleteBorrower($member);
1553
1554 delete all data fo borrowers and add record to deletedborrowers table
1555 C<&$member>this is the borrowernumber
1556
1557 =cut
1558
1559 sub MoveMemberToDeleted {
1560     my ($member) = @_;
1561     my $dbh = C4::Context->dbh;
1562     my $query;
1563     $query = qq|SELECT * 
1564           FROM borrowers 
1565           WHERE borrowernumber=?|;
1566     my $sth = $dbh->prepare($query);
1567     $sth->execute($member);
1568     my @data = $sth->fetchrow_array;
1569     $sth->finish;
1570     $sth =
1571       $dbh->prepare( "INSERT INTO deletedborrowers VALUES ("
1572           . ( "?," x ( scalar(@data) - 1 ) )
1573           . "?)" );
1574     $sth->execute(@data);
1575     $sth->finish;
1576 }
1577
1578 =head2 DelMember
1579
1580 DelMember($borrowernumber);
1581
1582 This function remove directly a borrower whitout writing it on deleteborrower.
1583 + Deletes reserves for the borrower
1584
1585 =cut
1586
1587 sub DelMember {
1588     my $dbh            = C4::Context->dbh;
1589     my $borrowernumber = shift;
1590     #warn "in delmember with $borrowernumber";
1591     return unless $borrowernumber;    # borrowernumber is mandatory.
1592
1593     my $query = qq|DELETE 
1594           FROM  reserves 
1595           WHERE borrowernumber=?|;
1596     my $sth = $dbh->prepare($query);
1597     $sth->execute($borrowernumber);
1598     $sth->finish;
1599     $query = "
1600        DELETE
1601        FROM borrowers
1602        WHERE borrowernumber = ?
1603    ";
1604     $sth = $dbh->prepare($query);
1605     $sth->execute($borrowernumber);
1606     $sth->finish;
1607     logaction("MEMBERS", "DELETE", $borrowernumber, "") if C4::Context->preference("BorrowersLog");
1608     return $sth->rows;
1609 }
1610
1611 =head2 ExtendMemberSubscriptionTo (OUEST-PROVENCE)
1612
1613     $date = ExtendMemberSubscriptionTo($borrowerid, $date);
1614
1615 Extending the subscription to a given date or to the expiry date calculated on ISO date.
1616 Returns ISO date.
1617
1618 =cut
1619
1620 sub ExtendMemberSubscriptionTo {
1621     my ( $borrowerid,$date) = @_;
1622     my $dbh = C4::Context->dbh;
1623     my $borrower = GetMember($borrowerid,'borrowernumber');
1624     unless ($date){
1625       $date=POSIX::strftime("%Y-%m-%d",localtime());
1626       my $borrower = GetMember($borrowerid,'borrowernumber');
1627       $date = GetExpiryDate( $borrower->{'categorycode'}, $date );
1628     }
1629     my $sth = $dbh->do(<<EOF);
1630 UPDATE borrowers 
1631 SET  dateexpiry='$date' 
1632 WHERE borrowernumber='$borrowerid'
1633 EOF
1634     # add enrolmentfee if needed
1635     $sth = $dbh->prepare("SELECT enrolmentfee FROM categories WHERE categorycode=?");
1636     $sth->execute($borrower->{'categorycode'});
1637     my ($enrolmentfee) = $sth->fetchrow;
1638     if ($enrolmentfee) {
1639         # insert fee in patron debts
1640         manualinvoice($borrower->{'borrowernumber'}, '', '', 'A', $enrolmentfee);
1641     }
1642     return $date if ($sth);
1643     return 0;
1644 }
1645
1646 =head2 GetRoadTypes (OUEST-PROVENCE)
1647
1648   ($idroadtypearrayref, $roadttype_hashref) = &GetRoadTypes();
1649
1650 Looks up the different road type . Returns two
1651 elements: a reference-to-array, which lists the id_roadtype
1652 codes, and a reference-to-hash, which maps the road type of the road .
1653
1654 =cut
1655
1656 sub GetRoadTypes {
1657     my $dbh   = C4::Context->dbh;
1658     my $query = qq|
1659 SELECT roadtypeid,road_type 
1660 FROM roadtype 
1661 ORDER BY road_type|;
1662     my $sth = $dbh->prepare($query);
1663     $sth->execute();
1664     my %roadtype;
1665     my @id;
1666
1667     #    insert empty value to create a empty choice in cgi popup
1668
1669     while ( my $data = $sth->fetchrow_hashref ) {
1670
1671         push @id, $data->{'roadtypeid'};
1672         $roadtype{ $data->{'roadtypeid'} } = $data->{'road_type'};
1673     }
1674
1675 #test to know if the table contain some records if no the function return nothing
1676     my $id = @id;
1677     $sth->finish;
1678     if ( $id eq 0 ) {
1679         return ();
1680     }
1681     else {
1682         unshift( @id, "" );
1683         return ( \@id, \%roadtype );
1684     }
1685 }
1686
1687
1688
1689 =head2 GetTitles (OUEST-PROVENCE)
1690
1691   ($borrowertitle)= &GetTitles();
1692
1693 Looks up the different title . Returns array  with all borrowers title
1694
1695 =cut
1696
1697 sub GetTitles {
1698     my @borrowerTitle = split /,|\|/,C4::Context->preference('BorrowersTitles');
1699     unshift( @borrowerTitle, "" );
1700     my $count=@borrowerTitle;
1701     if ($count == 1){
1702         return ();
1703     }
1704     else {
1705         return ( \@borrowerTitle);
1706     }
1707 }
1708
1709 =head2 GetPatronImage
1710
1711     my ($imagedata, $dberror) = GetPatronImage($cardnumber);
1712
1713 Returns the mimetype and binary image data of the image for the patron with the supplied cardnumber.
1714
1715 =cut
1716
1717 sub GetPatronImage {
1718     my ($cardnumber) = @_;
1719     warn "Cardnumber passed to GetPatronImage is $cardnumber" if $debug;
1720     my $dbh = C4::Context->dbh;
1721     my $query = "SELECT mimetype, imagefile FROM patronimage WHERE cardnumber = ?;";
1722     my $sth = $dbh->prepare($query);
1723     $sth->execute($cardnumber);
1724     my $imagedata = $sth->fetchrow_hashref;
1725     my $dberror = $sth->errstr;
1726     warn "Database error!" if $sth->errstr;
1727     $sth->finish;
1728     return $imagedata, $dberror;
1729 }
1730
1731 =head2 PutPatronImage
1732
1733     PutPatronImage($cardnumber, $mimetype, $imgfile);
1734
1735 Stores patron binary image data and mimetype in database.
1736 NOTE: This function is good for updating images as well as inserting new images in the database.
1737
1738 =cut
1739
1740 sub PutPatronImage {
1741     my ($cardnumber, $mimetype, $imgfile) = @_;
1742     warn "Parameters passed in: Cardnumber=$cardnumber, Mimetype=$mimetype, " . ($imgfile ? "Imagefile" : "No Imagefile") if $debug;
1743     my $dbh = C4::Context->dbh;
1744     my $query = "INSERT INTO patronimage (cardnumber, mimetype, imagefile) VALUES (?,?,?) ON DUPLICATE KEY UPDATE imagefile = ?;";
1745     my $sth = $dbh->prepare($query);
1746     $sth->execute($cardnumber,$mimetype,$imgfile,$imgfile);
1747     warn "Error returned inserting $cardnumber.$mimetype." if $sth->errstr;
1748     my $dberror = $sth->errstr;
1749     $sth->finish;
1750     return $dberror;
1751 }
1752
1753 =head2 RmPatronImage
1754
1755     my ($dberror) = RmPatronImage($cardnumber);
1756
1757 Removes the image for the patron with the supplied cardnumber.
1758
1759 =cut
1760
1761 sub RmPatronImage {
1762     my ($cardnumber) = @_;
1763     warn "Cardnumber passed to GetPatronImage is $cardnumber" if $debug;
1764     my $dbh = C4::Context->dbh;
1765     my $query = "DELETE FROM patronimage WHERE cardnumber = ?;";
1766     my $sth = $dbh->prepare($query);
1767     $sth->execute($cardnumber);
1768     my $dberror = $sth->errstr;
1769     warn "Database error!" if $sth->errstr;
1770     $sth->finish;
1771     return $dberror;
1772 }
1773
1774 =head2 GetRoadTypeDetails (OUEST-PROVENCE)
1775
1776   ($roadtype) = &GetRoadTypeDetails($roadtypeid);
1777
1778 Returns the description of roadtype
1779 C<&$roadtype>return description of road type
1780 C<&$roadtypeid>this is the value of roadtype s
1781
1782 =cut
1783
1784 sub GetRoadTypeDetails {
1785     my ($roadtypeid) = @_;
1786     my $dbh          = C4::Context->dbh;
1787     my $query        = qq|
1788 SELECT road_type 
1789 FROM roadtype 
1790 WHERE roadtypeid=?|;
1791     my $sth = $dbh->prepare($query);
1792     $sth->execute($roadtypeid);
1793     my $roadtype = $sth->fetchrow;
1794     return ($roadtype);
1795 }
1796
1797 =head2 GetBorrowersWhoHaveNotBorrowedSince
1798
1799 &GetBorrowersWhoHaveNotBorrowedSince($date)
1800
1801 this function get all borrowers who haven't borrowed since the date given on input arg.
1802       
1803 =cut
1804
1805 sub GetBorrowersWhoHaveNotBorrowedSince {
1806 ### TODO : It could be dangerous to delete Borrowers who have just been entered and who have not yet borrowed any book. May be good to add a dateexpiry or dateenrolled filter.      
1807        
1808                 my $filterdate = shift||POSIX::strftime("%Y-%m-%d",localtime());
1809     my $filterbranch = shift || 
1810                         ((C4::Context->preference('IndependantBranches') 
1811                              && C4::Context->userenv 
1812                              && C4::Context->userenv->{flags}!=1 
1813                              && C4::Context->userenv->{branch})
1814                          ? C4::Context->userenv->{branch}
1815                          : "");  
1816     my $dbh   = C4::Context->dbh;
1817     my $query = "
1818         SELECT borrowers.borrowernumber,max(issues.timestamp) as latestissue
1819         FROM   borrowers
1820           LEFT JOIN issues ON borrowers.borrowernumber = issues.borrowernumber
1821    ";
1822     my @query_params;
1823     if ($filterbranch && $filterbranch ne ""){ 
1824         $query.=" WHERE branchcode= ?";
1825         push @query_params,$filterbranch;
1826     }    
1827     $query.=" GROUP BY borrowers.borrowernumber";
1828     if ($filterdate){ 
1829         $query.=" HAVING latestissue <? OR latestissue IS NULL";
1830         push @query_params,$filterdate;
1831     }
1832     warn $query;
1833     my $sth = $dbh->prepare($query);
1834     if (scalar(@query_params)>0){  
1835         $sth->execute(@query_params);
1836     } 
1837     else {
1838         $sth->execute;
1839     }      
1840     
1841     my @results;
1842     while ( my $data = $sth->fetchrow_hashref ) {
1843         push @results, $data;
1844     }
1845     return \@results;
1846 }
1847
1848 =head2 GetBorrowersWhoHaveNeverBorrowed
1849
1850 $results = &GetBorrowersWhoHaveNeverBorrowed
1851
1852 this function get all borrowers who have never borrowed.
1853
1854 I<$result> is a ref to an array which all elements are a hasref.
1855
1856 =cut
1857
1858 sub GetBorrowersWhoHaveNeverBorrowed {
1859     my $filterbranch = shift || 
1860                         ((C4::Context->preference('IndependantBranches') 
1861                              && C4::Context->userenv 
1862                              && C4::Context->userenv->{flags}!=1 
1863                              && C4::Context->userenv->{branch})
1864                          ? C4::Context->userenv->{branch}
1865                          : "");  
1866     my $dbh   = C4::Context->dbh;
1867     my $query = "
1868         SELECT borrowers.borrowernumber,max(timestamp) as latestissue
1869         FROM   borrowers
1870           LEFT JOIN issues ON borrowers.borrowernumber = issues.borrowernumber
1871         WHERE issues.borrowernumber IS NULL
1872    ";
1873     my @query_params;
1874     if ($filterbranch && $filterbranch ne ""){ 
1875         $query.=" AND branchcode= ?";
1876         push @query_params,$filterbranch;
1877     }
1878     warn $query;
1879   
1880     my $sth = $dbh->prepare($query);
1881     if (scalar(@query_params)>0){  
1882         $sth->execute(@query_params);
1883     } 
1884     else {
1885         $sth->execute;
1886     }      
1887     
1888     my @results;
1889     while ( my $data = $sth->fetchrow_hashref ) {
1890         push @results, $data;
1891     }
1892     return \@results;
1893 }
1894
1895 =head2 GetBorrowersWithIssuesHistoryOlderThan
1896
1897 $results = &GetBorrowersWithIssuesHistoryOlderThan($date)
1898
1899 this function get all borrowers who has an issue history older than I<$date> given on input arg.
1900
1901 I<$result> is a ref to an array which all elements are a hashref.
1902 This hashref is containt the number of time this borrowers has borrowed before I<$date> and the borrowernumber.
1903
1904 =cut
1905
1906 sub GetBorrowersWithIssuesHistoryOlderThan {
1907     my $dbh  = C4::Context->dbh;
1908     my $date = shift ||POSIX::strftime("%Y-%m-%d",localtime());
1909     my $filterbranch = shift || 
1910                         ((C4::Context->preference('IndependantBranches') 
1911                              && C4::Context->userenv 
1912                              && C4::Context->userenv->{flags}!=1 
1913                              && C4::Context->userenv->{branch})
1914                          ? C4::Context->userenv->{branch}
1915                          : "");  
1916     my $query = "
1917        SELECT count(borrowernumber) as n,borrowernumber
1918        FROM old_issues
1919        WHERE returndate < ?
1920          AND borrowernumber IS NOT NULL 
1921     "; 
1922     if ($filterbranch){
1923         $query.="   AND branchcode=\'$filterbranch\'";
1924     }    
1925     $query.=" GROUP BY borrowernumber ";
1926     warn $query;
1927     my $sth = $dbh->prepare($query);
1928     $sth->execute($date);
1929     my @results;
1930
1931     while ( my $data = $sth->fetchrow_hashref ) {
1932         push @results, $data;
1933     }
1934     return \@results;
1935 }
1936
1937 =head2 GetBorrowersNamesAndLatestIssue
1938
1939 $results = &GetBorrowersNamesAndLatestIssueList(@borrowernumbers)
1940
1941 this function get borrowers Names and surnames and Issue information.
1942
1943 I<@borrowernumbers> is an array which all elements are borrowernumbers.
1944 This hashref is containt the number of time this borrowers has borrowed before I<$date> and the borrowernumber.
1945
1946 =cut
1947
1948 sub GetBorrowersNamesAndLatestIssue {
1949     my $dbh  = C4::Context->dbh;
1950     my @borrowernumbers=@_;  
1951     my $query = "
1952        SELECT surname,lastname, phone, email,max(timestamp)
1953        FROM borrowers 
1954          LEFT JOIN issues ON borrowers.borrowernumber=issues.borrowernumber
1955        GROUP BY borrowernumber
1956    ";
1957     my $sth = $dbh->prepare($query);
1958     $sth->execute;
1959     my $results = $sth->fetchall_arrayref({});
1960     return $results;
1961 }
1962 END { }    # module clean-up code here (global destructor)
1963
1964 1;
1965
1966 __END__
1967
1968 =back
1969
1970 =head1 AUTHOR
1971
1972 Koha Team
1973
1974 =cut