Bug 18810: Update Font Awesome to 4.7.0
[koha.git] / C4 / Reserves.pm
blob521b0723686b867183414c559daf70b348ab08a8
1 package C4::Reserves;
3 # Copyright 2000-2002 Katipo Communications
4 # 2006 SAN Ouest Provence
5 # 2007-2010 BibLibre Paul POULAIN
6 # 2011 Catalyst IT
8 # This file is part of Koha.
10 # Koha is free software; you can redistribute it and/or modify it
11 # under the terms of the GNU General Public License as published by
12 # the Free Software Foundation; either version 3 of the License, or
13 # (at your option) any later version.
15 # Koha is distributed in the hope that it will be useful, but
16 # WITHOUT ANY WARRANTY; without even the implied warranty of
17 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 # GNU General Public License for more details.
20 # You should have received a copy of the GNU General Public License
21 # along with Koha; if not, see <http://www.gnu.org/licenses>.
24 use strict;
25 #use warnings; FIXME - Bug 2505
26 use C4::Context;
27 use C4::Biblio;
28 use C4::Members;
29 use C4::Items;
30 use C4::Circulation;
31 use C4::Accounts;
33 # for _koha_notify_reserve
34 use C4::Members::Messaging;
35 use C4::Members qw();
36 use C4::Letters;
37 use C4::Log;
39 use Koha::Biblios;
40 use Koha::DateUtils;
41 use Koha::Calendar;
42 use Koha::Database;
43 use Koha::Hold;
44 use Koha::Old::Hold;
45 use Koha::Holds;
46 use Koha::Libraries;
47 use Koha::IssuingRules;
48 use Koha::Items;
49 use Koha::ItemTypes;
50 use Koha::Patrons;
52 use List::MoreUtils qw( firstidx any );
53 use Carp;
54 use Data::Dumper;
56 use vars qw(@ISA @EXPORT @EXPORT_OK %EXPORT_TAGS);
58 =head1 NAME
60 C4::Reserves - Koha functions for dealing with reservation.
62 =head1 SYNOPSIS
64 use C4::Reserves;
66 =head1 DESCRIPTION
68 This modules provides somes functions to deal with reservations.
70 Reserves are stored in reserves table.
71 The following columns contains important values :
72 - priority >0 : then the reserve is at 1st stage, and not yet affected to any item.
73 =0 : then the reserve is being dealed
74 - found : NULL : means the patron requested the 1st available, and we haven't chosen the item
75 T(ransit) : the reserve is linked to an item but is in transit to the pickup branch
76 W(aiting) : the reserve is linked to an item, is at the pickup branch, and is waiting on the hold shelf
77 F(inished) : the reserve has been completed, and is done
78 - itemnumber : empty : the reserve is still unaffected to an item
79 filled: the reserve is attached to an item
80 The complete workflow is :
81 ==== 1st use case ====
82 patron request a document, 1st available : P >0, F=NULL, I=NULL
83 a library having it run "transfertodo", and clic on the list
84 if there is no transfer to do, the reserve waiting
85 patron can pick it up P =0, F=W, I=filled
86 if there is a transfer to do, write in branchtransfer P =0, F=T, I=filled
87 The pickup library receive the book, it check in P =0, F=W, I=filled
88 The patron borrow the book P =0, F=F, I=filled
90 ==== 2nd use case ====
91 patron requests a document, a given item,
92 If pickup is holding branch P =0, F=W, I=filled
93 If transfer needed, write in branchtransfer P =0, F=T, I=filled
94 The pickup library receive the book, it checks it in P =0, F=W, I=filled
95 The patron borrow the book P =0, F=F, I=filled
97 =head1 FUNCTIONS
99 =cut
101 BEGIN {
102 require Exporter;
103 @ISA = qw(Exporter);
104 @EXPORT = qw(
105 &AddReserve
107 &GetReservesForBranch
108 &GetReserveStatus
110 &GetOtherReserves
112 &ModReserveFill
113 &ModReserveAffect
114 &ModReserve
115 &ModReserveStatus
116 &ModReserveCancelAll
117 &ModReserveMinusPriority
118 &MoveReserve
120 &CheckReserves
121 &CanBookBeReserved
122 &CanItemBeReserved
123 &CanReserveBeCanceledFromOpac
124 &CancelExpiredReserves
126 &AutoUnsuspendReserves
128 &IsAvailableForItemLevelRequest
130 &OPACItemHoldsAllowed
132 &AlterPriority
133 &ToggleLowestPriority
135 &ReserveSlip
136 &ToggleSuspend
137 &SuspendAll
139 &GetReservesControlBranch
141 IsItemOnHoldAndFound
143 GetMaxPatronHoldsForRecord
145 @EXPORT_OK = qw( MergeHolds );
148 =head2 AddReserve
150 AddReserve($branch,$borrowernumber,$biblionumber,$bibitems,$priority,$resdate,$expdate,$notes,$title,$checkitem,$found)
152 Adds reserve and generates HOLDPLACED message.
154 The following tables are available witin the HOLDPLACED message:
156 branches
157 borrowers
158 biblio
159 biblioitems
160 items
161 reserves
163 =cut
165 sub AddReserve {
166 my (
167 $branch, $borrowernumber, $biblionumber, $bibitems,
168 $priority, $resdate, $expdate, $notes,
169 $title, $checkitem, $found, $itemtype
170 ) = @_;
172 $resdate = output_pref( { str => dt_from_string( $resdate ), dateonly => 1, dateformat => 'iso' })
173 or output_pref({ dt => dt_from_string, dateonly => 1, dateformat => 'iso' });
175 $expdate = output_pref({ str => $expdate, dateonly => 1, dateformat => 'iso' });
177 if ( C4::Context->preference('AllowHoldDateInFuture') ) {
179 # Make room in reserves for this before those of a later reserve date
180 $priority = _ShiftPriorityByDateAndPriority( $biblionumber, $resdate, $priority );
183 my $waitingdate;
185 # If the reserv had the waiting status, we had the value of the resdate
186 if ( $found eq 'W' ) {
187 $waitingdate = $resdate;
190 # Don't add itemtype limit if specific item is selected
191 $itemtype = undef if $checkitem;
193 # updates take place here
194 my $hold = Koha::Hold->new(
196 borrowernumber => $borrowernumber,
197 biblionumber => $biblionumber,
198 reservedate => $resdate,
199 branchcode => $branch,
200 priority => $priority,
201 reservenotes => $notes,
202 itemnumber => $checkitem,
203 found => $found,
204 waitingdate => $waitingdate,
205 expirationdate => $expdate,
206 itemtype => $itemtype,
208 )->store();
210 logaction( 'HOLDS', 'CREATE', $hold->id, Dumper($hold->unblessed) )
211 if C4::Context->preference('HoldsLog');
213 my $reserve_id = $hold->id();
215 # add a reserve fee if needed
216 if ( C4::Context->preference('HoldFeeMode') ne 'any_time_is_collected' ) {
217 my $reserve_fee = GetReserveFee( $borrowernumber, $biblionumber );
218 ChargeReserveFee( $borrowernumber, $reserve_fee, $title );
221 _FixPriority({ biblionumber => $biblionumber});
223 # Send e-mail to librarian if syspref is active
224 if(C4::Context->preference("emailLibrarianWhenHoldIsPlaced")){
225 my $patron = Koha::Patrons->find( $borrowernumber );
226 my $library = $patron->library;
227 if ( my $letter = C4::Letters::GetPreparedLetter (
228 module => 'reserves',
229 letter_code => 'HOLDPLACED',
230 branchcode => $branch,
231 lang => $patron->lang,
232 tables => {
233 'branches' => $library->unblessed,
234 'borrowers' => $patron->unblessed,
235 'biblio' => $biblionumber,
236 'biblioitems' => $biblionumber,
237 'items' => $checkitem,
238 'reserves' => $hold->unblessed,
240 ) ) {
242 my $admin_email_address = $library->branchemail || C4::Context->preference('KohaAdminEmailAddress');
244 C4::Letters::EnqueueLetter(
245 { letter => $letter,
246 borrowernumber => $borrowernumber,
247 message_transport_type => 'email',
248 from_address => $admin_email_address,
249 to_address => $admin_email_address,
255 return $reserve_id;
258 =head2 CanBookBeReserved
260 $canReserve = &CanBookBeReserved($borrowernumber, $biblionumber)
261 if ($canReserve eq 'OK') { #We can reserve this Item! }
263 See CanItemBeReserved() for possible return values.
265 =cut
267 sub CanBookBeReserved{
268 my ($borrowernumber, $biblionumber) = @_;
270 my $items = GetItemnumbersForBiblio($biblionumber);
271 #get items linked via host records
272 my @hostitems = get_hostitemnumbers_of($biblionumber);
273 if (@hostitems){
274 push (@$items,@hostitems);
277 my $canReserve;
278 foreach my $item (@$items) {
279 $canReserve = CanItemBeReserved( $borrowernumber, $item );
280 return 'OK' if $canReserve eq 'OK';
282 return $canReserve;
285 =head2 CanItemBeReserved
287 $canReserve = &CanItemBeReserved($borrowernumber, $itemnumber)
288 if ($canReserve eq 'OK') { #We can reserve this Item! }
290 @RETURNS OK, if the Item can be reserved.
291 ageRestricted, if the Item is age restricted for this borrower.
292 damaged, if the Item is damaged.
293 cannotReserveFromOtherBranches, if syspref 'canreservefromotherbranches' is OK.
294 tooManyReserves, if the borrower has exceeded his maximum reserve amount.
295 notReservable, if holds on this item are not allowed
297 =cut
299 sub CanItemBeReserved {
300 my ( $borrowernumber, $itemnumber ) = @_;
302 my $dbh = C4::Context->dbh;
303 my $ruleitemtype; # itemtype of the matching issuing rule
304 my $allowedreserves = 0; # Total number of holds allowed across all records
305 my $holds_per_record = 1; # Total number of holds allowed for this one given record
307 # we retrieve borrowers and items informations #
308 # item->{itype} will come for biblioitems if necessery
309 my $item = GetItem($itemnumber);
310 my $biblio = Koha::Biblios->find( $item->{biblionumber} );
311 my $patron = Koha::Patrons->find( $borrowernumber );
312 my $borrower = $patron->unblessed;
314 # If an item is damaged and we don't allow holds on damaged items, we can stop right here
315 return 'damaged'
316 if ( $item->{damaged}
317 && !C4::Context->preference('AllowHoldsOnDamagedItems') );
319 # Check for the age restriction
320 my ( $ageRestriction, $daysToAgeRestriction ) =
321 C4::Circulation::GetAgeRestriction( $biblio->biblioitem->agerestriction, $borrower );
322 return 'ageRestricted' if $daysToAgeRestriction && $daysToAgeRestriction > 0;
324 # Check that the patron doesn't have an item level hold on this item already
325 return 'itemAlreadyOnHold'
326 if Koha::Holds->search( { borrowernumber => $borrowernumber, itemnumber => $itemnumber } )->count();
328 my $controlbranch = C4::Context->preference('ReservesControlBranch');
330 my $querycount = q{
331 SELECT count(*) AS count
332 FROM reserves
333 LEFT JOIN items USING (itemnumber)
334 LEFT JOIN biblioitems ON (reserves.biblionumber=biblioitems.biblionumber)
335 LEFT JOIN borrowers USING (borrowernumber)
336 WHERE borrowernumber = ?
339 my $branchcode = "";
340 my $branchfield = "reserves.branchcode";
342 if ( $controlbranch eq "ItemHomeLibrary" ) {
343 $branchfield = "items.homebranch";
344 $branchcode = $item->{homebranch};
346 elsif ( $controlbranch eq "PatronLibrary" ) {
347 $branchfield = "borrowers.branchcode";
348 $branchcode = $borrower->{branchcode};
351 # we retrieve rights
352 if ( my $rights = GetHoldRule( $borrower->{'categorycode'}, $item->{'itype'}, $branchcode ) ) {
353 $ruleitemtype = $rights->{itemtype};
354 $allowedreserves = $rights->{reservesallowed};
355 $holds_per_record = $rights->{holds_per_record};
357 else {
358 $ruleitemtype = '*';
361 $item = Koha::Items->find( $itemnumber );
362 my $holds = Koha::Holds->search(
364 borrowernumber => $borrowernumber,
365 biblionumber => $item->biblionumber,
366 found => undef, # Found holds don't count against a patron's holds limit
369 if ( $holds->count() >= $holds_per_record ) {
370 return "tooManyHoldsForThisRecord";
373 # we retrieve count
375 $querycount .= "AND $branchfield = ?";
377 # If using item-level itypes, fall back to the record
378 # level itemtype if the hold has no associated item
379 $querycount .=
380 C4::Context->preference('item-level_itypes')
381 ? " AND COALESCE( items.itype, biblioitems.itemtype ) = ?"
382 : " AND biblioitems.itemtype = ?"
383 if ( $ruleitemtype ne "*" );
385 my $sthcount = $dbh->prepare($querycount);
387 if ( $ruleitemtype eq "*" ) {
388 $sthcount->execute( $borrowernumber, $branchcode );
390 else {
391 $sthcount->execute( $borrowernumber, $branchcode, $ruleitemtype );
394 my $reservecount = "0";
395 if ( my $rowcount = $sthcount->fetchrow_hashref() ) {
396 $reservecount = $rowcount->{count};
399 # we check if it's ok or not
400 if ( $reservecount >= $allowedreserves ) {
401 return 'tooManyReserves';
404 my $circ_control_branch =
405 C4::Circulation::_GetCircControlBranch( $item->unblessed(), $borrower );
406 my $branchitemrule =
407 C4::Circulation::GetBranchItemRule( $circ_control_branch, $item->itype );
409 if ( $branchitemrule->{holdallowed} == 0 ) {
410 return 'notReservable';
413 if ( $branchitemrule->{holdallowed} == 1
414 && $borrower->{branchcode} ne $item->homebranch )
416 return 'cannotReserveFromOtherBranches';
419 # If reservecount is ok, we check item branch if IndependentBranches is ON
420 # and canreservefromotherbranches is OFF
421 if ( C4::Context->preference('IndependentBranches')
422 and !C4::Context->preference('canreservefromotherbranches') )
424 my $itembranch = $item->homebranch;
425 if ( $itembranch ne $borrower->{branchcode} ) {
426 return 'cannotReserveFromOtherBranches';
430 return 'OK';
433 =head2 CanReserveBeCanceledFromOpac
435 $number = CanReserveBeCanceledFromOpac($reserve_id, $borrowernumber);
437 returns 1 if reserve can be cancelled by user from OPAC.
438 First check if reserve belongs to user, next checks if reserve is not in
439 transfer or waiting status
441 =cut
443 sub CanReserveBeCanceledFromOpac {
444 my ($reserve_id, $borrowernumber) = @_;
446 return unless $reserve_id and $borrowernumber;
447 my $reserve = Koha::Holds->find($reserve_id);
449 return 0 unless $reserve->borrowernumber == $borrowernumber;
450 return 0 if ( $reserve->found eq 'W' ) or ( $reserve->found eq 'T' );
452 return 1;
456 =head2 GetOtherReserves
458 ($messages,$nextreservinfo)=$GetOtherReserves(itemnumber);
460 Check queued list of this document and check if this document must be transferred
462 =cut
464 sub GetOtherReserves {
465 my ($itemnumber) = @_;
466 my $messages;
467 my $nextreservinfo;
468 my ( undef, $checkreserves, undef ) = CheckReserves($itemnumber);
469 if ($checkreserves) {
470 my $iteminfo = GetItem($itemnumber);
471 if ( $iteminfo->{'holdingbranch'} ne $checkreserves->{'branchcode'} ) {
472 $messages->{'transfert'} = $checkreserves->{'branchcode'};
473 #minus priorities of others reservs
474 ModReserveMinusPriority(
475 $itemnumber,
476 $checkreserves->{'reserve_id'},
479 #launch the subroutine dotransfer
480 C4::Items::ModItemTransfer(
481 $itemnumber,
482 $iteminfo->{'holdingbranch'},
483 $checkreserves->{'branchcode'}
488 #step 2b : case of a reservation on the same branch, set the waiting status
489 else {
490 $messages->{'waiting'} = 1;
491 ModReserveMinusPriority(
492 $itemnumber,
493 $checkreserves->{'reserve_id'},
495 ModReserveStatus($itemnumber,'W');
498 $nextreservinfo = $checkreserves->{'borrowernumber'};
501 return ( $messages, $nextreservinfo );
504 =head2 ChargeReserveFee
506 $fee = ChargeReserveFee( $borrowernumber, $fee, $title );
508 Charge the fee for a reserve (if $fee > 0)
510 =cut
512 sub ChargeReserveFee {
513 my ( $borrowernumber, $fee, $title ) = @_;
514 return if !$fee || $fee==0; # the last test is needed to include 0.00
515 my $accquery = qq{
516 INSERT INTO accountlines ( borrowernumber, accountno, date, amount, description, accounttype, amountoutstanding ) VALUES (?, ?, NOW(), ?, ?, 'Res', ?)
518 my $dbh = C4::Context->dbh;
519 my $nextacctno = &getnextacctno( $borrowernumber );
520 $dbh->do( $accquery, undef, ( $borrowernumber, $nextacctno, $fee, "Reserve Charge - $title", $fee ) );
523 =head2 GetReserveFee
525 $fee = GetReserveFee( $borrowernumber, $biblionumber );
527 Calculate the fee for a reserve (if applicable).
529 =cut
531 sub GetReserveFee {
532 my ( $borrowernumber, $biblionumber ) = @_;
533 my $borquery = qq{
534 SELECT reservefee FROM borrowers LEFT JOIN categories ON borrowers.categorycode = categories.categorycode WHERE borrowernumber = ?
536 my $issue_qry = qq{
537 SELECT COUNT(*) FROM items
538 LEFT JOIN issues USING (itemnumber)
539 WHERE items.biblionumber=? AND issues.issue_id IS NULL
541 my $holds_qry = qq{
542 SELECT COUNT(*) FROM reserves WHERE biblionumber=? AND borrowernumber<>?
545 my $dbh = C4::Context->dbh;
546 my ( $fee ) = $dbh->selectrow_array( $borquery, undef, ($borrowernumber) );
547 my $hold_fee_mode = C4::Context->preference('HoldFeeMode') || 'not_always';
548 if( $fee and $fee > 0 and $hold_fee_mode eq 'not_always' ) {
549 # This is a reconstruction of the old code:
550 # Compare number of items with items issued, and optionally check holds
551 # If not all items are issued and there are no holds: charge no fee
552 # NOTE: Lost, damaged, not-for-loan, etc. are just ignored here
553 my ( $notissued, $reserved );
554 ( $notissued ) = $dbh->selectrow_array( $issue_qry, undef,
555 ( $biblionumber ) );
556 if( $notissued ) {
557 ( $reserved ) = $dbh->selectrow_array( $holds_qry, undef,
558 ( $biblionumber, $borrowernumber ) );
559 $fee = 0 if $reserved == 0;
562 return $fee;
565 =head2 GetReservesForBranch
567 @transreserv = GetReservesForBranch($frombranch);
569 =cut
571 sub GetReservesForBranch {
572 my ($frombranch) = @_;
573 my $dbh = C4::Context->dbh;
575 my $query = "
576 SELECT reserve_id,borrowernumber,reservedate,itemnumber,waitingdate, expirationdate
577 FROM reserves
578 WHERE priority='0'
579 AND found='W'
581 $query .= " AND branchcode=? " if ( $frombranch );
582 $query .= "ORDER BY waitingdate" ;
584 my $sth = $dbh->prepare($query);
585 if ($frombranch){
586 $sth->execute($frombranch);
587 } else {
588 $sth->execute();
591 my @transreserv;
592 my $i = 0;
593 while ( my $data = $sth->fetchrow_hashref ) {
594 $transreserv[$i] = $data;
595 $i++;
597 return (@transreserv);
600 =head2 GetReserveStatus
602 $reservestatus = GetReserveStatus($itemnumber);
604 Takes an itemnumber and returns the status of the reserve placed on it.
605 If several reserves exist, the reserve with the lower priority is given.
607 =cut
609 ## FIXME: I don't think this does what it thinks it does.
610 ## It only ever checks the first reserve result, even though
611 ## multiple reserves for that bib can have the itemnumber set
612 ## the sub is only used once in the codebase.
613 sub GetReserveStatus {
614 my ($itemnumber) = @_;
616 my $dbh = C4::Context->dbh;
618 my ($sth, $found, $priority);
619 if ( $itemnumber ) {
620 $sth = $dbh->prepare("SELECT found, priority FROM reserves WHERE itemnumber = ? order by priority LIMIT 1");
621 $sth->execute($itemnumber);
622 ($found, $priority) = $sth->fetchrow_array;
625 if(defined $found) {
626 return 'Waiting' if $found eq 'W' and $priority == 0;
627 return 'Finished' if $found eq 'F';
630 return 'Reserved' if $priority > 0;
632 return ''; # empty string here will remove need for checking undef, or less log lines
635 =head2 CheckReserves
637 ($status, $reserve, $all_reserves) = &CheckReserves($itemnumber);
638 ($status, $reserve, $all_reserves) = &CheckReserves(undef, $barcode);
639 ($status, $reserve, $all_reserves) = &CheckReserves($itemnumber,undef,$lookahead);
641 Find a book in the reserves.
643 C<$itemnumber> is the book's item number.
644 C<$lookahead> is the number of days to look in advance for future reserves.
646 As I understand it, C<&CheckReserves> looks for the given item in the
647 reserves. If it is found, that's a match, and C<$status> is set to
648 C<Waiting>.
650 Otherwise, it finds the most important item in the reserves with the
651 same biblio number as this book (I'm not clear on this) and returns it
652 with C<$status> set to C<Reserved>.
654 C<&CheckReserves> returns a two-element list:
656 C<$status> is either C<Waiting>, C<Reserved> (see above), or 0.
658 C<$reserve> is the reserve item that matched. It is a
659 reference-to-hash whose keys are mostly the fields of the reserves
660 table in the Koha database.
662 =cut
664 sub CheckReserves {
665 my ( $item, $barcode, $lookahead_days, $ignore_borrowers) = @_;
666 my $dbh = C4::Context->dbh;
667 my $sth;
668 my $select;
669 if (C4::Context->preference('item-level_itypes')){
670 $select = "
671 SELECT items.biblionumber,
672 items.biblioitemnumber,
673 itemtypes.notforloan,
674 items.notforloan AS itemnotforloan,
675 items.itemnumber,
676 items.damaged,
677 items.homebranch,
678 items.holdingbranch
679 FROM items
680 LEFT JOIN biblioitems ON items.biblioitemnumber = biblioitems.biblioitemnumber
681 LEFT JOIN itemtypes ON items.itype = itemtypes.itemtype
684 else {
685 $select = "
686 SELECT items.biblionumber,
687 items.biblioitemnumber,
688 itemtypes.notforloan,
689 items.notforloan AS itemnotforloan,
690 items.itemnumber,
691 items.damaged,
692 items.homebranch,
693 items.holdingbranch
694 FROM items
695 LEFT JOIN biblioitems ON items.biblioitemnumber = biblioitems.biblioitemnumber
696 LEFT JOIN itemtypes ON biblioitems.itemtype = itemtypes.itemtype
700 if ($item) {
701 $sth = $dbh->prepare("$select WHERE itemnumber = ?");
702 $sth->execute($item);
704 else {
705 $sth = $dbh->prepare("$select WHERE barcode = ?");
706 $sth->execute($barcode);
708 # note: we get the itemnumber because we might have started w/ just the barcode. Now we know for sure we have it.
709 my ( $biblio, $bibitem, $notforloan_per_itemtype, $notforloan_per_item, $itemnumber, $damaged, $item_homebranch, $item_holdingbranch ) = $sth->fetchrow_array;
711 return if ( $damaged && !C4::Context->preference('AllowHoldsOnDamagedItems') );
713 return unless $itemnumber; # bail if we got nothing.
715 # if item is not for loan it cannot be reserved either.....
716 # except where items.notforloan < 0 : This indicates the item is holdable.
717 return if ( $notforloan_per_item > 0 ) or $notforloan_per_itemtype;
719 # Find this item in the reserves
720 my @reserves = _Findgroupreserve( $bibitem, $biblio, $itemnumber, $lookahead_days, $ignore_borrowers);
722 # $priority and $highest are used to find the most important item
723 # in the list returned by &_Findgroupreserve. (The lower $priority,
724 # the more important the item.)
725 # $highest is the most important item we've seen so far.
726 my $highest;
727 if (scalar @reserves) {
728 my $LocalHoldsPriority = C4::Context->preference('LocalHoldsPriority');
729 my $LocalHoldsPriorityPatronControl = C4::Context->preference('LocalHoldsPriorityPatronControl');
730 my $LocalHoldsPriorityItemControl = C4::Context->preference('LocalHoldsPriorityItemControl');
732 my $priority = 10000000;
733 foreach my $res (@reserves) {
734 if ( $res->{'itemnumber'} == $itemnumber && $res->{'priority'} == 0) {
735 return ( "Waiting", $res, \@reserves ); # Found it
736 } else {
737 my $patron;
738 my $iteminfo;
739 my $local_hold_match;
741 if ($LocalHoldsPriority) {
742 $patron = Koha::Patrons->find( $res->{borrowernumber} );
743 $iteminfo = C4::Items::GetItem($itemnumber);
745 my $local_holds_priority_item_branchcode =
746 $iteminfo->{$LocalHoldsPriorityItemControl};
747 my $local_holds_priority_patron_branchcode =
748 ( $LocalHoldsPriorityPatronControl eq 'PickupLibrary' )
749 ? $res->{branchcode}
750 : ( $LocalHoldsPriorityPatronControl eq 'HomeLibrary' )
751 ? $patron->branchcode
752 : undef;
753 $local_hold_match =
754 $local_holds_priority_item_branchcode eq
755 $local_holds_priority_patron_branchcode;
758 # See if this item is more important than what we've got so far
759 if ( ( $res->{'priority'} && $res->{'priority'} < $priority ) || $local_hold_match ) {
760 $iteminfo ||= C4::Items::GetItem($itemnumber);
761 next if $res->{itemtype} && $res->{itemtype} ne _get_itype( $iteminfo );
762 $patron ||= Koha::Patrons->find( $res->{borrowernumber} );
763 my $branch = GetReservesControlBranch( $iteminfo, $patron->unblessed );
764 my $branchitemrule = C4::Circulation::GetBranchItemRule($branch,$iteminfo->{'itype'});
765 next if ($branchitemrule->{'holdallowed'} == 0);
766 next if (($branchitemrule->{'holdallowed'} == 1) && ($branch ne $patron->branchcode));
767 next if ( ($branchitemrule->{hold_fulfillment_policy} ne 'any') && ($res->{branchcode} ne $iteminfo->{ $branchitemrule->{hold_fulfillment_policy} }) );
768 $priority = $res->{'priority'};
769 $highest = $res;
770 last if $local_hold_match;
776 # If we get this far, then no exact match was found.
777 # We return the most important (i.e. next) reservation.
778 if ($highest) {
779 $highest->{'itemnumber'} = $item;
780 return ( "Reserved", $highest, \@reserves );
783 return ( '' );
786 =head2 CancelExpiredReserves
788 CancelExpiredReserves();
790 Cancels all reserves with an expiration date from before today.
792 =cut
794 sub CancelExpiredReserves {
796 my $today = dt_from_string();
797 my $cancel_on_holidays = C4::Context->preference('ExpireReservesOnHolidays');
799 my $dbh = C4::Context->dbh;
801 my $dtf = Koha::Database->new->schema->storage->datetime_parser;
802 # FIXME To move to Koha::Holds->search_expired (?)
803 my $holds = Koha::Holds->search(
805 expirationdate => { '<', $dtf->format_date($today) }
809 while ( my $hold = $holds->next ) {
810 my $calendar = Koha::Calendar->new( branchcode => $hold->branchcode );
812 next if !$cancel_on_holidays && $calendar->is_holiday( $today );
814 my $cancel_params = {};
815 if ( $hold->found eq 'W' ) {
816 $cancel_params->{charge_cancel_fee} = 1;
818 $hold->cancel( $cancel_params );
823 =head2 AutoUnsuspendReserves
825 AutoUnsuspendReserves();
827 Unsuspends all suspended reserves with a suspend_until date from before today.
829 =cut
831 sub AutoUnsuspendReserves {
832 my $today = dt_from_string();
834 my @holds = Koha::Holds->search( { suspend_until => { '<' => $today->ymd() } } );
836 map { $_->suspend(0)->suspend_until(undef)->store() } @holds;
839 =head2 ModReserve
841 ModReserve({ rank => $rank,
842 reserve_id => $reserve_id,
843 branchcode => $branchcode
844 [, itemnumber => $itemnumber ]
845 [, biblionumber => $biblionumber, $borrowernumber => $borrowernumber ]
848 Change a hold request's priority or cancel it.
850 C<$rank> specifies the effect of the change. If C<$rank>
851 is 'W' or 'n', nothing happens. This corresponds to leaving a
852 request alone when changing its priority in the holds queue
853 for a bib.
855 If C<$rank> is 'del', the hold request is cancelled.
857 If C<$rank> is an integer greater than zero, the priority of
858 the request is set to that value. Since priority != 0 means
859 that the item is not waiting on the hold shelf, setting the
860 priority to a non-zero value also sets the request's found
861 status and waiting date to NULL.
863 The optional C<$itemnumber> parameter is used only when
864 C<$rank> is a non-zero integer; if supplied, the itemnumber
865 of the hold request is set accordingly; if omitted, the itemnumber
866 is cleared.
868 B<FIXME:> Note that the forgoing can have the effect of causing
869 item-level hold requests to turn into title-level requests. This
870 will be fixed once reserves has separate columns for requested
871 itemnumber and supplying itemnumber.
873 =cut
875 sub ModReserve {
876 my ( $params ) = @_;
878 my $rank = $params->{'rank'};
879 my $reserve_id = $params->{'reserve_id'};
880 my $branchcode = $params->{'branchcode'};
881 my $itemnumber = $params->{'itemnumber'};
882 my $suspend_until = $params->{'suspend_until'};
883 my $borrowernumber = $params->{'borrowernumber'};
884 my $biblionumber = $params->{'biblionumber'};
886 return if $rank eq "W";
887 return if $rank eq "n";
889 return unless ( $reserve_id || ( $borrowernumber && ( $biblionumber || $itemnumber ) ) );
891 my $hold;
892 unless ( $reserve_id ) {
893 $hold = Koha::Holds->search({ biblionumber => $biblionumber, borrowernumber => $borrowernumber, itemnumber => $itemnumber });
894 return unless $hold; # FIXME Should raise an exception
895 $reserve_id = $hold->reserve_id;
898 $hold ||= Koha::Holds->find($reserve_id);
900 if ( $rank eq "del" ) {
901 $hold->cancel;
903 elsif ($rank =~ /^\d+/ and $rank > 0) {
904 logaction( 'HOLDS', 'MODIFY', $hold->reserve_id, Dumper($hold->unblessed) )
905 if C4::Context->preference('HoldsLog');
907 $hold->set(
909 priority => $rank,
910 branchcode => $branchcode,
911 itemnumber => $itemnumber,
912 found => undef,
913 waitingdate => undef
915 )->store();
917 if ( defined( $suspend_until ) ) {
918 if ( $suspend_until ) {
919 $suspend_until = eval { dt_from_string( $suspend_until ) };
920 $hold->suspend_hold( $suspend_until );
921 } else {
922 # If the hold is suspended leave the hold suspended, but convert it to an indefinite hold.
923 # If the hold is not suspended, this does nothing.
924 $hold->set( { suspend_until => undef } )->store();
928 _FixPriority({ reserve_id => $reserve_id, rank =>$rank });
932 =head2 ModReserveFill
934 &ModReserveFill($reserve);
936 Fill a reserve. If I understand this correctly, this means that the
937 reserved book has been found and given to the patron who reserved it.
939 C<$reserve> specifies the reserve to fill. It is a reference-to-hash
940 whose keys are fields from the reserves table in the Koha database.
942 =cut
944 sub ModReserveFill {
945 my ($res) = @_;
946 my $reserve_id = $res->{'reserve_id'};
948 my $hold = Koha::Holds->find($reserve_id);
950 # get the priority on this record....
951 my $priority = $hold->priority;
953 # update the hold statuses, no need to store it though, we will be deleting it anyway
954 $hold->set(
956 found => 'F',
957 priority => 0,
961 # FIXME Must call Koha::Hold->cancel ? => No, should call ->filled and add the correct log
962 Koha::Old::Hold->new( $hold->unblessed() )->store();
964 $hold->delete();
966 if ( C4::Context->preference('HoldFeeMode') eq 'any_time_is_collected' ) {
967 my $reserve_fee = GetReserveFee( $hold->borrowernumber, $hold->biblionumber );
968 ChargeReserveFee( $hold->borrowernumber, $reserve_fee, $hold->biblio->title );
971 # now fix the priority on the others (if the priority wasn't
972 # already sorted!)....
973 unless ( $priority == 0 ) {
974 _FixPriority( { reserve_id => $reserve_id, biblionumber => $hold->biblionumber } );
978 =head2 ModReserveStatus
980 &ModReserveStatus($itemnumber, $newstatus);
982 Update the reserve status for the active (priority=0) reserve.
984 $itemnumber is the itemnumber the reserve is on
986 $newstatus is the new status.
988 =cut
990 sub ModReserveStatus {
992 #first : check if we have a reservation for this item .
993 my ($itemnumber, $newstatus) = @_;
994 my $dbh = C4::Context->dbh;
996 my $query = "UPDATE reserves SET found = ?, waitingdate = NOW() WHERE itemnumber = ? AND found IS NULL AND priority = 0";
997 my $sth_set = $dbh->prepare($query);
998 $sth_set->execute( $newstatus, $itemnumber );
1000 if ( C4::Context->preference("ReturnToShelvingCart") && $newstatus ) {
1001 CartToShelf( $itemnumber );
1005 =head2 ModReserveAffect
1007 &ModReserveAffect($itemnumber,$borrowernumber,$diffBranchSend,$reserve_id);
1009 This function affect an item and a status for a given reserve, either fetched directly
1010 by record_id, or by borrowernumber and itemnumber or biblionumber. If only biblionumber
1011 is given, only first reserve returned is affected, which is ok for anything but
1012 multi-item holds.
1014 if $transferToDo is not set, then the status is set to "Waiting" as well.
1015 otherwise, a transfer is on the way, and the end of the transfer will
1016 take care of the waiting status
1018 =cut
1020 sub ModReserveAffect {
1021 my ( $itemnumber, $borrowernumber, $transferToDo, $reserve_id ) = @_;
1022 my $dbh = C4::Context->dbh;
1024 # we want to attach $itemnumber to $borrowernumber, find the biblionumber
1025 # attached to $itemnumber
1026 my $sth = $dbh->prepare("SELECT biblionumber FROM items WHERE itemnumber=?");
1027 $sth->execute($itemnumber);
1028 my ($biblionumber) = $sth->fetchrow;
1030 # get request - need to find out if item is already
1031 # waiting in order to not send duplicate hold filled notifications
1033 my $hold;
1034 # Find hold by id if we have it
1035 $hold = Koha::Holds->find( $reserve_id ) if $reserve_id;
1036 # Find item level hold for this item if there is one
1037 $hold ||= Koha::Holds->search( { borrowernumber => $borrowernumber, itemnumber => $itemnumber } )->next();
1038 # Find record level hold if there is no item level hold
1039 $hold ||= Koha::Holds->search( { borrowernumber => $borrowernumber, biblionumber => $biblionumber } )->next();
1041 return unless $hold;
1043 my $already_on_shelf = $hold->found && $hold->found eq 'W';
1045 $hold->itemnumber($itemnumber);
1046 $hold->set_waiting($transferToDo);
1048 _koha_notify_reserve( $hold->reserve_id )
1049 if ( !$transferToDo && !$already_on_shelf );
1051 _FixPriority( { biblionumber => $biblionumber } );
1053 if ( C4::Context->preference("ReturnToShelvingCart") ) {
1054 CartToShelf($itemnumber);
1057 return;
1060 =head2 ModReserveCancelAll
1062 ($messages,$nextreservinfo) = &ModReserveCancelAll($itemnumber,$borrowernumber);
1064 function to cancel reserv,check other reserves, and transfer document if it's necessary
1066 =cut
1068 sub ModReserveCancelAll {
1069 my $messages;
1070 my $nextreservinfo;
1071 my ( $itemnumber, $borrowernumber ) = @_;
1073 #step 1 : cancel the reservation
1074 my $holds = Koha::Holds->search({ itemnumber => $itemnumber, borrowernumber => $borrowernumber });
1075 return unless $holds->count;
1076 $holds->next->cancel;
1078 #step 2 launch the subroutine of the others reserves
1079 ( $messages, $nextreservinfo ) = GetOtherReserves($itemnumber);
1081 return ( $messages, $nextreservinfo );
1084 =head2 ModReserveMinusPriority
1086 &ModReserveMinusPriority($itemnumber,$borrowernumber,$biblionumber)
1088 Reduce the values of queued list
1090 =cut
1092 sub ModReserveMinusPriority {
1093 my ( $itemnumber, $reserve_id ) = @_;
1095 #first step update the value of the first person on reserv
1096 my $dbh = C4::Context->dbh;
1097 my $query = "
1098 UPDATE reserves
1099 SET priority = 0 , itemnumber = ?
1100 WHERE reserve_id = ?
1102 my $sth_upd = $dbh->prepare($query);
1103 $sth_upd->execute( $itemnumber, $reserve_id );
1104 # second step update all others reserves
1105 _FixPriority({ reserve_id => $reserve_id, rank => '0' });
1108 =head2 IsAvailableForItemLevelRequest
1110 my $is_available = IsAvailableForItemLevelRequest($item_record,$borrower_record);
1112 Checks whether a given item record is available for an
1113 item-level hold request. An item is available if
1115 * it is not lost AND
1116 * it is not damaged AND
1117 * it is not withdrawn AND
1118 * does not have a not for loan value > 0
1120 Need to check the issuingrules onshelfholds column,
1121 if this is set items on the shelf can be placed on hold
1123 Note that IsAvailableForItemLevelRequest() does not
1124 check if the staff operator is authorized to place
1125 a request on the item - in particular,
1126 this routine does not check IndependentBranches
1127 and canreservefromotherbranches.
1129 =cut
1131 sub IsAvailableForItemLevelRequest {
1132 my $item = shift;
1133 my $borrower = shift;
1135 my $dbh = C4::Context->dbh;
1136 # must check the notforloan setting of the itemtype
1137 # FIXME - a lot of places in the code do this
1138 # or something similar - need to be
1139 # consolidated
1140 my $itype = _get_itype($item);
1141 my $notforloan_per_itemtype
1142 = $dbh->selectrow_array("SELECT notforloan FROM itemtypes WHERE itemtype = ?",
1143 undef, $itype);
1145 return 0 if
1146 $notforloan_per_itemtype ||
1147 $item->{itemlost} ||
1148 $item->{notforloan} > 0 ||
1149 $item->{withdrawn} ||
1150 ($item->{damaged} && !C4::Context->preference('AllowHoldsOnDamagedItems'));
1152 my $on_shelf_holds = _OnShelfHoldsAllowed($itype,$borrower->{categorycode},$item->{holdingbranch});
1154 if ( $on_shelf_holds == 1 ) {
1155 return 1;
1156 } elsif ( $on_shelf_holds == 2 ) {
1157 my @items =
1158 Koha::Items->search( { biblionumber => $item->{biblionumber} } );
1160 my $any_available = 0;
1162 foreach my $i (@items) {
1163 $any_available = 1
1164 unless $i->itemlost
1165 || $i->notforloan > 0
1166 || $i->withdrawn
1167 || $i->onloan
1168 || IsItemOnHoldAndFound( $i->id )
1169 || ( $i->damaged
1170 && !C4::Context->preference('AllowHoldsOnDamagedItems') )
1171 || Koha::ItemTypes->find( $i->effective_itemtype() )->notforloan;
1174 return $any_available ? 0 : 1;
1177 return $item->{onloan} || GetReserveStatus($item->{itemnumber}) eq "Waiting";
1180 =head2 OnShelfHoldsAllowed
1182 OnShelfHoldsAllowed($itemtype,$borrowercategory,$branchcode);
1184 Checks issuingrules, using the borrowers categorycode, the itemtype, and branchcode to see if onshelf
1185 holds are allowed, returns true if so.
1187 =cut
1189 sub OnShelfHoldsAllowed {
1190 my ($item, $borrower) = @_;
1192 my $itype = _get_itype($item);
1193 return _OnShelfHoldsAllowed($itype,$borrower->{categorycode},$item->{holdingbranch});
1196 sub _get_itype {
1197 my $item = shift;
1199 my $itype;
1200 if (C4::Context->preference('item-level_itypes')) {
1201 # We can't trust GetItem to honour the syspref, so safest to do it ourselves
1202 # When GetItem is fixed, we can remove this
1203 $itype = $item->{itype};
1205 else {
1206 # XXX This is a bit dodgy. It relies on biblio itemtype column having different name.
1207 # So if we already have a biblioitems join when calling this function,
1208 # we don't need to access the database again
1209 $itype = $item->{itemtype};
1211 unless ($itype) {
1212 my $dbh = C4::Context->dbh;
1213 my $query = "SELECT itemtype FROM biblioitems WHERE biblioitemnumber = ? ";
1214 my $sth = $dbh->prepare($query);
1215 $sth->execute($item->{biblioitemnumber});
1216 if (my $data = $sth->fetchrow_hashref()){
1217 $itype = $data->{itemtype};
1220 return $itype;
1223 sub _OnShelfHoldsAllowed {
1224 my ($itype,$borrowercategory,$branchcode) = @_;
1226 my $issuing_rule = Koha::IssuingRules->get_effective_issuing_rule({ categorycode => $borrowercategory, itemtype => $itype, branchcode => $branchcode });
1227 return $issuing_rule ? $issuing_rule->onshelfholds : undef;
1230 =head2 AlterPriority
1232 AlterPriority( $where, $reserve_id );
1234 This function changes a reserve's priority up, down, to the top, or to the bottom.
1235 Input: $where is 'up', 'down', 'top' or 'bottom'. Biblionumber, Date reserve was placed
1237 =cut
1239 sub AlterPriority {
1240 my ( $where, $reserve_id ) = @_;
1242 my $hold = Koha::Holds->find( $reserve_id );
1243 return unless $hold;
1245 if ( $hold->cancellationdate ) {
1246 warn "I cannot alter the priority for reserve_id $reserve_id, the reserve has been cancelled (" . $hold->cancellationdate . ')';
1247 return;
1250 if ( $where eq 'up' || $where eq 'down' ) {
1252 my $priority = $hold->priority;
1253 $priority = $where eq 'up' ? $priority - 1 : $priority + 1;
1254 _FixPriority({ reserve_id => $reserve_id, rank => $priority })
1256 } elsif ( $where eq 'top' ) {
1258 _FixPriority({ reserve_id => $reserve_id, rank => '1' })
1260 } elsif ( $where eq 'bottom' ) {
1262 _FixPriority({ reserve_id => $reserve_id, rank => '999999' });
1265 # FIXME Should return the new priority
1268 =head2 ToggleLowestPriority
1270 ToggleLowestPriority( $borrowernumber, $biblionumber );
1272 This function sets the lowestPriority field to true if is false, and false if it is true.
1274 =cut
1276 sub ToggleLowestPriority {
1277 my ( $reserve_id ) = @_;
1279 my $dbh = C4::Context->dbh;
1281 my $sth = $dbh->prepare( "UPDATE reserves SET lowestPriority = NOT lowestPriority WHERE reserve_id = ?");
1282 $sth->execute( $reserve_id );
1284 _FixPriority({ reserve_id => $reserve_id, rank => '999999' });
1287 =head2 ToggleSuspend
1289 ToggleSuspend( $reserve_id );
1291 This function sets the suspend field to true if is false, and false if it is true.
1292 If the reserve is currently suspended with a suspend_until date, that date will
1293 be cleared when it is unsuspended.
1295 =cut
1297 sub ToggleSuspend {
1298 my ( $reserve_id, $suspend_until ) = @_;
1300 $suspend_until = dt_from_string($suspend_until) if ($suspend_until);
1302 my $hold = Koha::Holds->find( $reserve_id );
1304 if ( $hold->is_suspended ) {
1305 $hold->resume()
1306 } else {
1307 $hold->suspend_hold( $suspend_until );
1311 =head2 SuspendAll
1313 SuspendAll(
1314 borrowernumber => $borrowernumber,
1315 [ biblionumber => $biblionumber, ]
1316 [ suspend_until => $suspend_until, ]
1317 [ suspend => $suspend ]
1320 This function accepts a set of hash keys as its parameters.
1321 It requires either borrowernumber or biblionumber, or both.
1323 suspend_until is wholly optional.
1325 =cut
1327 sub SuspendAll {
1328 my %params = @_;
1330 my $borrowernumber = $params{'borrowernumber'} || undef;
1331 my $biblionumber = $params{'biblionumber'} || undef;
1332 my $suspend_until = $params{'suspend_until'} || undef;
1333 my $suspend = defined( $params{'suspend'} ) ? $params{'suspend'} : 1;
1335 $suspend_until = eval { dt_from_string($suspend_until) }
1336 if ( defined($suspend_until) );
1338 return unless ( $borrowernumber || $biblionumber );
1340 my $params;
1341 $params->{found} = undef;
1342 $params->{borrowernumber} = $borrowernumber if $borrowernumber;
1343 $params->{biblionumber} = $biblionumber if $biblionumber;
1345 my @holds = Koha::Holds->search($params);
1347 if ($suspend) {
1348 map { $_->suspend_hold($suspend_until) } @holds;
1350 else {
1351 map { $_->resume() } @holds;
1356 =head2 _FixPriority
1358 _FixPriority({
1359 reserve_id => $reserve_id,
1360 [rank => $rank,]
1361 [ignoreSetLowestRank => $ignoreSetLowestRank]
1366 _FixPriority({ biblionumber => $biblionumber});
1368 This routine adjusts the priority of a hold request and holds
1369 on the same bib.
1371 In the first form, where a reserve_id is passed, the priority of the
1372 hold is set to supplied rank, and other holds for that bib are adjusted
1373 accordingly. If the rank is "del", the hold is cancelled. If no rank
1374 is supplied, all of the holds on that bib have their priority adjusted
1375 as if the second form had been used.
1377 In the second form, where a biblionumber is passed, the holds on that
1378 bib (that are not captured) are sorted in order of increasing priority,
1379 then have reserves.priority set so that the first non-captured hold
1380 has its priority set to 1, the second non-captured hold has its priority
1381 set to 2, and so forth.
1383 In both cases, holds that have the lowestPriority flag on are have their
1384 priority adjusted to ensure that they remain at the end of the line.
1386 Note that the ignoreSetLowestRank parameter is meant to be used only
1387 when _FixPriority calls itself.
1389 =cut
1391 sub _FixPriority {
1392 my ( $params ) = @_;
1393 my $reserve_id = $params->{reserve_id};
1394 my $rank = $params->{rank} // '';
1395 my $ignoreSetLowestRank = $params->{ignoreSetLowestRank};
1396 my $biblionumber = $params->{biblionumber};
1398 my $dbh = C4::Context->dbh;
1400 my $hold;
1401 if ( $reserve_id ) {
1402 $hold = Koha::Holds->find( $reserve_id );
1403 return unless $hold;
1406 unless ( $biblionumber ) { # FIXME This is a very weird API
1407 $biblionumber = $hold->biblionumber;
1410 if ( $rank eq "del" ) { # FIXME will crash if called without $hold
1411 $hold->cancel;
1413 elsif ( $rank eq "W" || $rank eq "0" ) {
1415 # make sure priority for waiting or in-transit items is 0
1416 my $query = "
1417 UPDATE reserves
1418 SET priority = 0
1419 WHERE reserve_id = ?
1420 AND found IN ('W', 'T')
1422 my $sth = $dbh->prepare($query);
1423 $sth->execute( $reserve_id );
1425 my @priority;
1427 # get whats left
1428 my $query = "
1429 SELECT reserve_id, borrowernumber, reservedate
1430 FROM reserves
1431 WHERE biblionumber = ?
1432 AND ((found <> 'W' AND found <> 'T') OR found IS NULL)
1433 ORDER BY priority ASC
1435 my $sth = $dbh->prepare($query);
1436 $sth->execute( $biblionumber );
1437 while ( my $line = $sth->fetchrow_hashref ) {
1438 push( @priority, $line );
1441 # To find the matching index
1442 my $i;
1443 my $key = -1; # to allow for 0 to be a valid result
1444 for ( $i = 0 ; $i < @priority ; $i++ ) {
1445 if ( $reserve_id == $priority[$i]->{'reserve_id'} ) {
1446 $key = $i; # save the index
1447 last;
1451 # if index exists in array then move it to new position
1452 if ( $key > -1 && $rank ne 'del' && $rank > 0 ) {
1453 my $new_rank = $rank -
1454 1; # $new_rank is what you want the new index to be in the array
1455 my $moving_item = splice( @priority, $key, 1 );
1456 splice( @priority, $new_rank, 0, $moving_item );
1459 # now fix the priority on those that are left....
1460 $query = "
1461 UPDATE reserves
1462 SET priority = ?
1463 WHERE reserve_id = ?
1465 $sth = $dbh->prepare($query);
1466 for ( my $j = 0 ; $j < @priority ; $j++ ) {
1467 $sth->execute(
1468 $j + 1,
1469 $priority[$j]->{'reserve_id'}
1473 $sth = $dbh->prepare( "SELECT reserve_id FROM reserves WHERE lowestPriority = 1 ORDER BY priority" );
1474 $sth->execute();
1476 unless ( $ignoreSetLowestRank ) {
1477 while ( my $res = $sth->fetchrow_hashref() ) {
1478 _FixPriority({
1479 reserve_id => $res->{'reserve_id'},
1480 rank => '999999',
1481 ignoreSetLowestRank => 1
1487 =head2 _Findgroupreserve
1489 @results = &_Findgroupreserve($biblioitemnumber, $biblionumber, $itemnumber, $lookahead, $ignore_borrowers);
1491 Looks for a holds-queue based item-specific match first, then for a holds-queue title-level match, returning the
1492 first match found. If neither, then we look for non-holds-queue based holds.
1493 Lookahead is the number of days to look in advance.
1495 C<&_Findgroupreserve> returns :
1496 C<@results> is an array of references-to-hash whose keys are mostly
1497 fields from the reserves table of the Koha database, plus
1498 C<biblioitemnumber>.
1500 =cut
1502 sub _Findgroupreserve {
1503 my ( $bibitem, $biblio, $itemnumber, $lookahead, $ignore_borrowers) = @_;
1504 my $dbh = C4::Context->dbh;
1506 # TODO: consolidate at least the SELECT portion of the first 2 queries to a common $select var.
1507 # check for exact targeted match
1508 my $item_level_target_query = qq{
1509 SELECT reserves.biblionumber AS biblionumber,
1510 reserves.borrowernumber AS borrowernumber,
1511 reserves.reservedate AS reservedate,
1512 reserves.branchcode AS branchcode,
1513 reserves.cancellationdate AS cancellationdate,
1514 reserves.found AS found,
1515 reserves.reservenotes AS reservenotes,
1516 reserves.priority AS priority,
1517 reserves.timestamp AS timestamp,
1518 biblioitems.biblioitemnumber AS biblioitemnumber,
1519 reserves.itemnumber AS itemnumber,
1520 reserves.reserve_id AS reserve_id,
1521 reserves.itemtype AS itemtype
1522 FROM reserves
1523 JOIN biblioitems USING (biblionumber)
1524 JOIN hold_fill_targets USING (biblionumber, borrowernumber, itemnumber)
1525 WHERE found IS NULL
1526 AND priority > 0
1527 AND item_level_request = 1
1528 AND itemnumber = ?
1529 AND reservedate <= DATE_ADD(NOW(),INTERVAL ? DAY)
1530 AND suspend = 0
1531 ORDER BY priority
1533 my $sth = $dbh->prepare($item_level_target_query);
1534 $sth->execute($itemnumber, $lookahead||0);
1535 my @results;
1536 if ( my $data = $sth->fetchrow_hashref ) {
1537 push( @results, $data )
1538 unless any{ $data->{borrowernumber} eq $_ } @$ignore_borrowers ;
1540 return @results if @results;
1542 # check for title-level targeted match
1543 my $title_level_target_query = qq{
1544 SELECT reserves.biblionumber AS biblionumber,
1545 reserves.borrowernumber AS borrowernumber,
1546 reserves.reservedate AS reservedate,
1547 reserves.branchcode AS branchcode,
1548 reserves.cancellationdate AS cancellationdate,
1549 reserves.found AS found,
1550 reserves.reservenotes AS reservenotes,
1551 reserves.priority AS priority,
1552 reserves.timestamp AS timestamp,
1553 biblioitems.biblioitemnumber AS biblioitemnumber,
1554 reserves.itemnumber AS itemnumber,
1555 reserves.reserve_id AS reserve_id,
1556 reserves.itemtype AS itemtype
1557 FROM reserves
1558 JOIN biblioitems USING (biblionumber)
1559 JOIN hold_fill_targets USING (biblionumber, borrowernumber)
1560 WHERE found IS NULL
1561 AND priority > 0
1562 AND item_level_request = 0
1563 AND hold_fill_targets.itemnumber = ?
1564 AND reservedate <= DATE_ADD(NOW(),INTERVAL ? DAY)
1565 AND suspend = 0
1566 ORDER BY priority
1568 $sth = $dbh->prepare($title_level_target_query);
1569 $sth->execute($itemnumber, $lookahead||0);
1570 @results = ();
1571 if ( my $data = $sth->fetchrow_hashref ) {
1572 push( @results, $data )
1573 unless any{ $data->{borrowernumber} eq $_ } @$ignore_borrowers ;
1575 return @results if @results;
1577 my $query = qq{
1578 SELECT reserves.biblionumber AS biblionumber,
1579 reserves.borrowernumber AS borrowernumber,
1580 reserves.reservedate AS reservedate,
1581 reserves.waitingdate AS waitingdate,
1582 reserves.branchcode AS branchcode,
1583 reserves.cancellationdate AS cancellationdate,
1584 reserves.found AS found,
1585 reserves.reservenotes AS reservenotes,
1586 reserves.priority AS priority,
1587 reserves.timestamp AS timestamp,
1588 reserves.itemnumber AS itemnumber,
1589 reserves.reserve_id AS reserve_id,
1590 reserves.itemtype AS itemtype
1591 FROM reserves
1592 WHERE reserves.biblionumber = ?
1593 AND (reserves.itemnumber IS NULL OR reserves.itemnumber = ?)
1594 AND reserves.reservedate <= DATE_ADD(NOW(),INTERVAL ? DAY)
1595 AND suspend = 0
1596 ORDER BY priority
1598 $sth = $dbh->prepare($query);
1599 $sth->execute( $biblio, $itemnumber, $lookahead||0);
1600 @results = ();
1601 while ( my $data = $sth->fetchrow_hashref ) {
1602 push( @results, $data )
1603 unless any{ $data->{borrowernumber} eq $_ } @$ignore_borrowers ;
1605 return @results;
1608 =head2 _koha_notify_reserve
1610 _koha_notify_reserve( $hold->reserve_id );
1612 Sends a notification to the patron that their hold has been filled (through
1613 ModReserveAffect, _not_ ModReserveFill)
1615 The letter code for this notice may be found using the following query:
1617 select distinct letter_code
1618 from message_transports
1619 inner join message_attributes using (message_attribute_id)
1620 where message_name = 'Hold_Filled'
1622 This will probably sipmly be 'HOLD', but because it is defined in the database,
1623 it is subject to addition or change.
1625 The following tables are availalbe witin the notice:
1627 branches
1628 borrowers
1629 biblio
1630 biblioitems
1631 reserves
1632 items
1634 =cut
1636 sub _koha_notify_reserve {
1637 my $reserve_id = shift;
1638 my $hold = Koha::Holds->find($reserve_id);
1639 my $borrowernumber = $hold->borrowernumber;
1641 my $patron = Koha::Patrons->find( $borrowernumber );
1643 # Try to get the borrower's email address
1644 my $to_address = C4::Members::GetNoticeEmailAddress($borrowernumber);
1646 my $messagingprefs = C4::Members::Messaging::GetMessagingPreferences( {
1647 borrowernumber => $borrowernumber,
1648 message_name => 'Hold_Filled'
1649 } );
1651 my $library = Koha::Libraries->find( $hold->branchcode )->unblessed;
1653 my $admin_email_address = $library->{branchemail} || C4::Context->preference('KohaAdminEmailAddress');
1655 my %letter_params = (
1656 module => 'reserves',
1657 branchcode => $hold->branchcode,
1658 lang => $patron->lang,
1659 tables => {
1660 'branches' => $library,
1661 'borrowers' => $patron->unblessed,
1662 'biblio' => $hold->biblionumber,
1663 'biblioitems' => $hold->biblionumber,
1664 'reserves' => $hold->unblessed,
1665 'items' => $hold->itemnumber,
1669 my $notification_sent = 0; #Keeping track if a Hold_filled message is sent. If no message can be sent, then default to a print message.
1670 my $send_notification = sub {
1671 my ( $mtt, $letter_code ) = (@_);
1672 return unless defined $letter_code;
1673 $letter_params{letter_code} = $letter_code;
1674 $letter_params{message_transport_type} = $mtt;
1675 my $letter = C4::Letters::GetPreparedLetter ( %letter_params );
1676 unless ($letter) {
1677 warn "Could not find a letter called '$letter_params{'letter_code'}' for $mtt in the 'reserves' module";
1678 return;
1681 C4::Letters::EnqueueLetter( {
1682 letter => $letter,
1683 borrowernumber => $borrowernumber,
1684 from_address => $admin_email_address,
1685 message_transport_type => $mtt,
1686 } );
1689 while ( my ( $mtt, $letter_code ) = each %{ $messagingprefs->{transports} } ) {
1690 next if (
1691 ( $mtt eq 'email' and not $to_address ) # No email address
1692 or ( $mtt eq 'sms' and not $patron->smsalertnumber ) # No SMS number
1693 or ( $mtt eq 'phone' and C4::Context->preference('TalkingTechItivaPhoneNotification') ) # Notice is handled by TalkingTech_itiva_outbound.pl
1696 &$send_notification($mtt, $letter_code);
1697 $notification_sent++;
1699 #Making sure that a print notification is sent if no other transport types can be utilized.
1700 if (! $notification_sent) {
1701 &$send_notification('print', 'HOLD');
1706 =head2 _ShiftPriorityByDateAndPriority
1708 $new_priority = _ShiftPriorityByDateAndPriority( $biblionumber, $reservedate, $priority );
1710 This increments the priority of all reserves after the one
1711 with either the lowest date after C<$reservedate>
1712 or the lowest priority after C<$priority>.
1714 It effectively makes room for a new reserve to be inserted with a certain
1715 priority, which is returned.
1717 This is most useful when the reservedate can be set by the user. It allows
1718 the new reserve to be placed before other reserves that have a later
1719 reservedate. Since priority also is set by the form in reserves/request.pl
1720 the sub accounts for that too.
1722 =cut
1724 sub _ShiftPriorityByDateAndPriority {
1725 my ( $biblio, $resdate, $new_priority ) = @_;
1727 my $dbh = C4::Context->dbh;
1728 my $query = "SELECT priority FROM reserves WHERE biblionumber = ? AND ( reservedate > ? OR priority > ? ) ORDER BY priority ASC LIMIT 1";
1729 my $sth = $dbh->prepare( $query );
1730 $sth->execute( $biblio, $resdate, $new_priority );
1731 my $min_priority = $sth->fetchrow;
1732 # if no such matches are found, $new_priority remains as original value
1733 $new_priority = $min_priority if ( $min_priority );
1735 # Shift the priority up by one; works in conjunction with the next SQL statement
1736 $query = "UPDATE reserves
1737 SET priority = priority+1
1738 WHERE biblionumber = ?
1739 AND borrowernumber = ?
1740 AND reservedate = ?
1741 AND found IS NULL";
1742 my $sth_update = $dbh->prepare( $query );
1744 # Select all reserves for the biblio with priority greater than $new_priority, and order greatest to least
1745 $query = "SELECT borrowernumber, reservedate FROM reserves WHERE priority >= ? AND biblionumber = ? ORDER BY priority DESC";
1746 $sth = $dbh->prepare( $query );
1747 $sth->execute( $new_priority, $biblio );
1748 while ( my $row = $sth->fetchrow_hashref ) {
1749 $sth_update->execute( $biblio, $row->{borrowernumber}, $row->{reservedate} );
1752 return $new_priority; # so the caller knows what priority they wind up receiving
1755 =head2 OPACItemHoldsAllowed
1757 OPACItemHoldsAllowed($item_record,$borrower_record);
1759 Checks issuingrules, using the borrowers categorycode, the itemtype, and branchcode to see
1760 if specific item holds are allowed, returns true if so.
1762 =cut
1764 sub OPACItemHoldsAllowed {
1765 my ($item,$borrower) = @_;
1767 my $branchcode = $item->{homebranch} or die "No homebranch";
1768 my $itype;
1769 my $dbh = C4::Context->dbh;
1770 if (C4::Context->preference('item-level_itypes')) {
1771 # We can't trust GetItem to honour the syspref, so safest to do it ourselves
1772 # When GetItem is fixed, we can remove this
1773 $itype = $item->{itype};
1775 else {
1776 my $query = "SELECT itemtype FROM biblioitems WHERE biblioitemnumber = ? ";
1777 my $sth = $dbh->prepare($query);
1778 $sth->execute($item->{biblioitemnumber});
1779 if (my $data = $sth->fetchrow_hashref()){
1780 $itype = $data->{itemtype};
1784 my $query = "SELECT opacitemholds,categorycode,itemtype,branchcode FROM issuingrules WHERE
1785 (issuingrules.categorycode = ? OR issuingrules.categorycode = '*')
1787 (issuingrules.itemtype = ? OR issuingrules.itemtype = '*')
1789 (issuingrules.branchcode = ? OR issuingrules.branchcode = '*')
1790 ORDER BY
1791 issuingrules.categorycode desc,
1792 issuingrules.itemtype desc,
1793 issuingrules.branchcode desc
1794 LIMIT 1";
1795 my $sth = $dbh->prepare($query);
1796 $sth->execute($borrower->{categorycode},$itype,$branchcode);
1797 my $data = $sth->fetchrow_hashref;
1798 my $opacitemholds = uc substr ($data->{opacitemholds}, 0, 1);
1799 return '' if $opacitemholds eq 'N';
1800 return $opacitemholds;
1803 =head2 MoveReserve
1805 MoveReserve( $itemnumber, $borrowernumber, $cancelreserve )
1807 Use when checking out an item to handle reserves
1808 If $cancelreserve boolean is set to true, it will remove existing reserve
1810 =cut
1812 sub MoveReserve {
1813 my ( $itemnumber, $borrowernumber, $cancelreserve ) = @_;
1815 my $lookahead = C4::Context->preference('ConfirmFutureHolds'); #number of days to look for future holds
1816 my ( $restype, $res, $all_reserves ) = CheckReserves( $itemnumber, undef, $lookahead );
1817 return unless $res;
1819 my $biblionumber = $res->{biblionumber};
1821 if ($res->{borrowernumber} == $borrowernumber) {
1822 ModReserveFill($res);
1824 else {
1825 # warn "Reserved";
1826 # The item is reserved by someone else.
1827 # Find this item in the reserves
1829 my $borr_res;
1830 foreach (@$all_reserves) {
1831 $_->{'borrowernumber'} == $borrowernumber or next;
1832 $_->{'biblionumber'} == $biblionumber or next;
1834 $borr_res = $_;
1835 last;
1838 if ( $borr_res ) {
1839 # The item is reserved by the current patron
1840 ModReserveFill($borr_res);
1843 if ( $cancelreserve eq 'revert' ) { ## Revert waiting reserve to priority 1
1844 RevertWaitingStatus({ itemnumber => $itemnumber });
1846 elsif ( $cancelreserve eq 'cancel' || $cancelreserve ) { # cancel reserves on this item
1847 my $hold = Koha::Holds->find( $res->{reserve_id} );
1848 $hold->cancel;
1853 =head2 MergeHolds
1855 MergeHolds($dbh,$to_biblio, $from_biblio);
1857 This shifts the holds from C<$from_biblio> to C<$to_biblio> and reorders them by the date they were placed
1859 =cut
1861 sub MergeHolds {
1862 my ( $dbh, $to_biblio, $from_biblio ) = @_;
1863 my $sth = $dbh->prepare(
1864 "SELECT count(*) as reserve_count FROM reserves WHERE biblionumber = ?"
1866 $sth->execute($from_biblio);
1867 if ( my $data = $sth->fetchrow_hashref() ) {
1869 # holds exist on old record, if not we don't need to do anything
1870 $sth = $dbh->prepare(
1871 "UPDATE reserves SET biblionumber = ? WHERE biblionumber = ?");
1872 $sth->execute( $to_biblio, $from_biblio );
1874 # Reorder by date
1875 # don't reorder those already waiting
1877 $sth = $dbh->prepare(
1878 "SELECT * FROM reserves WHERE biblionumber = ? AND (found <> ? AND found <> ? OR found is NULL) ORDER BY reservedate ASC"
1880 my $upd_sth = $dbh->prepare(
1881 "UPDATE reserves SET priority = ? WHERE biblionumber = ? AND borrowernumber = ?
1882 AND reservedate = ? AND (itemnumber = ? or itemnumber is NULL) "
1884 $sth->execute( $to_biblio, 'W', 'T' );
1885 my $priority = 1;
1886 while ( my $reserve = $sth->fetchrow_hashref() ) {
1887 $upd_sth->execute(
1888 $priority, $to_biblio,
1889 $reserve->{'borrowernumber'}, $reserve->{'reservedate'},
1890 $reserve->{'itemnumber'}
1892 $priority++;
1897 =head2 RevertWaitingStatus
1899 RevertWaitingStatus({ itemnumber => $itemnumber });
1901 Reverts a 'waiting' hold back to a regular hold with a priority of 1.
1903 Caveat: Any waiting hold fixed with RevertWaitingStatus will be an
1904 item level hold, even if it was only a bibliolevel hold to
1905 begin with. This is because we can no longer know if a hold
1906 was item-level or bib-level after a hold has been set to
1907 waiting status.
1909 =cut
1911 sub RevertWaitingStatus {
1912 my ( $params ) = @_;
1913 my $itemnumber = $params->{'itemnumber'};
1915 return unless ( $itemnumber );
1917 my $dbh = C4::Context->dbh;
1919 ## Get the waiting reserve we want to revert
1920 my $query = "
1921 SELECT * FROM reserves
1922 WHERE itemnumber = ?
1923 AND found IS NOT NULL
1925 my $sth = $dbh->prepare( $query );
1926 $sth->execute( $itemnumber );
1927 my $reserve = $sth->fetchrow_hashref();
1929 ## Increment the priority of all other non-waiting
1930 ## reserves for this bib record
1931 $query = "
1932 UPDATE reserves
1934 priority = priority + 1
1935 WHERE
1936 biblionumber = ?
1938 priority > 0
1940 $sth = $dbh->prepare( $query );
1941 $sth->execute( $reserve->{'biblionumber'} );
1943 ## Fix up the currently waiting reserve
1944 $query = "
1945 UPDATE reserves
1947 priority = 1,
1948 found = NULL,
1949 waitingdate = NULL
1950 WHERE
1951 reserve_id = ?
1953 $sth = $dbh->prepare( $query );
1954 $sth->execute( $reserve->{'reserve_id'} );
1955 _FixPriority( { biblionumber => $reserve->{biblionumber} } );
1958 =head2 ReserveSlip
1960 ReserveSlip($branchcode, $borrowernumber, $biblionumber)
1962 Returns letter hash ( see C4::Letters::GetPreparedLetter ) or undef
1964 The letter code will be HOLD_SLIP, and the following tables are
1965 available within the slip:
1967 reserves
1968 branches
1969 borrowers
1970 biblio
1971 biblioitems
1972 items
1974 =cut
1976 sub ReserveSlip {
1977 my ($branch, $borrowernumber, $biblionumber) = @_;
1979 # return unless ( C4::Context->boolean_preference('printreserveslips') );
1980 my $patron = Koha::Patrons->find( $borrowernumber );
1982 my $hold = Koha::Holds->search({biblionumber => $biblionumber, borrowernumber => $borrowernumber })->next;
1983 return unless $hold;
1984 my $reserve = $hold->unblessed;
1986 return C4::Letters::GetPreparedLetter (
1987 module => 'circulation',
1988 letter_code => 'HOLD_SLIP',
1989 branchcode => $branch,
1990 lang => $patron->lang,
1991 tables => {
1992 'reserves' => $reserve,
1993 'branches' => $reserve->{branchcode},
1994 'borrowers' => $reserve->{borrowernumber},
1995 'biblio' => $reserve->{biblionumber},
1996 'biblioitems' => $reserve->{biblionumber},
1997 'items' => $reserve->{itemnumber},
2002 =head2 GetReservesControlBranch
2004 my $reserves_control_branch = GetReservesControlBranch($item, $borrower);
2006 Return the branchcode to be used to determine which reserves
2007 policy applies to a transaction.
2009 C<$item> is a hashref for an item. Only 'homebranch' is used.
2011 C<$borrower> is a hashref to borrower. Only 'branchcode' is used.
2013 =cut
2015 sub GetReservesControlBranch {
2016 my ( $item, $borrower ) = @_;
2018 my $reserves_control = C4::Context->preference('ReservesControlBranch');
2020 my $branchcode =
2021 ( $reserves_control eq 'ItemHomeLibrary' ) ? $item->{'homebranch'}
2022 : ( $reserves_control eq 'PatronLibrary' ) ? $borrower->{'branchcode'}
2023 : undef;
2025 return $branchcode;
2028 =head2 CalculatePriority
2030 my $p = CalculatePriority($biblionumber, $resdate);
2032 Calculate priority for a new reserve on biblionumber, placing it at
2033 the end of the line of all holds whose start date falls before
2034 the current system time and that are neither on the hold shelf
2035 or in transit.
2037 The reserve date parameter is optional; if it is supplied, the
2038 priority is based on the set of holds whose start date falls before
2039 the parameter value.
2041 After calculation of this priority, it is recommended to call
2042 _ShiftPriorityByDateAndPriority. Note that this is currently done in
2043 AddReserves.
2045 =cut
2047 sub CalculatePriority {
2048 my ( $biblionumber, $resdate ) = @_;
2050 my $sql = q{
2051 SELECT COUNT(*) FROM reserves
2052 WHERE biblionumber = ?
2053 AND priority > 0
2054 AND (found IS NULL OR found = '')
2056 #skip found==W or found==T (waiting or transit holds)
2057 if( $resdate ) {
2058 $sql.= ' AND ( reservedate <= ? )';
2060 else {
2061 $sql.= ' AND ( reservedate < NOW() )';
2063 my $dbh = C4::Context->dbh();
2064 my @row = $dbh->selectrow_array(
2065 $sql,
2066 undef,
2067 $resdate ? ($biblionumber, $resdate) : ($biblionumber)
2070 return @row ? $row[0]+1 : 1;
2073 =head2 IsItemOnHoldAndFound
2075 my $bool = IsItemFoundHold( $itemnumber );
2077 Returns true if the item is currently on hold
2078 and that hold has a non-null found status ( W, T, etc. )
2080 =cut
2082 sub IsItemOnHoldAndFound {
2083 my ($itemnumber) = @_;
2085 my $rs = Koha::Database->new()->schema()->resultset('Reserve');
2087 my $found = $rs->count(
2089 itemnumber => $itemnumber,
2090 found => { '!=' => undef }
2094 return $found;
2097 =head2 GetMaxPatronHoldsForRecord
2099 my $holds_per_record = ReservesControlBranch( $borrowernumber, $biblionumber );
2101 For multiple holds on a given record for a given patron, the max
2102 number of record level holds that a patron can be placed is the highest
2103 value of the holds_per_record rule for each item if the record for that
2104 patron. This subroutine finds and returns the highest holds_per_record
2105 rule value for a given patron id and record id.
2107 =cut
2109 sub GetMaxPatronHoldsForRecord {
2110 my ( $borrowernumber, $biblionumber ) = @_;
2112 my $patron = Koha::Patrons->find($borrowernumber);
2113 my @items = Koha::Items->search( { biblionumber => $biblionumber } );
2115 my $controlbranch = C4::Context->preference('ReservesControlBranch');
2117 my $categorycode = $patron->categorycode;
2118 my $branchcode;
2119 $branchcode = $patron->branchcode if ( $controlbranch eq "PatronLibrary" );
2121 my $max = 0;
2122 foreach my $item (@items) {
2123 my $itemtype = $item->effective_itemtype();
2125 $branchcode = $item->homebranch if ( $controlbranch eq "ItemHomeLibrary" );
2127 my $rule = GetHoldRule( $categorycode, $itemtype, $branchcode );
2128 my $holds_per_record = $rule ? $rule->{holds_per_record} : 0;
2129 $max = $holds_per_record if $holds_per_record > $max;
2132 return $max;
2135 =head2 GetHoldRule
2137 my $rule = GetHoldRule( $categorycode, $itemtype, $branchcode );
2139 Returns the matching hold related issuingrule fields for a given
2140 patron category, itemtype, and library.
2142 =cut
2144 sub GetHoldRule {
2145 my ( $categorycode, $itemtype, $branchcode ) = @_;
2147 my $dbh = C4::Context->dbh;
2149 my $sth = $dbh->prepare(
2151 SELECT categorycode, itemtype, branchcode, reservesallowed, holds_per_record
2152 FROM issuingrules
2153 WHERE (categorycode in (?,'*') )
2154 AND (itemtype IN (?,'*'))
2155 AND (branchcode IN (?,'*'))
2156 ORDER BY categorycode DESC,
2157 itemtype DESC,
2158 branchcode DESC
2162 $sth->execute( $categorycode, $itemtype, $branchcode );
2164 return $sth->fetchrow_hashref();
2167 =head1 AUTHOR
2169 Koha Development Team <http://koha-community.org/>
2171 =cut