Bug 31219: Prevent JS injection in patron extended attributes
[koha.git] / opac / opac-reserve.pl
1 #!/usr/bin/perl
2
3 # Copyright Katipo Communications 2002
4 # Copyright Koha Development team 2012
5 #
6 # This file is part of Koha.
7 #
8 # Koha is free software; you can redistribute it and/or modify it
9 # under the terms of the GNU General Public License as published by
10 # the Free Software Foundation; either version 3 of the License, or
11 # (at your option) any later version.
12 #
13 # Koha is distributed in the hope that it will be useful, but
14 # WITHOUT ANY WARRANTY; without even the implied warranty of
15 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 # GNU General Public License for more details.
17 #
18 # You should have received a copy of the GNU General Public License
19 # along with Koha; if not, see <http://www.gnu.org/licenses>.
20
21 use Modern::Perl;
22
23 use CGI qw ( -utf8 );
24 use C4::Auth qw( get_template_and_user );
25 use C4::Koha qw( getitemtypeimagelocation getitemtypeimagesrc );
26 use C4::Circulation qw( GetBranchItemRule GetTransfers );
27 use C4::Reserves qw( CanItemBeReserved CanBookBeReserved AddReserve GetReservesControlBranch ItemsAnyAvailableAndNotRestricted IsAvailableForItemLevelRequest );
28 use C4::Biblio qw( GetBiblioData GetFrameworkCode GetMarcBiblio );
29 use C4::Items qw( GetHostItemsInfo GetItemsInfo );
30 use C4::Output qw( output_html_with_http_headers );
31 use C4::Context;
32 use C4::Members;
33 use C4::Overdues;
34
35 use Koha::AuthorisedValues;
36 use Koha::Biblios;
37 use Koha::DateUtils qw( dt_from_string output_pref );
38 use Koha::CirculationRules;
39 use Koha::Items;
40 use Koha::ItemTypes;
41 use Koha::Checkouts;
42 use Koha::Libraries;
43 use Koha::Patrons;
44 use List::MoreUtils qw( uniq );
45
46 my $maxreserves = C4::Context->preference("maxreserves");
47
48 my $query = CGI->new;
49
50 # if OPACHoldRequests (for placing holds) is disabled, leave immediately
51 if ( ! C4::Context->preference('OPACHoldRequests') ) {
52     print $query->redirect("/cgi-bin/koha/errors/404.pl");
53     exit;
54 }
55
56 my ( $template, $borrowernumber, $cookie ) = get_template_and_user(
57     {
58         template_name   => "opac-reserve.tt",
59         query           => $query,
60         type            => "opac",
61     }
62 );
63
64 my ($show_holds_count, $show_priority);
65 for ( C4::Context->preference("OPACShowHoldQueueDetails") ) {
66     m/holds/o and $show_holds_count = 1;
67     m/priority/ and $show_priority = 1;
68 }
69
70 my $patron = Koha::Patrons->find( $borrowernumber, { prefetch => ['categorycode'] } );
71 my $category = $patron->category;
72
73 my $can_place_hold_if_available_at_pickup = C4::Context->preference('OPACHoldsIfAvailableAtPickup');
74 unless ( $can_place_hold_if_available_at_pickup ) {
75     my @patron_categories = split ',', C4::Context->preference('OPACHoldsIfAvailableAtPickupExceptions');
76     if ( @patron_categories ) {
77         my $categorycode = $patron->categorycode;
78         $can_place_hold_if_available_at_pickup = grep { $_ eq $categorycode } @patron_categories;
79     }
80 }
81
82 # check if this user can place a reserve, -1 means use sys pref, 0 means dont block, 1 means block
83 if ( $category->effective_BlockExpiredPatronOpacActions ) {
84
85     if ( $patron->is_expired ) {
86
87         # cannot reserve, their card has expired and the rules set mean this is not allowed
88         $template->param( message => 1, expired_patron => 1 );
89         output_html_with_http_headers $query, $cookie, $template->output, undef, { force_no_caching => 1 };
90         exit;
91     }
92 }
93
94 # Pass through any reserve charge
95 my $reservefee = $category->reservefee;
96 if ( $reservefee > 0){
97     $template->param( RESERVE_CHARGE => $reservefee);
98 }
99
100 my $itemtypes = { map { $_->{itemtype} => $_ } @{ Koha::ItemTypes->search_with_localization->unblessed } };
101
102 # There are two ways of calling this script, with a single biblio num
103 # or multiple biblio nums.
104 my $biblionumbers = $query->param('biblionumbers');
105 my $reserveMode = $query->param('reserve_mode');
106 if ($reserveMode && ($reserveMode eq 'single')) {
107     my $bib = $query->param('single_bib');
108     $biblionumbers = "$bib/";
109 }
110 if (! $biblionumbers) {
111     $biblionumbers = $query->param('biblionumber');
112 }
113
114 if ((! $biblionumbers) && (! $query->param('place_reserve'))) {
115     $template->param(message=>1, no_biblionumber=>1);
116     output_html_with_http_headers $query, $cookie, $template->output, undef, { force_no_caching => 1 };
117     exit;
118 }
119
120 # Pass the numbers to the page so they can be fed back
121 # when the hold is confirmed. TODO: Not necessary?
122 $template->param( biblionumbers => $biblionumbers );
123
124 # Each biblio number is suffixed with '/', e.g. "1/2/3/"
125 my @biblionumbers = split /\//, $biblionumbers;
126 if (($#biblionumbers < 0) && (! $query->param('place_reserve'))) {
127     # TODO: New message?
128     $template->param(message=>1, no_biblionumber=>1);
129     output_html_with_http_headers $query, $cookie, $template->output, undef, { force_no_caching => 1 };
130     exit;
131 }
132
133
134 # pass the pickup branch along....
135 my $branch = $query->param('branch') || $patron->branchcode || C4::Context->userenv->{branch} || '' ;
136 $template->param( branch => $branch );
137
138 #
139 #
140 # Build hashes of the requested biblio(item)s and items.
141 #
142 #
143
144 my %biblioDataHash; # Hash of biblionumber to biblio/biblioitems record.
145 my %itemInfoHash; # Hash of itemnumber to item info.
146 foreach my $biblioNumber (@biblionumbers) {
147
148     my $biblioData = GetBiblioData($biblioNumber);
149     $biblioDataHash{$biblioNumber} = $biblioData;
150
151     my @itemInfos = GetItemsInfo($biblioNumber);
152
153     my $marcrecord= GetMarcBiblio({ biblionumber => $biblioNumber });
154
155     # flag indicating existence of at least one item linked via a host record
156     my $hostitemsflag;
157     # adding items linked via host biblios
158     my @hostitemInfos = GetHostItemsInfo($marcrecord);
159     if (@hostitemInfos){
160         $hostitemsflag =1;
161         push (@itemInfos,@hostitemInfos);
162     }
163
164     $biblioData->{itemInfos} = \@itemInfos;
165     foreach my $itemInfo (@itemInfos) {
166         $itemInfoHash{$itemInfo->{itemnumber}} = $itemInfo;
167     }
168
169     # Compute the priority rank.
170     my $biblio = Koha::Biblios->find( $biblioNumber );
171     next unless $biblio;
172
173     $biblioData->{object} = $biblio;
174     my $holds = $biblio->holds;
175     my $rank = $holds->count;
176     $biblioData->{reservecount} = 1;    # new reserve
177     while ( my $hold = $holds->next ) {
178         if ( $hold->is_waiting ) {
179             $rank--;
180         }
181         else {
182             $biblioData->{reservecount}++;
183         }
184     }
185     $biblioData->{rank} = $rank + 1;
186 }
187
188 #
189 #
190 # If this is the second time through this script, it
191 # means we are carrying out the hold request, possibly
192 # with a specific item for each biblionumber.
193 #
194 #
195 if ( $query->param('place_reserve') ) {
196     my $reserve_cnt = 0;
197     if ($maxreserves) {
198         $reserve_cnt = $patron->holds->count;
199     }
200
201     # List is composed of alternating biblio/item/branch
202     my $selectedItems = $query->param('selecteditems');
203
204     if ($query->param('reserve_mode') eq 'single') {
205         # This indicates non-JavaScript mode, so there was
206         # only a single biblio number selected.
207         my $bib = $query->param('single_bib');
208         my $item = $query->param("checkitem_$bib");
209         if ($item eq 'any') {
210             $item = '';
211         }
212         my $branch = $query->param('branch');
213         $selectedItems = "$bib/$item/$branch/";
214     }
215
216     $selectedItems =~ s!/$!!;
217     my @selectedItems = split /\//, $selectedItems, -1;
218
219     # Make sure there is a biblionum/itemnum/branch triplet for each item.
220     # The itemnum can be 'any', meaning next available.
221     my $selectionCount = @selectedItems;
222     if (($selectionCount == 0) || (($selectionCount % 3) != 0)) {
223         $template->param(message=>1, bad_data=>1);
224         output_html_with_http_headers $query, $cookie, $template->output, undef, { force_no_caching => 1 };
225         exit;
226     }
227
228     my $failed_holds = 0;
229     while (@selectedItems) {
230         my $biblioNum = shift(@selectedItems);
231         my $itemNum   = shift(@selectedItems);
232         my $branch    = shift(@selectedItems);    # i.e., branch code, not name
233
234         my $canreserve = 0;
235
236         my $singleBranchMode = Koha::Libraries->search->count == 1;
237         if ( $singleBranchMode || ! C4::Context->preference("OPACAllowUserToChooseBranch") )
238         {    # single branch mode or disabled user choosing
239             $branch = $patron->branchcode;
240         }
241
242         # When choosing a specific item, the default pickup library should be dictated by the default hold policy
243         if ( ! C4::Context->preference("OPACAllowUserToChooseBranch") && $itemNum ) {
244             my $item = Koha::Items->find( $itemNum );
245             my $type = $item->effective_itemtype;
246             my $rule = GetBranchItemRule( $patron->branchcode, $type );
247
248             if ( $rule->{hold_fulfillment_policy} eq 'any' || $rule->{hold_fulfillment_policy} eq 'patrongroup' ) {
249                 $branch = $patron->branchcode;
250             } elsif ( $rule->{hold_fulfillment_policy} eq 'holdgroup' ){
251                 $branch = $item->homebranch;
252             } else {
253                 my $policy = $rule->{hold_fulfillment_policy};
254                 $branch = $item->$policy;
255             }
256         }
257
258 #item may belong to a host biblio, if yes change biblioNum to hosts bilbionumber
259         if ( $itemNum ne '' ) {
260             my $item = Koha::Items->find( $itemNum );
261             my $hostbiblioNum = $item->biblio->biblionumber;
262             if ( $hostbiblioNum ne $biblioNum ) {
263                 $biblioNum = $hostbiblioNum;
264             }
265         }
266
267         my $biblioData = $biblioDataHash{$biblioNum};
268         my $found;
269
270         # Check for user supplied reserve date
271         my $startdate;
272         if (   C4::Context->preference('AllowHoldDateInFuture')
273             && C4::Context->preference('OPACAllowHoldDateInFuture') )
274         {
275             $startdate = $query->param("reserve_date_$biblioNum");
276         }
277
278         my $expiration_date = $query->param("expiration_date_$biblioNum");
279
280         my $itemtype = $query->param('itemtype') || undef;
281         $itemtype = undef if $itemNum;
282
283         my $rank = $biblioData->{rank};
284         if ( $itemNum ne '' ) {
285             $canreserve = 1 if CanItemBeReserved( $borrowernumber, $itemNum, $branch )->{status} eq 'OK';
286         }
287         else {
288             $canreserve = 1
289               if CanBookBeReserved( $borrowernumber, $biblioNum, $branch, { itemtype => $itemtype } )->{status} eq 'OK';
290
291             # Inserts a null into the 'itemnumber' field of 'reserves' table.
292             $itemNum = undef;
293         }
294         my $notes = $query->param('notes_'.$biblioNum)||'';
295
296         if (   $maxreserves
297             && $reserve_cnt >= $maxreserves )
298         {
299             $canreserve = 0;
300         }
301
302         unless ( $can_place_hold_if_available_at_pickup ) {
303             my $items_in_this_library = Koha::Items->search({ biblionumber => $biblioNum, holdingbranch => $branch });
304             my $nb_of_items_issued = $items_in_this_library->search({ 'issue.itemnumber' => { not => undef }}, { join => 'issue' })->count;
305             my $nb_of_items_unavailable = $items_in_this_library->search({ -or => { lost => { '!=' => 0 }, damaged => { '!=' => 0 }, } });
306             if ( $items_in_this_library->count > $nb_of_items_issued + $nb_of_items_unavailable ) {
307                 $canreserve = 0
308             }
309         }
310
311         # Here we actually do the reserveration. Stage 3.
312         if ($canreserve) {
313             my $reserve_id = AddReserve(
314                 {
315                     branchcode       => $branch,
316                     borrowernumber   => $borrowernumber,
317                     biblionumber     => $biblioNum,
318                     priority         => $rank,
319                     reservation_date => $startdate,
320                     expiration_date  => $expiration_date,
321                     notes            => $notes,
322                     title            => $biblioData->{title},
323                     itemnumber       => $itemNum,
324                     found            => $found,
325                     itemtype         => $itemtype,
326                 }
327             );
328             $failed_holds++ unless $reserve_id;
329             ++$reserve_cnt;
330         }
331     }
332
333     print $query->redirect("/cgi-bin/koha/opac-user.pl?" . ( $failed_holds ? "failed_holds=$failed_holds" : q|| ) . "#opac-user-holds");
334     exit;
335 }
336
337 #
338 #
339 # Here we check that the borrower can actually make reserves Stage 1.
340 #
341 #
342 my $noreserves     = 0;
343 my $maxoutstanding = C4::Context->preference("maxoutstanding");
344 $template->param( noreserve => 1 ) unless $maxoutstanding;
345 my $amountoutstanding = $patron->account->balance;
346 if ( $amountoutstanding && ($amountoutstanding > $maxoutstanding) ) {
347     my $amount = sprintf "%.02f", $amountoutstanding;
348     $template->param( message => 1 );
349     $noreserves = 1;
350     $template->param( too_much_oweing => $amount );
351 }
352
353 if ( $patron->gonenoaddress && ($patron->gonenoaddress == 1) ) {
354     $noreserves = 1;
355     $template->param(
356         message => 1,
357         GNA     => 1
358     );
359 }
360
361 if ( $patron->lost && ($patron->lost == 1) ) {
362     $noreserves = 1;
363     $template->param(
364         message => 1,
365         lost    => 1
366     );
367 }
368
369 if ( $patron->is_debarred ) {
370     $noreserves = 1;
371     $template->param(
372         message          => 1,
373         debarred         => 1,
374         debarred_comment => $patron->debarredcomment,
375         debarred_date    => $patron->debarred,
376     );
377 }
378
379 my $holds = $patron->holds;
380 my $reserves_count = $holds->count;
381 $template->param( RESERVES => $holds->unblessed );
382 if ( $maxreserves && ( $reserves_count >= $maxreserves ) ) {
383     $template->param( message => 1 );
384     $noreserves = 1;
385     $template->param( too_many_reserves => $holds->count );
386 }
387
388 unless ( $noreserves ) {
389     my $requested_reserves_count = scalar( @biblionumbers );
390     if ( $maxreserves && ( $reserves_count + $requested_reserves_count > $maxreserves ) ) {
391         $template->param( new_reserves_allowed => $maxreserves - $reserves_count );
392     }
393 }
394
395 unless ($noreserves) {
396     $template->param( select_item_types => 1 );
397 }
398
399
400 #
401 #
402 # Build the template parameters that will show the info
403 # and items for each biblionumber.
404 #
405 #
406
407 my $biblioLoop = [];
408 my $numBibsAvailable = 0;
409 my $itemdata_enumchron = 0;
410 my $itemdata_ccode = 0;
411 my $anyholdable = 0;
412 my $itemLevelTypes = C4::Context->preference('item-level_itypes');
413 my $pickup_locations = Koha::Libraries->search({ pickup_location => 1 });
414 $template->param('item_level_itypes' => $itemLevelTypes);
415
416 foreach my $biblioNum (@biblionumbers) {
417
418     # Init the bib item with the choices for branch pickup
419     my %biblioLoopIter;
420
421     # Get relevant biblio data.
422     my $biblioData = $biblioDataHash{$biblioNum};
423     if (! $biblioData) {
424         $template->param(message=>1, bad_biblionumber=>$biblioNum);
425         output_html_with_http_headers $query, $cookie, $template->output, undef, { force_no_caching => 1 };
426         exit;
427     }
428
429     my @not_available_at = ();
430     my $biblio = $biblioData->{object};
431     foreach my $library ( $pickup_locations->as_list ) {
432         push( @not_available_at, $library->branchcode ) unless $biblio->can_be_transferred({ to => $library });
433     }
434
435     my $frameworkcode = GetFrameworkCode( $biblioData->{biblionumber} );
436     $biblioLoopIter{biblionumber} = $biblioData->{biblionumber};
437     $biblioLoopIter{title} = $biblioData->{title};
438     $biblioLoopIter{subtitle} = $biblioData->{'subtitle'};
439     $biblioLoopIter{medium} = $biblioData->{medium};
440     $biblioLoopIter{part_number} = $biblioData->{part_number};
441     $biblioLoopIter{part_name} = $biblioData->{part_name};
442     $biblioLoopIter{author} = $biblioData->{author};
443     $biblioLoopIter{rank} = $biblioData->{rank};
444     $biblioLoopIter{reservecount} = $biblioData->{reservecount};
445     $biblioLoopIter{already_reserved} = $biblioData->{already_reserved};
446     $biblioLoopIter{reqholdnotes}=0; #TODO: For future use
447
448     if (!$itemLevelTypes && $biblioData->{itemtype}) {
449         $biblioLoopIter{translated_description} = $itemtypes->{$biblioData->{itemtype}}{translated_description};
450         $biblioLoopIter{imageurl} = getitemtypeimagesrc() . "/". $itemtypes->{$biblioData->{itemtype}}{imageurl};
451     }
452
453     foreach my $itemInfo (@{$biblioData->{itemInfos}}) {
454         if ($itemLevelTypes && $itemInfo->{itype}) {
455             $itemInfo->{translated_description} = $itemtypes->{$itemInfo->{itype}}{translated_description};
456             $itemInfo->{imageurl} = getitemtypeimagesrc() . "/". $itemtypes->{$itemInfo->{itype}}{imageurl};
457         }
458
459         if (!$itemInfo->{'notforloan'} && !($itemInfo->{'itemnotforloan'} > 0)) {
460             $biblioLoopIter{forloan} = 1;
461         }
462     }
463
464     my @notforloan_avs = Koha::AuthorisedValues->search_by_koha_field({ kohafield => 'items.notforloan', frameworkcode => $frameworkcode });
465     my $notforloan_label_of = { map { $_->authorised_value => $_->opac_description } @notforloan_avs };
466
467     my $visible_items = { map { $_->itemnumber => $_ } $biblio->items->filter_by_visible_in_opac( { patron => $patron } )->as_list };
468
469     # Only keep the items that are visible in the opac (i.e. those in %visible_items)
470     # FIXME: We should get rid of itemInfos altogether and use $visible_items
471     $biblioData->{itemInfos} = [ grep { $visible_items->{ $_->{itemnumber} } } @{ $biblioData->{itemInfos} } ];
472
473     $biblioLoopIter{itemLoop} = [];
474     my $numCopiesAvailable = 0;
475     my $numCopiesOPACAvailable = 0;
476     # iterating through all items first to check if any of them available
477     # to pass this value further inside down to IsAvailableForItemLevelRequest to
478     # it's complicated logic to analyse.
479     # (before this loop was inside that sub loop so it was O(n^2) )
480     my $items_any_available;
481     $items_any_available = ItemsAnyAvailableAndNotRestricted( { biblionumber => $biblioNum, patron => $patron }) if $patron;
482     foreach my $itemInfo (@{$biblioData->{itemInfos}}) {
483         my $itemNum = $itemInfo->{itemnumber};
484         my $item = $visible_items->{$itemNum};
485         my $itemLoopIter = {};
486
487         $itemLoopIter->{itemnumber} = $itemNum;
488         $itemLoopIter->{barcode} = $itemInfo->{barcode};
489         $itemLoopIter->{homeBranchName} = $itemInfo->{homebranch};
490         $itemLoopIter->{callNumber} = $itemInfo->{itemcallnumber};
491         $itemLoopIter->{enumchron} = $itemInfo->{enumchron};
492         $itemLoopIter->{ccode} = $itemInfo->{ccode};
493         $itemLoopIter->{copynumber} = $itemInfo->{copynumber};
494         if ($itemLevelTypes) {
495             $itemLoopIter->{translated_description} = $itemInfo->{translated_description};
496             $itemLoopIter->{itype} = $itemInfo->{itype};
497             $itemLoopIter->{imageurl} = $itemInfo->{imageurl};
498         }
499
500         # If the holdingbranch is different than the homebranch, we show the
501         # holdingbranch of the document too.
502         if ( $itemInfo->{homebranch} ne $itemInfo->{holdingbranch} ) {
503             $itemLoopIter->{holdingBranchName} = $itemInfo->{holdingbranch};
504         }
505
506         # If the item is currently on loan, we display its return date and
507         # change the background color.
508         my $issue = Koha::Checkouts->find( { itemnumber => $itemNum } );
509         if ( $issue ) {
510             $itemLoopIter->{dateDue} = $issue->date_due;
511             $itemLoopIter->{onloan} = 'onloan';
512         }
513
514         # checking reserve
515         my $holds = $item->current_holds;
516
517         if ( my $first_hold = $holds->next ) {
518             $itemLoopIter->{backgroundcolor} = 'reserved';
519             $itemLoopIter->{reservedate}     = output_pref({ dt => dt_from_string($first_hold->reservedate), dateonly => 1 }); # FIXME Should be formatted in the template
520             $itemLoopIter->{ExpectedAtLibrary}         = $first_hold->branchcode;
521             $itemLoopIter->{waitingdate} = $first_hold->waitingdate;
522         }
523
524         $itemLoopIter->{notforloan} = $itemInfo->{notforloan};
525         $itemLoopIter->{itemnotforloan} = $itemInfo->{itemnotforloan};
526
527         # Management of the notforloan document
528         if ( $itemLoopIter->{notforloan} || $itemLoopIter->{itemnotforloan}) {
529             $itemLoopIter->{backgroundcolor} = 'other';
530             $itemLoopIter->{notforloanvalue} =
531               $notforloan_label_of->{ $itemLoopIter->{notforloan} };
532         }
533
534         # Management of lost or long overdue items
535         if ( $itemInfo->{itemlost} ) {
536
537             # FIXME localized strings should never be in Perl code
538             $itemLoopIter->{message} =
539                 $itemInfo->{itemlost} == 1 ? "(lost)"
540               : $itemInfo->{itemlost} == 2 ? "(long overdue)"
541               : "";
542             $itemInfo->{backgroundcolor} = 'other';
543         }
544
545         # Check of the transferred documents
546         my ( $transfertwhen, $transfertfrom, $transfertto ) =
547           GetTransfers($itemNum);
548         if ( $transfertwhen && ($transfertwhen ne '') ) {
549             $itemLoopIter->{transfertwhen} = output_pref({ dt => dt_from_string($transfertwhen), dateonly => 1 });
550             $itemLoopIter->{transfertfrom} = $transfertfrom;
551             $itemLoopIter->{transfertto} = $transfertto;
552             $itemLoopIter->{nocancel} = 1;
553         }
554
555         # if the items belongs to a host record, show link to host record
556         if ( $itemInfo->{biblionumber} ne $biblioNum ) {
557             $biblioLoopIter{hostitemsflag}    = 1;
558             $itemLoopIter->{hostbiblionumber} = $itemInfo->{biblionumber};
559             $itemLoopIter->{hosttitle}        = Koha::Biblios->find( $itemInfo->{biblionumber} )->title;
560         }
561
562         # If there is no loan, return and transfer, we show a checkbox.
563         $itemLoopIter->{notforloan} = $itemLoopIter->{notforloan} || 0;
564
565         my $patron_unblessed = $patron->unblessed;
566         my $branch = GetReservesControlBranch( $itemInfo, $patron_unblessed );
567
568         my $policy_holdallowed = !$itemLoopIter->{already_reserved};
569         # items_any_available defined outside of the current loop,
570         # so we avoiding loop inside IsAvailableForItemLevelRequest:
571         $policy_holdallowed &&=
572             CanItemBeReserved( $borrowernumber, $itemNum )->{status} eq 'OK' &&
573             IsAvailableForItemLevelRequest($item, $patron, undef, $items_any_available);
574
575         if ($policy_holdallowed) {
576             my $opac_hold_policy = Koha::CirculationRules->get_opacitemholds_policy( { item => $item, patron => $patron } );
577             if ( $opac_hold_policy ne 'N' ) { # If Y or F
578                 $itemLoopIter->{available} = 1;
579                 $numCopiesOPACAvailable++;
580                 $biblioLoopIter{force_hold} = 1 if $opac_hold_policy eq 'F';
581             }
582             $numCopiesAvailable++;
583
584             unless ( $can_place_hold_if_available_at_pickup ) {
585                 my $items_in_this_library = Koha::Items->search({ biblionumber => $itemInfo->{biblionumber}, holdingbranch => $itemInfo->{holdingbranch} });
586                 my $nb_of_items_issued = $items_in_this_library->search({ 'issue.itemnumber' => { not => undef }}, { join => 'issue' })->count;
587                 if ( $items_in_this_library->count > $nb_of_items_issued ) {
588                     push @not_available_at, $itemInfo->{holdingbranch};
589                 }
590             }
591         }
592
593         $itemLoopIter->{imageurl} = getitemtypeimagelocation( 'opac', $itemtypes->{ $itemInfo->{itype} }{imageurl} );
594
595     # Show serial enumeration when needed
596         if ($itemLoopIter->{enumchron}) {
597             $itemdata_enumchron = 1;
598         }
599     # Show collection when needed
600         if ($itemLoopIter->{ccode}) {
601             $itemdata_ccode = 1;
602         }
603
604         push @{$biblioLoopIter{itemLoop}}, $itemLoopIter;
605     }
606     $template->param(
607         itemdata_enumchron => $itemdata_enumchron,
608         itemdata_ccode     => $itemdata_ccode,
609     );
610
611     if ($numCopiesAvailable > 0) {
612         $numBibsAvailable++;
613         $biblioLoopIter{bib_available} = 1;
614         $biblioLoopIter{holdable} = 1;
615         $biblioLoopIter{itemholdable} = 1 if $numCopiesOPACAvailable;
616     }
617     if ($biblioLoopIter{already_reserved}) {
618         $biblioLoopIter{holdable} = undef;
619         $biblioLoopIter{itemholdable} = undef;
620     }
621     if ( $biblioLoopIter{holdable} ) {
622         @not_available_at = uniq @not_available_at;
623         $biblioLoopIter{not_available_at} = \@not_available_at ;
624     }
625
626     unless ( $can_place_hold_if_available_at_pickup ) {
627         @not_available_at = uniq @not_available_at;
628         $biblioLoopIter{not_available_at} = \@not_available_at ;
629         # The record is not holdable is not available at any of the libraries
630         if ( Koha::Libraries->search->count == @not_available_at ) {
631             $biblioLoopIter{holdable} = 0;
632         }
633     }
634
635     my $status = CanBookBeReserved( $borrowernumber, $biblioNum )->{status};
636     $biblioLoopIter{holdable} &&= $status eq 'OK';
637     $biblioLoopIter{$status} = 1;
638
639     if ( $biblioLoopIter{holdable} and C4::Context->preference('AllowHoldItemTypeSelection') ) {
640         # build the allowed item types loop
641         my $rs = $biblio->items->search(
642             undef,
643             {   select => [ { distinct => 'itype' } ],
644                 as     => 'item_type'
645             }
646         );
647
648         my @item_types =
649           grep { CanBookBeReserved( $borrowernumber, $biblioNum, $branch, { itemtype => $_ } )->{status} eq 'OK' }
650           $rs->get_column('item_type');
651
652         $biblioLoopIter{allowed_item_types} = \@item_types;
653     }
654
655     # For multiple holds per record, if a patron has previously placed a hold,
656     # the patron can only place more holds of the same type. That is, if the
657     # patron placed a record level hold, all the holds the patron places must
658     # be record level. If the patron placed an item level hold, all holds
659     # the patron places must be item level
660     my $forced_hold_level = Koha::Holds->search(
661         {
662             borrowernumber => $borrowernumber,
663             biblionumber   => $biblioNum,
664             found          => undef,
665         }
666     )->forced_hold_level();
667     if ($forced_hold_level) {
668         $biblioLoopIter{force_hold}   = 1 if $forced_hold_level eq 'item';
669         $biblioLoopIter{itemholdable} = 0 if $forced_hold_level eq 'record';
670         $biblioLoopIter{forced_hold_level} = $forced_hold_level;
671     }
672
673
674     push @$biblioLoop, \%biblioLoopIter;
675
676     $anyholdable = 1 if $biblioLoopIter{holdable};
677 }
678
679 unless ($pickup_locations->count) {
680     $numBibsAvailable = 0;
681     $anyholdable = 0;
682     $template->param(
683         message => 1,
684         no_pickup_locations => 1
685     );
686 }
687
688 if ( $numBibsAvailable == 0 || $anyholdable == 0) {
689     $template->param( none_available => 1 );
690 }
691
692 if (scalar @biblionumbers > 1) {
693     $template->param( multi_hold => 1);
694 }
695
696 my $show_notes=C4::Context->preference('OpacHoldNotes');
697 $template->param(OpacHoldNotes=>$show_notes);
698
699 # display infos
700 $template->param(bibitemloop => $biblioLoop);
701 # can set reserve date in future
702 if (
703     C4::Context->preference( 'AllowHoldDateInFuture' ) &&
704     C4::Context->preference( 'OPACAllowHoldDateInFuture' )
705     ) {
706     $template->param(
707             reserve_in_future         => 1,
708     );
709 }
710
711 output_html_with_http_headers $query, $cookie, $template->output, undef, { force_no_caching => 1 };