Merge remote branch 'kc/new/bug_5240' into kcmaster
[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
17 # with Koha; if not, write to the Free Software Foundation, Inc.,
18 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
19
20
21 use strict;
22 #use warnings; FIXME - Bug 2505
23 use C4::Context;
24 use C4::Dates qw(format_date_in_iso);
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 use C4::Accounts;
31 use C4::Biblio;
32 use C4::SQLHelper qw(InsertInTable UpdateInTable SearchInTable);
33 use C4::Members::Attributes qw(SearchIdMatchingAttribute);
34
35 our ($VERSION,@ISA,@EXPORT,@EXPORT_OK,$debug);
36
37 BEGIN {
38         $VERSION = 3.02;
39         $debug = $ENV{DEBUG} || 0;
40         require Exporter;
41         @ISA = qw(Exporter);
42         #Get data
43         push @EXPORT, qw(
44                 &Search
45                 &SearchMember 
46                 &GetMemberDetails
47                 &GetMember
48
49                 &GetGuarantees 
50
51                 &GetMemberIssuesAndFines
52                 &GetPendingIssues
53                 &GetAllIssues
54
55                 &get_institutions 
56                 &getzipnamecity 
57                 &getidcity
58
59                 &GetFirstValidEmailAddress
60
61                 &GetAge 
62                 &GetCities 
63                 &GetRoadTypes 
64                 &GetRoadTypeDetails 
65                 &GetSortDetails
66                 &GetTitles
67
68     &GetPatronImage
69     &PutPatronImage
70     &RmPatronImage
71
72                 &IsMemberBlocked
73                 &GetMemberAccountRecords
74                 &GetBorNotifyAcctRecord
75
76                 &GetborCatFromCatType 
77                 &GetBorrowercategory
78     &GetBorrowercategoryList
79
80                 &GetBorrowersWhoHaveNotBorrowedSince
81                 &GetBorrowersWhoHaveNeverBorrowed
82                 &GetBorrowersWithIssuesHistoryOlderThan
83
84                 &GetExpiryDate
85
86                 &AddMessage
87                 &DeleteMessage
88                 &GetMessages
89                 &GetMessagesCount
90         );
91
92         #Modify data
93         push @EXPORT, qw(
94                 &ModMember
95                 &changepassword
96         );
97
98         #Delete data
99         push @EXPORT, qw(
100                 &DelMember
101         );
102
103         #Insert data
104         push @EXPORT, qw(
105                 &AddMember
106                 &add_member_orgs
107                 &MoveMemberToDeleted
108                 &ExtendMemberSubscriptionTo
109         );
110
111         #Check data
112     push @EXPORT, qw(
113         &checkuniquemember
114         &checkuserpassword
115         &Check_Userid
116         &Generate_Userid
117         &fixEthnicity
118         &ethnicitycategories
119         &fixup_cardnumber
120         &checkcardnumber
121     );
122 }
123
124 =head1 NAME
125
126 C4::Members - Perl Module containing convenience functions for member handling
127
128 =head1 SYNOPSIS
129
130 use C4::Members;
131
132 =head1 DESCRIPTION
133
134 This module contains routines for adding, modifying and deleting members/patrons/borrowers 
135
136 =head1 FUNCTIONS
137
138 =head2 SearchMember
139
140   ($count, $borrowers) = &SearchMember($searchstring, $type, 
141                      $category_type, $filter, $showallbranches);
142
143 Looks up patrons (borrowers) by name.
144
145 BUGFIX 499: C<$type> is now used to determine type of search.
146 if $type is "simple", search is performed on the first letter of the
147 surname only.
148
149 $category_type is used to get a specified type of user. 
150 (mainly adults when creating a child.)
151
152 C<$searchstring> is a space-separated list of search terms. Each term
153 must match the beginning a borrower's surname, first name, or other
154 name.
155
156 C<$filter> is assumed to be a list of elements to filter results on
157
158 C<$showallbranches> is used in IndependantBranches Context to display all branches results.
159
160 C<&SearchMember> returns a two-element list. C<$borrowers> is a
161 reference-to-array; each element is a reference-to-hash, whose keys
162 are the fields of the C<borrowers> table in the Koha database.
163 C<$count> is the number of elements in C<$borrowers>.
164
165 =cut
166
167 #'
168 #used by member enquiries from the intranet
169 sub SearchMember {
170     my ($searchstring, $orderby, $type,$category_type,$filter,$showallbranches ) = @_;
171     my $dbh   = C4::Context->dbh;
172     my $query = "";
173     my $count;
174     my @data;
175     my @bind = ();
176     
177     # this is used by circulation everytime a new borrowers cardnumber is scanned
178     # so we can check an exact match first, if that works return, otherwise do the rest
179     $query = "SELECT * FROM borrowers
180         LEFT JOIN categories ON borrowers.categorycode=categories.categorycode
181         ";
182     my $sth = $dbh->prepare("$query WHERE cardnumber = ?");
183     $sth->execute($searchstring);
184     my $data = $sth->fetchall_arrayref({});
185     if (@$data){
186         return ( scalar(@$data), $data );
187     }
188
189     if ( $type eq "simple" )    # simple search for one letter only
190     {
191         $query .= ($category_type ? " AND category_type = ".$dbh->quote($category_type) : ""); 
192         $query .= " WHERE (surname LIKE ? OR cardnumber like ?) ";
193         if (C4::Context->preference("IndependantBranches") && !$showallbranches){
194           if (C4::Context->userenv && C4::Context->userenv->{flags} % 2 !=1 && C4::Context->userenv->{'branch'}){
195             $query.=" AND borrowers.branchcode =".$dbh->quote(C4::Context->userenv->{'branch'}) unless (C4::Context->userenv->{'branch'} eq "insecure");
196           }
197         }
198         $query.=" ORDER BY $orderby";
199         @bind = ("$searchstring%","$searchstring");
200     }
201     else    # advanced search looking in surname, firstname and othernames
202     {
203         @data  = split( ' ', $searchstring );
204         $count = @data;
205         $query .= " WHERE ";
206         if (C4::Context->preference("IndependantBranches") && !$showallbranches){
207           if (C4::Context->userenv && C4::Context->userenv->{flags} % 2 !=1 && C4::Context->userenv->{'branch'}){
208             $query.=" borrowers.branchcode =".$dbh->quote(C4::Context->userenv->{'branch'})." AND " unless (C4::Context->userenv->{'branch'} eq "insecure");
209           }      
210         }     
211         $query.="((surname LIKE ? OR surname LIKE ?
212                 OR firstname  LIKE ? OR firstname LIKE ?
213                 OR othernames LIKE ? OR othernames LIKE ?)
214         " .
215         ($category_type?" AND category_type = ".$dbh->quote($category_type):"");
216         @bind = (
217             "$data[0]%", "% $data[0]%", "$data[0]%", "% $data[0]%",
218             "$data[0]%", "% $data[0]%"
219         );
220         for ( my $i = 1 ; $i < $count ; $i++ ) {
221             $query = $query . " AND (" . " surname LIKE ? OR surname LIKE ?
222                 OR firstname  LIKE ? OR firstname LIKE ?
223                 OR othernames LIKE ? OR othernames LIKE ?)";
224             push( @bind,
225                 "$data[$i]%",   "% $data[$i]%", "$data[$i]%",
226                 "% $data[$i]%", "$data[$i]%",   "% $data[$i]%" );
227
228             # FIXME - .= <<EOT;
229         }
230         $query = $query . ") OR cardnumber LIKE ? ";
231         push( @bind, $searchstring );
232         $query .= "order by $orderby";
233
234         # FIXME - .= <<EOT;
235     }
236
237     $sth = $dbh->prepare($query);
238
239     $debug and print STDERR "Q $orderby : $query\n";
240     $sth->execute(@bind);
241     my @results;
242     $data = $sth->fetchall_arrayref({});
243
244     return ( scalar(@$data), $data );
245 }
246
247 =head2 Search
248
249   $borrowers_result_array_ref = &Search($filter,$orderby, $limit, 
250                        $columns_out, $search_on_fields,$searchtype);
251
252 Looks up patrons (borrowers) on filter.
253
254 BUGFIX 499: C<$type> is now used to determine type of search.
255 if $type is "simple", search is performed on the first letter of the
256 surname only.
257
258 $category_type is used to get a specified type of user. 
259 (mainly adults when creating a child.)
260
261 C<$filter> can be
262    - a space-separated list of search terms. Implicit AND is done on them
263    - a hash ref containing fieldnames associated with queried value
264    - an array ref combining the two previous elements Implicit OR is done between each array element
265
266
267 C<$orderby> is an arrayref of hashref. Contains the name of the field and 0 or 1 depending if order is ascending or descending
268
269 C<$limit> is there to allow limiting number of results returned
270
271 C<&columns_out> is an array ref to the fieldnames you want to see in the result list
272
273 C<&search_on_fields> is an array ref to the fieldnames you want to limit search on when you are using string search
274
275 C<&searchtype> is a string telling the type of search you want todo : start_with, exact or contains are allowed
276
277 =cut
278
279 sub Search {
280     my ($filter,$orderby, $limit, $columns_out, $search_on_fields,$searchtype) = @_;
281         my @filters;
282         if (ref($filter) eq "ARRAY"){
283                 push @filters,@$filter;
284         }
285         else {
286                 push @filters,$filter;
287         }
288     if (C4::Context->preference('ExtendedPatronAttributes')) {
289                 my $matching_records = C4::Members::Attributes::SearchIdMatchingAttribute($filter);
290                 push @filters,@$matching_records;
291     }
292         $searchtype||="start_with";
293         my $data=SearchInTable("borrowers",\@filters,$orderby,$limit,$columns_out,$search_on_fields,$searchtype);
294
295     return ( $data );
296 }
297
298 =head2 GetMemberDetails
299
300 ($borrower) = &GetMemberDetails($borrowernumber, $cardnumber);
301
302 Looks up a patron and returns information about him or her. If
303 C<$borrowernumber> is true (nonzero), C<&GetMemberDetails> looks
304 up the borrower by number; otherwise, it looks up the borrower by card
305 number.
306
307 C<$borrower> is a reference-to-hash whose keys are the fields of the
308 borrowers table in the Koha database. In addition,
309 C<$borrower-E<gt>{flags}> is a hash giving more detailed information
310 about the patron. Its keys act as flags :
311
312     if $borrower->{flags}->{LOST} {
313         # Patron's card was reported lost
314     }
315
316 If the state of a flag means that the patron should not be
317 allowed to borrow any more books, then it will have a C<noissues> key
318 with a true value.
319
320 See patronflags for more details.
321
322 C<$borrower-E<gt>{authflags}> is a hash giving more detailed information
323 about the top-level permissions flags set for the borrower.  For example,
324 if a user has the "editcatalogue" permission,
325 C<$borrower-E<gt>{authflags}-E<gt>{editcatalogue}> will exist and have
326 the value "1".
327
328 =cut
329
330 sub GetMemberDetails {
331     my ( $borrowernumber, $cardnumber ) = @_;
332     my $dbh = C4::Context->dbh;
333     my $query;
334     my $sth;
335     if ($borrowernumber) {
336         $sth = $dbh->prepare("select borrowers.*,category_type,categories.description from borrowers left join categories on borrowers.categorycode=categories.categorycode where  borrowernumber=?");
337         $sth->execute($borrowernumber);
338     }
339     elsif ($cardnumber) {
340         $sth = $dbh->prepare("select borrowers.*,category_type,categories.description from borrowers left join categories on borrowers.categorycode=categories.categorycode where cardnumber=?");
341         $sth->execute($cardnumber);
342     }
343     else {
344         return undef;
345     }
346     my $borrower = $sth->fetchrow_hashref;
347     my ($amount) = GetMemberAccountRecords( $borrowernumber);
348     $borrower->{'amountoutstanding'} = $amount;
349     # FIXME - patronflags calls GetMemberAccountRecords... just have patronflags return $amount
350     my $flags = patronflags( $borrower);
351     my $accessflagshash;
352
353     $sth = $dbh->prepare("select bit,flag from userflags");
354     $sth->execute;
355     while ( my ( $bit, $flag ) = $sth->fetchrow ) {
356         if ( $borrower->{'flags'} && $borrower->{'flags'} & 2**$bit ) {
357             $accessflagshash->{$flag} = 1;
358         }
359     }
360     $borrower->{'flags'}     = $flags;
361     $borrower->{'authflags'} = $accessflagshash;
362
363     # find out how long the membership lasts
364     $sth =
365       $dbh->prepare(
366         "select enrolmentperiod from categories where categorycode = ?");
367     $sth->execute( $borrower->{'categorycode'} );
368     my $enrolment = $sth->fetchrow;
369     $borrower->{'enrolmentperiod'} = $enrolment;
370     return ($borrower);    #, $flags, $accessflagshash);
371 }
372
373 =head2 patronflags
374
375  $flags = &patronflags($patron);
376
377 This function is not exported.
378
379 The following will be set where applicable:
380  $flags->{CHARGES}->{amount}        Amount of debt
381  $flags->{CHARGES}->{noissues}      Set if debt amount >$5.00 (or syspref noissuescharge)
382  $flags->{CHARGES}->{message}       Message -- deprecated
383
384  $flags->{CREDITS}->{amount}        Amount of credit
385  $flags->{CREDITS}->{message}       Message -- deprecated
386
387  $flags->{  GNA  }                  Patron has no valid address
388  $flags->{  GNA  }->{noissues}      Set for each GNA
389  $flags->{  GNA  }->{message}       "Borrower has no valid address" -- deprecated
390
391  $flags->{ LOST  }                  Patron's card reported lost
392  $flags->{ LOST  }->{noissues}      Set for each LOST
393  $flags->{ LOST  }->{message}       Message -- deprecated
394
395  $flags->{DBARRED}                  Set if patron debarred, no access
396  $flags->{DBARRED}->{noissues}      Set for each DBARRED
397  $flags->{DBARRED}->{message}       Message -- deprecated
398
399  $flags->{ NOTES }
400  $flags->{ NOTES }->{message}       The note itself.  NOT deprecated
401
402  $flags->{ ODUES }                  Set if patron has overdue books.
403  $flags->{ ODUES }->{message}       "Yes"  -- deprecated
404  $flags->{ ODUES }->{itemlist}      ref-to-array: list of overdue books
405  $flags->{ ODUES }->{itemlisttext}  Text list of overdue items -- deprecated
406
407  $flags->{WAITING}                  Set if any of patron's reserves are available
408  $flags->{WAITING}->{message}       Message -- deprecated
409  $flags->{WAITING}->{itemlist}      ref-to-array: list of available items
410
411 =over 
412
413 =item C<$flags-E<gt>{ODUES}-E<gt>{itemlist}> is a reference-to-array listing the
414 overdue items. Its elements are references-to-hash, each describing an
415 overdue item. The keys are selected fields from the issues, biblio,
416 biblioitems, and items tables of the Koha database.
417
418 =item C<$flags-E<gt>{ODUES}-E<gt>{itemlisttext}> is a string giving a text listing of
419 the overdue items, one per line.  Deprecated.
420
421 =item C<$flags-E<gt>{WAITING}-E<gt>{itemlist}> is a reference-to-array listing the
422 available items. Each element is a reference-to-hash whose keys are
423 fields from the reserves table of the Koha database.
424
425 =back
426
427 All the "message" fields that include language generated in this function are deprecated, 
428 because such strings belong properly in the display layer.
429
430 The "message" field that comes from the DB is OK.
431
432 =cut
433
434 # TODO: use {anonymous => hashes} instead of a dozen %flaginfo
435 # FIXME rename this function.
436 sub patronflags {
437     my %flags;
438     my ( $patroninformation) = @_;
439     my $dbh=C4::Context->dbh;
440     my ($amount) = GetMemberAccountRecords( $patroninformation->{'borrowernumber'});
441     if ( $amount > 0 ) {
442         my %flaginfo;
443         my $noissuescharge = C4::Context->preference("noissuescharge") || 5;
444         $flaginfo{'message'} = sprintf "Patron owes \$%.02f", $amount;
445         $flaginfo{'amount'}  = sprintf "%.02f", $amount;
446         if ( $amount > $noissuescharge ) {
447             $flaginfo{'noissues'} = 1;
448         }
449         $flags{'CHARGES'} = \%flaginfo;
450     }
451     elsif ( $amount < 0 ) {
452         my %flaginfo;
453         $flaginfo{'message'} = sprintf "Patron has credit of \$%.02f", -$amount;
454         $flaginfo{'amount'}  = sprintf "%.02f", $amount;
455         $flags{'CREDITS'} = \%flaginfo;
456     }
457     if (   $patroninformation->{'gonenoaddress'}
458         && $patroninformation->{'gonenoaddress'} == 1 )
459     {
460         my %flaginfo;
461         $flaginfo{'message'}  = 'Borrower has no valid address.';
462         $flaginfo{'noissues'} = 1;
463         $flags{'GNA'}         = \%flaginfo;
464     }
465     if ( $patroninformation->{'lost'} && $patroninformation->{'lost'} == 1 ) {
466         my %flaginfo;
467         $flaginfo{'message'}  = 'Borrower\'s card reported lost.';
468         $flaginfo{'noissues'} = 1;
469         $flags{'LOST'}        = \%flaginfo;
470     }
471     if (   $patroninformation->{'debarred'}
472         && $patroninformation->{'debarred'} == 1 )
473     {
474         my %flaginfo;
475         $flaginfo{'message'}  = 'Borrower is Debarred.';
476         $flaginfo{'noissues'} = 1;
477         $flags{'DBARRED'}     = \%flaginfo;
478     }
479     if (   $patroninformation->{'borrowernotes'}
480         && $patroninformation->{'borrowernotes'} )
481     {
482         my %flaginfo;
483         $flaginfo{'message'} = $patroninformation->{'borrowernotes'};
484         $flags{'NOTES'}      = \%flaginfo;
485     }
486     my ( $odues, $itemsoverdue ) = checkoverdues($patroninformation->{'borrowernumber'});
487     if ( $odues && $odues > 0 ) {
488         my %flaginfo;
489         $flaginfo{'message'}  = "Yes";
490         $flaginfo{'itemlist'} = $itemsoverdue;
491         foreach ( sort { $a->{'date_due'} cmp $b->{'date_due'} }
492             @$itemsoverdue )
493         {
494             $flaginfo{'itemlisttext'} .=
495               "$_->{'date_due'} $_->{'barcode'} $_->{'title'} \n";  # newline is display layer
496         }
497         $flags{'ODUES'} = \%flaginfo;
498     }
499     my @itemswaiting = C4::Reserves::GetReservesFromBorrowernumber( $patroninformation->{'borrowernumber'},'W' );
500     my $nowaiting = scalar @itemswaiting;
501     if ( $nowaiting > 0 ) {
502         my %flaginfo;
503         $flaginfo{'message'}  = "Reserved items available";
504         $flaginfo{'itemlist'} = \@itemswaiting;
505         $flags{'WAITING'}     = \%flaginfo;
506     }
507     return ( \%flags );
508 }
509
510
511 =head2 GetMember
512
513   $borrower = &GetMember(%information);
514
515 Retrieve the first patron record meeting on criteria listed in the
516 C<%information> hash, which should contain one or more
517 pairs of borrowers column names and values, e.g.,
518
519    $borrower = GetMember(borrowernumber => id);
520
521 C<&GetBorrower> returns a reference-to-hash whose keys are the fields of
522 the C<borrowers> table in the Koha database.
523
524 FIXME: GetMember() is used throughout the code as a lookup
525 on a unique key such as the borrowernumber, but this meaning is not
526 enforced in the routine itself.
527
528 =cut
529
530 #'
531 sub GetMember {
532     my ( %information ) = @_;
533     if (exists $information{borrowernumber} && !defined $information{borrowernumber}) {
534         #passing mysql's kohaadmin?? Makes no sense as a query
535         return;
536     }
537     my $dbh = C4::Context->dbh;
538     my $select =
539     q{SELECT borrowers.*, categories.category_type, categories.description
540     FROM borrowers 
541     LEFT JOIN categories on borrowers.categorycode=categories.categorycode WHERE };
542     my $more_p = 0;
543     my @values = ();
544     for (keys %information ) {
545         if ($more_p) {
546             $select .= ' AND ';
547         }
548         else {
549             $more_p++;
550         }
551
552         if (defined $information{$_}) {
553             $select .= "$_ = ?";
554             push @values, $information{$_};
555         }
556         else {
557             $select .= "$_ IS NULL";
558         }
559     }
560     $debug && warn $select, " ",values %information;
561     my $sth = $dbh->prepare("$select");
562     $sth->execute(map{$information{$_}} keys %information);
563     my $data = $sth->fetchall_arrayref({});
564     #FIXME interface to this routine now allows generation of a result set
565     #so whole array should be returned but bowhere in the current code expects this
566     if (@{$data} ) {
567         return $data->[0];
568     }
569
570     return;
571 }
572
573
574 =head2 IsMemberBlocked
575
576   my ($block_status, $count) = IsMemberBlocked( $borrowernumber );
577
578 Returns whether a patron has overdue items that may result
579 in a block or whether the patron has active fine days
580 that would block circulation privileges.
581
582 C<$block_status> can have the following values:
583
584 1 if the patron has outstanding fine days, in which case C<$count> is the number of them
585
586 -1 if the patron has overdue items, in which case C<$count> is the number of them
587
588 0 if the patron has no overdue items or outstanding fine days, in which case C<$count> is 0
589
590 Outstanding fine days are checked before current overdue items
591 are.
592
593 FIXME: this needs to be split into two functions; a potential block
594 based on the number of current overdue items could be orthogonal
595 to a block based on whether the patron has any fine days accrued.
596
597 =cut
598
599 sub IsMemberBlocked {
600     my $borrowernumber = shift;
601     my $dbh            = C4::Context->dbh;
602
603     # does patron have current fine days?
604         my $strsth=qq{
605             SELECT
606             ADDDATE(returndate, finedays * DATEDIFF(returndate,date_due) ) AS blockingdate,
607             DATEDIFF(ADDDATE(returndate, finedays * DATEDIFF(returndate,date_due)),NOW()) AS blockedcount
608             FROM old_issues
609         };
610     if(C4::Context->preference("item-level_itypes")){
611         $strsth.=
612                 qq{ LEFT JOIN items ON (items.itemnumber=old_issues.itemnumber)
613             LEFT JOIN issuingrules ON (issuingrules.itemtype=items.itype)}
614     }else{
615         $strsth .= 
616                 qq{ LEFT JOIN items ON (items.itemnumber=old_issues.itemnumber)
617             LEFT JOIN biblioitems ON (biblioitems.biblioitemnumber=items.biblioitemnumber)
618             LEFT JOIN issuingrules ON (issuingrules.itemtype=biblioitems.itemtype) };
619     }
620         $strsth.=
621         qq{ WHERE finedays IS NOT NULL
622             AND  date_due < returndate
623             AND borrowernumber = ?
624             ORDER BY blockingdate DESC, blockedcount DESC
625             LIMIT 1};
626         my $sth=$dbh->prepare($strsth);
627     $sth->execute($borrowernumber);
628     my $row = $sth->fetchrow_hashref;
629     my $blockeddate  = $row->{'blockeddate'};
630     my $blockedcount = $row->{'blockedcount'};
631
632     return (1, $blockedcount) if $blockedcount > 0;
633
634     # if he have late issues
635     $sth = $dbh->prepare(
636         "SELECT COUNT(*) as latedocs
637          FROM issues
638          WHERE borrowernumber = ?
639          AND date_due < curdate()"
640     );
641     $sth->execute($borrowernumber);
642     my $latedocs = $sth->fetchrow_hashref->{'latedocs'};
643
644     return (-1, $latedocs) if $latedocs > 0;
645
646     return (0, 0);
647 }
648
649 =head2 GetMemberIssuesAndFines
650
651   ($overdue_count, $issue_count, $total_fines) = &GetMemberIssuesAndFines($borrowernumber);
652
653 Returns aggregate data about items borrowed by the patron with the
654 given borrowernumber.
655
656 C<&GetMemberIssuesAndFines> returns a three-element array.  C<$overdue_count> is the
657 number of overdue items the patron currently has borrowed. C<$issue_count> is the
658 number of books the patron currently has borrowed.  C<$total_fines> is
659 the total fine currently due by the borrower.
660
661 =cut
662
663 #'
664 sub GetMemberIssuesAndFines {
665     my ( $borrowernumber ) = @_;
666     my $dbh   = C4::Context->dbh;
667     my $query = "SELECT COUNT(*) FROM issues WHERE borrowernumber = ?";
668
669     $debug and warn $query."\n";
670     my $sth = $dbh->prepare($query);
671     $sth->execute($borrowernumber);
672     my $issue_count = $sth->fetchrow_arrayref->[0];
673
674     $sth = $dbh->prepare(
675         "SELECT COUNT(*) FROM issues 
676          WHERE borrowernumber = ? 
677          AND date_due < curdate()"
678     );
679     $sth->execute($borrowernumber);
680     my $overdue_count = $sth->fetchrow_arrayref->[0];
681
682     $sth = $dbh->prepare("SELECT SUM(amountoutstanding) FROM accountlines WHERE borrowernumber = ?");
683     $sth->execute($borrowernumber);
684     my $total_fines = $sth->fetchrow_arrayref->[0];
685
686     return ($overdue_count, $issue_count, $total_fines);
687 }
688
689 sub columns(;$) {
690     return @{C4::Context->dbh->selectcol_arrayref("SHOW columns from borrowers")};
691 }
692
693 =head2 ModMember
694
695   my $success = ModMember(borrowernumber => $borrowernumber,
696                                             [ field => value ]... );
697
698 Modify borrower's data.  All date fields should ALREADY be in ISO format.
699
700 return :
701 true on success, or false on failure
702
703 =cut
704
705 sub ModMember {
706     my (%data) = @_;
707     # test to know if you must update or not the borrower password
708     if (exists $data{password}) {
709         if ($data{password} eq '****' or $data{password} eq '') {
710             delete $data{password};
711         } else {
712             $data{password} = md5_base64($data{password});
713         }
714     }
715         my $execute_success=UpdateInTable("borrowers",\%data);
716 # ok if its an adult (type) it may have borrowers that depend on it as a guarantor
717 # so when we update information for an adult we should check for guarantees and update the relevant part
718 # of their records, ie addresses and phone numbers
719     my $borrowercategory= GetBorrowercategory( $data{'category_type'} );
720     if ( exists  $borrowercategory->{'category_type'} && $borrowercategory->{'category_type'} eq ('A' || 'S') ) {
721         # is adult check guarantees;
722         UpdateGuarantees(%data);
723     }
724     logaction("MEMBERS", "MODIFY", $data{'borrowernumber'}, "UPDATE (executed w/ arg: $data{'borrowernumber'})") 
725         if C4::Context->preference("BorrowersLog");
726
727     return $execute_success;
728 }
729
730
731 =head2 AddMember
732
733   $borrowernumber = &AddMember(%borrower);
734
735 insert new borrower into table
736 Returns the borrowernumber
737
738 =cut
739
740 #'
741 sub AddMember {
742     my (%data) = @_;
743     my $dbh = C4::Context->dbh;
744     $data{'password'} = '!' if (not $data{'password'} and $data{'userid'});
745     $data{'password'} = md5_base64( $data{'password'} ) if $data{'password'};
746         $data{'borrowernumber'}=InsertInTable("borrowers",\%data);      
747     # mysql_insertid is probably bad.  not necessarily accurate and mysql-specific at best.
748     logaction("MEMBERS", "CREATE", $data{'borrowernumber'}, "") if C4::Context->preference("BorrowersLog");
749     
750     # check for enrollment fee & add it if needed
751     my $sth = $dbh->prepare("SELECT enrolmentfee FROM categories WHERE categorycode=?");
752     $sth->execute($data{'categorycode'});
753     my ($enrolmentfee) = $sth->fetchrow;
754     if ($enrolmentfee && $enrolmentfee > 0) {
755         # insert fee in patron debts
756         manualinvoice($data{'borrowernumber'}, '', '', 'A', $enrolmentfee);
757     }
758     return $data{'borrowernumber'};
759 }
760
761
762 sub Check_Userid {
763     my ($uid,$member) = @_;
764     my $dbh = C4::Context->dbh;
765     # Make sure the userid chosen is unique and not theirs if non-empty. If it is not,
766     # Then we need to tell the user and have them create a new one.
767     my $sth =
768       $dbh->prepare(
769         "SELECT * FROM borrowers WHERE userid=? AND borrowernumber != ?");
770     $sth->execute( $uid, $member );
771     if ( ( $uid ne '' ) && ( my $row = $sth->fetchrow_hashref ) ) {
772         return 0;
773     }
774     else {
775         return 1;
776     }
777 }
778
779 sub Generate_Userid {
780   my ($borrowernumber, $firstname, $surname) = @_;
781   my $newuid;
782   my $offset = 0;
783   do {
784     $firstname =~ s/[[:digit:][:space:][:blank:][:punct:][:cntrl:]]//g;
785     $surname =~ s/[[:digit:][:space:][:blank:][:punct:][:cntrl:]]//g;
786     $newuid = lc("$firstname.$surname");
787     $newuid .= $offset unless $offset == 0;
788     $offset++;
789
790    } while (!Check_Userid($newuid,$borrowernumber));
791
792    return $newuid;
793 }
794
795 sub changepassword {
796     my ( $uid, $member, $digest ) = @_;
797     my $dbh = C4::Context->dbh;
798
799 #Make sure the userid chosen is unique and not theirs if non-empty. If it is not,
800 #Then we need to tell the user and have them create a new one.
801     my $resultcode;
802     my $sth =
803       $dbh->prepare(
804         "SELECT * FROM borrowers WHERE userid=? AND borrowernumber != ?");
805     $sth->execute( $uid, $member );
806     if ( ( $uid ne '' ) && ( my $row = $sth->fetchrow_hashref ) ) {
807         $resultcode=0;
808     }
809     else {
810         #Everything is good so we can update the information.
811         $sth =
812           $dbh->prepare(
813             "update borrowers set userid=?, password=? where borrowernumber=?");
814         $sth->execute( $uid, $digest, $member );
815         $resultcode=1;
816     }
817     
818     logaction("MEMBERS", "CHANGE PASS", $member, "") if C4::Context->preference("BorrowersLog");
819     return $resultcode;    
820 }
821
822
823
824 =head2 fixup_cardnumber
825
826 Warning: The caller is responsible for locking the members table in write
827 mode, to avoid database corruption.
828
829 =cut
830
831 use vars qw( @weightings );
832 my @weightings = ( 8, 4, 6, 3, 5, 2, 1 );
833
834 sub fixup_cardnumber ($) {
835     my ($cardnumber) = @_;
836     my $autonumber_members = C4::Context->boolean_preference('autoMemberNum') || 0;
837
838     # Find out whether member numbers should be generated
839     # automatically. Should be either "1" or something else.
840     # Defaults to "0", which is interpreted as "no".
841
842     #     if ($cardnumber !~ /\S/ && $autonumber_members) {
843     ($autonumber_members) or return $cardnumber;
844     my $checkdigit = C4::Context->preference('checkdigit');
845     my $dbh = C4::Context->dbh;
846     if ( $checkdigit and $checkdigit eq 'katipo' ) {
847
848         # if checkdigit is selected, calculate katipo-style cardnumber.
849         # otherwise, just use the max()
850         # purpose: generate checksum'd member numbers.
851         # We'll assume we just got the max value of digits 2-8 of member #'s
852         # from the database and our job is to increment that by one,
853         # determine the 1st and 9th digits and return the full string.
854         my $sth = $dbh->prepare(
855             "select max(substring(borrowers.cardnumber,2,7)) as new_num from borrowers"
856         );
857         $sth->execute;
858         my $data = $sth->fetchrow_hashref;
859         $cardnumber = $data->{new_num};
860         if ( !$cardnumber ) {    # If DB has no values,
861             $cardnumber = 1000000;    # start at 1000000
862         } else {
863             $cardnumber += 1;
864         }
865
866         my $sum = 0;
867         for ( my $i = 0 ; $i < 8 ; $i += 1 ) {
868             # read weightings, left to right, 1 char at a time
869             my $temp1 = $weightings[$i];
870
871             # sequence left to right, 1 char at a time
872             my $temp2 = substr( $cardnumber, $i, 1 );
873
874             # mult each char 1-7 by its corresponding weighting
875             $sum += $temp1 * $temp2;
876         }
877
878         my $rem = ( $sum % 11 );
879         $rem = 'X' if $rem == 10;
880
881         return "V$cardnumber$rem";
882      } else {
883
884      # MODIFIED BY JF: mysql4.1 allows casting as an integer, which is probably
885      # better. I'll leave the original in in case it needs to be changed for you
886      # my $sth=$dbh->prepare("select max(borrowers.cardnumber) from borrowers");
887         my $sth = $dbh->prepare(
888             "select max(cast(cardnumber as signed)) from borrowers"
889         );
890         $sth->execute;
891         my ($result) = $sth->fetchrow;
892         return $result + 1;
893     }
894     return $cardnumber;     # just here as a fallback/reminder 
895 }
896
897 =head2 GetGuarantees
898
899   ($num_children, $children_arrayref) = &GetGuarantees($parent_borrno);
900   $child0_cardno = $children_arrayref->[0]{"cardnumber"};
901   $child0_borrno = $children_arrayref->[0]{"borrowernumber"};
902
903 C<&GetGuarantees> takes a borrower number (e.g., that of a patron
904 with children) and looks up the borrowers who are guaranteed by that
905 borrower (i.e., the patron's children).
906
907 C<&GetGuarantees> returns two values: an integer giving the number of
908 borrowers guaranteed by C<$parent_borrno>, and a reference to an array
909 of references to hash, which gives the actual results.
910
911 =cut
912
913 #'
914 sub GetGuarantees {
915     my ($borrowernumber) = @_;
916     my $dbh              = C4::Context->dbh;
917     my $sth              =
918       $dbh->prepare(
919 "select cardnumber,borrowernumber, firstname, surname from borrowers where guarantorid=?"
920       );
921     $sth->execute($borrowernumber);
922
923     my @dat;
924     my $data = $sth->fetchall_arrayref({}); 
925     return ( scalar(@$data), $data );
926 }
927
928 =head2 UpdateGuarantees
929
930   &UpdateGuarantees($parent_borrno);
931   
932
933 C<&UpdateGuarantees> borrower data for an adult and updates all the guarantees
934 with the modified information
935
936 =cut
937
938 #'
939 sub UpdateGuarantees {
940     my %data = shift;
941     my $dbh = C4::Context->dbh;
942     my ( $count, $guarantees ) = GetGuarantees( $data{'borrowernumber'} );
943     foreach my $guarantee (@$guarantees){
944         my $guaquery = qq|UPDATE borrowers 
945               SET address=?,fax=?,B_city=?,mobile=?,city=?,phone=?
946               WHERE borrowernumber=?
947         |;
948         my $sth = $dbh->prepare($guaquery);
949         $sth->execute($data{'address'},$data{'fax'},$data{'B_city'},$data{'mobile'},$data{'city'},$data{'phone'},$guarantee->{'borrowernumber'});
950     }
951 }
952 =head2 GetPendingIssues
953
954   my $issues = &GetPendingIssues($borrowernumber);
955
956 Looks up what the patron with the given borrowernumber has borrowed.
957
958 C<&GetPendingIssues> returns a
959 reference-to-array where each element is a reference-to-hash; the
960 keys are the fields from the C<issues>, C<biblio>, and C<items> tables.
961 The keys include C<biblioitems> fields except marc and marcxml.
962
963 =cut
964
965 #'
966 sub GetPendingIssues {
967     my ($borrowernumber) = @_;
968     # must avoid biblioitems.* to prevent large marc and marcxml fields from killing performance
969     # FIXME: namespace collision: each table has "timestamp" fields.  Which one is "timestamp" ?
970     # FIXME: circ/ciculation.pl tries to sort by timestamp!
971     # FIXME: C4::Print::printslip tries to sort by timestamp!
972     # FIXME: namespace collision: other collisions possible.
973     # FIXME: most of this data isn't really being used by callers.
974     my $sth = C4::Context->dbh->prepare(
975    "SELECT issues.*,
976             items.*,
977            biblio.*,
978            biblioitems.volume,
979            biblioitems.number,
980            biblioitems.itemtype,
981            biblioitems.isbn,
982            biblioitems.issn,
983            biblioitems.publicationyear,
984            biblioitems.publishercode,
985            biblioitems.volumedate,
986            biblioitems.volumedesc,
987            biblioitems.lccn,
988            biblioitems.url,
989            issues.timestamp AS timestamp,
990            issues.renewals  AS renewals,
991             items.renewals  AS totalrenewals
992     FROM   issues
993     LEFT JOIN items       ON items.itemnumber       =      issues.itemnumber
994     LEFT JOIN biblio      ON items.biblionumber     =      biblio.biblionumber
995     LEFT JOIN biblioitems ON items.biblioitemnumber = biblioitems.biblioitemnumber
996     WHERE
997       borrowernumber=?
998     ORDER BY issues.issuedate"
999     );
1000     $sth->execute($borrowernumber);
1001     my $data = $sth->fetchall_arrayref({});
1002     my $today = C4::Dates->new->output('iso');
1003     foreach (@$data) {
1004         $_->{date_due} or next;
1005         ($_->{date_due} lt $today) and $_->{overdue} = 1;
1006     }
1007     return $data;
1008 }
1009
1010 =head2 GetAllIssues
1011
1012   $issues = &GetAllIssues($borrowernumber, $sortkey, $limit);
1013
1014 Looks up what the patron with the given borrowernumber has borrowed,
1015 and sorts the results.
1016
1017 C<$sortkey> is the name of a field on which to sort the results. This
1018 should be the name of a field in the C<issues>, C<biblio>,
1019 C<biblioitems>, or C<items> table in the Koha database.
1020
1021 C<$limit> is the maximum number of results to return.
1022
1023 C<&GetAllIssues> an arrayref, C<$issues>, of hashrefs, the keys of which
1024 are the fields from the C<issues>, C<biblio>, C<biblioitems>, and
1025 C<items> tables of the Koha database.
1026
1027 =cut
1028
1029 #'
1030 sub GetAllIssues {
1031     my ( $borrowernumber, $order, $limit ) = @_;
1032
1033     #FIXME: sanity-check order and limit
1034     my $dbh   = C4::Context->dbh;
1035     my $query =
1036   "SELECT *, issues.timestamp as issuestimestamp, issues.renewals AS renewals,items.renewals AS totalrenewals,items.timestamp AS itemstimestamp 
1037   FROM issues 
1038   LEFT JOIN items on items.itemnumber=issues.itemnumber
1039   LEFT JOIN biblio ON items.biblionumber=biblio.biblionumber
1040   LEFT JOIN biblioitems ON items.biblioitemnumber=biblioitems.biblioitemnumber
1041   WHERE borrowernumber=? 
1042   UNION ALL
1043   SELECT *, old_issues.timestamp as issuestimestamp, old_issues.renewals AS renewals,items.renewals AS totalrenewals,items.timestamp AS itemstimestamp 
1044   FROM old_issues 
1045   LEFT JOIN items on items.itemnumber=old_issues.itemnumber
1046   LEFT JOIN biblio ON items.biblionumber=biblio.biblionumber
1047   LEFT JOIN biblioitems ON items.biblioitemnumber=biblioitems.biblioitemnumber
1048   WHERE borrowernumber=? 
1049   order by $order";
1050     if ( $limit != 0 ) {
1051         $query .= " limit $limit";
1052     }
1053
1054     my $sth = $dbh->prepare($query);
1055     $sth->execute($borrowernumber, $borrowernumber);
1056     my @result;
1057     my $i = 0;
1058     while ( my $data = $sth->fetchrow_hashref ) {
1059         push @result, $data;
1060     }
1061
1062     return \@result;
1063 }
1064
1065
1066 =head2 GetMemberAccountRecords
1067
1068   ($total, $acctlines, $count) = &GetMemberAccountRecords($borrowernumber);
1069
1070 Looks up accounting data for the patron with the given borrowernumber.
1071
1072 C<&GetMemberAccountRecords> returns a three-element array. C<$acctlines> is a
1073 reference-to-array, where each element is a reference-to-hash; the
1074 keys are the fields of the C<accountlines> table in the Koha database.
1075 C<$count> is the number of elements in C<$acctlines>. C<$total> is the
1076 total amount outstanding for all of the account lines.
1077
1078 =cut
1079
1080 #'
1081 sub GetMemberAccountRecords {
1082     my ($borrowernumber,$date) = @_;
1083     my $dbh = C4::Context->dbh;
1084     my @acctlines;
1085     my $numlines = 0;
1086     my $strsth      = qq(
1087                         SELECT * 
1088                         FROM accountlines 
1089                         WHERE borrowernumber=?);
1090     my @bind = ($borrowernumber);
1091     if ($date && $date ne ''){
1092             $strsth.=" AND date < ? ";
1093             push(@bind,$date);
1094     }
1095     $strsth.=" ORDER BY date desc,timestamp DESC";
1096     my $sth= $dbh->prepare( $strsth );
1097     $sth->execute( @bind );
1098     my $total = 0;
1099     while ( my $data = $sth->fetchrow_hashref ) {
1100                 my $biblio = GetBiblioFromItemNumber($data->{itemnumber}) if $data->{itemnumber};
1101                 $data->{biblionumber} = $biblio->{biblionumber};
1102                 $data->{title} = $biblio->{title};
1103         $acctlines[$numlines] = $data;
1104         $numlines++;
1105         $total += int(1000 * $data->{'amountoutstanding'}); # convert float to integer to avoid round-off errors
1106     }
1107     $total /= 1000;
1108     return ( $total, \@acctlines,$numlines);
1109 }
1110
1111 =head2 GetBorNotifyAcctRecord
1112
1113   ($count, $acctlines, $total) = &GetBorNotifyAcctRecord($params,$notifyid);
1114
1115 Looks up accounting data for the patron with the given borrowernumber per file number.
1116
1117 (FIXME - I'm not at all sure what this is about.)
1118
1119 C<&GetBorNotifyAcctRecord> returns a three-element array. C<$acctlines> is a
1120 reference-to-array, where each element is a reference-to-hash; the
1121 keys are the fields of the C<accountlines> table in the Koha database.
1122 C<$count> is the number of elements in C<$acctlines>. C<$total> is the
1123 total amount outstanding for all of the account lines.
1124
1125 =cut
1126
1127 sub GetBorNotifyAcctRecord {
1128     my ( $borrowernumber, $notifyid ) = @_;
1129     my $dbh = C4::Context->dbh;
1130     my @acctlines;
1131     my $numlines = 0;
1132     my $sth = $dbh->prepare(
1133             "SELECT * 
1134                 FROM accountlines 
1135                 WHERE borrowernumber=? 
1136                     AND notify_id=? 
1137                     AND amountoutstanding != '0' 
1138                 ORDER BY notify_id,accounttype
1139                 ");
1140 #                    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')
1141
1142     $sth->execute( $borrowernumber, $notifyid );
1143     my $total = 0;
1144     while ( my $data = $sth->fetchrow_hashref ) {
1145         $acctlines[$numlines] = $data;
1146         $numlines++;
1147         $total += int(100 * $data->{'amountoutstanding'});
1148     }
1149     $total /= 100;
1150     return ( $total, \@acctlines, $numlines );
1151 }
1152
1153 =head2 checkuniquemember (OUEST-PROVENCE)
1154
1155   ($result,$categorycode)  = &checkuniquemember($collectivity,$surname,$firstname,$dateofbirth);
1156
1157 Checks that a member exists or not in the database.
1158
1159 C<&result> is nonzero (=exist) or 0 (=does not exist)
1160 C<&categorycode> is from categorycode table
1161 C<&collectivity> is 1 (= we add a collectivity) or 0 (= we add a physical member)
1162 C<&surname> is the surname
1163 C<&firstname> is the firstname (only if collectivity=0)
1164 C<&dateofbirth> is the date of birth in ISO format (only if collectivity=0)
1165
1166 =cut
1167
1168 # FIXME: This function is not legitimate.  Multiple patrons might have the same first/last name and birthdate.
1169 # This is especially true since first name is not even a required field.
1170
1171 sub checkuniquemember {
1172     my ( $collectivity, $surname, $firstname, $dateofbirth ) = @_;
1173     my $dbh = C4::Context->dbh;
1174     my $request = ($collectivity) ?
1175         "SELECT borrowernumber,categorycode FROM borrowers WHERE surname=? " :
1176             ($dateofbirth) ?
1177             "SELECT borrowernumber,categorycode FROM borrowers WHERE surname=? and firstname=?  and dateofbirth=?" :
1178             "SELECT borrowernumber,categorycode FROM borrowers WHERE surname=? and firstname=?";
1179     my $sth = $dbh->prepare($request);
1180     if ($collectivity) {
1181         $sth->execute( uc($surname) );
1182     } elsif($dateofbirth){
1183         $sth->execute( uc($surname), ucfirst($firstname), $dateofbirth );
1184     }else{
1185         $sth->execute( uc($surname), ucfirst($firstname));
1186     }
1187     my @data = $sth->fetchrow;
1188     ( $data[0] ) and return $data[0], $data[1];
1189     return 0;
1190 }
1191
1192 sub checkcardnumber {
1193     my ($cardnumber,$borrowernumber) = @_;
1194     my $dbh = C4::Context->dbh;
1195     my $query = "SELECT * FROM borrowers WHERE cardnumber=?";
1196     $query .= " AND borrowernumber <> ?" if ($borrowernumber);
1197   my $sth = $dbh->prepare($query);
1198   if ($borrowernumber) {
1199    $sth->execute($cardnumber,$borrowernumber);
1200   } else { 
1201      $sth->execute($cardnumber);
1202   } 
1203     if (my $data= $sth->fetchrow_hashref()){
1204         return 1;
1205     }
1206     else {
1207         return 0;
1208     }
1209 }  
1210
1211
1212 =head2 getzipnamecity (OUEST-PROVENCE)
1213
1214 take all info from table city for the fields city and  zip
1215 check for the name and the zip code of the city selected
1216
1217 =cut
1218
1219 sub getzipnamecity {
1220     my ($cityid) = @_;
1221     my $dbh      = C4::Context->dbh;
1222     my $sth      =
1223       $dbh->prepare(
1224         "select city_name,city_zipcode from cities where cityid=? ");
1225     $sth->execute($cityid);
1226     my @data = $sth->fetchrow;
1227     return $data[0], $data[1];
1228 }
1229
1230
1231 =head2 getdcity (OUEST-PROVENCE)
1232
1233 recover cityid  with city_name condition
1234
1235 =cut
1236
1237 sub getidcity {
1238     my ($city_name) = @_;
1239     my $dbh = C4::Context->dbh;
1240     my $sth = $dbh->prepare("select cityid from cities where city_name=? ");
1241     $sth->execute($city_name);
1242     my $data = $sth->fetchrow;
1243     return $data;
1244 }
1245
1246 =head2 GetFirstValidEmailAddress
1247
1248   $email = GetFirstValidEmailAddress($borrowernumber);
1249
1250 Return the first valid email address for a borrower, given the borrowernumber.  For now, the order 
1251 is defined as email, emailpro, B_email.  Returns the empty string if the borrower has no email 
1252 addresses.
1253
1254 =cut
1255
1256 sub GetFirstValidEmailAddress {
1257     my $borrowernumber = shift;
1258     my $dbh = C4::Context->dbh;
1259     my $sth = $dbh->prepare( "SELECT email, emailpro, B_email FROM borrowers where borrowernumber = ? ");
1260     $sth->execute( $borrowernumber );
1261     my $data = $sth->fetchrow_hashref;
1262
1263     if ($data->{'email'}) {
1264        return $data->{'email'};
1265     } elsif ($data->{'emailpro'}) {
1266        return $data->{'emailpro'};
1267     } elsif ($data->{'B_email'}) {
1268        return $data->{'B_email'};
1269     } else {
1270        return '';
1271     }
1272 }
1273
1274 =head2 GetExpiryDate 
1275
1276   $expirydate = GetExpiryDate($categorycode, $dateenrolled);
1277
1278 Calculate expiry date given a categorycode and starting date.  Date argument must be in ISO format.
1279 Return date is also in ISO format.
1280
1281 =cut
1282
1283 sub GetExpiryDate {
1284     my ( $categorycode, $dateenrolled ) = @_;
1285     my $enrolments;
1286     if ($categorycode) {
1287         my $dbh = C4::Context->dbh;
1288         my $sth = $dbh->prepare("SELECT enrolmentperiod,enrolmentperioddate FROM categories WHERE categorycode=?");
1289         $sth->execute($categorycode);
1290         $enrolments = $sth->fetchrow_hashref;
1291     }
1292     # die "GetExpiryDate: for enrollmentperiod $enrolmentperiod (category '$categorycode') starting $dateenrolled.\n";
1293     my @date = split (/-/,$dateenrolled);
1294     if($enrolments->{enrolmentperiod}){
1295         return sprintf("%04d-%02d-%02d", Add_Delta_YM(@date,0,$enrolments->{enrolmentperiod}));
1296     }else{
1297         return $enrolments->{enrolmentperioddate};
1298     }
1299 }
1300
1301 =head2 checkuserpassword (OUEST-PROVENCE)
1302
1303 check for the password and login are not used
1304 return the number of record 
1305 0=> NOT USED 1=> USED
1306
1307 =cut
1308
1309 sub checkuserpassword {
1310     my ( $borrowernumber, $userid, $password ) = @_;
1311     $password = md5_base64($password);
1312     my $dbh = C4::Context->dbh;
1313     my $sth =
1314       $dbh->prepare(
1315 "Select count(*) from borrowers where borrowernumber !=? and userid =? and password=? "
1316       );
1317     $sth->execute( $borrowernumber, $userid, $password );
1318     my $number_rows = $sth->fetchrow;
1319     return $number_rows;
1320
1321 }
1322
1323 =head2 GetborCatFromCatType
1324
1325   ($codes_arrayref, $labels_hashref) = &GetborCatFromCatType();
1326
1327 Looks up the different types of borrowers in the database. Returns two
1328 elements: a reference-to-array, which lists the borrower category
1329 codes, and a reference-to-hash, which maps the borrower category codes
1330 to category descriptions.
1331
1332 =cut
1333
1334 #'
1335 sub GetborCatFromCatType {
1336     my ( $category_type, $action ) = @_;
1337         # FIXME - This API  seems both limited and dangerous. 
1338     my $dbh     = C4::Context->dbh;
1339     my $request = qq|   SELECT categorycode,description 
1340             FROM categories 
1341             $action
1342             ORDER BY categorycode|;
1343     my $sth = $dbh->prepare($request);
1344         if ($action) {
1345         $sth->execute($category_type);
1346     }
1347     else {
1348         $sth->execute();
1349     }
1350
1351     my %labels;
1352     my @codes;
1353
1354     while ( my $data = $sth->fetchrow_hashref ) {
1355         push @codes, $data->{'categorycode'};
1356         $labels{ $data->{'categorycode'} } = $data->{'description'};
1357     }
1358     return ( \@codes, \%labels );
1359 }
1360
1361 =head2 GetBorrowercategory
1362
1363   $hashref = &GetBorrowercategory($categorycode);
1364
1365 Given the borrower's category code, the function returns the corresponding
1366 data hashref for a comprehensive information display.
1367
1368   $arrayref_hashref = &GetBorrowercategory;
1369
1370 If no category code provided, the function returns all the categories.
1371
1372 =cut
1373
1374 sub GetBorrowercategory {
1375     my ($catcode) = @_;
1376     my $dbh       = C4::Context->dbh;
1377     if ($catcode){
1378         my $sth       =
1379         $dbh->prepare(
1380     "SELECT description,dateofbirthrequired,upperagelimit,category_type 
1381     FROM categories 
1382     WHERE categorycode = ?"
1383         );
1384         $sth->execute($catcode);
1385         my $data =
1386         $sth->fetchrow_hashref;
1387         return $data;
1388     } 
1389     return;  
1390 }    # sub getborrowercategory
1391
1392 =head2 GetBorrowercategoryList
1393
1394   $arrayref_hashref = &GetBorrowercategoryList;
1395 If no category code provided, the function returns all the categories.
1396
1397 =cut
1398
1399 sub GetBorrowercategoryList {
1400     my $dbh       = C4::Context->dbh;
1401     my $sth       =
1402     $dbh->prepare(
1403     "SELECT * 
1404     FROM categories 
1405     ORDER BY description"
1406         );
1407     $sth->execute;
1408     my $data =
1409     $sth->fetchall_arrayref({});
1410     return $data;
1411 }    # sub getborrowercategory
1412
1413 =head2 ethnicitycategories
1414
1415   ($codes_arrayref, $labels_hashref) = &ethnicitycategories();
1416
1417 Looks up the different ethnic types in the database. Returns two
1418 elements: a reference-to-array, which lists the ethnicity codes, and a
1419 reference-to-hash, which maps the ethnicity codes to ethnicity
1420 descriptions.
1421
1422 =cut
1423
1424 #'
1425
1426 sub ethnicitycategories {
1427     my $dbh = C4::Context->dbh;
1428     my $sth = $dbh->prepare("Select code,name from ethnicity order by name");
1429     $sth->execute;
1430     my %labels;
1431     my @codes;
1432     while ( my $data = $sth->fetchrow_hashref ) {
1433         push @codes, $data->{'code'};
1434         $labels{ $data->{'code'} } = $data->{'name'};
1435     }
1436     return ( \@codes, \%labels );
1437 }
1438
1439 =head2 fixEthnicity
1440
1441   $ethn_name = &fixEthnicity($ethn_code);
1442
1443 Takes an ethnicity code (e.g., "european" or "pi") and returns the
1444 corresponding descriptive name from the C<ethnicity> table in the
1445 Koha database ("European" or "Pacific Islander").
1446
1447 =cut
1448
1449 #'
1450
1451 sub fixEthnicity {
1452     my $ethnicity = shift;
1453     return unless $ethnicity;
1454     my $dbh       = C4::Context->dbh;
1455     my $sth       = $dbh->prepare("Select name from ethnicity where code = ?");
1456     $sth->execute($ethnicity);
1457     my $data = $sth->fetchrow_hashref;
1458     return $data->{'name'};
1459 }    # sub fixEthnicity
1460
1461 =head2 GetAge
1462
1463   $dateofbirth,$date = &GetAge($date);
1464
1465 this function return the borrowers age with the value of dateofbirth
1466
1467 =cut
1468
1469 #'
1470 sub GetAge{
1471     my ( $date, $date_ref ) = @_;
1472
1473     if ( not defined $date_ref ) {
1474         $date_ref = sprintf( '%04d-%02d-%02d', Today() );
1475     }
1476
1477     my ( $year1, $month1, $day1 ) = split /-/, $date;
1478     my ( $year2, $month2, $day2 ) = split /-/, $date_ref;
1479
1480     my $age = $year2 - $year1;
1481     if ( $month1 . $day1 > $month2 . $day2 ) {
1482         $age--;
1483     }
1484
1485     return $age;
1486 }    # sub get_age
1487
1488 =head2 get_institutions
1489
1490   $insitutions = get_institutions();
1491
1492 Just returns a list of all the borrowers of type I, borrownumber and name
1493
1494 =cut
1495
1496 #'
1497 sub get_institutions {
1498     my $dbh = C4::Context->dbh();
1499     my $sth =
1500       $dbh->prepare(
1501 "SELECT borrowernumber,surname FROM borrowers WHERE categorycode=? ORDER BY surname"
1502       );
1503     $sth->execute('I');
1504     my %orgs;
1505     while ( my $data = $sth->fetchrow_hashref() ) {
1506         $orgs{ $data->{'borrowernumber'} } = $data;
1507     }
1508     return ( \%orgs );
1509
1510 }    # sub get_institutions
1511
1512 =head2 add_member_orgs
1513
1514   add_member_orgs($borrowernumber,$borrowernumbers);
1515
1516 Takes a borrowernumber and a list of other borrowernumbers and inserts them into the borrowers_to_borrowers table
1517
1518 =cut
1519
1520 #'
1521 sub add_member_orgs {
1522     my ( $borrowernumber, $otherborrowers ) = @_;
1523     my $dbh   = C4::Context->dbh();
1524     my $query =
1525       "INSERT INTO borrowers_to_borrowers (borrower1,borrower2) VALUES (?,?)";
1526     my $sth = $dbh->prepare($query);
1527     foreach my $otherborrowernumber (@$otherborrowers) {
1528         $sth->execute( $borrowernumber, $otherborrowernumber );
1529     }
1530
1531 }    # sub add_member_orgs
1532
1533 =head2 GetCities
1534
1535   $cityarrayref = GetCities();
1536
1537   Returns an array_ref of the entries in the cities table
1538   If there are entries in the table an empty row is returned
1539   This is currently only used to populate a popup in memberentry
1540
1541 =cut
1542
1543 sub GetCities {
1544
1545     my $dbh   = C4::Context->dbh;
1546     my $city_arr = $dbh->selectall_arrayref(
1547         q|SELECT cityid,city_zipcode,city_name FROM cities ORDER BY city_name|,
1548         { Slice => {} });
1549     if ( @{$city_arr} ) {
1550         unshift @{$city_arr}, {
1551             city_zipcode => q{},
1552             city_name    => q{},
1553             cityid       => q{},
1554         };
1555     }
1556
1557     return  $city_arr;
1558 }
1559
1560 =head2 GetSortDetails (OUEST-PROVENCE)
1561
1562   ($lib) = &GetSortDetails($category,$sortvalue);
1563
1564 Returns the authorized value  details
1565 C<&$lib>return value of authorized value details
1566 C<&$sortvalue>this is the value of authorized value 
1567 C<&$category>this is the value of authorized value category
1568
1569 =cut
1570
1571 sub GetSortDetails {
1572     my ( $category, $sortvalue ) = @_;
1573     my $dbh   = C4::Context->dbh;
1574     my $query = qq|SELECT lib 
1575         FROM authorised_values 
1576         WHERE category=?
1577         AND authorised_value=? |;
1578     my $sth = $dbh->prepare($query);
1579     $sth->execute( $category, $sortvalue );
1580     my $lib = $sth->fetchrow;
1581     return ($lib) if ($lib);
1582     return ($sortvalue) unless ($lib);
1583 }
1584
1585 =head2 MoveMemberToDeleted
1586
1587   $result = &MoveMemberToDeleted($borrowernumber);
1588
1589 Copy the record from borrowers to deletedborrowers table.
1590
1591 =cut
1592
1593 # FIXME: should do it in one SQL statement w/ subquery
1594 # Otherwise, we should return the @data on success
1595
1596 sub MoveMemberToDeleted {
1597     my ($member) = shift or return;
1598     my $dbh = C4::Context->dbh;
1599     my $query = qq|SELECT * 
1600           FROM borrowers 
1601           WHERE borrowernumber=?|;
1602     my $sth = $dbh->prepare($query);
1603     $sth->execute($member);
1604     my @data = $sth->fetchrow_array;
1605     (@data) or return;  # if we got a bad borrowernumber, there's nothing to insert
1606     $sth =
1607       $dbh->prepare( "INSERT INTO deletedborrowers VALUES ("
1608           . ( "?," x ( scalar(@data) - 1 ) )
1609           . "?)" );
1610     $sth->execute(@data);
1611 }
1612
1613 =head2 DelMember
1614
1615     DelMember($borrowernumber);
1616
1617 This function remove directly a borrower whitout writing it on deleteborrower.
1618 + Deletes reserves for the borrower
1619
1620 =cut
1621
1622 sub DelMember {
1623     my $dbh            = C4::Context->dbh;
1624     my $borrowernumber = shift;
1625     #warn "in delmember with $borrowernumber";
1626     return unless $borrowernumber;    # borrowernumber is mandatory.
1627
1628     my $query = qq|DELETE 
1629           FROM  reserves 
1630           WHERE borrowernumber=?|;
1631     my $sth = $dbh->prepare($query);
1632     $sth->execute($borrowernumber);
1633     $query = "
1634        DELETE
1635        FROM borrowers
1636        WHERE borrowernumber = ?
1637    ";
1638     $sth = $dbh->prepare($query);
1639     $sth->execute($borrowernumber);
1640     logaction("MEMBERS", "DELETE", $borrowernumber, "") if C4::Context->preference("BorrowersLog");
1641     return $sth->rows;
1642 }
1643
1644 =head2 ExtendMemberSubscriptionTo (OUEST-PROVENCE)
1645
1646     $date = ExtendMemberSubscriptionTo($borrowerid, $date);
1647
1648 Extending the subscription to a given date or to the expiry date calculated on ISO date.
1649 Returns ISO date.
1650
1651 =cut
1652
1653 sub ExtendMemberSubscriptionTo {
1654     my ( $borrowerid,$date) = @_;
1655     my $dbh = C4::Context->dbh;
1656     my $borrower = GetMember('borrowernumber'=>$borrowerid);
1657     unless ($date){
1658       $date=POSIX::strftime("%Y-%m-%d",localtime());
1659       $date = GetExpiryDate( $borrower->{'categorycode'}, $date );
1660     }
1661     my $sth = $dbh->do(<<EOF);
1662 UPDATE borrowers 
1663 SET  dateexpiry='$date' 
1664 WHERE borrowernumber='$borrowerid'
1665 EOF
1666     # add enrolmentfee if needed
1667     $sth = $dbh->prepare("SELECT enrolmentfee FROM categories WHERE categorycode=?");
1668     $sth->execute($borrower->{'categorycode'});
1669     my ($enrolmentfee) = $sth->fetchrow;
1670     if ($enrolmentfee && $enrolmentfee > 0) {
1671         # insert fee in patron debts
1672         manualinvoice($borrower->{'borrowernumber'}, '', '', 'A', $enrolmentfee);
1673     }
1674     return $date if ($sth);
1675     return 0;
1676 }
1677
1678 =head2 GetRoadTypes (OUEST-PROVENCE)
1679
1680   ($idroadtypearrayref, $roadttype_hashref) = &GetRoadTypes();
1681
1682 Looks up the different road type . Returns two
1683 elements: a reference-to-array, which lists the id_roadtype
1684 codes, and a reference-to-hash, which maps the road type of the road .
1685
1686 =cut
1687
1688 sub GetRoadTypes {
1689     my $dbh   = C4::Context->dbh;
1690     my $query = qq|
1691 SELECT roadtypeid,road_type 
1692 FROM roadtype 
1693 ORDER BY road_type|;
1694     my $sth = $dbh->prepare($query);
1695     $sth->execute();
1696     my %roadtype;
1697     my @id;
1698
1699     #    insert empty value to create a empty choice in cgi popup
1700
1701     while ( my $data = $sth->fetchrow_hashref ) {
1702
1703         push @id, $data->{'roadtypeid'};
1704         $roadtype{ $data->{'roadtypeid'} } = $data->{'road_type'};
1705     }
1706
1707 #test to know if the table contain some records if no the function return nothing
1708     my $id = @id;
1709     if ( $id eq 0 ) {
1710         return ();
1711     }
1712     else {
1713         unshift( @id, "" );
1714         return ( \@id, \%roadtype );
1715     }
1716 }
1717
1718
1719
1720 =head2 GetTitles (OUEST-PROVENCE)
1721
1722   ($borrowertitle)= &GetTitles();
1723
1724 Looks up the different title . Returns array  with all borrowers title
1725
1726 =cut
1727
1728 sub GetTitles {
1729     my @borrowerTitle = split (/,|\|/,C4::Context->preference('BorrowersTitles'));
1730     unshift( @borrowerTitle, "" );
1731     my $count=@borrowerTitle;
1732     if ($count == 1){
1733         return ();
1734     }
1735     else {
1736         return ( \@borrowerTitle);
1737     }
1738 }
1739
1740 =head2 GetPatronImage
1741
1742     my ($imagedata, $dberror) = GetPatronImage($cardnumber);
1743
1744 Returns the mimetype and binary image data of the image for the patron with the supplied cardnumber.
1745
1746 =cut
1747
1748 sub GetPatronImage {
1749     my ($cardnumber) = @_;
1750     warn "Cardnumber passed to GetPatronImage is $cardnumber" if $debug;
1751     my $dbh = C4::Context->dbh;
1752     my $query = 'SELECT mimetype, imagefile FROM patronimage WHERE cardnumber = ?';
1753     my $sth = $dbh->prepare($query);
1754     $sth->execute($cardnumber);
1755     my $imagedata = $sth->fetchrow_hashref;
1756     warn "Database error!" if $sth->errstr;
1757     return $imagedata, $sth->errstr;
1758 }
1759
1760 =head2 PutPatronImage
1761
1762     PutPatronImage($cardnumber, $mimetype, $imgfile);
1763
1764 Stores patron binary image data and mimetype in database.
1765 NOTE: This function is good for updating images as well as inserting new images in the database.
1766
1767 =cut
1768
1769 sub PutPatronImage {
1770     my ($cardnumber, $mimetype, $imgfile) = @_;
1771     warn "Parameters passed in: Cardnumber=$cardnumber, Mimetype=$mimetype, " . ($imgfile ? "Imagefile" : "No Imagefile") if $debug;
1772     my $dbh = C4::Context->dbh;
1773     my $query = "INSERT INTO patronimage (cardnumber, mimetype, imagefile) VALUES (?,?,?) ON DUPLICATE KEY UPDATE imagefile = ?;";
1774     my $sth = $dbh->prepare($query);
1775     $sth->execute($cardnumber,$mimetype,$imgfile,$imgfile);
1776     warn "Error returned inserting $cardnumber.$mimetype." if $sth->errstr;
1777     return $sth->errstr;
1778 }
1779
1780 =head2 RmPatronImage
1781
1782     my ($dberror) = RmPatronImage($cardnumber);
1783
1784 Removes the image for the patron with the supplied cardnumber.
1785
1786 =cut
1787
1788 sub RmPatronImage {
1789     my ($cardnumber) = @_;
1790     warn "Cardnumber passed to GetPatronImage is $cardnumber" if $debug;
1791     my $dbh = C4::Context->dbh;
1792     my $query = "DELETE FROM patronimage WHERE cardnumber = ?;";
1793     my $sth = $dbh->prepare($query);
1794     $sth->execute($cardnumber);
1795     my $dberror = $sth->errstr;
1796     warn "Database error!" if $sth->errstr;
1797     return $dberror;
1798 }
1799
1800 =head2 GetRoadTypeDetails (OUEST-PROVENCE)
1801
1802   ($roadtype) = &GetRoadTypeDetails($roadtypeid);
1803
1804 Returns the description of roadtype
1805 C<&$roadtype>return description of road type
1806 C<&$roadtypeid>this is the value of roadtype s
1807
1808 =cut
1809
1810 sub GetRoadTypeDetails {
1811     my ($roadtypeid) = @_;
1812     my $dbh          = C4::Context->dbh;
1813     my $query        = qq|
1814 SELECT road_type 
1815 FROM roadtype 
1816 WHERE roadtypeid=?|;
1817     my $sth = $dbh->prepare($query);
1818     $sth->execute($roadtypeid);
1819     my $roadtype = $sth->fetchrow;
1820     return ($roadtype);
1821 }
1822
1823 =head2 GetBorrowersWhoHaveNotBorrowedSince
1824
1825   &GetBorrowersWhoHaveNotBorrowedSince($date)
1826
1827 this function get all borrowers who haven't borrowed since the date given on input arg.
1828
1829 =cut
1830
1831 sub GetBorrowersWhoHaveNotBorrowedSince {
1832     my $filterdate = shift||POSIX::strftime("%Y-%m-%d",localtime());
1833     my $filterexpiry = shift;
1834     my $filterbranch = shift || 
1835                         ((C4::Context->preference('IndependantBranches') 
1836                              && C4::Context->userenv 
1837                              && C4::Context->userenv->{flags} % 2 !=1 
1838                              && C4::Context->userenv->{branch})
1839                          ? C4::Context->userenv->{branch}
1840                          : "");  
1841     my $dbh   = C4::Context->dbh;
1842     my $query = "
1843         SELECT borrowers.borrowernumber,
1844                max(old_issues.timestamp) as latestissue,
1845                max(issues.timestamp) as currentissue
1846         FROM   borrowers
1847         JOIN   categories USING (categorycode)
1848         LEFT JOIN old_issues USING (borrowernumber)
1849         LEFT JOIN issues USING (borrowernumber) 
1850         WHERE  category_type <> 'S'
1851         AND borrowernumber NOT IN (SELECT guarantorid FROM borrowers WHERE guarantorid IS NOT NULL AND guarantorid <> 0) 
1852    ";
1853     my @query_params;
1854     if ($filterbranch && $filterbranch ne ""){ 
1855         $query.=" AND borrowers.branchcode= ?";
1856         push @query_params,$filterbranch;
1857     }
1858     if($filterexpiry){
1859         $query .= " AND dateexpiry < ? ";
1860         push @query_params,$filterdate;
1861     }
1862     $query.=" GROUP BY borrowers.borrowernumber";
1863     if ($filterdate){ 
1864         $query.=" HAVING (latestissue < ? OR latestissue IS NULL) 
1865                   AND currentissue IS NULL";
1866         push @query_params,$filterdate;
1867     }
1868     warn $query if $debug;
1869     my $sth = $dbh->prepare($query);
1870     if (scalar(@query_params)>0){  
1871         $sth->execute(@query_params);
1872     } 
1873     else {
1874         $sth->execute;
1875     }      
1876     
1877     my @results;
1878     while ( my $data = $sth->fetchrow_hashref ) {
1879         push @results, $data;
1880     }
1881     return \@results;
1882 }
1883
1884 =head2 GetBorrowersWhoHaveNeverBorrowed
1885
1886   $results = &GetBorrowersWhoHaveNeverBorrowed
1887
1888 This function get all borrowers who have never borrowed.
1889
1890 I<$result> is a ref to an array which all elements are a hasref.
1891
1892 =cut
1893
1894 sub GetBorrowersWhoHaveNeverBorrowed {
1895     my $filterbranch = shift || 
1896                         ((C4::Context->preference('IndependantBranches') 
1897                              && C4::Context->userenv 
1898                              && C4::Context->userenv->{flags} % 2 !=1 
1899                              && C4::Context->userenv->{branch})
1900                          ? C4::Context->userenv->{branch}
1901                          : "");  
1902     my $dbh   = C4::Context->dbh;
1903     my $query = "
1904         SELECT borrowers.borrowernumber,max(timestamp) as latestissue
1905         FROM   borrowers
1906           LEFT JOIN issues ON borrowers.borrowernumber = issues.borrowernumber
1907         WHERE issues.borrowernumber IS NULL
1908    ";
1909     my @query_params;
1910     if ($filterbranch && $filterbranch ne ""){ 
1911         $query.=" AND borrowers.branchcode= ?";
1912         push @query_params,$filterbranch;
1913     }
1914     warn $query if $debug;
1915   
1916     my $sth = $dbh->prepare($query);
1917     if (scalar(@query_params)>0){  
1918         $sth->execute(@query_params);
1919     } 
1920     else {
1921         $sth->execute;
1922     }      
1923     
1924     my @results;
1925     while ( my $data = $sth->fetchrow_hashref ) {
1926         push @results, $data;
1927     }
1928     return \@results;
1929 }
1930
1931 =head2 GetBorrowersWithIssuesHistoryOlderThan
1932
1933   $results = &GetBorrowersWithIssuesHistoryOlderThan($date)
1934
1935 this function get all borrowers who has an issue history older than I<$date> given on input arg.
1936
1937 I<$result> is a ref to an array which all elements are a hashref.
1938 This hashref is containt the number of time this borrowers has borrowed before I<$date> and the borrowernumber.
1939
1940 =cut
1941
1942 sub GetBorrowersWithIssuesHistoryOlderThan {
1943     my $dbh  = C4::Context->dbh;
1944     my $date = shift ||POSIX::strftime("%Y-%m-%d",localtime());
1945     my $filterbranch = shift || 
1946                         ((C4::Context->preference('IndependantBranches') 
1947                              && C4::Context->userenv 
1948                              && C4::Context->userenv->{flags} % 2 !=1 
1949                              && C4::Context->userenv->{branch})
1950                          ? C4::Context->userenv->{branch}
1951                          : "");  
1952     my $query = "
1953        SELECT count(borrowernumber) as n,borrowernumber
1954        FROM old_issues
1955        WHERE returndate < ?
1956          AND borrowernumber IS NOT NULL 
1957     "; 
1958     my @query_params;
1959     push @query_params, $date;
1960     if ($filterbranch){
1961         $query.="   AND branchcode = ?";
1962         push @query_params, $filterbranch;
1963     }    
1964     $query.=" GROUP BY borrowernumber ";
1965     warn $query if $debug;
1966     my $sth = $dbh->prepare($query);
1967     $sth->execute(@query_params);
1968     my @results;
1969
1970     while ( my $data = $sth->fetchrow_hashref ) {
1971         push @results, $data;
1972     }
1973     return \@results;
1974 }
1975
1976 =head2 GetBorrowersNamesAndLatestIssue
1977
1978   $results = &GetBorrowersNamesAndLatestIssueList(@borrowernumbers)
1979
1980 this function get borrowers Names and surnames and Issue information.
1981
1982 I<@borrowernumbers> is an array which all elements are borrowernumbers.
1983 This hashref is containt the number of time this borrowers has borrowed before I<$date> and the borrowernumber.
1984
1985 =cut
1986
1987 sub GetBorrowersNamesAndLatestIssue {
1988     my $dbh  = C4::Context->dbh;
1989     my @borrowernumbers=@_;  
1990     my $query = "
1991        SELECT surname,lastname, phone, email,max(timestamp)
1992        FROM borrowers 
1993          LEFT JOIN issues ON borrowers.borrowernumber=issues.borrowernumber
1994        GROUP BY borrowernumber
1995    ";
1996     my $sth = $dbh->prepare($query);
1997     $sth->execute;
1998     my $results = $sth->fetchall_arrayref({});
1999     return $results;
2000 }
2001
2002 =head2 DebarMember
2003
2004   my $success = DebarMember( $borrowernumber );
2005
2006 marks a Member as debarred, and therefore unable to checkout any more
2007 items.
2008
2009 return :
2010 true on success, false on failure
2011
2012 =cut
2013
2014 sub DebarMember {
2015     my $borrowernumber = shift;
2016
2017     return unless defined $borrowernumber;
2018     return unless $borrowernumber =~ /^\d+$/;
2019
2020     return ModMember( borrowernumber => $borrowernumber,
2021                       debarred       => 1 );
2022     
2023 }
2024
2025 =head2 AddMessage
2026
2027   AddMessage( $borrowernumber, $message_type, $message, $branchcode );
2028
2029 Adds a message to the messages table for the given borrower.
2030
2031 Returns:
2032   True on success
2033   False on failure
2034
2035 =cut
2036
2037 sub AddMessage {
2038     my ( $borrowernumber, $message_type, $message, $branchcode ) = @_;
2039
2040     my $dbh  = C4::Context->dbh;
2041
2042     if ( ! ( $borrowernumber && $message_type && $message && $branchcode ) ) {
2043       return;
2044     }
2045
2046     my $query = "INSERT INTO messages ( borrowernumber, branchcode, message_type, message ) VALUES ( ?, ?, ?, ? )";
2047     my $sth = $dbh->prepare($query);
2048     $sth->execute( $borrowernumber, $branchcode, $message_type, $message );
2049
2050     return 1;
2051 }
2052
2053 =head2 GetMessages
2054
2055   GetMessages( $borrowernumber, $type );
2056
2057 $type is message type, B for borrower, or L for Librarian.
2058 Empty type returns all messages of any type.
2059
2060 Returns all messages for the given borrowernumber
2061
2062 =cut
2063
2064 sub GetMessages {
2065     my ( $borrowernumber, $type, $branchcode ) = @_;
2066
2067     if ( ! $type ) {
2068       $type = '%';
2069     }
2070
2071     my $dbh  = C4::Context->dbh;
2072
2073     my $query = "SELECT
2074                   branches.branchname,
2075                   messages.*,
2076                   message_date,
2077                   messages.branchcode LIKE '$branchcode' AS can_delete
2078                   FROM messages, branches
2079                   WHERE borrowernumber = ?
2080                   AND message_type LIKE ?
2081                   AND messages.branchcode = branches.branchcode
2082                   ORDER BY message_date DESC";
2083     my $sth = $dbh->prepare($query);
2084     $sth->execute( $borrowernumber, $type ) ;
2085     my @results;
2086
2087     while ( my $data = $sth->fetchrow_hashref ) {
2088         my $d = C4::Dates->new( $data->{message_date}, 'iso' );
2089         $data->{message_date_formatted} = $d->output;
2090         push @results, $data;
2091     }
2092     return \@results;
2093
2094 }
2095
2096 =head2 GetMessages
2097
2098   GetMessagesCount( $borrowernumber, $type );
2099
2100 $type is message type, B for borrower, or L for Librarian.
2101 Empty type returns all messages of any type.
2102
2103 Returns the number of messages for the given borrowernumber
2104
2105 =cut
2106
2107 sub GetMessagesCount {
2108     my ( $borrowernumber, $type, $branchcode ) = @_;
2109
2110     if ( ! $type ) {
2111       $type = '%';
2112     }
2113
2114     my $dbh  = C4::Context->dbh;
2115
2116     my $query = "SELECT COUNT(*) as MsgCount FROM messages WHERE borrowernumber = ? AND message_type LIKE ?";
2117     my $sth = $dbh->prepare($query);
2118     $sth->execute( $borrowernumber, $type ) ;
2119     my @results;
2120
2121     my $data = $sth->fetchrow_hashref;
2122     my $count = $data->{'MsgCount'};
2123
2124     return $count;
2125 }
2126
2127
2128
2129 =head2 DeleteMessage
2130
2131   DeleteMessage( $message_id );
2132
2133 =cut
2134
2135 sub DeleteMessage {
2136     my ( $message_id ) = @_;
2137
2138     my $dbh = C4::Context->dbh;
2139
2140     my $query = "DELETE FROM messages WHERE message_id = ?";
2141     my $sth = $dbh->prepare($query);
2142     $sth->execute( $message_id );
2143
2144 }
2145
2146 END { }    # module clean-up code here (global destructor)
2147
2148 1;
2149
2150 __END__
2151
2152 =head1 AUTHOR
2153
2154 Koha Team
2155
2156 =cut