3 # Copyright 2000-2003 Katipo Communications
5 # This file is part of Koha.
7 # Koha is free software; you can redistribute it and/or modify it under the
8 # terms of the GNU General Public License as published by the Free Software
9 # Foundation; either version 2 of the License, or (at your option) any later
12 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
13 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
14 # A PARTICULAR PURPOSE. See the GNU General Public License for more details.
16 # You should have received a copy of the GNU General Public License along with
17 # Koha; if not, write to the Free Software Foundation, Inc., 59 Temple Place,
18 # Suite 330, Boston, MA 02111-1307 USA
23 use C4::Dates qw(format_date_in_iso);
24 use Digest::MD5 qw(md5_base64);
25 use Date::Calc qw/Today Add_Delta_YM/;
26 use C4::Log; # logaction
31 use C4::SQLHelper qw(InsertInTable UpdateInTable);
33 our ($VERSION,@ISA,@EXPORT,@EXPORT_OK,$debug);
37 $debug = $ENV{DEBUG} || 0;
48 &GetMemberIssuesAndFines
68 &GetMemberAccountRecords
69 &GetBorNotifyAcctRecord
73 &GetBorrowercategoryList
75 &GetBorrowersWhoHaveNotBorrowedSince
76 &GetBorrowersWhoHaveNeverBorrowed
77 &GetBorrowersWithIssuesHistoryOlderThan
103 &ExtendMemberSubscriptionTo
121 C4::Members - Perl Module containing convenience functions for member handling
129 This module contains routines for adding, modifying and deleting members/patrons/borrowers
137 ($count, $borrowers) = &SearchMember($searchstring, $type,$category_type,$filter,$showallbranches);
141 Looks up patrons (borrowers) by name.
143 BUGFIX 499: C<$type> is now used to determine type of search.
144 if $type is "simple", search is performed on the first letter of the
147 $category_type is used to get a specified type of user.
148 (mainly adults when creating a child.)
150 C<$searchstring> is a space-separated list of search terms. Each term
151 must match the beginning a borrower's surname, first name, or other
154 C<$filter> is assumed to be a list of elements to filter results on
156 C<$showallbranches> is used in IndependantBranches Context to display all branches results.
158 C<&SearchMember> returns a two-element list. C<$borrowers> is a
159 reference-to-array; each element is a reference-to-hash, whose keys
160 are the fields of the C<borrowers> table in the Koha database.
161 C<$count> is the number of elements in C<$borrowers>.
166 #used by member enquiries from the intranet
167 #called by member.pl and circ/circulation.pl
169 my ($searchstring, $orderby, $type,$category_type,$filter,$showallbranches ) = @_;
170 my $dbh = C4::Context->dbh;
176 # this is used by circulation everytime a new borrowers cardnumber is scanned
177 # so we can check an exact match first, if that works return, otherwise do the rest
178 $query = "SELECT * FROM borrowers
179 LEFT JOIN categories ON borrowers.categorycode=categories.categorycode
181 my $sth = $dbh->prepare("$query WHERE cardnumber = ?");
182 $sth->execute($searchstring);
183 my $data = $sth->fetchall_arrayref({});
185 return ( scalar(@$data), $data );
188 if ( $type eq "simple" ) # simple search for one letter only
190 $query .= ($category_type ? " AND category_type = ".$dbh->quote($category_type) : "");
191 $query .= " WHERE (surname LIKE ? OR cardnumber like ?) ";
192 if (C4::Context->preference("IndependantBranches") && !$showallbranches){
193 if (C4::Context->userenv && C4::Context->userenv->{flags} % 2 !=1 && C4::Context->userenv->{'branch'}){
194 $query.=" AND borrowers.branchcode =".$dbh->quote(C4::Context->userenv->{'branch'}) unless (C4::Context->userenv->{'branch'} eq "insecure");
197 $query.=" ORDER BY $orderby";
198 @bind = ("$searchstring%","$searchstring");
200 else # advanced search looking in surname, firstname and othernames
202 @data = split( ' ', $searchstring );
205 if (C4::Context->preference("IndependantBranches") && !$showallbranches){
206 if (C4::Context->userenv && C4::Context->userenv->{flags} % 2 !=1 && C4::Context->userenv->{'branch'}){
207 $query.=" borrowers.branchcode =".$dbh->quote(C4::Context->userenv->{'branch'})." AND " unless (C4::Context->userenv->{'branch'} eq "insecure");
210 $query.="((surname LIKE ? OR surname LIKE ?
211 OR firstname LIKE ? OR firstname LIKE ?
212 OR othernames LIKE ? OR othernames LIKE ?)
214 ($category_type?" AND category_type = ".$dbh->quote($category_type):"");
216 "$data[0]%", "% $data[0]%", "$data[0]%", "% $data[0]%",
217 "$data[0]%", "% $data[0]%"
219 for ( my $i = 1 ; $i < $count ; $i++ ) {
220 $query = $query . " AND (" . " surname LIKE ? OR surname LIKE ?
221 OR firstname LIKE ? OR firstname LIKE ?
222 OR othernames LIKE ? OR othernames LIKE ?)";
224 "$data[$i]%", "% $data[$i]%", "$data[$i]%",
225 "% $data[$i]%", "$data[$i]%", "% $data[$i]%" );
229 $query = $query . ") OR cardnumber LIKE ? ";
230 push( @bind, $searchstring );
231 if (C4::Context->preference('ExtendedPatronAttributes')) {
232 $query .= "OR borrowernumber IN (
233 SELECT borrowernumber
234 FROM borrower_attributes
235 JOIN borrower_attribute_types USING (code)
236 WHERE staff_searchable = 1
239 push (@bind, $searchstring);
241 $query .= "order by $orderby";
246 $sth = $dbh->prepare($query);
248 $debug and print STDERR "Q $orderby : $query\n";
249 $sth->execute(@bind);
251 $data = $sth->fetchall_arrayref({});
253 return ( scalar(@$data), $data );
256 =head2 GetMemberDetails
258 ($borrower) = &GetMemberDetails($borrowernumber, $cardnumber);
260 Looks up a patron and returns information about him or her. If
261 C<$borrowernumber> is true (nonzero), C<&GetMemberDetails> looks
262 up the borrower by number; otherwise, it looks up the borrower by card
265 C<$borrower> is a reference-to-hash whose keys are the fields of the
266 borrowers table in the Koha database. In addition,
267 C<$borrower-E<gt>{flags}> is a hash giving more detailed information
268 about the patron. Its keys act as flags :
270 if $borrower->{flags}->{LOST} {
271 # Patron's card was reported lost
274 If the state of a flag means that the patron should not be
275 allowed to borrow any more books, then it will have a C<noissues> key
278 See patronflags for more details.
280 C<$borrower-E<gt>{authflags}> is a hash giving more detailed information
281 about the top-level permissions flags set for the borrower. For example,
282 if a user has the "editcatalogue" permission,
283 C<$borrower-E<gt>{authflags}-E<gt>{editcatalogue}> will exist and have
288 sub GetMemberDetails {
289 my ( $borrowernumber, $cardnumber ) = @_;
290 my $dbh = C4::Context->dbh;
293 if ($borrowernumber) {
294 $sth = $dbh->prepare("select borrowers.*,category_type,categories.description from borrowers left join categories on borrowers.categorycode=categories.categorycode where borrowernumber=?");
295 $sth->execute($borrowernumber);
297 elsif ($cardnumber) {
298 $sth = $dbh->prepare("select borrowers.*,category_type,categories.description from borrowers left join categories on borrowers.categorycode=categories.categorycode where cardnumber=?");
299 $sth->execute($cardnumber);
304 my $borrower = $sth->fetchrow_hashref;
305 my ($amount) = GetMemberAccountRecords( $borrowernumber);
306 $borrower->{'amountoutstanding'} = $amount;
307 # FIXME - patronflags calls GetMemberAccountRecords... just have patronflags return $amount
308 my $flags = patronflags( $borrower);
311 $sth = $dbh->prepare("select bit,flag from userflags");
313 while ( my ( $bit, $flag ) = $sth->fetchrow ) {
314 if ( $borrower->{'flags'} && $borrower->{'flags'} & 2**$bit ) {
315 $accessflagshash->{$flag} = 1;
318 $borrower->{'flags'} = $flags;
319 $borrower->{'authflags'} = $accessflagshash;
321 # find out how long the membership lasts
324 "select enrolmentperiod from categories where categorycode = ?");
325 $sth->execute( $borrower->{'categorycode'} );
326 my $enrolment = $sth->fetchrow;
327 $borrower->{'enrolmentperiod'} = $enrolment;
328 return ($borrower); #, $flags, $accessflagshash);
333 $flags = &patronflags($patron);
335 This function is not exported.
337 The following will be set where applicable:
338 $flags->{CHARGES}->{amount} Amount of debt
339 $flags->{CHARGES}->{noissues} Set if debt amount >$5.00 (or syspref noissuescharge)
340 $flags->{CHARGES}->{message} Message -- deprecated
342 $flags->{CREDITS}->{amount} Amount of credit
343 $flags->{CREDITS}->{message} Message -- deprecated
345 $flags->{ GNA } Patron has no valid address
346 $flags->{ GNA }->{noissues} Set for each GNA
347 $flags->{ GNA }->{message} "Borrower has no valid address" -- deprecated
349 $flags->{ LOST } Patron's card reported lost
350 $flags->{ LOST }->{noissues} Set for each LOST
351 $flags->{ LOST }->{message} Message -- deprecated
353 $flags->{DBARRED} Set if patron debarred, no access
354 $flags->{DBARRED}->{noissues} Set for each DBARRED
355 $flags->{DBARRED}->{message} Message -- deprecated
358 $flags->{ NOTES }->{message} The note itself. NOT deprecated
360 $flags->{ ODUES } Set if patron has overdue books.
361 $flags->{ ODUES }->{message} "Yes" -- deprecated
362 $flags->{ ODUES }->{itemlist} ref-to-array: list of overdue books
363 $flags->{ ODUES }->{itemlisttext} Text list of overdue items -- deprecated
365 $flags->{WAITING} Set if any of patron's reserves are available
366 $flags->{WAITING}->{message} Message -- deprecated
367 $flags->{WAITING}->{itemlist} ref-to-array: list of available items
371 C<$flags-E<gt>{ODUES}-E<gt>{itemlist}> is a reference-to-array listing the
372 overdue items. Its elements are references-to-hash, each describing an
373 overdue item. The keys are selected fields from the issues, biblio,
374 biblioitems, and items tables of the Koha database.
376 C<$flags-E<gt>{ODUES}-E<gt>{itemlisttext}> is a string giving a text listing of
377 the overdue items, one per line. Deprecated.
379 C<$flags-E<gt>{WAITING}-E<gt>{itemlist}> is a reference-to-array listing the
380 available items. Each element is a reference-to-hash whose keys are
381 fields from the reserves table of the Koha database.
385 All the "message" fields that include language generated in this function are deprecated,
386 because such strings belong properly in the display layer.
388 The "message" field that comes from the DB is OK.
392 # TODO: use {anonymous => hashes} instead of a dozen %flaginfo
393 # FIXME rename this function.
396 my ( $patroninformation) = @_;
397 my $dbh=C4::Context->dbh;
398 my ($amount) = GetMemberAccountRecords( $patroninformation->{'borrowernumber'});
401 my $noissuescharge = C4::Context->preference("noissuescharge") || 5;
402 $flaginfo{'message'} = sprintf "Patron owes \$%.02f", $amount;
403 $flaginfo{'amount'} = sprintf "%.02f", $amount;
404 if ( $amount > $noissuescharge ) {
405 $flaginfo{'noissues'} = 1;
407 $flags{'CHARGES'} = \%flaginfo;
409 elsif ( $amount < 0 ) {
411 $flaginfo{'message'} = sprintf "Patron has credit of \$%.02f", -$amount;
412 $flaginfo{'amount'} = sprintf "%.02f", $amount;
413 $flags{'CREDITS'} = \%flaginfo;
415 if ( $patroninformation->{'gonenoaddress'}
416 && $patroninformation->{'gonenoaddress'} == 1 )
419 $flaginfo{'message'} = 'Borrower has no valid address.';
420 $flaginfo{'noissues'} = 1;
421 $flags{'GNA'} = \%flaginfo;
423 if ( $patroninformation->{'lost'} && $patroninformation->{'lost'} == 1 ) {
425 $flaginfo{'message'} = 'Borrower\'s card reported lost.';
426 $flaginfo{'noissues'} = 1;
427 $flags{'LOST'} = \%flaginfo;
429 if ( $patroninformation->{'debarred'}
430 && $patroninformation->{'debarred'} == 1 )
433 $flaginfo{'message'} = 'Borrower is Debarred.';
434 $flaginfo{'noissues'} = 1;
435 $flags{'DBARRED'} = \%flaginfo;
437 if ( $patroninformation->{'borrowernotes'}
438 && $patroninformation->{'borrowernotes'} )
441 $flaginfo{'message'} = $patroninformation->{'borrowernotes'};
442 $flags{'NOTES'} = \%flaginfo;
444 my ( $odues, $itemsoverdue ) = checkoverdues($patroninformation->{'borrowernumber'});
447 $flaginfo{'message'} = "Yes";
448 $flaginfo{'itemlist'} = $itemsoverdue;
449 foreach ( sort { $a->{'date_due'} cmp $b->{'date_due'} }
452 $flaginfo{'itemlisttext'} .=
453 "$_->{'date_due'} $_->{'barcode'} $_->{'title'} \n"; # newline is display layer
455 $flags{'ODUES'} = \%flaginfo;
457 my @itemswaiting = C4::Reserves::GetReservesFromBorrowernumber( $patroninformation->{'borrowernumber'},'W' );
458 my $nowaiting = scalar @itemswaiting;
459 if ( $nowaiting > 0 ) {
461 $flaginfo{'message'} = "Reserved items available";
462 $flaginfo{'itemlist'} = \@itemswaiting;
463 $flags{'WAITING'} = \%flaginfo;
471 $borrower = &GetMember(%information);
473 Looks up information about a patron (borrower) by either card number
474 ,firstname, or borrower number, depending on $type value.
475 If C<$type> == 'cardnumber', C<&GetBorrower>
476 searches by cardnumber then by firstname if not found in cardnumber;
477 otherwise, it searches by borrowernumber.
479 C<&GetBorrower> returns a reference-to-hash whose keys are the fields of
480 the C<borrowers> table in the Koha database.
486 my ( %information ) = @_;
487 my $dbh = C4::Context->dbh;
490 SELECT borrowers.*, categories.category_type, categories.description
492 LEFT JOIN categories on borrowers.categorycode=categories.categorycode
494 $select.=" WHERE ".join(" AND ",map {"$_ = ?"}keys %information);
496 $debug && warn $select, " ",values %information;
497 $sth = $dbh->prepare("$select");
498 $sth->execute(map{$information{$_}} keys %information);
499 my $data = $sth->fetchall_arrayref({});
500 return undef if (scalar(@$data)==0);
501 if (scalar(@$data)==1) {return $$data[0];}
502 ($data) and return $data;
506 =head2 IsMemberBlocked
510 my $blocked = IsMemberBlocked( $borrowernumber );
512 return the status, and the number of day or documents, depends his punishment
515 -1 if the user have overdue returns
516 1 if the user is punished X days
517 0 if the user is authorised to loan
523 sub IsMemberBlocked {
524 my $borrowernumber = shift;
525 my $dbh = C4::Context->dbh;
526 # if he have late issues
527 my $sth = $dbh->prepare(
528 "SELECT COUNT(*) as latedocs
530 WHERE borrowernumber = ?
531 AND date_due < now()"
533 $sth->execute($borrowernumber);
534 my $latedocs = $sth->fetchrow_hashref->{'latedocs'};
536 return (-1, $latedocs) if $latedocs > 0;
540 ADDDATE(returndate, finedays * DATEDIFF(returndate,date_due) ) AS blockingdate,
541 DATEDIFF(ADDDATE(returndate, finedays * DATEDIFF(returndate,date_due)),NOW()) AS blockedcount
544 # or if he must wait to loan
545 if(C4::Context->preference("item-level_itypes")){
547 qq{ LEFT JOIN items ON (items.itemnumber=old_issues.itemnumber)
548 LEFT JOIN issuingrules ON (issuingrules.itemtype=items.itype)}
551 qq{ LEFT JOIN items ON (items.itemnumber=old_issues.itemnumber)
552 LEFT JOIN biblioitems ON (biblioitems.biblioitemnumber=items.biblioitemnumber)
553 LEFT JOIN issuingrules ON (issuingrules.itemtype=biblioitems.itemtype) };
556 qq{ WHERE finedays IS NOT NULL
557 AND date_due < returndate
558 AND borrowernumber = ?
559 ORDER BY blockingdate DESC, blockedcount DESC
561 $sth=$dbh->prepare($strsth);
562 $sth->execute($borrowernumber);
563 my $row = $sth->fetchrow_hashref;
564 my $blockeddate = $row->{'blockeddate'};
565 my $blockedcount = $row->{'blockedcount'};
567 return (1, $blockedcount) if $blockedcount > 0;
572 =head2 GetMemberIssuesAndFines
574 ($overdue_count, $issue_count, $total_fines) = &GetMemberIssuesAndFines($borrowernumber);
576 Returns aggregate data about items borrowed by the patron with the
577 given borrowernumber.
579 C<&GetMemberIssuesAndFines> returns a three-element array. C<$overdue_count> is the
580 number of overdue items the patron currently has borrowed. C<$issue_count> is the
581 number of books the patron currently has borrowed. C<$total_fines> is
582 the total fine currently due by the borrower.
587 sub GetMemberIssuesAndFines {
588 my ( $borrowernumber ) = @_;
589 my $dbh = C4::Context->dbh;
590 my $query = "SELECT COUNT(*) FROM issues WHERE borrowernumber = ?";
592 $debug and warn $query."\n";
593 my $sth = $dbh->prepare($query);
594 $sth->execute($borrowernumber);
595 my $issue_count = $sth->fetchrow_arrayref->[0];
597 $sth = $dbh->prepare(
598 "SELECT COUNT(*) FROM issues
599 WHERE borrowernumber = ?
600 AND date_due < now()"
602 $sth->execute($borrowernumber);
603 my $overdue_count = $sth->fetchrow_arrayref->[0];
605 $sth = $dbh->prepare("SELECT SUM(amountoutstanding) FROM accountlines WHERE borrowernumber = ?");
606 $sth->execute($borrowernumber);
607 my $total_fines = $sth->fetchrow_arrayref->[0];
609 return ($overdue_count, $issue_count, $total_fines);
613 return @{C4::Context->dbh->selectcol_arrayref("SHOW columns from borrowers")};
622 my $success = ModMember(borrowernumber => $borrowernumber, [ field => value ]... );
624 Modify borrower's data. All date fields should ALREADY be in ISO format.
627 true on success, or false on failure
634 # test to know if you must update or not the borrower password
635 if (exists $data{password}) {
636 if ($data{password} eq '****' or $data{password} eq '') {
637 delete $data{password};
639 $data{password} = md5_base64($data{password});
642 my $execute_success=UpdateInTable("borrowers",\%data);
643 # ok if its an adult (type) it may have borrowers that depend on it as a guarantor
644 # so when we update information for an adult we should check for guarantees and update the relevant part
645 # of their records, ie addresses and phone numbers
646 my $borrowercategory= GetBorrowercategory( $data{'category_type'} );
647 if ( exists $borrowercategory->{'category_type'} && $borrowercategory->{'category_type'} eq ('A' || 'S') ) {
648 # is adult check guarantees;
649 UpdateGuarantees(%data);
651 logaction("MEMBERS", "MODIFY", $data{'borrowernumber'}, "UPDATE (executed w/ arg: $data{'borrowernumber'})")
652 if C4::Context->preference("BorrowersLog");
654 return $execute_success;
662 $borrowernumber = &AddMember(%borrower);
664 insert new borrower into table
665 Returns the borrowernumber
672 my $dbh = C4::Context->dbh;
673 $data{'userid'} = '' unless $data{'password'};
674 $data{'password'} = md5_base64( $data{'password'} ) if $data{'password'};
675 $data{'borrowernumber'}=InsertInTable("borrowers",\%data);
676 # mysql_insertid is probably bad. not necessarily accurate and mysql-specific at best.
677 logaction("MEMBERS", "CREATE", $data{'borrowernumber'}, "") if C4::Context->preference("BorrowersLog");
679 # check for enrollment fee & add it if needed
680 my $sth = $dbh->prepare("SELECT enrolmentfee FROM categories WHERE categorycode=?");
681 $sth->execute($data{'categorycode'});
682 my ($enrolmentfee) = $sth->fetchrow;
683 if ($enrolmentfee && $enrolmentfee > 0) {
684 # insert fee in patron debts
685 manualinvoice($data{'borrowernumber'}, '', '', 'A', $enrolmentfee);
687 return $data{'borrowernumber'};
692 my ($uid,$member) = @_;
693 my $dbh = C4::Context->dbh;
694 # Make sure the userid chosen is unique and not theirs if non-empty. If it is not,
695 # Then we need to tell the user and have them create a new one.
698 "SELECT * FROM borrowers WHERE userid=? AND borrowernumber != ?");
699 $sth->execute( $uid, $member );
700 if ( ( $uid ne '' ) && ( my $row = $sth->fetchrow_hashref ) ) {
708 sub Generate_Userid {
709 my ($borrowernumber, $firstname, $surname) = @_;
713 $firstname =~ s/[[:digit:][:space:][:blank:][:punct:][:cntrl:]]//g;
714 $surname =~ s/[[:digit:][:space:][:blank:][:punct:][:cntrl:]]//g;
715 $newuid = lc("$firstname.$surname");
716 $newuid .= $offset unless $offset == 0;
719 } while (!Check_Userid($newuid,$borrowernumber));
725 my ( $uid, $member, $digest ) = @_;
726 my $dbh = C4::Context->dbh;
728 #Make sure the userid chosen is unique and not theirs if non-empty. If it is not,
729 #Then we need to tell the user and have them create a new one.
733 "SELECT * FROM borrowers WHERE userid=? AND borrowernumber != ?");
734 $sth->execute( $uid, $member );
735 if ( ( $uid ne '' ) && ( my $row = $sth->fetchrow_hashref ) ) {
739 #Everything is good so we can update the information.
742 "update borrowers set userid=?, password=? where borrowernumber=?");
743 $sth->execute( $uid, $digest, $member );
747 logaction("MEMBERS", "CHANGE PASS", $member, "") if C4::Context->preference("BorrowersLog");
753 =head2 fixup_cardnumber
755 Warning: The caller is responsible for locking the members table in write
756 mode, to avoid database corruption.
760 use vars qw( @weightings );
761 my @weightings = ( 8, 4, 6, 3, 5, 2, 1 );
763 sub fixup_cardnumber ($) {
764 my ($cardnumber) = @_;
765 my $autonumber_members = C4::Context->boolean_preference('autoMemberNum') || 0;
767 # Find out whether member numbers should be generated
768 # automatically. Should be either "1" or something else.
769 # Defaults to "0", which is interpreted as "no".
771 # if ($cardnumber !~ /\S/ && $autonumber_members) {
772 ($autonumber_members) or return $cardnumber;
773 my $checkdigit = C4::Context->preference('checkdigit');
774 my $dbh = C4::Context->dbh;
775 if ( $checkdigit and $checkdigit eq 'katipo' ) {
777 # if checkdigit is selected, calculate katipo-style cardnumber.
778 # otherwise, just use the max()
779 # purpose: generate checksum'd member numbers.
780 # We'll assume we just got the max value of digits 2-8 of member #'s
781 # from the database and our job is to increment that by one,
782 # determine the 1st and 9th digits and return the full string.
783 my $sth = $dbh->prepare(
784 "select max(substring(borrowers.cardnumber,2,7)) as new_num from borrowers"
787 my $data = $sth->fetchrow_hashref;
788 $cardnumber = $data->{new_num};
789 if ( !$cardnumber ) { # If DB has no values,
790 $cardnumber = 1000000; # start at 1000000
796 for ( my $i = 0 ; $i < 8 ; $i += 1 ) {
797 # read weightings, left to right, 1 char at a time
798 my $temp1 = $weightings[$i];
800 # sequence left to right, 1 char at a time
801 my $temp2 = substr( $cardnumber, $i, 1 );
803 # mult each char 1-7 by its corresponding weighting
804 $sum += $temp1 * $temp2;
807 my $rem = ( $sum % 11 );
808 $rem = 'X' if $rem == 10;
810 return "V$cardnumber$rem";
813 # MODIFIED BY JF: mysql4.1 allows casting as an integer, which is probably
814 # better. I'll leave the original in in case it needs to be changed for you
815 # my $sth=$dbh->prepare("select max(borrowers.cardnumber) from borrowers");
816 my $sth = $dbh->prepare(
817 "select max(cast(cardnumber as signed)) from borrowers"
820 my ($result) = $sth->fetchrow;
823 return $cardnumber; # just here as a fallback/reminder
828 ($num_children, $children_arrayref) = &GetGuarantees($parent_borrno);
829 $child0_cardno = $children_arrayref->[0]{"cardnumber"};
830 $child0_borrno = $children_arrayref->[0]{"borrowernumber"};
832 C<&GetGuarantees> takes a borrower number (e.g., that of a patron
833 with children) and looks up the borrowers who are guaranteed by that
834 borrower (i.e., the patron's children).
836 C<&GetGuarantees> returns two values: an integer giving the number of
837 borrowers guaranteed by C<$parent_borrno>, and a reference to an array
838 of references to hash, which gives the actual results.
844 my ($borrowernumber) = @_;
845 my $dbh = C4::Context->dbh;
848 "select cardnumber,borrowernumber, firstname, surname from borrowers where guarantorid=?"
850 $sth->execute($borrowernumber);
853 my $data = $sth->fetchall_arrayref({});
854 return ( scalar(@$data), $data );
857 =head2 UpdateGuarantees
859 &UpdateGuarantees($parent_borrno);
862 C<&UpdateGuarantees> borrower data for an adult and updates all the guarantees
863 with the modified information
868 sub UpdateGuarantees {
870 my $dbh = C4::Context->dbh;
871 my ( $count, $guarantees ) = GetGuarantees( $data{'borrowernumber'} );
872 for ( my $i = 0 ; $i < $count ; $i++ ) {
875 # It looks like the $i is only being returned to handle walking through
876 # the array, which is probably better done as a foreach loop.
878 my $guaquery = qq|UPDATE borrowers
879 SET address='$data{'address'}',fax='$data{'fax'}',
880 B_city='$data{'B_city'}',mobile='$data{'mobile'}',city='$data{'city'}',phone='$data{'phone'}'
881 WHERE borrowernumber='$guarantees->[$i]->{'borrowernumber'}'
883 my $sth3 = $dbh->prepare($guaquery);
887 =head2 GetPendingIssues
889 my $issues = &GetPendingIssues($borrowernumber);
891 Looks up what the patron with the given borrowernumber has borrowed.
893 C<&GetPendingIssues> returns a
894 reference-to-array where each element is a reference-to-hash; the
895 keys are the fields from the C<issues>, C<biblio>, and C<items> tables.
896 The keys include C<biblioitems> fields except marc and marcxml.
901 sub GetPendingIssues {
902 my ($borrowernumber) = @_;
903 # must avoid biblioitems.* to prevent large marc and marcxml fields from killing performance
904 # FIXME: namespace collision: each table has "timestamp" fields. Which one is "timestamp" ?
905 # FIXME: circ/ciculation.pl tries to sort by timestamp!
906 # FIXME: C4::Print::printslip tries to sort by timestamp!
907 # FIXME: namespace collision: other collisions possible.
908 # FIXME: most of this data isn't really being used by callers.
909 my $sth = C4::Context->dbh->prepare(
915 biblioitems.itemtype,
918 biblioitems.publicationyear,
919 biblioitems.publishercode,
920 biblioitems.volumedate,
921 biblioitems.volumedesc,
924 issues.timestamp AS timestamp,
925 issues.renewals AS renewals,
926 items.renewals AS totalrenewals
928 LEFT JOIN items ON items.itemnumber = issues.itemnumber
929 LEFT JOIN biblio ON items.biblionumber = biblio.biblionumber
930 LEFT JOIN biblioitems ON items.biblioitemnumber = biblioitems.biblioitemnumber
933 ORDER BY issues.issuedate"
935 $sth->execute($borrowernumber);
936 my $data = $sth->fetchall_arrayref({});
937 my $today = C4::Dates->new->output('iso');
939 $_->{date_due} or next;
940 ($_->{date_due} lt $today) and $_->{overdue} = 1;
947 ($count, $issues) = &GetAllIssues($borrowernumber, $sortkey, $limit);
949 Looks up what the patron with the given borrowernumber has borrowed,
950 and sorts the results.
952 C<$sortkey> is the name of a field on which to sort the results. This
953 should be the name of a field in the C<issues>, C<biblio>,
954 C<biblioitems>, or C<items> table in the Koha database.
956 C<$limit> is the maximum number of results to return.
958 C<&GetAllIssues> returns a two-element array. C<$issues> is a
959 reference-to-array, where each element is a reference-to-hash; the
960 keys are the fields from the C<issues>, C<biblio>, C<biblioitems>, and
961 C<items> tables of the Koha database. C<$count> is the number of
962 elements in C<$issues>
968 my ( $borrowernumber, $order, $limit ) = @_;
970 #FIXME: sanity-check order and limit
971 my $dbh = C4::Context->dbh;
974 "SELECT *,issues.renewals AS renewals,items.renewals AS totalrenewals,items.timestamp AS itemstimestamp
976 LEFT JOIN items on items.itemnumber=issues.itemnumber
977 LEFT JOIN biblio ON items.biblionumber=biblio.biblionumber
978 LEFT JOIN biblioitems ON items.biblioitemnumber=biblioitems.biblioitemnumber
979 WHERE borrowernumber=?
981 SELECT *,old_issues.renewals AS renewals,items.renewals AS totalrenewals,items.timestamp AS itemstimestamp
983 LEFT JOIN items on items.itemnumber=old_issues.itemnumber
984 LEFT JOIN biblio ON items.biblionumber=biblio.biblionumber
985 LEFT JOIN biblioitems ON items.biblioitemnumber=biblioitems.biblioitemnumber
986 WHERE borrowernumber=?
989 $query .= " limit $limit";
993 my $sth = $dbh->prepare($query);
994 $sth->execute($borrowernumber, $borrowernumber);
997 while ( my $data = $sth->fetchrow_hashref ) {
1003 # get all issued items for borrowernumber from oldissues table
1004 # large chunk of older issues data put into table oldissues
1005 # to speed up db calls for issuing items
1006 if ( C4::Context->preference("ReadingHistory") ) {
1007 # FIXME oldissues (not to be confused with old_issues) is
1008 # apparently specific to HLT. Not sure if the ReadingHistory
1009 # syspref is still required, as old_issues by design
1010 # is no longer checked with each loan.
1011 my $query2 = "SELECT * FROM oldissues
1012 LEFT JOIN items ON items.itemnumber=oldissues.itemnumber
1013 LEFT JOIN biblio ON items.biblionumber=biblio.biblionumber
1014 LEFT JOIN biblioitems ON items.biblioitemnumber=biblioitems.biblioitemnumber
1015 WHERE borrowernumber=?
1017 if ( $limit != 0 ) {
1018 $limit = $limit - $count;
1019 $query2 .= " limit $limit";
1022 my $sth2 = $dbh->prepare($query2);
1023 $sth2->execute($borrowernumber);
1025 while ( my $data2 = $sth2->fetchrow_hashref ) {
1026 $result[$i] = $data2;
1031 return ( $i, \@result );
1035 =head2 GetMemberAccountRecords
1037 ($total, $acctlines, $count) = &GetMemberAccountRecords($borrowernumber);
1039 Looks up accounting data for the patron with the given borrowernumber.
1041 C<&GetMemberAccountRecords> returns a three-element array. C<$acctlines> is a
1042 reference-to-array, where each element is a reference-to-hash; the
1043 keys are the fields of the C<accountlines> table in the Koha database.
1044 C<$count> is the number of elements in C<$acctlines>. C<$total> is the
1045 total amount outstanding for all of the account lines.
1050 sub GetMemberAccountRecords {
1051 my ($borrowernumber,$date) = @_;
1052 my $dbh = C4::Context->dbh;
1058 WHERE borrowernumber=?);
1059 my @bind = ($borrowernumber);
1060 if ($date && $date ne ''){
1061 $strsth.=" AND date < ? ";
1064 $strsth.=" ORDER BY date desc,timestamp DESC";
1065 my $sth= $dbh->prepare( $strsth );
1066 $sth->execute( @bind );
1068 while ( my $data = $sth->fetchrow_hashref ) {
1069 my $biblio = GetBiblioFromItemNumber($data->{itemnumber}) if $data->{itemnumber};
1070 $data->{biblionumber} = $biblio->{biblionumber};
1071 $data->{title} = $biblio->{title};
1072 $acctlines[$numlines] = $data;
1074 $total += int(1000 * $data->{'amountoutstanding'}); # convert float to integer to avoid round-off errors
1077 return ( $total, \@acctlines,$numlines);
1080 =head2 GetBorNotifyAcctRecord
1082 ($count, $acctlines, $total) = &GetBorNotifyAcctRecord($params,$notifyid);
1084 Looks up accounting data for the patron with the given borrowernumber per file number.
1086 (FIXME - I'm not at all sure what this is about.)
1088 C<&GetBorNotifyAcctRecord> returns a three-element array. C<$acctlines> is a
1089 reference-to-array, where each element is a reference-to-hash; the
1090 keys are the fields of the C<accountlines> table in the Koha database.
1091 C<$count> is the number of elements in C<$acctlines>. C<$total> is the
1092 total amount outstanding for all of the account lines.
1096 sub GetBorNotifyAcctRecord {
1097 my ( $borrowernumber, $notifyid ) = @_;
1098 my $dbh = C4::Context->dbh;
1101 my $sth = $dbh->prepare(
1104 WHERE borrowernumber=?
1106 AND amountoutstanding != '0'
1107 ORDER BY notify_id,accounttype
1109 # AND (accounttype='FU' OR accounttype='N' OR accounttype='M'OR accounttype='A'OR accounttype='F'OR accounttype='L' OR accounttype='IP' OR accounttype='CH' OR accounttype='RE' OR accounttype='RL')
1111 $sth->execute( $borrowernumber, $notifyid );
1113 while ( my $data = $sth->fetchrow_hashref ) {
1114 $acctlines[$numlines] = $data;
1116 $total += int(100 * $data->{'amountoutstanding'});
1119 return ( $total, \@acctlines, $numlines );
1122 =head2 checkuniquemember (OUEST-PROVENCE)
1124 ($result,$categorycode) = &checkuniquemember($collectivity,$surname,$firstname,$dateofbirth);
1126 Checks that a member exists or not in the database.
1128 C<&result> is nonzero (=exist) or 0 (=does not exist)
1129 C<&categorycode> is from categorycode table
1130 C<&collectivity> is 1 (= we add a collectivity) or 0 (= we add a physical member)
1131 C<&surname> is the surname
1132 C<&firstname> is the firstname (only if collectivity=0)
1133 C<&dateofbirth> is the date of birth in ISO format (only if collectivity=0)
1137 # FIXME: This function is not legitimate. Multiple patrons might have the same first/last name and birthdate.
1138 # This is especially true since first name is not even a required field.
1140 sub checkuniquemember {
1141 my ( $collectivity, $surname, $firstname, $dateofbirth ) = @_;
1142 my $dbh = C4::Context->dbh;
1143 my $request = ($collectivity) ?
1144 "SELECT borrowernumber,categorycode FROM borrowers WHERE surname=? " :
1146 "SELECT borrowernumber,categorycode FROM borrowers WHERE surname=? and firstname=? and dateofbirth=?" :
1147 "SELECT borrowernumber,categorycode FROM borrowers WHERE surname=? and firstname=?";
1148 my $sth = $dbh->prepare($request);
1149 if ($collectivity) {
1150 $sth->execute( uc($surname) );
1151 } elsif($dateofbirth){
1152 $sth->execute( uc($surname), ucfirst($firstname), $dateofbirth );
1154 $sth->execute( uc($surname), ucfirst($firstname));
1156 my @data = $sth->fetchrow;
1157 ( $data[0] ) and return $data[0], $data[1];
1161 sub checkcardnumber {
1162 my ($cardnumber,$borrowernumber) = @_;
1163 my $dbh = C4::Context->dbh;
1164 my $query = "SELECT * FROM borrowers WHERE cardnumber=?";
1165 $query .= " AND borrowernumber <> ?" if ($borrowernumber);
1166 my $sth = $dbh->prepare($query);
1167 if ($borrowernumber) {
1168 $sth->execute($cardnumber,$borrowernumber);
1170 $sth->execute($cardnumber);
1172 if (my $data= $sth->fetchrow_hashref()){
1181 =head2 getzipnamecity (OUEST-PROVENCE)
1183 take all info from table city for the fields city and zip
1184 check for the name and the zip code of the city selected
1188 sub getzipnamecity {
1190 my $dbh = C4::Context->dbh;
1193 "select city_name,city_zipcode from cities where cityid=? ");
1194 $sth->execute($cityid);
1195 my @data = $sth->fetchrow;
1196 return $data[0], $data[1];
1200 =head2 getdcity (OUEST-PROVENCE)
1202 recover cityid with city_name condition
1207 my ($city_name) = @_;
1208 my $dbh = C4::Context->dbh;
1209 my $sth = $dbh->prepare("select cityid from cities where city_name=? ");
1210 $sth->execute($city_name);
1211 my $data = $sth->fetchrow;
1216 =head2 GetExpiryDate
1218 $expirydate = GetExpiryDate($categorycode, $dateenrolled);
1220 Calculate expiry date given a categorycode and starting date. Date argument must be in ISO format.
1221 Return date is also in ISO format.
1226 my ( $categorycode, $dateenrolled ) = @_;
1227 my $enrolmentperiod = 12; # reasonable default
1228 if ($categorycode) {
1229 my $dbh = C4::Context->dbh;
1230 my $sth = $dbh->prepare("select enrolmentperiod from categories where categorycode=?");
1231 $sth->execute($categorycode);
1232 $enrolmentperiod = $sth->fetchrow;
1234 # die "GetExpiryDate: for enrollmentperiod $enrolmentperiod (category '$categorycode') starting $dateenrolled.\n";
1235 my @date = split /-/,$dateenrolled;
1236 return sprintf("%04d-%02d-%02d", Add_Delta_YM(@date,0,$enrolmentperiod));
1239 =head2 checkuserpassword (OUEST-PROVENCE)
1241 check for the password and login are not used
1242 return the number of record
1243 0=> NOT USED 1=> USED
1247 sub checkuserpassword {
1248 my ( $borrowernumber, $userid, $password ) = @_;
1249 $password = md5_base64($password);
1250 my $dbh = C4::Context->dbh;
1253 "Select count(*) from borrowers where borrowernumber !=? and userid =? and password=? "
1255 $sth->execute( $borrowernumber, $userid, $password );
1256 my $number_rows = $sth->fetchrow;
1257 return $number_rows;
1261 =head2 GetborCatFromCatType
1263 ($codes_arrayref, $labels_hashref) = &GetborCatFromCatType();
1265 Looks up the different types of borrowers in the database. Returns two
1266 elements: a reference-to-array, which lists the borrower category
1267 codes, and a reference-to-hash, which maps the borrower category codes
1268 to category descriptions.
1273 sub GetborCatFromCatType {
1274 my ( $category_type, $action ) = @_;
1275 # FIXME - This API seems both limited and dangerous.
1276 my $dbh = C4::Context->dbh;
1277 my $request = qq| SELECT categorycode,description
1280 ORDER BY categorycode|;
1281 my $sth = $dbh->prepare($request);
1283 $sth->execute($category_type);
1292 while ( my $data = $sth->fetchrow_hashref ) {
1293 push @codes, $data->{'categorycode'};
1294 $labels{ $data->{'categorycode'} } = $data->{'description'};
1296 return ( \@codes, \%labels );
1299 =head2 GetBorrowercategory
1301 $hashref = &GetBorrowercategory($categorycode);
1303 Given the borrower's category code, the function returns the corresponding
1304 data hashref for a comprehensive information display.
1306 $arrayref_hashref = &GetBorrowercategory;
1307 If no category code provided, the function returns all the categories.
1311 sub GetBorrowercategory {
1313 my $dbh = C4::Context->dbh;
1317 "SELECT description,dateofbirthrequired,upperagelimit,category_type
1319 WHERE categorycode = ?"
1321 $sth->execute($catcode);
1323 $sth->fetchrow_hashref;
1327 } # sub getborrowercategory
1329 =head2 GetBorrowercategoryList
1331 $arrayref_hashref = &GetBorrowercategoryList;
1332 If no category code provided, the function returns all the categories.
1336 sub GetBorrowercategoryList {
1337 my $dbh = C4::Context->dbh;
1342 ORDER BY description"
1346 $sth->fetchall_arrayref({});
1348 } # sub getborrowercategory
1350 =head2 ethnicitycategories
1352 ($codes_arrayref, $labels_hashref) = ðnicitycategories();
1354 Looks up the different ethnic types in the database. Returns two
1355 elements: a reference-to-array, which lists the ethnicity codes, and a
1356 reference-to-hash, which maps the ethnicity codes to ethnicity
1363 sub ethnicitycategories {
1364 my $dbh = C4::Context->dbh;
1365 my $sth = $dbh->prepare("Select code,name from ethnicity order by name");
1369 while ( my $data = $sth->fetchrow_hashref ) {
1370 push @codes, $data->{'code'};
1371 $labels{ $data->{'code'} } = $data->{'name'};
1373 return ( \@codes, \%labels );
1378 $ethn_name = &fixEthnicity($ethn_code);
1380 Takes an ethnicity code (e.g., "european" or "pi") and returns the
1381 corresponding descriptive name from the C<ethnicity> table in the
1382 Koha database ("European" or "Pacific Islander").
1389 my $ethnicity = shift;
1390 return unless $ethnicity;
1391 my $dbh = C4::Context->dbh;
1392 my $sth = $dbh->prepare("Select name from ethnicity where code = ?");
1393 $sth->execute($ethnicity);
1394 my $data = $sth->fetchrow_hashref;
1395 return $data->{'name'};
1396 } # sub fixEthnicity
1400 $dateofbirth,$date = &GetAge($date);
1402 this function return the borrowers age with the value of dateofbirth
1408 my ( $date, $date_ref ) = @_;
1410 if ( not defined $date_ref ) {
1411 $date_ref = sprintf( '%04d-%02d-%02d', Today() );
1414 my ( $year1, $month1, $day1 ) = split /-/, $date;
1415 my ( $year2, $month2, $day2 ) = split /-/, $date_ref;
1417 my $age = $year2 - $year1;
1418 if ( $month1 . $day1 > $month2 . $day2 ) {
1425 =head2 get_institutions
1426 $insitutions = get_institutions();
1428 Just returns a list of all the borrowers of type I, borrownumber and name
1433 sub get_institutions {
1434 my $dbh = C4::Context->dbh();
1437 "SELECT borrowernumber,surname FROM borrowers WHERE categorycode=? ORDER BY surname"
1441 while ( my $data = $sth->fetchrow_hashref() ) {
1442 $orgs{ $data->{'borrowernumber'} } = $data;
1446 } # sub get_institutions
1448 =head2 add_member_orgs
1450 add_member_orgs($borrowernumber,$borrowernumbers);
1452 Takes a borrowernumber and a list of other borrowernumbers and inserts them into the borrowers_to_borrowers table
1457 sub add_member_orgs {
1458 my ( $borrowernumber, $otherborrowers ) = @_;
1459 my $dbh = C4::Context->dbh();
1461 "INSERT INTO borrowers_to_borrowers (borrower1,borrower2) VALUES (?,?)";
1462 my $sth = $dbh->prepare($query);
1463 foreach my $otherborrowernumber (@$otherborrowers) {
1464 $sth->execute( $borrowernumber, $otherborrowernumber );
1467 } # sub add_member_orgs
1469 =head2 GetCities (OUEST-PROVENCE)
1471 ($id_cityarrayref, $city_hashref) = &GetCities();
1473 Looks up the different city and zip in the database. Returns two
1474 elements: a reference-to-array, which lists the zip city
1475 codes, and a reference-to-hash, which maps the name of the city.
1476 WHERE =>OUEST PROVENCE OR EXTERIEUR
1482 #my ($type_city) = @_;
1483 my $dbh = C4::Context->dbh;
1484 my $query = qq|SELECT cityid,city_zipcode,city_name
1486 ORDER BY city_name|;
1487 my $sth = $dbh->prepare($query);
1489 #$sth->execute($type_city);
1493 # insert empty value to create a empty choice in cgi popup
1496 while ( my $data = $sth->fetchrow_hashref ) {
1497 push @id, $data->{'city_zipcode'}."|".$data->{'city_name'};
1498 $city{ $data->{'city_zipcode'}."|".$data->{'city_name'} } = $data->{'city_name'};
1501 #test to know if the table contain some records if no the function return nothing
1504 # all we have is the one blank row
1509 return ( \@id, \%city );
1513 =head2 GetSortDetails (OUEST-PROVENCE)
1515 ($lib) = &GetSortDetails($category,$sortvalue);
1517 Returns the authorized value details
1518 C<&$lib>return value of authorized value details
1519 C<&$sortvalue>this is the value of authorized value
1520 C<&$category>this is the value of authorized value category
1524 sub GetSortDetails {
1525 my ( $category, $sortvalue ) = @_;
1526 my $dbh = C4::Context->dbh;
1527 my $query = qq|SELECT lib
1528 FROM authorised_values
1530 AND authorised_value=? |;
1531 my $sth = $dbh->prepare($query);
1532 $sth->execute( $category, $sortvalue );
1533 my $lib = $sth->fetchrow;
1534 return ($lib) if ($lib);
1535 return ($sortvalue) unless ($lib);
1538 =head2 MoveMemberToDeleted
1540 $result = &MoveMemberToDeleted($borrowernumber);
1542 Copy the record from borrowers to deletedborrowers table.
1546 # FIXME: should do it in one SQL statement w/ subquery
1547 # Otherwise, we should return the @data on success
1549 sub MoveMemberToDeleted {
1550 my ($member) = shift or return;
1551 my $dbh = C4::Context->dbh;
1552 my $query = qq|SELECT *
1554 WHERE borrowernumber=?|;
1555 my $sth = $dbh->prepare($query);
1556 $sth->execute($member);
1557 my @data = $sth->fetchrow_array;
1558 (@data) or return; # if we got a bad borrowernumber, there's nothing to insert
1560 $dbh->prepare( "INSERT INTO deletedborrowers VALUES ("
1561 . ( "?," x ( scalar(@data) - 1 ) )
1563 $sth->execute(@data);
1568 DelMember($borrowernumber);
1570 This function remove directly a borrower whitout writing it on deleteborrower.
1571 + Deletes reserves for the borrower
1576 my $dbh = C4::Context->dbh;
1577 my $borrowernumber = shift;
1578 #warn "in delmember with $borrowernumber";
1579 return unless $borrowernumber; # borrowernumber is mandatory.
1581 my $query = qq|DELETE
1583 WHERE borrowernumber=?|;
1584 my $sth = $dbh->prepare($query);
1585 $sth->execute($borrowernumber);
1589 WHERE borrowernumber = ?
1591 $sth = $dbh->prepare($query);
1592 $sth->execute($borrowernumber);
1593 logaction("MEMBERS", "DELETE", $borrowernumber, "") if C4::Context->preference("BorrowersLog");
1597 =head2 ExtendMemberSubscriptionTo (OUEST-PROVENCE)
1599 $date = ExtendMemberSubscriptionTo($borrowerid, $date);
1601 Extending the subscription to a given date or to the expiry date calculated on ISO date.
1606 sub ExtendMemberSubscriptionTo {
1607 my ( $borrowerid,$date) = @_;
1608 my $dbh = C4::Context->dbh;
1609 my $borrower = GetMember('borrowernumber'=>$borrowerid);
1611 $date=POSIX::strftime("%Y-%m-%d",localtime());
1612 $date = GetExpiryDate( $borrower->{'categorycode'}, $date );
1614 my $sth = $dbh->do(<<EOF);
1616 SET dateexpiry='$date'
1617 WHERE borrowernumber='$borrowerid'
1619 # add enrolmentfee if needed
1620 $sth = $dbh->prepare("SELECT enrolmentfee FROM categories WHERE categorycode=?");
1621 $sth->execute($borrower->{'categorycode'});
1622 my ($enrolmentfee) = $sth->fetchrow;
1623 if ($enrolmentfee && $enrolmentfee > 0) {
1624 # insert fee in patron debts
1625 manualinvoice($borrower->{'borrowernumber'}, '', '', 'A', $enrolmentfee);
1627 return $date if ($sth);
1631 =head2 GetRoadTypes (OUEST-PROVENCE)
1633 ($idroadtypearrayref, $roadttype_hashref) = &GetRoadTypes();
1635 Looks up the different road type . Returns two
1636 elements: a reference-to-array, which lists the id_roadtype
1637 codes, and a reference-to-hash, which maps the road type of the road .
1642 my $dbh = C4::Context->dbh;
1644 SELECT roadtypeid,road_type
1646 ORDER BY road_type|;
1647 my $sth = $dbh->prepare($query);
1652 # insert empty value to create a empty choice in cgi popup
1654 while ( my $data = $sth->fetchrow_hashref ) {
1656 push @id, $data->{'roadtypeid'};
1657 $roadtype{ $data->{'roadtypeid'} } = $data->{'road_type'};
1660 #test to know if the table contain some records if no the function return nothing
1667 return ( \@id, \%roadtype );
1673 =head2 GetTitles (OUEST-PROVENCE)
1675 ($borrowertitle)= &GetTitles();
1677 Looks up the different title . Returns array with all borrowers title
1682 my @borrowerTitle = split /,|\|/,C4::Context->preference('BorrowersTitles');
1683 unshift( @borrowerTitle, "" );
1684 my $count=@borrowerTitle;
1689 return ( \@borrowerTitle);
1693 =head2 GetPatronImage
1695 my ($imagedata, $dberror) = GetPatronImage($cardnumber);
1697 Returns the mimetype and binary image data of the image for the patron with the supplied cardnumber.
1701 sub GetPatronImage {
1702 my ($cardnumber) = @_;
1703 warn "Cardnumber passed to GetPatronImage is $cardnumber" if $debug;
1704 my $dbh = C4::Context->dbh;
1705 my $query = 'SELECT mimetype, imagefile FROM patronimage WHERE cardnumber = ?';
1706 my $sth = $dbh->prepare($query);
1707 $sth->execute($cardnumber);
1708 my $imagedata = $sth->fetchrow_hashref;
1709 warn "Database error!" if $sth->errstr;
1710 return $imagedata, $sth->errstr;
1713 =head2 PutPatronImage
1715 PutPatronImage($cardnumber, $mimetype, $imgfile);
1717 Stores patron binary image data and mimetype in database.
1718 NOTE: This function is good for updating images as well as inserting new images in the database.
1722 sub PutPatronImage {
1723 my ($cardnumber, $mimetype, $imgfile) = @_;
1724 warn "Parameters passed in: Cardnumber=$cardnumber, Mimetype=$mimetype, " . ($imgfile ? "Imagefile" : "No Imagefile") if $debug;
1725 my $dbh = C4::Context->dbh;
1726 my $query = "INSERT INTO patronimage (cardnumber, mimetype, imagefile) VALUES (?,?,?) ON DUPLICATE KEY UPDATE imagefile = ?;";
1727 my $sth = $dbh->prepare($query);
1728 $sth->execute($cardnumber,$mimetype,$imgfile,$imgfile);
1729 warn "Error returned inserting $cardnumber.$mimetype." if $sth->errstr;
1730 return $sth->errstr;
1733 =head2 RmPatronImage
1735 my ($dberror) = RmPatronImage($cardnumber);
1737 Removes the image for the patron with the supplied cardnumber.
1742 my ($cardnumber) = @_;
1743 warn "Cardnumber passed to GetPatronImage is $cardnumber" if $debug;
1744 my $dbh = C4::Context->dbh;
1745 my $query = "DELETE FROM patronimage WHERE cardnumber = ?;";
1746 my $sth = $dbh->prepare($query);
1747 $sth->execute($cardnumber);
1748 my $dberror = $sth->errstr;
1749 warn "Database error!" if $sth->errstr;
1753 =head2 GetRoadTypeDetails (OUEST-PROVENCE)
1755 ($roadtype) = &GetRoadTypeDetails($roadtypeid);
1757 Returns the description of roadtype
1758 C<&$roadtype>return description of road type
1759 C<&$roadtypeid>this is the value of roadtype s
1763 sub GetRoadTypeDetails {
1764 my ($roadtypeid) = @_;
1765 my $dbh = C4::Context->dbh;
1769 WHERE roadtypeid=?|;
1770 my $sth = $dbh->prepare($query);
1771 $sth->execute($roadtypeid);
1772 my $roadtype = $sth->fetchrow;
1776 =head2 GetBorrowersWhoHaveNotBorrowedSince
1778 &GetBorrowersWhoHaveNotBorrowedSince($date)
1780 this function get all borrowers who haven't borrowed since the date given on input arg.
1784 sub GetBorrowersWhoHaveNotBorrowedSince {
1785 ### TODO : It could be dangerous to delete Borrowers who have just been entered and who have not yet borrowed any book. May be good to add a dateexpiry or dateenrolled filter.
1787 my $filterdate = shift||POSIX::strftime("%Y-%m-%d",localtime());
1788 my $filterbranch = shift ||
1789 ((C4::Context->preference('IndependantBranches')
1790 && C4::Context->userenv
1791 && C4::Context->userenv->{flags} % 2 !=1
1792 && C4::Context->userenv->{branch})
1793 ? C4::Context->userenv->{branch}
1795 my $dbh = C4::Context->dbh;
1797 SELECT borrowers.borrowernumber,max(issues.timestamp) as latestissue
1799 JOIN categories USING (categorycode)
1800 LEFT JOIN issues ON borrowers.borrowernumber = issues.borrowernumber
1801 WHERE category_type <> 'S'
1804 if ($filterbranch && $filterbranch ne ""){
1805 $query.=" AND borrowers.branchcode= ?";
1806 push @query_params,$filterbranch;
1808 $query.=" GROUP BY borrowers.borrowernumber";
1810 $query.=" HAVING latestissue <? OR latestissue IS NULL";
1811 push @query_params,$filterdate;
1813 warn $query if $debug;
1814 my $sth = $dbh->prepare($query);
1815 if (scalar(@query_params)>0){
1816 $sth->execute(@query_params);
1823 while ( my $data = $sth->fetchrow_hashref ) {
1824 push @results, $data;
1829 =head2 GetBorrowersWhoHaveNeverBorrowed
1831 $results = &GetBorrowersWhoHaveNeverBorrowed
1833 this function get all borrowers who have never borrowed.
1835 I<$result> is a ref to an array which all elements are a hasref.
1839 sub GetBorrowersWhoHaveNeverBorrowed {
1840 my $filterbranch = shift ||
1841 ((C4::Context->preference('IndependantBranches')
1842 && C4::Context->userenv
1843 && C4::Context->userenv->{flags} % 2 !=1
1844 && C4::Context->userenv->{branch})
1845 ? C4::Context->userenv->{branch}
1847 my $dbh = C4::Context->dbh;
1849 SELECT borrowers.borrowernumber,max(timestamp) as latestissue
1851 LEFT JOIN issues ON borrowers.borrowernumber = issues.borrowernumber
1852 WHERE issues.borrowernumber IS NULL
1855 if ($filterbranch && $filterbranch ne ""){
1856 $query.=" AND borrowers.branchcode= ?";
1857 push @query_params,$filterbranch;
1859 warn $query if $debug;
1861 my $sth = $dbh->prepare($query);
1862 if (scalar(@query_params)>0){
1863 $sth->execute(@query_params);
1870 while ( my $data = $sth->fetchrow_hashref ) {
1871 push @results, $data;
1876 =head2 GetBorrowersWithIssuesHistoryOlderThan
1878 $results = &GetBorrowersWithIssuesHistoryOlderThan($date)
1880 this function get all borrowers who has an issue history older than I<$date> given on input arg.
1882 I<$result> is a ref to an array which all elements are a hashref.
1883 This hashref is containt the number of time this borrowers has borrowed before I<$date> and the borrowernumber.
1887 sub GetBorrowersWithIssuesHistoryOlderThan {
1888 my $dbh = C4::Context->dbh;
1889 my $date = shift ||POSIX::strftime("%Y-%m-%d",localtime());
1890 my $filterbranch = shift ||
1891 ((C4::Context->preference('IndependantBranches')
1892 && C4::Context->userenv
1893 && C4::Context->userenv->{flags} % 2 !=1
1894 && C4::Context->userenv->{branch})
1895 ? C4::Context->userenv->{branch}
1898 SELECT count(borrowernumber) as n,borrowernumber
1900 WHERE returndate < ?
1901 AND borrowernumber IS NOT NULL
1904 push @query_params, $date;
1906 $query.=" AND branchcode = ?";
1907 push @query_params, $filterbranch;
1909 $query.=" GROUP BY borrowernumber ";
1910 warn $query if $debug;
1911 my $sth = $dbh->prepare($query);
1912 $sth->execute(@query_params);
1915 while ( my $data = $sth->fetchrow_hashref ) {
1916 push @results, $data;
1921 =head2 GetBorrowersNamesAndLatestIssue
1923 $results = &GetBorrowersNamesAndLatestIssueList(@borrowernumbers)
1925 this function get borrowers Names and surnames and Issue information.
1927 I<@borrowernumbers> is an array which all elements are borrowernumbers.
1928 This hashref is containt the number of time this borrowers has borrowed before I<$date> and the borrowernumber.
1932 sub GetBorrowersNamesAndLatestIssue {
1933 my $dbh = C4::Context->dbh;
1934 my @borrowernumbers=@_;
1936 SELECT surname,lastname, phone, email,max(timestamp)
1938 LEFT JOIN issues ON borrowers.borrowernumber=issues.borrowernumber
1939 GROUP BY borrowernumber
1941 my $sth = $dbh->prepare($query);
1943 my $results = $sth->fetchall_arrayref({});
1951 my $success = DebarMember( $borrowernumber );
1953 marks a Member as debarred, and therefore unable to checkout any more
1957 true on success, false on failure
1964 my $borrowernumber = shift;
1966 return unless defined $borrowernumber;
1967 return unless $borrowernumber =~ /^\d+$/;
1969 return ModMember( borrowernumber => $borrowernumber,
1978 AddMessage( $borrowernumber, $message_type, $message, $branchcode );
1980 Adds a message to the messages table for the given borrower.
1991 my ( $borrowernumber, $message_type, $message, $branchcode ) = @_;
1993 my $dbh = C4::Context->dbh;
1995 if ( ! ( $borrowernumber && $message_type && $message && $branchcode ) ) {
1999 my $query = "INSERT INTO messages ( borrowernumber, branchcode, message_type, message ) VALUES ( ?, ?, ?, ? )";
2000 my $sth = $dbh->prepare($query);
2001 $sth->execute( $borrowernumber, $branchcode, $message_type, $message );
2010 GetMessages( $borrowernumber, $type );
2012 $type is message type, B for borrower, or L for Librarian.
2013 Empty type returns all messages of any type.
2015 Returns all messages for the given borrowernumber
2022 my ( $borrowernumber, $type, $branchcode ) = @_;
2028 my $dbh = C4::Context->dbh;
2031 branches.branchname,
2033 DATE_FORMAT( message_date, '%m/%d/%Y' ) AS message_date_formatted,
2034 messages.branchcode LIKE '$branchcode' AS can_delete
2035 FROM messages, branches
2036 WHERE borrowernumber = ?
2037 AND message_type LIKE ?
2038 AND messages.branchcode = branches.branchcode
2039 ORDER BY message_date DESC";
2040 my $sth = $dbh->prepare($query);
2041 $sth->execute( $borrowernumber, $type ) ;
2044 while ( my $data = $sth->fetchrow_hashref ) {
2045 push @results, $data;
2055 GetMessagesCount( $borrowernumber, $type );
2057 $type is message type, B for borrower, or L for Librarian.
2058 Empty type returns all messages of any type.
2060 Returns the number of messages for the given borrowernumber
2066 sub GetMessagesCount {
2067 my ( $borrowernumber, $type, $branchcode ) = @_;
2073 my $dbh = C4::Context->dbh;
2075 my $query = "SELECT COUNT(*) as MsgCount FROM messages WHERE borrowernumber = ? AND message_type LIKE ?";
2076 my $sth = $dbh->prepare($query);
2077 $sth->execute( $borrowernumber, $type ) ;
2080 my $data = $sth->fetchrow_hashref;
2081 my $count = $data->{'MsgCount'};
2088 =head2 DeleteMessage
2092 DeleteMessage( $message_id );
2099 my ( $message_id ) = @_;
2101 my $dbh = C4::Context->dbh;
2103 my $query = "DELETE FROM messages WHERE message_id = ?";
2104 my $sth = $dbh->prepare($query);
2105 $sth->execute( $message_id );
2109 END { } # module clean-up code here (global destructor)