Increment version for 3.22.21
[koha.git] / C4 / Members.pm
1 package C4::Members;
2
3 # Copyright 2000-2003 Katipo Communications
4 # Copyright 2010 BibLibre
5 # Parts Copyright 2010 Catalyst IT
6 #
7 # This file is part of Koha.
8 #
9 # Koha is free software; you can redistribute it and/or modify it
10 # under the terms of the GNU General Public License as published by
11 # the Free Software Foundation; either version 3 of the License, or
12 # (at your option) any later version.
13 #
14 # Koha is distributed in the hope that it will be useful, but
15 # WITHOUT ANY WARRANTY; without even the implied warranty of
16 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 # GNU General Public License for more details.
18 #
19 # You should have received a copy of the GNU General Public License
20 # along with Koha; if not, see <http://www.gnu.org/licenses>.
21
22
23 use strict;
24 #use warnings; FIXME - Bug 2505
25 use C4::Context;
26 use String::Random qw( random_string );
27 use Date::Calc qw/Today Add_Delta_YM check_date Date_to_Days/;
28 use C4::Log; # logaction
29 use C4::Overdues;
30 use C4::Reserves;
31 use C4::Accounts;
32 use C4::Biblio;
33 use C4::Letters;
34 use C4::Members::Attributes qw(SearchIdMatchingAttribute UpdateBorrowerAttribute);
35 use C4::NewsChannels; #get slip news
36 use DateTime;
37 use Koha::Database;
38 use Koha::DateUtils;
39 use Koha::Borrower::Debarments qw(IsDebarred);
40 use Text::Unaccent qw( unac_string );
41 use Koha::AuthUtils qw(hash_password);
42 use Koha::Database;
43 use Koha::Schema;
44
45 our ($VERSION,@ISA,@EXPORT,@EXPORT_OK,$debug);
46
47 use Module::Load::Conditional qw( can_load );
48 if ( ! can_load( modules => { 'Koha::NorwegianPatronDB' => undef } ) ) {
49    $debug && warn "Unable to load Koha::NorwegianPatronDB";
50 }
51
52
53 BEGIN {
54     $VERSION = 3.07.00.049;
55     $debug = $ENV{DEBUG} || 0;
56     require Exporter;
57     @ISA = qw(Exporter);
58     #Get data
59     push @EXPORT, qw(
60         &Search
61         &GetMemberDetails
62         &GetMemberRelatives
63         &GetMember
64
65         &GetGuarantees
66
67         &GetMemberIssuesAndFines
68         &GetPendingIssues
69         &GetAllIssues
70
71         &getzipnamecity
72         &getidcity
73
74         &GetFirstValidEmailAddress
75         &GetNoticeEmailAddress
76
77         &GetAge
78         &GetCities
79         &GetSortDetails
80         &GetTitles
81
82         &GetPatronImage
83         &PutPatronImage
84         &RmPatronImage
85
86         &GetHideLostItemsPreference
87
88         &IsMemberBlocked
89         &GetMemberAccountRecords
90         &GetBorNotifyAcctRecord
91
92         &GetborCatFromCatType
93         &GetBorrowercategory
94         GetBorrowerCategorycode
95         &GetBorrowercategoryList
96
97         &GetBorrowersToExpunge
98         &GetBorrowersWhoHaveNeverBorrowed
99         &GetBorrowersWithIssuesHistoryOlderThan
100
101         &GetExpiryDate
102         &GetUpcomingMembershipExpires
103
104         &AddMessage
105         &DeleteMessage
106         &GetMessages
107         &GetMessagesCount
108
109         &IssueSlip
110         GetBorrowersWithEmail
111
112         HasOverdues
113         GetOverduesForPatron
114     );
115
116     #Modify data
117     push @EXPORT, qw(
118         &ModMember
119         &changepassword
120          &ModPrivacy
121     );
122
123     #Delete data
124     push @EXPORT, qw(
125         &DelMember
126     );
127
128     #Insert data
129     push @EXPORT, qw(
130         &AddMember
131         &AddMember_Opac
132         &MoveMemberToDeleted
133         &ExtendMemberSubscriptionTo
134     );
135
136     #Check data
137     push @EXPORT, qw(
138         &checkuniquemember
139         &checkuserpassword
140         &Check_Userid
141         &Generate_Userid
142         &fixup_cardnumber
143         &checkcardnumber
144     );
145 }
146
147 =head1 NAME
148
149 C4::Members - Perl Module containing convenience functions for member handling
150
151 =head1 SYNOPSIS
152
153 use C4::Members;
154
155 =head1 DESCRIPTION
156
157 This module contains routines for adding, modifying and deleting members/patrons/borrowers 
158
159 =head1 FUNCTIONS
160
161 =head2 GetMemberDetails
162
163 ($borrower) = &GetMemberDetails($borrowernumber, $cardnumber);
164
165 Looks up a patron and returns information about him or her. If
166 C<$borrowernumber> is true (nonzero), C<&GetMemberDetails> looks
167 up the borrower by number; otherwise, it looks up the borrower by card
168 number.
169
170 C<$borrower> is a reference-to-hash whose keys are the fields of the
171 borrowers table in the Koha database. In addition,
172 C<$borrower-E<gt>{flags}> is a hash giving more detailed information
173 about the patron. Its keys act as flags :
174
175     if $borrower->{flags}->{LOST} {
176         # Patron's card was reported lost
177     }
178
179 If the state of a flag means that the patron should not be
180 allowed to borrow any more books, then it will have a C<noissues> key
181 with a true value.
182
183 See patronflags for more details.
184
185 C<$borrower-E<gt>{authflags}> is a hash giving more detailed information
186 about the top-level permissions flags set for the borrower.  For example,
187 if a user has the "editcatalogue" permission,
188 C<$borrower-E<gt>{authflags}-E<gt>{editcatalogue}> will exist and have
189 the value "1".
190
191 =cut
192
193 sub GetMemberDetails {
194     my ( $borrowernumber, $cardnumber ) = @_;
195     my $dbh = C4::Context->dbh;
196     my $query;
197     my $sth;
198     if ($borrowernumber) {
199         $sth = $dbh->prepare("
200             SELECT borrowers.*,
201                    category_type,
202                    categories.description,
203                    categories.BlockExpiredPatronOpacActions,
204                    reservefee,
205                    enrolmentperiod
206             FROM borrowers
207             LEFT JOIN categories ON borrowers.categorycode=categories.categorycode
208             WHERE borrowernumber = ?
209         ");
210         $sth->execute($borrowernumber);
211     }
212     elsif ($cardnumber) {
213         $sth = $dbh->prepare("
214             SELECT borrowers.*,
215                    category_type,
216                    categories.description,
217                    categories.BlockExpiredPatronOpacActions,
218                    reservefee,
219                    enrolmentperiod
220             FROM borrowers
221             LEFT JOIN categories ON borrowers.categorycode = categories.categorycode
222             WHERE cardnumber = ?
223         ");
224         $sth->execute($cardnumber);
225     }
226     else {
227         return;
228     }
229     my $borrower = $sth->fetchrow_hashref;
230     return unless $borrower;
231     my ($amount) = GetMemberAccountRecords($borrower->{borrowernumber});
232     $borrower->{'amountoutstanding'} = $amount;
233     # FIXME - patronflags calls GetMemberAccountRecords... just have patronflags return $amount
234     my $flags = patronflags( $borrower);
235     my $accessflagshash;
236
237     $sth = $dbh->prepare("select bit,flag from userflags");
238     $sth->execute;
239     while ( my ( $bit, $flag ) = $sth->fetchrow ) {
240         if ( $borrower->{'flags'} && $borrower->{'flags'} & 2**$bit ) {
241             $accessflagshash->{$flag} = 1;
242         }
243     }
244     $borrower->{'flags'}     = $flags;
245     $borrower->{'authflags'} = $accessflagshash;
246
247     # Handle setting the true behavior for BlockExpiredPatronOpacActions
248     $borrower->{'BlockExpiredPatronOpacActions'} =
249       C4::Context->preference('BlockExpiredPatronOpacActions')
250       if ( $borrower->{'BlockExpiredPatronOpacActions'} == -1 );
251
252     $borrower->{'is_expired'} = 0;
253     $borrower->{'is_expired'} = 1 if
254       defined($borrower->{dateexpiry}) &&
255       $borrower->{'dateexpiry'} ne '0000-00-00' &&
256       Date_to_Days( Today() ) >
257       Date_to_Days( split /-/, $borrower->{'dateexpiry'} );
258
259     return ($borrower);    #, $flags, $accessflagshash);
260 }
261
262 =head2 patronflags
263
264  $flags = &patronflags($patron);
265
266 This function is not exported.
267
268 The following will be set where applicable:
269  $flags->{CHARGES}->{amount}        Amount of debt
270  $flags->{CHARGES}->{noissues}      Set if debt amount >$5.00 (or syspref noissuescharge)
271  $flags->{CHARGES}->{message}       Message -- deprecated
272
273  $flags->{CREDITS}->{amount}        Amount of credit
274  $flags->{CREDITS}->{message}       Message -- deprecated
275
276  $flags->{  GNA  }                  Patron has no valid address
277  $flags->{  GNA  }->{noissues}      Set for each GNA
278  $flags->{  GNA  }->{message}       "Borrower has no valid address" -- deprecated
279
280  $flags->{ LOST  }                  Patron's card reported lost
281  $flags->{ LOST  }->{noissues}      Set for each LOST
282  $flags->{ LOST  }->{message}       Message -- deprecated
283
284  $flags->{DBARRED}                  Set if patron debarred, no access
285  $flags->{DBARRED}->{noissues}      Set for each DBARRED
286  $flags->{DBARRED}->{message}       Message -- deprecated
287
288  $flags->{ NOTES }
289  $flags->{ NOTES }->{message}       The note itself.  NOT deprecated
290
291  $flags->{ ODUES }                  Set if patron has overdue books.
292  $flags->{ ODUES }->{message}       "Yes"  -- deprecated
293  $flags->{ ODUES }->{itemlist}      ref-to-array: list of overdue books
294  $flags->{ ODUES }->{itemlisttext}  Text list of overdue items -- deprecated
295
296  $flags->{WAITING}                  Set if any of patron's reserves are available
297  $flags->{WAITING}->{message}       Message -- deprecated
298  $flags->{WAITING}->{itemlist}      ref-to-array: list of available items
299
300 =over 
301
302 =item C<$flags-E<gt>{ODUES}-E<gt>{itemlist}> is a reference-to-array listing the
303 overdue items. Its elements are references-to-hash, each describing an
304 overdue item. The keys are selected fields from the issues, biblio,
305 biblioitems, and items tables of the Koha database.
306
307 =item C<$flags-E<gt>{ODUES}-E<gt>{itemlisttext}> is a string giving a text listing of
308 the overdue items, one per line.  Deprecated.
309
310 =item C<$flags-E<gt>{WAITING}-E<gt>{itemlist}> is a reference-to-array listing the
311 available items. Each element is a reference-to-hash whose keys are
312 fields from the reserves table of the Koha database.
313
314 =back
315
316 All the "message" fields that include language generated in this function are deprecated, 
317 because such strings belong properly in the display layer.
318
319 The "message" field that comes from the DB is OK.
320
321 =cut
322
323 # TODO: use {anonymous => hashes} instead of a dozen %flaginfo
324 # FIXME rename this function.
325 sub patronflags {
326     my %flags;
327     my ( $patroninformation) = @_;
328     my $dbh=C4::Context->dbh;
329     my ($balance, $owing) = GetMemberAccountBalance( $patroninformation->{'borrowernumber'});
330     if ( $owing > 0 ) {
331         my %flaginfo;
332         my $noissuescharge = C4::Context->preference("noissuescharge") || 5;
333         $flaginfo{'message'} = sprintf 'Patron owes %.02f', $owing;
334         $flaginfo{'amount'}  = sprintf "%.02f", $owing;
335         if ( $owing > $noissuescharge && !C4::Context->preference("AllowFineOverride") ) {
336             $flaginfo{'noissues'} = 1;
337         }
338         $flags{'CHARGES'} = \%flaginfo;
339     }
340     elsif ( $balance < 0 ) {
341         my %flaginfo;
342         $flaginfo{'message'} = sprintf 'Patron has credit of %.02f', -$balance;
343         $flaginfo{'amount'}  = sprintf "%.02f", $balance;
344         $flags{'CREDITS'} = \%flaginfo;
345     }
346     if (   $patroninformation->{'gonenoaddress'}
347         && $patroninformation->{'gonenoaddress'} == 1 )
348     {
349         my %flaginfo;
350         $flaginfo{'message'}  = 'Borrower has no valid address.';
351         $flaginfo{'noissues'} = 1;
352         $flags{'GNA'}         = \%flaginfo;
353     }
354     if ( $patroninformation->{'lost'} && $patroninformation->{'lost'} == 1 ) {
355         my %flaginfo;
356         $flaginfo{'message'}  = 'Borrower\'s card reported lost.';
357         $flaginfo{'noissues'} = 1;
358         $flags{'LOST'}        = \%flaginfo;
359     }
360     if ( $patroninformation->{'debarred'} && check_date( split( /-/, $patroninformation->{'debarred'} ) ) ) {
361         if ( Date_to_Days(Date::Calc::Today) < Date_to_Days( split( /-/, $patroninformation->{'debarred'} ) ) ) {
362             my %flaginfo;
363             $flaginfo{'debarredcomment'} = $patroninformation->{'debarredcomment'};
364             $flaginfo{'message'}         = $patroninformation->{'debarredcomment'};
365             $flaginfo{'noissues'}        = 1;
366             $flaginfo{'dateend'}         = $patroninformation->{'debarred'};
367             $flags{'DBARRED'}           = \%flaginfo;
368         }
369     }
370     if (   $patroninformation->{'borrowernotes'}
371         && $patroninformation->{'borrowernotes'} )
372     {
373         my %flaginfo;
374         $flaginfo{'message'} = $patroninformation->{'borrowernotes'};
375         $flags{'NOTES'}      = \%flaginfo;
376     }
377     my ( $odues, $itemsoverdue ) = C4::Overdues::checkoverdues($patroninformation->{'borrowernumber'});
378     if ( $odues && $odues > 0 ) {
379         my %flaginfo;
380         $flaginfo{'message'}  = "Yes";
381         $flaginfo{'itemlist'} = $itemsoverdue;
382         foreach ( sort { $a->{'date_due'} cmp $b->{'date_due'} }
383             @$itemsoverdue )
384         {
385             $flaginfo{'itemlisttext'} .=
386               "$_->{'date_due'} $_->{'barcode'} $_->{'title'} \n";  # newline is display layer
387         }
388         $flags{'ODUES'} = \%flaginfo;
389     }
390     my @itemswaiting = C4::Reserves::GetReservesFromBorrowernumber( $patroninformation->{'borrowernumber'},'W' );
391     my $nowaiting = scalar @itemswaiting;
392     if ( $nowaiting > 0 ) {
393         my %flaginfo;
394         $flaginfo{'message'}  = "Reserved items available";
395         $flaginfo{'itemlist'} = \@itemswaiting;
396         $flags{'WAITING'}     = \%flaginfo;
397     }
398     return ( \%flags );
399 }
400
401
402 =head2 GetMember
403
404   $borrower = &GetMember(%information);
405
406 Retrieve the first patron record meeting on criteria listed in the
407 C<%information> hash, which should contain one or more
408 pairs of borrowers column names and values, e.g.,
409
410    $borrower = GetMember(borrowernumber => id);
411
412 C<&GetBorrower> returns a reference-to-hash whose keys are the fields of
413 the C<borrowers> table in the Koha database.
414
415 FIXME: GetMember() is used throughout the code as a lookup
416 on a unique key such as the borrowernumber, but this meaning is not
417 enforced in the routine itself.
418
419 =cut
420
421 #'
422 sub GetMember {
423     my ( %information ) = @_;
424     if (exists $information{borrowernumber} && !defined $information{borrowernumber}) {
425         #passing mysql's kohaadmin?? Makes no sense as a query
426         return;
427     }
428     my $dbh = C4::Context->dbh;
429     my $select =
430     q{SELECT borrowers.*, categories.category_type, categories.description
431     FROM borrowers 
432     LEFT JOIN categories on borrowers.categorycode=categories.categorycode WHERE };
433     my $more_p = 0;
434     my @values = ();
435     for (keys %information ) {
436         if ($more_p) {
437             $select .= ' AND ';
438         }
439         else {
440             $more_p++;
441         }
442
443         if (defined $information{$_}) {
444             $select .= "$_ = ?";
445             push @values, $information{$_};
446         }
447         else {
448             $select .= "$_ IS NULL";
449         }
450     }
451     $debug && warn $select, " ",values %information;
452     my $sth = $dbh->prepare("$select");
453     $sth->execute(@values);
454     my $data = $sth->fetchall_arrayref({});
455     #FIXME interface to this routine now allows generation of a result set
456     #so whole array should be returned but bowhere in the current code expects this
457     if (@{$data} ) {
458         return $data->[0];
459     }
460
461     return;
462 }
463
464 =head2 GetMemberRelatives
465
466  @borrowernumbers = GetMemberRelatives($borrowernumber);
467
468  C<GetMemberRelatives> returns a borrowersnumber's list of guarantor/guarantees of the member given in parameter
469
470 =cut
471
472 sub GetMemberRelatives {
473     my $borrowernumber = shift;
474     my $dbh = C4::Context->dbh;
475     my @glist;
476
477     # Getting guarantor
478     my $query = "SELECT guarantorid FROM borrowers WHERE borrowernumber=?";
479     my $sth = $dbh->prepare($query);
480     $sth->execute($borrowernumber);
481     my $data = $sth->fetchrow_arrayref();
482     push @glist, $data->[0] if $data->[0];
483     my $guarantor = $data->[0] ? $data->[0] : undef;
484
485     # Getting guarantees
486     $query = "SELECT borrowernumber FROM borrowers WHERE guarantorid=?";
487     $sth = $dbh->prepare($query);
488     $sth->execute($borrowernumber);
489     while ($data = $sth->fetchrow_arrayref()) {
490        push @glist, $data->[0];
491     }
492
493     # Getting sibling guarantees
494     if ($guarantor) {
495         $query = "SELECT borrowernumber FROM borrowers WHERE guarantorid=?";
496         $sth = $dbh->prepare($query);
497         $sth->execute($guarantor);
498         while ($data = $sth->fetchrow_arrayref()) {
499            push @glist, $data->[0] if ($data->[0] != $borrowernumber);
500         }
501     }
502
503     return @glist;
504 }
505
506 =head2 IsMemberBlocked
507
508   my ($block_status, $count) = IsMemberBlocked( $borrowernumber );
509
510 Returns whether a patron is restricted or has overdue items that may result
511 in a block of circulation privileges.
512
513 C<$block_status> can have the following values:
514
515 1 if the patron is currently restricted, in which case
516 C<$count> is the expiration date (9999-12-31 for indefinite)
517
518 -1 if the patron has overdue items, in which case C<$count> is the number of them
519
520 0 if the patron has no overdue items or outstanding fine days, in which case C<$count> is 0
521
522 Existing active restrictions are checked before current overdue items.
523
524 =cut
525
526 sub IsMemberBlocked {
527     my $borrowernumber = shift;
528     my $dbh            = C4::Context->dbh;
529
530     my $blockeddate = Koha::Borrower::Debarments::IsDebarred($borrowernumber);
531
532     return ( 1, $blockeddate ) if $blockeddate;
533
534     # if he have late issues
535     my $sth = $dbh->prepare(
536         "SELECT COUNT(*) as latedocs
537          FROM issues
538          WHERE borrowernumber = ?
539          AND date_due < now()"
540     );
541     $sth->execute($borrowernumber);
542     my $latedocs = $sth->fetchrow_hashref->{'latedocs'};
543
544     return ( -1, $latedocs ) if $latedocs > 0;
545
546     return ( 0, 0 );
547 }
548
549 =head2 GetMemberIssuesAndFines
550
551   ($overdue_count, $issue_count, $total_fines) = &GetMemberIssuesAndFines($borrowernumber);
552
553 Returns aggregate data about items borrowed by the patron with the
554 given borrowernumber.
555
556 C<&GetMemberIssuesAndFines> returns a three-element array.  C<$overdue_count> is the
557 number of overdue items the patron currently has borrowed. C<$issue_count> is the
558 number of books the patron currently has borrowed.  C<$total_fines> is
559 the total fine currently due by the borrower.
560
561 =cut
562
563 #'
564 sub GetMemberIssuesAndFines {
565     my ( $borrowernumber ) = @_;
566     my $dbh   = C4::Context->dbh;
567     my $query = "SELECT COUNT(*) FROM issues WHERE borrowernumber = ?";
568
569     $debug and warn $query."\n";
570     my $sth = $dbh->prepare($query);
571     $sth->execute($borrowernumber);
572     my $issue_count = $sth->fetchrow_arrayref->[0];
573
574     $sth = $dbh->prepare(
575         "SELECT COUNT(*) FROM issues 
576          WHERE borrowernumber = ? 
577          AND date_due < now()"
578     );
579     $sth->execute($borrowernumber);
580     my $overdue_count = $sth->fetchrow_arrayref->[0];
581
582     $sth = $dbh->prepare("SELECT SUM(amountoutstanding) FROM accountlines WHERE borrowernumber = ?");
583     $sth->execute($borrowernumber);
584     my $total_fines = $sth->fetchrow_arrayref->[0];
585
586     return ($overdue_count, $issue_count, $total_fines);
587 }
588
589
590 =head2 columns
591
592   my @columns = C4::Member::columns();
593
594 Returns an array of borrowers' table columns on success,
595 and an empty array on failure.
596
597 =cut
598
599 sub columns {
600
601     # Pure ANSI SQL goodness.
602     my $sql = 'SELECT * FROM borrowers WHERE 1=0;';
603
604     # Get the database handle.
605     my $dbh = C4::Context->dbh;
606
607     # Run the SQL statement to load STH's readonly properties.
608     my $sth = $dbh->prepare($sql);
609     my $rv = $sth->execute();
610
611     # This only fails if the table doesn't exist.
612     # This will always be called AFTER an install or upgrade,
613     # so borrowers will exist!
614     my @data;
615     if ($sth->{NUM_OF_FIELDS}>0) {
616         @data = @{$sth->{NAME}};
617     }
618     else {
619         @data = ();
620     }
621     return @data;
622 }
623
624
625 =head2 ModMember
626
627   my $success = ModMember(borrowernumber => $borrowernumber,
628                                             [ field => value ]... );
629
630 Modify borrower's data.  All date fields should ALREADY be in ISO format.
631
632 return :
633 true on success, or false on failure
634
635 =cut
636
637 sub ModMember {
638     my (%data) = @_;
639     # test to know if you must update or not the borrower password
640     if (exists $data{password}) {
641         if ($data{password} eq '****' or $data{password} eq '') {
642             delete $data{password};
643         } else {
644             if ( C4::Context->preference('NorwegianPatronDBEnable') && C4::Context->preference('NorwegianPatronDBEnable') == 1 ) {
645                 # Update the hashed PIN in borrower_sync.hashed_pin, before Koha hashes it
646                 Koha::NorwegianPatronDB::NLUpdateHashedPIN( $data{'borrowernumber'}, $data{password} );
647             }
648             $data{password} = hash_password($data{password});
649         }
650     }
651     my $old_categorycode = GetBorrowerCategorycode( $data{borrowernumber} );
652
653     # get only the columns of a borrower
654     my $schema = Koha::Database->new()->schema;
655     my @columns = $schema->source('Borrower')->columns;
656     my $new_borrower = { map { join(' ', @columns) =~ /$_/ ? ( $_ => $data{$_} ) : () } keys(%data) };
657     delete $new_borrower->{flags};
658
659     $new_borrower->{dateofbirth}  ||= undef if exists $new_borrower->{dateofbirth};
660     $new_borrower->{dateenrolled} ||= undef if exists $new_borrower->{dateenrolled};
661     $new_borrower->{dateexpiry}   ||= undef if exists $new_borrower->{dateexpiry};
662     $new_borrower->{debarred}     ||= undef if exists $new_borrower->{debarred};
663     my $rs = $schema->resultset('Borrower')->search({
664         borrowernumber => $new_borrower->{borrowernumber},
665      });
666
667     delete $new_borrower->{userid} if exists $new_borrower->{userid} and not $new_borrower->{userid};
668
669     my $execute_success = $rs->update($new_borrower);
670     if ($execute_success ne '0E0') { # only proceed if the update was a success
671         # ok if its an adult (type) it may have borrowers that depend on it as a guarantor
672         # so when we update information for an adult we should check for guarantees and update the relevant part
673         # of their records, ie addresses and phone numbers
674         my $borrowercategory= GetBorrowercategory( $data{'category_type'} );
675         if ( exists  $borrowercategory->{'category_type'} && $borrowercategory->{'category_type'} eq ('A' || 'S') ) {
676             # is adult check guarantees;
677             UpdateGuarantees(%data);
678         }
679
680         # If the patron changes to a category with enrollment fee, we add a fee
681         if ( $data{categorycode} and $data{categorycode} ne $old_categorycode ) {
682             if ( C4::Context->preference('FeeOnChangePatronCategory') ) {
683                 AddEnrolmentFeeIfNeeded( $data{categorycode}, $data{borrowernumber} );
684             }
685         }
686
687         # If NorwegianPatronDBEnable is enabled, we set syncstatus to something that a
688         # cronjob will use for syncing with NL
689         if ( C4::Context->preference('NorwegianPatronDBEnable') && C4::Context->preference('NorwegianPatronDBEnable') == 1 ) {
690             my $borrowersync = Koha::Database->new->schema->resultset('BorrowerSync')->find({
691                 'synctype'       => 'norwegianpatrondb',
692                 'borrowernumber' => $data{'borrowernumber'}
693             });
694             # Do not set to "edited" if syncstatus is "new". We need to sync as new before
695             # we can sync as changed. And the "new sync" will pick up all changes since
696             # the patron was created anyway.
697             if ( $borrowersync->syncstatus ne 'new' && $borrowersync->syncstatus ne 'delete' ) {
698                 $borrowersync->update( { 'syncstatus' => 'edited' } );
699             }
700             # Set the value of 'sync'
701             $borrowersync->update( { 'sync' => $data{'sync'} } );
702             # Try to do the live sync
703             Koha::NorwegianPatronDB::NLSync({ 'borrowernumber' => $data{'borrowernumber'} });
704         }
705
706         logaction("MEMBERS", "MODIFY", $data{'borrowernumber'}, "UPDATE (executed w/ arg: $data{'borrowernumber'})") if C4::Context->preference("BorrowersLog");
707     }
708     return $execute_success;
709 }
710
711 =head2 AddMember
712
713   $borrowernumber = &AddMember(%borrower);
714
715 insert new borrower into table
716
717 (%borrower keys are database columns. Database columns could be
718 different in different versions. Please look into database for correct
719 column names.)
720
721 Returns the borrowernumber upon success
722
723 Returns as undef upon any db error without further processing
724
725 =cut
726
727 #'
728 sub AddMember {
729     my (%data) = @_;
730     my $dbh = C4::Context->dbh;
731     my $schema = Koha::Database->new()->schema;
732
733     # generate a proper login if none provided
734     $data{'userid'} = Generate_Userid( $data{'borrowernumber'}, $data{'firstname'}, $data{'surname'} )
735       if ( $data{'userid'} eq '' || !Check_Userid( $data{'userid'} ) );
736
737     # add expiration date if it isn't already there
738     unless ( $data{'dateexpiry'} ) {
739         $data{'dateexpiry'} = GetExpiryDate( $data{'categorycode'}, output_pref( { dt => dt_from_string, dateonly => 1, dateformat => 'iso' } ) );
740     }
741
742     # add enrollment date if it isn't already there
743     unless ( $data{'dateenrolled'} ) {
744         $data{'dateenrolled'} = output_pref( { dt => dt_from_string, dateonly => 1, dateformat => 'iso' } );
745     }
746
747     my $patron_category = $schema->resultset('Category')->find( $data{'categorycode'} );
748     $data{'privacy'} =
749         $patron_category->default_privacy() eq 'default' ? 1
750       : $patron_category->default_privacy() eq 'never'   ? 2
751       : $patron_category->default_privacy() eq 'forever' ? 0
752       :                                                    undef;
753     # Make a copy of the plain text password for later use
754     my $plain_text_password = $data{'password'};
755
756     # create a disabled account if no password provided
757     $data{'password'} = ($data{'password'})? hash_password($data{'password'}) : '!';
758
759     # we don't want invalid dates in the db (mysql has a bad habit of inserting 0000-00-00
760     $data{'dateofbirth'} = undef if( not $data{'dateofbirth'} );
761     $data{'debarred'} = undef if ( not $data{'debarred'} );
762     $data{'guarantorid'} = undef if ( not $data{'guarantorid'} );
763
764     # get only the columns of Borrower
765     my @columns = $schema->source('Borrower')->columns;
766     my $new_member = { map { join(' ',@columns) =~ /$_/ ? ( $_ => $data{$_} )  : () } keys(%data) } ;
767     delete $new_member->{borrowernumber};
768
769     my $rs = $schema->resultset('Borrower');
770     $data{borrowernumber} = $rs->create($new_member)->id;
771
772     # If NorwegianPatronDBEnable is enabled, we set syncstatus to something that a
773     # cronjob will use for syncing with NL
774     if ( exists $data{'borrowernumber'} && C4::Context->preference('NorwegianPatronDBEnable') && C4::Context->preference('NorwegianPatronDBEnable') == 1 ) {
775         Koha::Database->new->schema->resultset('BorrowerSync')->create({
776             'borrowernumber' => $data{'borrowernumber'},
777             'synctype'       => 'norwegianpatrondb',
778             'sync'           => 1,
779             'syncstatus'     => 'new',
780             'hashed_pin'     => Koha::NorwegianPatronDB::NLEncryptPIN( $plain_text_password ),
781         });
782     }
783
784     # mysql_insertid is probably bad.  not necessarily accurate and mysql-specific at best.
785     logaction("MEMBERS", "CREATE", $data{'borrowernumber'}, "") if C4::Context->preference("BorrowersLog");
786
787     AddEnrolmentFeeIfNeeded( $data{categorycode}, $data{borrowernumber} );
788
789     return $data{borrowernumber};
790 }
791
792 =head2 Check_Userid
793
794     my $uniqueness = Check_Userid($userid,$borrowernumber);
795
796     $borrowernumber is optional (i.e. it can contain a blank value). If $userid is passed with a blank $borrowernumber variable, the database will be checked for all instances of that userid (i.e. userid=? AND borrowernumber != '').
797
798     If $borrowernumber is provided, the database will be checked for every instance of that userid coupled with a different borrower(number) than the one provided.
799
800     return :
801         0 for not unique (i.e. this $userid already exists)
802         1 for unique (i.e. this $userid does not exist, or this $userid/$borrowernumber combination already exists)
803
804 =cut
805
806 sub Check_Userid {
807     my ( $uid, $borrowernumber ) = @_;
808
809     return 0 unless ($uid); # userid is a unique column, we should assume NULL is not unique
810
811     return 0 if ( $uid eq C4::Context->config('user') );
812
813     my $rs = Koha::Database->new()->schema()->resultset('Borrower');
814
815     my $params;
816     $params->{userid} = $uid;
817     $params->{borrowernumber} = { '!=' => $borrowernumber } if ($borrowernumber);
818
819     my $count = $rs->count( $params );
820
821     return $count ? 0 : 1;
822 }
823
824 =head2 Generate_Userid
825
826     my $newuid = Generate_Userid($borrowernumber, $firstname, $surname);
827
828     Generate a userid using the $surname and the $firstname (if there is a value in $firstname).
829
830     $borrowernumber is optional (i.e. it can contain a blank value). A value is passed when generating a new userid for an existing borrower. When a new userid is created for a new borrower, a blank value is passed to this sub.
831
832     return :
833         new userid ($firstname.$surname if there is a $firstname, or $surname if there is no value in $firstname) plus offset (0 if the $newuid is unique, or a higher numeric value if Check_Userid finds an existing match for the $newuid in the database).
834
835 =cut
836
837 sub Generate_Userid {
838   my ($borrowernumber, $firstname, $surname) = @_;
839   my $newuid;
840   my $offset = 0;
841   #The script will "do" the following code and increment the $offset until Check_Userid = 1 (i.e. until $newuid comes back as unique)
842   do {
843     $firstname =~ s/[[:digit:][:space:][:blank:][:punct:][:cntrl:]]//g;
844     $surname =~ s/[[:digit:][:space:][:blank:][:punct:][:cntrl:]]//g;
845     $newuid = lc(($firstname)? "$firstname.$surname" : $surname);
846     $newuid = unac_string('utf-8',$newuid);
847     $newuid .= $offset unless $offset == 0;
848     $offset++;
849
850    } while (!Check_Userid($newuid,$borrowernumber));
851
852    return $newuid;
853 }
854
855 sub changepassword {
856     my ( $uid, $member, $digest ) = @_;
857     my $dbh = C4::Context->dbh;
858
859 #Make sure the userid chosen is unique and not theirs if non-empty. If it is not,
860 #Then we need to tell the user and have them create a new one.
861     my $resultcode;
862     my $sth =
863       $dbh->prepare(
864         "SELECT * FROM borrowers WHERE userid=? AND borrowernumber != ?");
865     $sth->execute( $uid, $member );
866     if ( ( $uid ne '' ) && ( my $row = $sth->fetchrow_hashref ) ) {
867         $resultcode=0;
868     }
869     else {
870         #Everything is good so we can update the information.
871         $sth =
872           $dbh->prepare(
873             "update borrowers set userid=?, password=? where borrowernumber=?");
874         $sth->execute( $uid, $digest, $member );
875         $resultcode=1;
876     }
877     
878     logaction("MEMBERS", "CHANGE PASS", $member, "") if C4::Context->preference("BorrowersLog");
879     return $resultcode;    
880 }
881
882
883
884 =head2 fixup_cardnumber
885
886 Warning: The caller is responsible for locking the members table in write
887 mode, to avoid database corruption.
888
889 =cut
890
891 use vars qw( @weightings );
892 my @weightings = ( 8, 4, 6, 3, 5, 2, 1 );
893
894 sub fixup_cardnumber {
895     my ($cardnumber) = @_;
896     my $autonumber_members = C4::Context->boolean_preference('autoMemberNum') || 0;
897
898     # Find out whether member numbers should be generated
899     # automatically. Should be either "1" or something else.
900     # Defaults to "0", which is interpreted as "no".
901
902     #     if ($cardnumber !~ /\S/ && $autonumber_members) {
903     ($autonumber_members) or return $cardnumber;
904     my $checkdigit = C4::Context->preference('checkdigit');
905     my $dbh = C4::Context->dbh;
906     if ( $checkdigit and $checkdigit eq 'katipo' ) {
907
908         # if checkdigit is selected, calculate katipo-style cardnumber.
909         # otherwise, just use the max()
910         # purpose: generate checksum'd member numbers.
911         # We'll assume we just got the max value of digits 2-8 of member #'s
912         # from the database and our job is to increment that by one,
913         # determine the 1st and 9th digits and return the full string.
914         my $sth = $dbh->prepare(
915             "select max(substring(borrowers.cardnumber,2,7)) as new_num from borrowers"
916         );
917         $sth->execute;
918         my $data = $sth->fetchrow_hashref;
919         $cardnumber = $data->{new_num};
920         if ( !$cardnumber ) {    # If DB has no values,
921             $cardnumber = 1000000;    # start at 1000000
922         } else {
923             $cardnumber += 1;
924         }
925
926         my $sum = 0;
927         for ( my $i = 0 ; $i < 8 ; $i += 1 ) {
928             # read weightings, left to right, 1 char at a time
929             my $temp1 = $weightings[$i];
930
931             # sequence left to right, 1 char at a time
932             my $temp2 = substr( $cardnumber, $i, 1 );
933
934             # mult each char 1-7 by its corresponding weighting
935             $sum += $temp1 * $temp2;
936         }
937
938         my $rem = ( $sum % 11 );
939         $rem = 'X' if $rem == 10;
940
941         return "V$cardnumber$rem";
942      } else {
943
944         my $sth = $dbh->prepare(
945             'SELECT MAX( CAST( cardnumber AS SIGNED ) ) FROM borrowers WHERE cardnumber REGEXP "^-?[0-9]+$"'
946         );
947         $sth->execute;
948         my ($result) = $sth->fetchrow;
949         return $result + 1;
950     }
951     return $cardnumber;     # just here as a fallback/reminder 
952 }
953
954 =head2 GetGuarantees
955
956   ($num_children, $children_arrayref) = &GetGuarantees($parent_borrno);
957   $child0_cardno = $children_arrayref->[0]{"cardnumber"};
958   $child0_borrno = $children_arrayref->[0]{"borrowernumber"};
959
960 C<&GetGuarantees> takes a borrower number (e.g., that of a patron
961 with children) and looks up the borrowers who are guaranteed by that
962 borrower (i.e., the patron's children).
963
964 C<&GetGuarantees> returns two values: an integer giving the number of
965 borrowers guaranteed by C<$parent_borrno>, and a reference to an array
966 of references to hash, which gives the actual results.
967
968 =cut
969
970 #'
971 sub GetGuarantees {
972     my ($borrowernumber) = @_;
973     my $dbh              = C4::Context->dbh;
974     my $sth              =
975       $dbh->prepare(
976 "select cardnumber,borrowernumber, firstname, surname from borrowers where guarantorid=?"
977       );
978     $sth->execute($borrowernumber);
979
980     my @dat;
981     my $data = $sth->fetchall_arrayref({}); 
982     return ( scalar(@$data), $data );
983 }
984
985 =head2 UpdateGuarantees
986
987   &UpdateGuarantees($parent_borrno);
988   
989
990 C<&UpdateGuarantees> borrower data for an adult and updates all the guarantees
991 with the modified information
992
993 =cut
994
995 #'
996 sub UpdateGuarantees {
997     my %data = shift;
998     my $dbh = C4::Context->dbh;
999     my ( $count, $guarantees ) = GetGuarantees( $data{'borrowernumber'} );
1000     foreach my $guarantee (@$guarantees){
1001         my $guaquery = qq|UPDATE borrowers 
1002               SET address=?,fax=?,B_city=?,mobile=?,city=?,phone=?
1003               WHERE borrowernumber=?
1004         |;
1005         my $sth = $dbh->prepare($guaquery);
1006         $sth->execute($data{'address'},$data{'fax'},$data{'B_city'},$data{'mobile'},$data{'city'},$data{'phone'},$guarantee->{'borrowernumber'});
1007     }
1008 }
1009 =head2 GetPendingIssues
1010
1011   my $issues = &GetPendingIssues(@borrowernumber);
1012
1013 Looks up what the patron with the given borrowernumber has borrowed.
1014
1015 C<&GetPendingIssues> returns a
1016 reference-to-array where each element is a reference-to-hash; the
1017 keys are the fields from the C<issues>, C<biblio>, and C<items> tables.
1018 The keys include C<biblioitems> fields except marc and marcxml.
1019
1020 =cut
1021
1022 #'
1023 sub GetPendingIssues {
1024     my @borrowernumbers = @_;
1025
1026     unless (@borrowernumbers ) { # return a ref_to_array
1027         return \@borrowernumbers; # to not cause surprise to caller
1028     }
1029
1030     # Borrowers part of the query
1031     my $bquery = '';
1032     for (my $i = 0; $i < @borrowernumbers; $i++) {
1033         $bquery .= ' issues.borrowernumber = ?';
1034         if ($i < $#borrowernumbers ) {
1035             $bquery .= ' OR';
1036         }
1037     }
1038
1039     # must avoid biblioitems.* to prevent large marc and marcxml fields from killing performance
1040     # FIXME: namespace collision: each table has "timestamp" fields.  Which one is "timestamp" ?
1041     # FIXME: circ/ciculation.pl tries to sort by timestamp!
1042     # FIXME: namespace collision: other collisions possible.
1043     # FIXME: most of this data isn't really being used by callers.
1044     my $query =
1045    "SELECT issues.*,
1046             items.*,
1047            biblio.*,
1048            biblioitems.volume,
1049            biblioitems.number,
1050            biblioitems.itemtype,
1051            biblioitems.isbn,
1052            biblioitems.issn,
1053            biblioitems.publicationyear,
1054            biblioitems.publishercode,
1055            biblioitems.volumedate,
1056            biblioitems.volumedesc,
1057            biblioitems.lccn,
1058            biblioitems.url,
1059            borrowers.firstname,
1060            borrowers.surname,
1061            borrowers.cardnumber,
1062            issues.timestamp AS timestamp,
1063            issues.renewals  AS renewals,
1064            issues.borrowernumber AS borrowernumber,
1065             items.renewals  AS totalrenewals
1066     FROM   issues
1067     LEFT JOIN items       ON items.itemnumber       =      issues.itemnumber
1068     LEFT JOIN biblio      ON items.biblionumber     =      biblio.biblionumber
1069     LEFT JOIN biblioitems ON items.biblioitemnumber = biblioitems.biblioitemnumber
1070     LEFT JOIN borrowers ON issues.borrowernumber = borrowers.borrowernumber
1071     WHERE
1072       $bquery
1073     ORDER BY issues.issuedate"
1074     ;
1075
1076     my $sth = C4::Context->dbh->prepare($query);
1077     $sth->execute(@borrowernumbers);
1078     my $data = $sth->fetchall_arrayref({});
1079     my $today = dt_from_string;
1080     foreach (@{$data}) {
1081         if ($_->{issuedate}) {
1082             $_->{issuedate} = dt_from_string($_->{issuedate}, 'sql');
1083         }
1084         $_->{date_due_sql} = $_->{date_due};
1085         # FIXME no need to have this value
1086         $_->{date_due} or next;
1087         $_->{date_due_sql} = $_->{date_due};
1088         # FIXME no need to have this value
1089         $_->{date_due} = dt_from_string($_->{date_due}, 'sql');
1090         if ( DateTime->compare($_->{date_due}, $today) == -1 ) {
1091             $_->{overdue} = 1;
1092         }
1093     }
1094     return $data;
1095 }
1096
1097 =head2 GetAllIssues
1098
1099   $issues = &GetAllIssues($borrowernumber, $sortkey, $limit);
1100
1101 Looks up what the patron with the given borrowernumber has borrowed,
1102 and sorts the results.
1103
1104 C<$sortkey> is the name of a field on which to sort the results. This
1105 should be the name of a field in the C<issues>, C<biblio>,
1106 C<biblioitems>, or C<items> table in the Koha database.
1107
1108 C<$limit> is the maximum number of results to return.
1109
1110 C<&GetAllIssues> an arrayref, C<$issues>, of hashrefs, the keys of which
1111 are the fields from the C<issues>, C<biblio>, C<biblioitems>, and
1112 C<items> tables of the Koha database.
1113
1114 =cut
1115
1116 #'
1117 sub GetAllIssues {
1118     my ( $borrowernumber, $order, $limit ) = @_;
1119
1120     return unless $borrowernumber;
1121     $order = 'date_due desc' unless $order;
1122
1123     my $dbh = C4::Context->dbh;
1124     my $query =
1125 'SELECT *, issues.timestamp as issuestimestamp, issues.renewals AS renewals,items.renewals AS totalrenewals,items.timestamp AS itemstimestamp
1126   FROM issues 
1127   LEFT JOIN items on items.itemnumber=issues.itemnumber
1128   LEFT JOIN biblio ON items.biblionumber=biblio.biblionumber
1129   LEFT JOIN biblioitems ON items.biblioitemnumber=biblioitems.biblioitemnumber
1130   WHERE borrowernumber=? 
1131   UNION ALL
1132   SELECT *, old_issues.timestamp as issuestimestamp, old_issues.renewals AS renewals,items.renewals AS totalrenewals,items.timestamp AS itemstimestamp 
1133   FROM old_issues 
1134   LEFT JOIN items on items.itemnumber=old_issues.itemnumber
1135   LEFT JOIN biblio ON items.biblionumber=biblio.biblionumber
1136   LEFT JOIN biblioitems ON items.biblioitemnumber=biblioitems.biblioitemnumber
1137   WHERE borrowernumber=? AND old_issues.itemnumber IS NOT NULL
1138   order by ' . $order;
1139     if ($limit) {
1140         $query .= " limit $limit";
1141     }
1142
1143     my $sth = $dbh->prepare($query);
1144     $sth->execute( $borrowernumber, $borrowernumber );
1145     return $sth->fetchall_arrayref( {} );
1146 }
1147
1148
1149 =head2 GetMemberAccountRecords
1150
1151   ($total, $acctlines, $count) = &GetMemberAccountRecords($borrowernumber);
1152
1153 Looks up accounting data for the patron with the given borrowernumber.
1154
1155 C<&GetMemberAccountRecords> returns a three-element array. C<$acctlines> is a
1156 reference-to-array, where each element is a reference-to-hash; the
1157 keys are the fields of the C<accountlines> table in the Koha database.
1158 C<$count> is the number of elements in C<$acctlines>. C<$total> is the
1159 total amount outstanding for all of the account lines.
1160
1161 =cut
1162
1163 sub GetMemberAccountRecords {
1164     my ($borrowernumber) = @_;
1165     my $dbh = C4::Context->dbh;
1166     my @acctlines;
1167     my $numlines = 0;
1168     my $strsth      = qq(
1169                         SELECT * 
1170                         FROM accountlines 
1171                         WHERE borrowernumber=?);
1172     $strsth.=" ORDER BY accountlines_id desc";
1173     my $sth= $dbh->prepare( $strsth );
1174     $sth->execute( $borrowernumber );
1175
1176     my $total = 0;
1177     while ( my $data = $sth->fetchrow_hashref ) {
1178         if ( $data->{itemnumber} ) {
1179             my $biblio = GetBiblioFromItemNumber( $data->{itemnumber} );
1180             $data->{biblionumber} = $biblio->{biblionumber};
1181             $data->{title}        = $biblio->{title};
1182         }
1183         $acctlines[$numlines] = $data;
1184         $numlines++;
1185         $total += sprintf "%.0f", 1000*$data->{amountoutstanding}; # convert float to integer to avoid round-off errors
1186     }
1187     $total /= 1000;
1188     return ( $total, \@acctlines,$numlines);
1189 }
1190
1191 =head2 GetMemberAccountBalance
1192
1193   ($total_balance, $non_issue_balance, $other_charges) = &GetMemberAccountBalance($borrowernumber);
1194
1195 Calculates amount immediately owing by the patron - non-issue charges.
1196 Based on GetMemberAccountRecords.
1197 Charges exempt from non-issue are:
1198 * Res (reserves)
1199 * Rent (rental) if RentalsInNoissuesCharge syspref is set to false
1200 * Manual invoices if ManInvInNoissuesCharge syspref is set to false
1201
1202 =cut
1203
1204 sub GetMemberAccountBalance {
1205     my ($borrowernumber) = @_;
1206
1207     my $ACCOUNT_TYPE_LENGTH = 5; # this is plain ridiculous...
1208
1209     my @not_fines;
1210     push @not_fines, 'Res' unless C4::Context->preference('HoldsInNoissuesCharge');
1211     push @not_fines, 'Rent' unless C4::Context->preference('RentalsInNoissuesCharge');
1212     unless ( C4::Context->preference('ManInvInNoissuesCharge') ) {
1213         my $dbh = C4::Context->dbh;
1214         my $man_inv_types = $dbh->selectcol_arrayref(qq{SELECT authorised_value FROM authorised_values WHERE category = 'MANUAL_INV'});
1215         push @not_fines, map substr($_, 0, $ACCOUNT_TYPE_LENGTH), @$man_inv_types;
1216     }
1217     my %not_fine = map {$_ => 1} @not_fines;
1218
1219     my ($total, $acctlines) = GetMemberAccountRecords($borrowernumber);
1220     my $other_charges = 0;
1221     foreach (@$acctlines) {
1222         $other_charges += $_->{amountoutstanding} if $not_fine{ substr($_->{accounttype}, 0, $ACCOUNT_TYPE_LENGTH) };
1223     }
1224
1225     return ( $total, $total - $other_charges, $other_charges);
1226 }
1227
1228 =head2 GetBorNotifyAcctRecord
1229
1230   ($total, $acctlines, $count) = &GetBorNotifyAcctRecord($params,$notifyid);
1231
1232 Looks up accounting data for the patron with the given borrowernumber per file number.
1233
1234 C<&GetBorNotifyAcctRecord> returns a three-element array. C<$acctlines> is a
1235 reference-to-array, where each element is a reference-to-hash; the
1236 keys are the fields of the C<accountlines> table in the Koha database.
1237 C<$count> is the number of elements in C<$acctlines>. C<$total> is the
1238 total amount outstanding for all of the account lines.
1239
1240 =cut
1241
1242 sub GetBorNotifyAcctRecord {
1243     my ( $borrowernumber, $notifyid ) = @_;
1244     my $dbh = C4::Context->dbh;
1245     my @acctlines;
1246     my $numlines = 0;
1247     my $sth = $dbh->prepare(
1248             "SELECT * 
1249                 FROM accountlines 
1250                 WHERE borrowernumber=? 
1251                     AND notify_id=? 
1252                     AND amountoutstanding != '0' 
1253                 ORDER BY notify_id,accounttype
1254                 ");
1255
1256     $sth->execute( $borrowernumber, $notifyid );
1257     my $total = 0;
1258     while ( my $data = $sth->fetchrow_hashref ) {
1259         if ( $data->{itemnumber} ) {
1260             my $biblio = GetBiblioFromItemNumber( $data->{itemnumber} );
1261             $data->{biblionumber} = $biblio->{biblionumber};
1262             $data->{title}        = $biblio->{title};
1263         }
1264         $acctlines[$numlines] = $data;
1265         $numlines++;
1266         $total += int(100 * $data->{'amountoutstanding'});
1267     }
1268     $total /= 100;
1269     return ( $total, \@acctlines, $numlines );
1270 }
1271
1272 =head2 checkuniquemember (OUEST-PROVENCE)
1273
1274   ($result,$categorycode)  = &checkuniquemember($collectivity,$surname,$firstname,$dateofbirth);
1275
1276 Checks that a member exists or not in the database.
1277
1278 C<&result> is nonzero (=exist) or 0 (=does not exist)
1279 C<&categorycode> is from categorycode table
1280 C<&collectivity> is 1 (= we add a collectivity) or 0 (= we add a physical member)
1281 C<&surname> is the surname
1282 C<&firstname> is the firstname (only if collectivity=0)
1283 C<&dateofbirth> is the date of birth in ISO format (only if collectivity=0)
1284
1285 =cut
1286
1287 # FIXME: This function is not legitimate.  Multiple patrons might have the same first/last name and birthdate.
1288 # This is especially true since first name is not even a required field.
1289
1290 sub checkuniquemember {
1291     my ( $collectivity, $surname, $firstname, $dateofbirth ) = @_;
1292     my $dbh = C4::Context->dbh;
1293     my $request = ($collectivity) ?
1294         "SELECT borrowernumber,categorycode FROM borrowers WHERE surname=? " :
1295             ($dateofbirth) ?
1296             "SELECT borrowernumber,categorycode FROM borrowers WHERE surname=? and firstname=?  and dateofbirth=?" :
1297             "SELECT borrowernumber,categorycode FROM borrowers WHERE surname=? and firstname=?";
1298     my $sth = $dbh->prepare($request);
1299     if ($collectivity) {
1300         $sth->execute( uc($surname) );
1301     } elsif($dateofbirth){
1302         $sth->execute( uc($surname), ucfirst($firstname), $dateofbirth );
1303     }else{
1304         $sth->execute( uc($surname), ucfirst($firstname));
1305     }
1306     my @data = $sth->fetchrow;
1307     ( $data[0] ) and return $data[0], $data[1];
1308     return 0;
1309 }
1310
1311 sub checkcardnumber {
1312     my ( $cardnumber, $borrowernumber ) = @_;
1313
1314     # If cardnumber is null, we assume they're allowed.
1315     return 0 unless defined $cardnumber;
1316
1317     my $dbh = C4::Context->dbh;
1318     my $query = "SELECT * FROM borrowers WHERE cardnumber=?";
1319     $query .= " AND borrowernumber <> ?" if ($borrowernumber);
1320     my $sth = $dbh->prepare($query);
1321     $sth->execute(
1322         $cardnumber,
1323         ( $borrowernumber ? $borrowernumber : () )
1324     );
1325
1326     return 1 if $sth->fetchrow_hashref;
1327
1328     my ( $min_length, $max_length ) = get_cardnumber_length();
1329     return 2
1330         if length $cardnumber > $max_length
1331         or length $cardnumber < $min_length;
1332
1333     return 0;
1334 }
1335
1336 =head2 get_cardnumber_length
1337
1338     my ($min, $max) = C4::Members::get_cardnumber_length()
1339
1340 Returns the minimum and maximum length for patron cardnumbers as
1341 determined by the CardnumberLength system preference, the
1342 BorrowerMandatoryField system preference, and the width of the
1343 database column.
1344
1345 =cut
1346
1347 sub get_cardnumber_length {
1348     my ( $min, $max ) = ( 0, 16 ); # borrowers.cardnumber is a nullable varchar(16)
1349     $min = 1 if C4::Context->preference('BorrowerMandatoryField') =~ /cardnumber/;
1350     if ( my $cardnumber_length = C4::Context->preference('CardnumberLength') ) {
1351         # Is integer and length match
1352         if ( $cardnumber_length =~ m|^\d+$| ) {
1353             $min = $max = $cardnumber_length
1354                 if $cardnumber_length >= $min
1355                     and $cardnumber_length <= $max;
1356         }
1357         # Else assuming it is a range
1358         elsif ( $cardnumber_length =~ m|(\d*),(\d*)| ) {
1359             $min = $1 if $1 and $min < $1;
1360             $max = $2 if $2 and $max > $2;
1361         }
1362
1363     }
1364     my $borrower = Koha::Schema->resultset('Borrower');
1365     my $field_size = $borrower->result_source->column_info('cardnumber')->{size};
1366     $min = $field_size if $min > $field_size;
1367     return ( $min, $max );
1368 }
1369
1370 =head2 getzipnamecity (OUEST-PROVENCE)
1371
1372 take all info from table city for the fields city and  zip
1373 check for the name and the zip code of the city selected
1374
1375 =cut
1376
1377 sub getzipnamecity {
1378     my ($cityid) = @_;
1379     my $dbh      = C4::Context->dbh;
1380     my $sth      =
1381       $dbh->prepare(
1382         "select city_name,city_state,city_zipcode,city_country from cities where cityid=? ");
1383     $sth->execute($cityid);
1384     my @data = $sth->fetchrow;
1385     return $data[0], $data[1], $data[2], $data[3];
1386 }
1387
1388
1389 =head2 getdcity (OUEST-PROVENCE)
1390
1391 recover cityid  with city_name condition
1392
1393 =cut
1394
1395 sub getidcity {
1396     my ($city_name) = @_;
1397     my $dbh = C4::Context->dbh;
1398     my $sth = $dbh->prepare("select cityid from cities where city_name=? ");
1399     $sth->execute($city_name);
1400     my $data = $sth->fetchrow;
1401     return $data;
1402 }
1403
1404 =head2 GetFirstValidEmailAddress
1405
1406   $email = GetFirstValidEmailAddress($borrowernumber);
1407
1408 Return the first valid email address for a borrower, given the borrowernumber.  For now, the order 
1409 is defined as email, emailpro, B_email.  Returns the empty string if the borrower has no email 
1410 addresses.
1411
1412 =cut
1413
1414 sub GetFirstValidEmailAddress {
1415     my $borrowernumber = shift;
1416     my $dbh = C4::Context->dbh;
1417     my $sth = $dbh->prepare( "SELECT email, emailpro, B_email FROM borrowers where borrowernumber = ? ");
1418     $sth->execute( $borrowernumber );
1419     my $data = $sth->fetchrow_hashref;
1420
1421     if ($data->{'email'}) {
1422        return $data->{'email'};
1423     } elsif ($data->{'emailpro'}) {
1424        return $data->{'emailpro'};
1425     } elsif ($data->{'B_email'}) {
1426        return $data->{'B_email'};
1427     } else {
1428        return '';
1429     }
1430 }
1431
1432 =head2 GetNoticeEmailAddress
1433
1434   $email = GetNoticeEmailAddress($borrowernumber);
1435
1436 Return the email address of borrower used for notices, given the borrowernumber.
1437 Returns the empty string if no email address.
1438
1439 =cut
1440
1441 sub GetNoticeEmailAddress {
1442     my $borrowernumber = shift;
1443
1444     my $which_address = C4::Context->preference("AutoEmailPrimaryAddress");
1445     # if syspref is set to 'first valid' (value == OFF), look up email address
1446     if ( $which_address eq 'OFF' ) {
1447         return GetFirstValidEmailAddress($borrowernumber);
1448     }
1449     # specified email address field
1450     my $dbh = C4::Context->dbh;
1451     my $sth = $dbh->prepare( qq{
1452         SELECT $which_address AS primaryemail
1453         FROM borrowers
1454         WHERE borrowernumber=?
1455     } );
1456     $sth->execute($borrowernumber);
1457     my $data = $sth->fetchrow_hashref;
1458     return $data->{'primaryemail'} || '';
1459 }
1460
1461 =head2 GetExpiryDate 
1462
1463   $expirydate = GetExpiryDate($categorycode, $dateenrolled);
1464
1465 Calculate expiry date given a categorycode and starting date.  Date argument must be in ISO format.
1466 Return date is also in ISO format.
1467
1468 =cut
1469
1470 sub GetExpiryDate {
1471     my ( $categorycode, $dateenrolled ) = @_;
1472     my $enrolments;
1473     if ($categorycode) {
1474         my $dbh = C4::Context->dbh;
1475         my $sth = $dbh->prepare("SELECT enrolmentperiod,enrolmentperioddate FROM categories WHERE categorycode=?");
1476         $sth->execute($categorycode);
1477         $enrolments = $sth->fetchrow_hashref;
1478     }
1479     # die "GetExpiryDate: for enrollmentperiod $enrolmentperiod (category '$categorycode') starting $dateenrolled.\n";
1480     my @date = split (/-/,$dateenrolled);
1481     if($enrolments->{enrolmentperiod}){
1482         return sprintf("%04d-%02d-%02d", Add_Delta_YM(@date,0,$enrolments->{enrolmentperiod}));
1483     }else{
1484         return $enrolments->{enrolmentperioddate};
1485     }
1486 }
1487
1488 =head2 GetUpcomingMembershipExpires
1489
1490   my $upcoming_mem_expires = GetUpcomingMembershipExpires();
1491
1492 =cut
1493
1494 sub GetUpcomingMembershipExpires {
1495     my $dbh = C4::Context->dbh;
1496     my $days = C4::Context->preference("MembershipExpiryDaysNotice") || 0;
1497     my $dateexpiry = output_pref({ dt => (dt_from_string()->add( days => $days)), dateformat => 'iso', dateonly => 1 });
1498
1499     my $query = "
1500         SELECT borrowers.*, categories.description,
1501         branches.branchname, branches.branchemail FROM borrowers
1502         LEFT JOIN branches on borrowers.branchcode = branches.branchcode
1503         LEFT JOIN categories on borrowers.categorycode = categories.categorycode
1504         WHERE dateexpiry = ?;
1505     ";
1506     my $sth = $dbh->prepare($query);
1507     $sth->execute($dateexpiry);
1508     my $results = $sth->fetchall_arrayref({});
1509     return $results;
1510 }
1511
1512 =head2 GetborCatFromCatType
1513
1514   ($codes_arrayref, $labels_hashref) = &GetborCatFromCatType();
1515
1516 Looks up the different types of borrowers in the database. Returns two
1517 elements: a reference-to-array, which lists the borrower category
1518 codes, and a reference-to-hash, which maps the borrower category codes
1519 to category descriptions.
1520
1521 =cut
1522
1523 #'
1524 sub GetborCatFromCatType {
1525     my ( $category_type, $action, $no_branch_limit ) = @_;
1526
1527     my $branch_limit = $no_branch_limit
1528         ? 0
1529         : C4::Context->userenv ? C4::Context->userenv->{"branch"} : "";
1530
1531     # FIXME - This API  seems both limited and dangerous.
1532     my $dbh     = C4::Context->dbh;
1533
1534     my $request = qq{
1535         SELECT DISTINCT categories.categorycode, categories.description
1536         FROM categories
1537     };
1538     $request .= qq{
1539         LEFT JOIN categories_branches ON categories.categorycode = categories_branches.categorycode
1540     } if $branch_limit;
1541     if($action) {
1542         $request .= " $action ";
1543         $request .= " AND (branchcode = ? OR branchcode IS NULL)" if $branch_limit;
1544     } else {
1545         $request .= " WHERE branchcode = ? OR branchcode IS NULL" if $branch_limit;
1546     }
1547     $request .= " ORDER BY categorycode";
1548
1549     my $sth = $dbh->prepare($request);
1550     $sth->execute(
1551         $action ? $category_type : (),
1552         $branch_limit ? $branch_limit : ()
1553     );
1554
1555     my %labels;
1556     my @codes;
1557
1558     while ( my $data = $sth->fetchrow_hashref ) {
1559         push @codes, $data->{'categorycode'};
1560         $labels{ $data->{'categorycode'} } = $data->{'description'};
1561     }
1562     $sth->finish;
1563     return ( \@codes, \%labels );
1564 }
1565
1566 =head2 GetBorrowercategory
1567
1568   $hashref = &GetBorrowercategory($categorycode);
1569
1570 Given the borrower's category code, the function returns the corresponding
1571 data hashref for a comprehensive information display.
1572
1573 =cut
1574
1575 sub GetBorrowercategory {
1576     my ($catcode) = @_;
1577     my $dbh       = C4::Context->dbh;
1578     if ($catcode){
1579         my $sth       =
1580         $dbh->prepare(
1581     "SELECT description,dateofbirthrequired,upperagelimit,category_type 
1582     FROM categories 
1583     WHERE categorycode = ?"
1584         );
1585         $sth->execute($catcode);
1586         my $data =
1587         $sth->fetchrow_hashref;
1588         return $data;
1589     } 
1590     return;  
1591 }    # sub getborrowercategory
1592
1593
1594 =head2 GetBorrowerCategorycode
1595
1596     $categorycode = &GetBorrowerCategoryCode( $borrowernumber );
1597
1598 Given the borrowernumber, the function returns the corresponding categorycode
1599
1600 =cut
1601
1602 sub GetBorrowerCategorycode {
1603     my ( $borrowernumber ) = @_;
1604     my $dbh = C4::Context->dbh;
1605     my $sth = $dbh->prepare( qq{
1606         SELECT categorycode
1607         FROM borrowers
1608         WHERE borrowernumber = ?
1609     } );
1610     $sth->execute( $borrowernumber );
1611     return $sth->fetchrow;
1612 }
1613
1614 =head2 GetBorrowercategoryList
1615
1616   $arrayref_hashref = &GetBorrowercategoryList;
1617 If no category code provided, the function returns all the categories.
1618
1619 =cut
1620
1621 sub GetBorrowercategoryList {
1622     my $no_branch_limit = @_ ? shift : 0;
1623     my $branch_limit = $no_branch_limit
1624         ? 0
1625         : C4::Context->userenv ? C4::Context->userenv->{"branch"} : "";
1626     my $dbh       = C4::Context->dbh;
1627     my $query = "SELECT categories.* FROM categories";
1628     $query .= qq{
1629         LEFT JOIN categories_branches ON categories.categorycode = categories_branches.categorycode
1630         WHERE branchcode = ? OR branchcode IS NULL GROUP BY description
1631     } if $branch_limit;
1632     $query .= " ORDER BY description";
1633     my $sth = $dbh->prepare( $query );
1634     $sth->execute( $branch_limit ? $branch_limit : () );
1635     my $data = $sth->fetchall_arrayref( {} );
1636     $sth->finish;
1637     return $data;
1638 }    # sub getborrowercategory
1639
1640 =head2 GetAge
1641
1642   $dateofbirth,$date = &GetAge($date);
1643
1644 this function return the borrowers age with the value of dateofbirth
1645
1646 =cut
1647
1648 #'
1649 sub GetAge{
1650     my ( $date, $date_ref ) = @_;
1651
1652     if ( not defined $date_ref ) {
1653         $date_ref = sprintf( '%04d-%02d-%02d', Today() );
1654     }
1655
1656     my ( $year1, $month1, $day1 ) = split /-/, $date;
1657     my ( $year2, $month2, $day2 ) = split /-/, $date_ref;
1658
1659     my $age = $year2 - $year1;
1660     if ( $month1 . $day1 > $month2 . $day2 ) {
1661         $age--;
1662     }
1663
1664     return $age;
1665 }    # sub get_age
1666
1667 =head2 SetAge
1668
1669   $borrower = C4::Members::SetAge($borrower, $datetimeduration);
1670   $borrower = C4::Members::SetAge($borrower, '0015-12-10');
1671   $borrower = C4::Members::SetAge($borrower, $datetimeduration, $datetime_reference);
1672
1673   eval { $borrower = C4::Members::SetAge($borrower, '015-1-10'); };
1674   if ($@) {print $@;} #Catch a bad ISO Date or kill your script!
1675
1676 This function sets the borrower's dateofbirth to match the given age.
1677 Optionally relative to the given $datetime_reference.
1678
1679 @PARAM1 koha.borrowers-object
1680 @PARAM2 DateTime::Duration-object as the desired age
1681         OR a ISO 8601 Date. (To make the API more pleasant)
1682 @PARAM3 DateTime-object as the relative date, defaults to now().
1683 RETURNS The given borrower reference @PARAM1.
1684 DIES    If there was an error with the ISO Date handling.
1685
1686 =cut
1687
1688 #'
1689 sub SetAge{
1690     my ( $borrower, $datetimeduration, $datetime_ref ) = @_;
1691     $datetime_ref = DateTime->now() unless $datetime_ref;
1692
1693     if ($datetimeduration && ref $datetimeduration ne 'DateTime::Duration') {
1694         if ($datetimeduration =~ /^(\d{4})-(\d{2})-(\d{2})/) {
1695             $datetimeduration = DateTime::Duration->new(years => $1, months => $2, days => $3);
1696         }
1697         else {
1698             die "C4::Members::SetAge($borrower, $datetimeduration), datetimeduration not a valid ISO 8601 Date!\n";
1699         }
1700     }
1701
1702     my $new_datetime_ref = $datetime_ref->clone();
1703     $new_datetime_ref->subtract_duration( $datetimeduration );
1704
1705     $borrower->{dateofbirth} = $new_datetime_ref->ymd();
1706
1707     return $borrower;
1708 }    # sub SetAge
1709
1710 =head2 GetCities
1711
1712   $cityarrayref = GetCities();
1713
1714   Returns an array_ref of the entries in the cities table
1715   If there are entries in the table an empty row is returned
1716   This is currently only used to populate a popup in memberentry
1717
1718 =cut
1719
1720 sub GetCities {
1721
1722     my $dbh   = C4::Context->dbh;
1723     my $city_arr = $dbh->selectall_arrayref(
1724         q|SELECT cityid,city_zipcode,city_name,city_state,city_country FROM cities ORDER BY city_name|,
1725         { Slice => {} });
1726     if ( @{$city_arr} ) {
1727         unshift @{$city_arr}, {
1728             city_zipcode => q{},
1729             city_name    => q{},
1730             cityid       => q{},
1731             city_state   => q{},
1732             city_country => q{},
1733         };
1734     }
1735
1736     return  $city_arr;
1737 }
1738
1739 =head2 GetSortDetails (OUEST-PROVENCE)
1740
1741   ($lib) = &GetSortDetails($category,$sortvalue);
1742
1743 Returns the authorized value  details
1744 C<&$lib>return value of authorized value details
1745 C<&$sortvalue>this is the value of authorized value 
1746 C<&$category>this is the value of authorized value category
1747
1748 =cut
1749
1750 sub GetSortDetails {
1751     my ( $category, $sortvalue ) = @_;
1752     my $dbh   = C4::Context->dbh;
1753     my $query = qq|SELECT lib 
1754         FROM authorised_values 
1755         WHERE category=?
1756         AND authorised_value=? |;
1757     my $sth = $dbh->prepare($query);
1758     $sth->execute( $category, $sortvalue );
1759     my $lib = $sth->fetchrow;
1760     return ($lib) if ($lib);
1761     return ($sortvalue) unless ($lib);
1762 }
1763
1764 =head2 MoveMemberToDeleted
1765
1766   $result = &MoveMemberToDeleted($borrowernumber);
1767
1768 Copy the record from borrowers to deletedborrowers table.
1769 The routine returns 1 for success, undef for failure.
1770
1771 =cut
1772
1773 sub MoveMemberToDeleted {
1774     my ($member) = shift or return;
1775
1776     my $schema       = Koha::Database->new()->schema();
1777     my $borrowers_rs = $schema->resultset('Borrower');
1778     $borrowers_rs->result_class('DBIx::Class::ResultClass::HashRefInflator');
1779     my $borrower = $borrowers_rs->find($member);
1780     return unless $borrower;
1781
1782     delete $borrower->{updated_on};
1783
1784     my $deleted = $schema->resultset('Deletedborrower')->create($borrower);
1785
1786     return $deleted ? 1 : undef;
1787 }
1788
1789 =head2 DelMember
1790
1791     DelMember($borrowernumber);
1792
1793 This function remove directly a borrower whitout writing it on deleteborrower.
1794 + Deletes reserves for the borrower
1795
1796 =cut
1797
1798 sub DelMember {
1799     my $dbh            = C4::Context->dbh;
1800     my $borrowernumber = shift;
1801     #warn "in delmember with $borrowernumber";
1802     return unless $borrowernumber;    # borrowernumber is mandatory.
1803
1804     my $query = qq|DELETE 
1805           FROM  reserves 
1806           WHERE borrowernumber=?|;
1807     my $sth = $dbh->prepare($query);
1808     $sth->execute($borrowernumber);
1809     $query = "
1810        DELETE
1811        FROM borrowers
1812        WHERE borrowernumber = ?
1813    ";
1814     $sth = $dbh->prepare($query);
1815     $sth->execute($borrowernumber);
1816     logaction("MEMBERS", "DELETE", $borrowernumber, "") if C4::Context->preference("BorrowersLog");
1817     return $sth->rows;
1818 }
1819
1820 =head2 HandleDelBorrower
1821
1822      HandleDelBorrower($borrower);
1823
1824 When a member is deleted (DelMember in Members.pm), you should call me first.
1825 This routine deletes/moves lists and entries for the deleted member/borrower.
1826 Lists owned by the borrower are deleted, but entries from the borrower to
1827 other lists are kept.
1828
1829 =cut
1830
1831 sub HandleDelBorrower {
1832     my ($borrower)= @_;
1833     my $query;
1834     my $dbh = C4::Context->dbh;
1835
1836     #Delete all lists and all shares of this borrower
1837     #Consistent with the approach Koha uses on deleting individual lists
1838     #Note that entries in virtualshelfcontents added by this borrower to
1839     #lists of others will be handled by a table constraint: the borrower
1840     #is set to NULL in those entries.
1841     $query="DELETE FROM virtualshelves WHERE owner=?";
1842     $dbh->do($query,undef,($borrower));
1843
1844     #NOTE:
1845     #We could handle the above deletes via a constraint too.
1846     #But a new BZ report 11889 has been opened to discuss another approach.
1847     #Instead of deleting we could also disown lists (based on a pref).
1848     #In that way we could save shared and public lists.
1849     #The current table constraints support that idea now.
1850     #This pref should then govern the results of other routines/methods such as
1851     #Koha::Virtualshelf->new->delete too.
1852 }
1853
1854 =head2 ExtendMemberSubscriptionTo (OUEST-PROVENCE)
1855
1856     $date = ExtendMemberSubscriptionTo($borrowerid, $date);
1857
1858 Extending the subscription to a given date or to the expiry date calculated on ISO date.
1859 Returns ISO date.
1860
1861 =cut
1862
1863 sub ExtendMemberSubscriptionTo {
1864     my ( $borrowerid,$date) = @_;
1865     my $dbh = C4::Context->dbh;
1866     my $borrower = GetMember('borrowernumber'=>$borrowerid);
1867     unless ($date){
1868       $date = (C4::Context->preference('BorrowerRenewalPeriodBase') eq 'dateexpiry') ?
1869                                         eval { output_pref( { dt => dt_from_string( $borrower->{'dateexpiry'}  ), dateonly => 1, dateformat => 'iso' } ); }
1870                                         :
1871                                         output_pref( { dt => dt_from_string, dateonly => 1, dateformat => 'iso' } );
1872       $date = GetExpiryDate( $borrower->{'categorycode'}, $date );
1873     }
1874     my $sth = $dbh->do(<<EOF);
1875 UPDATE borrowers 
1876 SET  dateexpiry='$date' 
1877 WHERE borrowernumber='$borrowerid'
1878 EOF
1879
1880     AddEnrolmentFeeIfNeeded( $borrower->{categorycode}, $borrower->{borrowernumber} );
1881
1882     logaction("MEMBERS", "RENEW", $borrower->{'borrowernumber'}, "Membership renewed")if C4::Context->preference("BorrowersLog");
1883     return $date if ($sth);
1884     return 0;
1885 }
1886
1887 =head2 GetTitles (OUEST-PROVENCE)
1888
1889   ($borrowertitle)= &GetTitles();
1890
1891 Looks up the different title . Returns array  with all borrowers title
1892
1893 =cut
1894
1895 sub GetTitles {
1896     my @borrowerTitle = split (/,|\|/,C4::Context->preference('BorrowersTitles'));
1897     unshift( @borrowerTitle, "" );
1898     my $count=@borrowerTitle;
1899     if ($count == 1){
1900         return ();
1901     }
1902     else {
1903         return ( \@borrowerTitle);
1904     }
1905 }
1906
1907 =head2 GetPatronImage
1908
1909     my ($imagedata, $dberror) = GetPatronImage($borrowernumber);
1910
1911 Returns the mimetype and binary image data of the image for the patron with the supplied borrowernumber.
1912
1913 =cut
1914
1915 sub GetPatronImage {
1916     my ($borrowernumber) = @_;
1917     warn "Borrowernumber passed to GetPatronImage is $borrowernumber" if $debug;
1918     my $dbh = C4::Context->dbh;
1919     my $query = 'SELECT mimetype, imagefile FROM patronimage WHERE borrowernumber = ?';
1920     my $sth = $dbh->prepare($query);
1921     $sth->execute($borrowernumber);
1922     my $imagedata = $sth->fetchrow_hashref;
1923     warn "Database error!" if $sth->errstr;
1924     return $imagedata, $sth->errstr;
1925 }
1926
1927 =head2 PutPatronImage
1928
1929     PutPatronImage($cardnumber, $mimetype, $imgfile);
1930
1931 Stores patron binary image data and mimetype in database.
1932 NOTE: This function is good for updating images as well as inserting new images in the database.
1933
1934 =cut
1935
1936 sub PutPatronImage {
1937     my ($cardnumber, $mimetype, $imgfile) = @_;
1938     warn "Parameters passed in: Cardnumber=$cardnumber, Mimetype=$mimetype, " . ($imgfile ? "Imagefile" : "No Imagefile") if $debug;
1939     my $dbh = C4::Context->dbh;
1940     my $query = "INSERT INTO patronimage (borrowernumber, mimetype, imagefile) VALUES ( ( SELECT borrowernumber from borrowers WHERE cardnumber = ? ),?,?) ON DUPLICATE KEY UPDATE imagefile = ?;";
1941     my $sth = $dbh->prepare($query);
1942     $sth->execute($cardnumber,$mimetype,$imgfile,$imgfile);
1943     warn "Error returned inserting $cardnumber.$mimetype." if $sth->errstr;
1944     return $sth->errstr;
1945 }
1946
1947 =head2 RmPatronImage
1948
1949     my ($dberror) = RmPatronImage($borrowernumber);
1950
1951 Removes the image for the patron with the supplied borrowernumber.
1952
1953 =cut
1954
1955 sub RmPatronImage {
1956     my ($borrowernumber) = @_;
1957     warn "Borrowernumber passed to GetPatronImage is $borrowernumber" if $debug;
1958     my $dbh = C4::Context->dbh;
1959     my $query = "DELETE FROM patronimage WHERE borrowernumber = ?;";
1960     my $sth = $dbh->prepare($query);
1961     $sth->execute($borrowernumber);
1962     my $dberror = $sth->errstr;
1963     warn "Database error!" if $sth->errstr;
1964     return $dberror;
1965 }
1966
1967 =head2 GetHideLostItemsPreference
1968
1969   $hidelostitemspref = &GetHideLostItemsPreference($borrowernumber);
1970
1971 Returns the HideLostItems preference for the patron category of the supplied borrowernumber
1972 C<&$hidelostitemspref>return value of function, 0 or 1
1973
1974 =cut
1975
1976 sub GetHideLostItemsPreference {
1977     my ($borrowernumber) = @_;
1978     my $dbh = C4::Context->dbh;
1979     my $query = "SELECT hidelostitems FROM borrowers,categories WHERE borrowers.categorycode = categories.categorycode AND borrowernumber = ?";
1980     my $sth = $dbh->prepare($query);
1981     $sth->execute($borrowernumber);
1982     my $hidelostitems = $sth->fetchrow;    
1983     return $hidelostitems;    
1984 }
1985
1986 =head2 GetBorrowersToExpunge
1987
1988   $borrowers = &GetBorrowersToExpunge(
1989       not_borrowed_since   => $not_borrowed_since,
1990       expired_before       => $expired_before,
1991       category_code        => $category_code,
1992       branchcode           => $branchcode
1993   );
1994
1995   This function get all borrowers based on the given criteria.
1996
1997 =cut
1998
1999 sub GetBorrowersToExpunge {
2000     my $params = shift;
2001
2002     my $filterdate     = $params->{'not_borrowed_since'};
2003     my $filterexpiry   = $params->{'expired_before'};
2004     my $filtercategory = $params->{'category_code'};
2005     my $filterbranch   = $params->{'branchcode'} ||
2006                         ((C4::Context->preference('IndependentBranches')
2007                              && C4::Context->userenv 
2008                              && !C4::Context->IsSuperLibrarian()
2009                              && C4::Context->userenv->{branch})
2010                          ? C4::Context->userenv->{branch}
2011                          : "");  
2012
2013     my $dbh   = C4::Context->dbh;
2014     my $query = q|
2015         SELECT borrowers.borrowernumber,
2016                MAX(old_issues.timestamp) AS latestissue,
2017                MAX(issues.timestamp) AS currentissue
2018         FROM   borrowers
2019         JOIN   categories USING (categorycode)
2020         LEFT JOIN (
2021             SELECT guarantorid
2022             FROM borrowers
2023             WHERE guarantorid IS NOT NULL
2024                 AND guarantorid <> 0
2025         ) as tmp ON borrowers.borrowernumber=tmp.guarantorid
2026         LEFT JOIN old_issues USING (borrowernumber)
2027         LEFT JOIN issues USING (borrowernumber) 
2028         WHERE  category_type <> 'S'
2029         AND tmp.guarantorid IS NULL
2030    |;
2031
2032     my @query_params;
2033     if ( $filterbranch && $filterbranch ne "" ) {
2034         $query.= " AND borrowers.branchcode = ? ";
2035         push( @query_params, $filterbranch );
2036     }
2037     if ( $filterexpiry ) {
2038         $query .= " AND dateexpiry < ? ";
2039         push( @query_params, $filterexpiry );
2040     }
2041     if ( $filtercategory ) {
2042         $query .= " AND categorycode = ? ";
2043         push( @query_params, $filtercategory );
2044     }
2045     $query.=" GROUP BY borrowers.borrowernumber HAVING currentissue IS NULL ";
2046     if ( $filterdate ) {
2047         $query.=" AND ( latestissue < ? OR latestissue IS NULL ) ";
2048         push @query_params,$filterdate;
2049     }
2050     warn $query if $debug;
2051
2052     my $sth = $dbh->prepare($query);
2053     if (scalar(@query_params)>0){  
2054         $sth->execute(@query_params);
2055     } 
2056     else {
2057         $sth->execute;
2058     }      
2059     
2060     my @results;
2061     while ( my $data = $sth->fetchrow_hashref ) {
2062         push @results, $data;
2063     }
2064     return \@results;
2065 }
2066
2067 =head2 GetBorrowersWhoHaveNeverBorrowed
2068
2069   $results = &GetBorrowersWhoHaveNeverBorrowed
2070
2071 This function get all borrowers who have never borrowed.
2072
2073 I<$result> is a ref to an array which all elements are a hasref.
2074
2075 =cut
2076
2077 sub GetBorrowersWhoHaveNeverBorrowed {
2078     my $filterbranch = shift || 
2079                         ((C4::Context->preference('IndependentBranches')
2080                              && C4::Context->userenv 
2081                              && !C4::Context->IsSuperLibrarian()
2082                              && C4::Context->userenv->{branch})
2083                          ? C4::Context->userenv->{branch}
2084                          : "");  
2085     my $dbh   = C4::Context->dbh;
2086     my $query = "
2087         SELECT borrowers.borrowernumber,max(timestamp) as latestissue
2088         FROM   borrowers
2089           LEFT JOIN issues ON borrowers.borrowernumber = issues.borrowernumber
2090         WHERE issues.borrowernumber IS NULL
2091    ";
2092     my @query_params;
2093     if ($filterbranch && $filterbranch ne ""){ 
2094         $query.=" AND borrowers.branchcode= ?";
2095         push @query_params,$filterbranch;
2096     }
2097     warn $query if $debug;
2098   
2099     my $sth = $dbh->prepare($query);
2100     if (scalar(@query_params)>0){  
2101         $sth->execute(@query_params);
2102     } 
2103     else {
2104         $sth->execute;
2105     }      
2106     
2107     my @results;
2108     while ( my $data = $sth->fetchrow_hashref ) {
2109         push @results, $data;
2110     }
2111     return \@results;
2112 }
2113
2114 =head2 GetBorrowersWithIssuesHistoryOlderThan
2115
2116   $results = &GetBorrowersWithIssuesHistoryOlderThan($date)
2117
2118 this function get all borrowers who has an issue history older than I<$date> given on input arg.
2119
2120 I<$result> is a ref to an array which all elements are a hashref.
2121 This hashref is containt the number of time this borrowers has borrowed before I<$date> and the borrowernumber.
2122
2123 =cut
2124
2125 sub GetBorrowersWithIssuesHistoryOlderThan {
2126     my $dbh  = C4::Context->dbh;
2127     my $date = shift ||POSIX::strftime("%Y-%m-%d",localtime());
2128     my $filterbranch = shift || 
2129                         ((C4::Context->preference('IndependentBranches')
2130                              && C4::Context->userenv 
2131                              && !C4::Context->IsSuperLibrarian()
2132                              && C4::Context->userenv->{branch})
2133                          ? C4::Context->userenv->{branch}
2134                          : "");  
2135     my $query = "
2136        SELECT count(borrowernumber) as n,borrowernumber
2137        FROM old_issues
2138        WHERE returndate < ?
2139          AND borrowernumber IS NOT NULL 
2140     "; 
2141     my @query_params;
2142     push @query_params, $date;
2143     if ($filterbranch){
2144         $query.="   AND branchcode = ?";
2145         push @query_params, $filterbranch;
2146     }    
2147     $query.=" GROUP BY borrowernumber ";
2148     warn $query if $debug;
2149     my $sth = $dbh->prepare($query);
2150     $sth->execute(@query_params);
2151     my @results;
2152
2153     while ( my $data = $sth->fetchrow_hashref ) {
2154         push @results, $data;
2155     }
2156     return \@results;
2157 }
2158
2159 =head2 GetBorrowersNamesAndLatestIssue
2160
2161   $results = &GetBorrowersNamesAndLatestIssueList(@borrowernumbers)
2162
2163 this function get borrowers Names and surnames and Issue information.
2164
2165 I<@borrowernumbers> is an array which all elements are borrowernumbers.
2166 This hashref is containt the number of time this borrowers has borrowed before I<$date> and the borrowernumber.
2167
2168 =cut
2169
2170 sub GetBorrowersNamesAndLatestIssue {
2171     my $dbh  = C4::Context->dbh;
2172     my @borrowernumbers=@_;  
2173     my $query = "
2174        SELECT surname,lastname, phone, email,max(timestamp)
2175        FROM borrowers 
2176          LEFT JOIN issues ON borrowers.borrowernumber=issues.borrowernumber
2177        GROUP BY borrowernumber
2178    ";
2179     my $sth = $dbh->prepare($query);
2180     $sth->execute;
2181     my $results = $sth->fetchall_arrayref({});
2182     return $results;
2183 }
2184
2185 =head2 ModPrivacy
2186
2187   my $success = ModPrivacy( $borrowernumber, $privacy );
2188
2189 Update the privacy of a patron.
2190
2191 return :
2192 true on success, false on failure
2193
2194 =cut
2195
2196 sub ModPrivacy {
2197     my $borrowernumber = shift;
2198     my $privacy = shift;
2199     return unless defined $borrowernumber;
2200     return unless $borrowernumber =~ /^\d+$/;
2201
2202     return ModMember( borrowernumber => $borrowernumber,
2203                       privacy        => $privacy );
2204 }
2205
2206 =head2 AddMessage
2207
2208   AddMessage( $borrowernumber, $message_type, $message, $branchcode );
2209
2210 Adds a message to the messages table for the given borrower.
2211
2212 Returns:
2213   True on success
2214   False on failure
2215
2216 =cut
2217
2218 sub AddMessage {
2219     my ( $borrowernumber, $message_type, $message, $branchcode ) = @_;
2220
2221     my $dbh  = C4::Context->dbh;
2222
2223     if ( ! ( $borrowernumber && $message_type && $message && $branchcode ) ) {
2224       return;
2225     }
2226
2227     my $query = "INSERT INTO messages ( borrowernumber, branchcode, message_type, message ) VALUES ( ?, ?, ?, ? )";
2228     my $sth = $dbh->prepare($query);
2229     $sth->execute( $borrowernumber, $branchcode, $message_type, $message );
2230     logaction("MEMBERS", "ADDCIRCMESSAGE", $borrowernumber, $message) if C4::Context->preference("BorrowersLog");
2231     return 1;
2232 }
2233
2234 =head2 GetMessages
2235
2236   GetMessages( $borrowernumber, $type );
2237
2238 $type is message type, B for borrower, or L for Librarian.
2239 Empty type returns all messages of any type.
2240
2241 Returns all messages for the given borrowernumber
2242
2243 =cut
2244
2245 sub GetMessages {
2246     my ( $borrowernumber, $type, $branchcode ) = @_;
2247
2248     if ( ! $type ) {
2249       $type = '%';
2250     }
2251
2252     my $dbh  = C4::Context->dbh;
2253
2254     my $query = "SELECT
2255                   branches.branchname,
2256                   messages.*,
2257                   message_date,
2258                   messages.branchcode LIKE '$branchcode' AS can_delete
2259                   FROM messages, branches
2260                   WHERE borrowernumber = ?
2261                   AND message_type LIKE ?
2262                   AND messages.branchcode = branches.branchcode
2263                   ORDER BY message_date DESC";
2264     my $sth = $dbh->prepare($query);
2265     $sth->execute( $borrowernumber, $type ) ;
2266     my @results;
2267
2268     while ( my $data = $sth->fetchrow_hashref ) {
2269         $data->{message_date_formatted} = output_pref( { dt => dt_from_string( $data->{message_date} ), dateonly => 1, dateformat => 'iso' } );
2270         push @results, $data;
2271     }
2272     return \@results;
2273
2274 }
2275
2276 =head2 GetMessages
2277
2278   GetMessagesCount( $borrowernumber, $type );
2279
2280 $type is message type, B for borrower, or L for Librarian.
2281 Empty type returns all messages of any type.
2282
2283 Returns the number of messages for the given borrowernumber
2284
2285 =cut
2286
2287 sub GetMessagesCount {
2288     my ( $borrowernumber, $type, $branchcode ) = @_;
2289
2290     if ( ! $type ) {
2291       $type = '%';
2292     }
2293
2294     my $dbh  = C4::Context->dbh;
2295
2296     my $query = "SELECT COUNT(*) as MsgCount FROM messages WHERE borrowernumber = ? AND message_type LIKE ?";
2297     my $sth = $dbh->prepare($query);
2298     $sth->execute( $borrowernumber, $type ) ;
2299     my @results;
2300
2301     my $data = $sth->fetchrow_hashref;
2302     my $count = $data->{'MsgCount'};
2303
2304     return $count;
2305 }
2306
2307
2308
2309 =head2 DeleteMessage
2310
2311   DeleteMessage( $message_id );
2312
2313 =cut
2314
2315 sub DeleteMessage {
2316     my ( $message_id ) = @_;
2317
2318     my $dbh = C4::Context->dbh;
2319     my $query = "SELECT * FROM messages WHERE message_id = ?";
2320     my $sth = $dbh->prepare($query);
2321     $sth->execute( $message_id );
2322     my $message = $sth->fetchrow_hashref();
2323
2324     $query = "DELETE FROM messages WHERE message_id = ?";
2325     $sth = $dbh->prepare($query);
2326     $sth->execute( $message_id );
2327     logaction("MEMBERS", "DELCIRCMESSAGE", $message->{'borrowernumber'}, $message->{'message'}) if C4::Context->preference("BorrowersLog");
2328 }
2329
2330 =head2 IssueSlip
2331
2332   IssueSlip($branchcode, $borrowernumber, $quickslip)
2333
2334   Returns letter hash ( see C4::Letters::GetPreparedLetter )
2335
2336   $quickslip is boolean, to indicate whether we want a quick slip
2337
2338   IssueSlip populates ISSUESLIP and ISSUEQSLIP, and will make the following expansions:
2339
2340   Both slips:
2341
2342       <<branches.*>>
2343       <<borrowers.*>>
2344
2345   ISSUESLIP:
2346
2347       <checkedout>
2348          <<biblio.*>>
2349          <<items.*>>
2350          <<biblioitems.*>>
2351          <<issues.*>>
2352       </checkedout>
2353
2354       <overdue>
2355          <<biblio.*>>
2356          <<items.*>>
2357          <<biblioitems.*>>
2358          <<issues.*>>
2359       </overdue>
2360
2361       <news>
2362          <<opac_news.*>>
2363       </news>
2364
2365   ISSUEQSLIP:
2366
2367       <checkedout>
2368          <<biblio.*>>
2369          <<items.*>>
2370          <<biblioitems.*>>
2371          <<issues.*>>
2372       </checkedout>
2373
2374   NOTE: Not all table fields are available, pleasee see GetPendingIssues for a list of available fields.
2375
2376 =cut
2377
2378 sub IssueSlip {
2379     my ($branch, $borrowernumber, $quickslip) = @_;
2380
2381     # FIXME Check callers before removing this statement
2382     #return unless $borrowernumber;
2383
2384     my @issues = @{ GetPendingIssues($borrowernumber) };
2385
2386     for my $issue (@issues) {
2387         $issue->{date_due} = $issue->{date_due_sql};
2388         if ($quickslip) {
2389             my $today = output_pref({ dt => dt_from_string, dateformat => 'iso', dateonly => 1 });
2390             if ( substr( $issue->{issuedate}, 0, 10 ) eq $today
2391                 or substr( $issue->{lastreneweddate}, 0, 10 ) eq $today ) {
2392                   $issue->{now} = 1;
2393             };
2394         }
2395     }
2396
2397     # Sort on timestamp then on issuedate (useful for tests and could be if modified in a batch
2398     @issues = sort {
2399         my $s = $b->{timestamp} <=> $a->{timestamp};
2400         $s == 0 ?
2401              $b->{issuedate} <=> $a->{issuedate} : $s;
2402     } @issues;
2403
2404     my ($letter_code, %repeat);
2405     if ( $quickslip ) {
2406         $letter_code = 'ISSUEQSLIP';
2407         %repeat =  (
2408             'checkedout' => [ map {
2409                 'biblio'       => $_,
2410                 'items'        => $_,
2411                 'biblioitems'  => $_,
2412                 'issues'       => $_,
2413             }, grep { $_->{'now'} } @issues ],
2414         );
2415     }
2416     else {
2417         $letter_code = 'ISSUESLIP';
2418         %repeat =  (
2419             'checkedout' => [ map {
2420                 'biblio'       => $_,
2421                 'items'        => $_,
2422                 'biblioitems'  => $_,
2423                 'issues'       => $_,
2424             }, grep { !$_->{'overdue'} } @issues ],
2425
2426             'overdue' => [ map {
2427                 'biblio'       => $_,
2428                 'items'        => $_,
2429                 'biblioitems'  => $_,
2430                 'issues'       => $_,
2431             }, grep { $_->{'overdue'} } @issues ],
2432
2433             'news' => [ map {
2434                 $_->{'timestamp'} = $_->{'newdate'};
2435                 { opac_news => $_ }
2436             } @{ GetNewsToDisplay("slip",$branch) } ],
2437         );
2438     }
2439
2440     return  C4::Letters::GetPreparedLetter (
2441         module => 'circulation',
2442         letter_code => $letter_code,
2443         branchcode => $branch,
2444         tables => {
2445             'branches'    => $branch,
2446             'borrowers'   => $borrowernumber,
2447         },
2448         repeat => \%repeat,
2449     );
2450 }
2451
2452 =head2 GetBorrowersWithEmail
2453
2454     ([$borrnum,$userid], ...) = GetBorrowersWithEmail('me@example.com');
2455
2456 This gets a list of users and their basic details from their email address.
2457 As it's possible for multiple user to have the same email address, it provides
2458 you with all of them. If there is no userid for the user, there will be an
2459 C<undef> there. An empty list will be returned if there are no matches.
2460
2461 =cut
2462
2463 sub GetBorrowersWithEmail {
2464     my $email = shift;
2465
2466     my $dbh = C4::Context->dbh;
2467
2468     my $query = "SELECT borrowernumber, userid FROM borrowers WHERE email=?";
2469     my $sth=$dbh->prepare($query);
2470     $sth->execute($email);
2471     my @result = ();
2472     while (my $ref = $sth->fetch) {
2473         push @result, $ref;
2474     }
2475     die "Failure searching for borrowers by email address: $sth->errstr" if $sth->err;
2476     return @result;
2477 }
2478
2479 =head2 AddMember_Opac
2480
2481 =cut
2482
2483 sub AddMember_Opac {
2484     my ( %borrower ) = @_;
2485
2486     $borrower{'categorycode'} = C4::Context->preference('PatronSelfRegistrationDefaultCategory');
2487
2488     my $sr = new String::Random;
2489     $sr->{'A'} = [ 'A'..'Z', 'a'..'z' ];
2490     my $password = $sr->randpattern("AAAAAAAAAA");
2491     $borrower{'password'} = $password;
2492
2493     $borrower{'cardnumber'} = fixup_cardnumber();
2494
2495     my $borrowernumber = AddMember(%borrower);
2496
2497     return ( $borrowernumber, $password );
2498 }
2499
2500 =head2 AddEnrolmentFeeIfNeeded
2501
2502     AddEnrolmentFeeIfNeeded( $borrower->{categorycode}, $borrower->{borrowernumber} );
2503
2504 Add enrolment fee for a patron if needed.
2505
2506 =cut
2507
2508 sub AddEnrolmentFeeIfNeeded {
2509     my ( $categorycode, $borrowernumber ) = @_;
2510     # check for enrollment fee & add it if needed
2511     my $dbh = C4::Context->dbh;
2512     my $sth = $dbh->prepare(q{
2513         SELECT enrolmentfee
2514         FROM categories
2515         WHERE categorycode=?
2516     });
2517     $sth->execute( $categorycode );
2518     if ( $sth->err ) {
2519         warn sprintf('Database returned the following error: %s', $sth->errstr);
2520         return;
2521     }
2522     my ($enrolmentfee) = $sth->fetchrow;
2523     if ($enrolmentfee && $enrolmentfee > 0) {
2524         # insert fee in patron debts
2525         C4::Accounts::manualinvoice( $borrowernumber, '', '', 'A', $enrolmentfee );
2526     }
2527 }
2528
2529 =head2 HasOverdues
2530
2531 =cut
2532
2533 sub HasOverdues {
2534     my ( $borrowernumber ) = @_;
2535
2536     my $sql = "SELECT COUNT(*) FROM issues WHERE date_due < NOW() AND borrowernumber = ?";
2537     my $sth = C4::Context->dbh->prepare( $sql );
2538     $sth->execute( $borrowernumber );
2539     my ( $count ) = $sth->fetchrow_array();
2540
2541     return $count;
2542 }
2543
2544 =head2 DeleteExpiredOpacRegistrations
2545
2546     Delete accounts that haven't been upgraded from the 'temporary' category
2547     Returns the number of removed patrons
2548
2549 =cut
2550
2551 sub DeleteExpiredOpacRegistrations {
2552
2553     my $delay = C4::Context->preference('PatronSelfRegistrationExpireTemporaryAccountsDelay');
2554     my $category_code = C4::Context->preference('PatronSelfRegistrationDefaultCategory');
2555
2556     return 0 if not $category_code or not defined $delay or $delay eq q||;
2557
2558     my $query = qq|
2559 SELECT borrowernumber
2560 FROM borrowers
2561 WHERE categorycode = ? AND DATEDIFF( NOW(), dateenrolled ) > ? |;
2562
2563     my $dbh = C4::Context->dbh;
2564     my $sth = $dbh->prepare($query);
2565     $sth->execute( $category_code, $delay );
2566     my $cnt=0;
2567     while ( my ($borrowernumber) = $sth->fetchrow_array() ) {
2568         DelMember($borrowernumber);
2569         $cnt++;
2570     }
2571     return $cnt;
2572 }
2573
2574 =head2 DeleteUnverifiedOpacRegistrations
2575
2576     Delete all unverified self registrations in borrower_modifications,
2577     older than the specified number of days.
2578
2579 =cut
2580
2581 sub DeleteUnverifiedOpacRegistrations {
2582     my ( $days ) = @_;
2583     my $dbh = C4::Context->dbh;
2584     my $sql=qq|
2585 DELETE FROM borrower_modifications
2586 WHERE borrowernumber = 0 AND DATEDIFF( NOW(), timestamp ) > ?|;
2587     my $cnt=$dbh->do($sql, undef, ($days) );
2588     return $cnt eq '0E0'? 0: $cnt;
2589 }
2590
2591 sub GetOverduesForPatron {
2592     my ( $borrowernumber ) = @_;
2593
2594     my $sql = "
2595         SELECT *
2596         FROM issues, items, biblio, biblioitems
2597         WHERE items.itemnumber=issues.itemnumber
2598           AND biblio.biblionumber   = items.biblionumber
2599           AND biblio.biblionumber   = biblioitems.biblionumber
2600           AND issues.borrowernumber = ?
2601           AND date_due < NOW()
2602     ";
2603
2604     my $sth = C4::Context->dbh->prepare( $sql );
2605     $sth->execute( $borrowernumber );
2606
2607     return $sth->fetchall_arrayref({});
2608 }
2609
2610 END { }    # module clean-up code here (global destructor)
2611
2612 1;
2613
2614 __END__
2615
2616 =head1 AUTHOR
2617
2618 Koha Team
2619
2620 =cut