Bug 6629 : Sanitizing input from language cookie
[koha.git] / opac / opac-reserve.pl
1 #!/usr/bin/perl
2
3 # This file is part of Koha.
4 #
5 # Koha is free software; you can redistribute it and/or modify it under the
6 # terms of the GNU General Public License as published by the Free Software
7 # Foundation; either version 2 of the License, or (at your option) any later
8 # version.
9 #
10 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
11 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
12 # A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
13 #
14 # You should have received a copy of the GNU General Public License along with
15 # Koha; if not, write to the Free Software Foundation, Inc., 59 Temple Place,
16 # Suite 330, Boston, MA  02111-1307 USA
17
18 use strict;
19 use warnings;
20 use CGI;
21 use C4::Auth;    # checkauth, getborrowernumber.
22 use C4::Koha;
23 use C4::Circulation;
24 use C4::Reserves;
25 use C4::Biblio;
26 use C4::Items;
27 use C4::Output;
28 use C4::Dates qw/format_date/;
29 use C4::Context;
30 use C4::Members;
31 use C4::Branch; # GetBranches
32 use C4::Debug;
33 # use Data::Dumper;
34
35 my $MAXIMUM_NUMBER_OF_RESERVES = C4::Context->preference("maxreserves");
36
37 my $query = new CGI;
38 my ( $template, $borrowernumber, $cookie ) = get_template_and_user(
39     {
40         template_name   => "opac-reserve.tmpl",
41         query           => $query,
42         type            => "opac",
43         authnotrequired => 0,
44         flagsrequired   => { borrow => 1 },
45         debug           => 1,
46     }
47 );
48 my $OPACDisplayRequestPriority = (C4::Context->preference("OPACDisplayRequestPriority")) ? 1 : 0;
49 sub get_out ($$$) {
50         output_html_with_http_headers(shift,shift,shift); # $query, $cookie, $template->output;
51         exit;
52 }
53
54 # get borrower information ....
55 my ( $borr ) = GetMemberDetails( $borrowernumber );
56
57 # Pass through any reserve charge
58 if ($borr->{reservefee} > 0){
59     $template->param( RESERVE_CHARGE => sprintf("%.2f",$borr->{reservefee}));
60 }
61 # get branches and itemtypes
62 my $branches = GetBranches();
63 my $itemTypes = GetItemTypes();
64
65 # There are two ways of calling this script, with a single biblio num
66 # or multiple biblio nums.
67 my $biblionumbers = $query->param('biblionumbers');
68 my $reserveMode = $query->param('reserve_mode');
69 if ($reserveMode && ($reserveMode eq 'single')) {
70     my $bib = $query->param('single_bib');
71     $biblionumbers = "$bib/";
72 }
73 if (! $biblionumbers) {
74     $biblionumbers = $query->param('biblionumber');
75 }
76
77 if ((! $biblionumbers) && (! $query->param('place_reserve'))) {
78     $template->param(message=>1, no_biblionumber=>1);
79     &get_out($query, $cookie, $template->output);
80 }
81
82 # Pass the numbers to the page so they can be fed back
83 # when the hold is confirmed. TODO: Not necessary?
84 $template->param( biblionumbers => $biblionumbers );
85
86 # Each biblio number is suffixed with '/', e.g. "1/2/3/"
87 my @biblionumbers = split /\//, $biblionumbers;
88 if (($#biblionumbers < 0) && (! $query->param('place_reserve'))) {
89     # TODO: New message?
90     $template->param(message=>1, no_biblionumber=>1);
91     &get_out($query, $cookie, $template->output);
92 }
93
94 # pass the pickup branch along....
95 my $branch = $query->param('branch') || $borr->{'branchcode'} || C4::Context->userenv->{branch} || '' ;
96 ($branches->{$branch}) or $branch = "";     # Confirm branch is real
97 $template->param( branch => $branch );
98
99 # make branch selection options...
100 my $CGIbranchloop = GetBranchesLoop($branch);
101 $template->param( CGIbranch => $CGIbranchloop );
102
103 # Is the person allowed to choose their branch
104 my $OPACChooseBranch = (C4::Context->preference("OPACAllowUserToChooseBranch")) ? 1 : 0;
105
106 $template->param( choose_branch => $OPACChooseBranch);
107
108 #
109 #
110 # Build hashes of the requested biblio(item)s and items.
111 #
112 #
113
114 # Hash of biblionumber to biblio/biblioitems record.
115 my %biblioDataHash;
116
117 # Hash of itemnumber to item info.
118 my %itemInfoHash;
119
120 foreach my $biblioNumber (@biblionumbers) {
121
122     my $biblioData = GetBiblioData($biblioNumber);
123     $biblioDataHash{$biblioNumber} = $biblioData;
124
125     my @itemInfos = GetItemsInfo($biblioNumber);
126
127     my $marcrecord= GetMarcBiblio($biblioNumber);
128
129         # flag indicating existence of at least one item linked via a host record
130         my $hostitemsflag;
131         # adding items linked via host biblios
132         my @hostitemInfos = GetHostItemsInfo($marcrecord);
133         if (@hostitemInfos){
134                 $hostitemsflag =1;
135                 push (@itemInfos,@hostitemInfos);
136         }
137
138
139
140     $biblioData->{itemInfos} = \@itemInfos;
141     foreach my $itemInfo (@itemInfos) {
142         $itemInfoHash{$itemInfo->{itemnumber}} = $itemInfo;
143     }
144
145     # Compute the priority rank.
146     my ( $rank, $reserves ) = GetReservesFromBiblionumber($biblioNumber,1);
147     $biblioData->{reservecount} = $rank;
148     foreach my $res (@$reserves) {
149         my $found = $res->{'found'};
150         if ( $found && ($found eq 'W') ) {
151             $rank--;
152         }
153     }
154     $rank++;
155     $biblioData->{rank} = $rank;
156 }
157
158 #
159 #
160 # If this is the second time through this script, it
161 # means we are carrying out the hold request, possibly
162 # with a specific item for each biblionumber.
163 #
164 #
165 if ( $query->param('place_reserve') ) {
166     my $notes = $query->param('notes');
167         my $canreserve=0;
168
169     # List is composed of alternating biblio/item/branch
170     my $selectedItems = $query->param('selecteditems');
171
172     if ($query->param('reserve_mode') eq 'single') {
173         # This indicates non-JavaScript mode, so there was
174         # only a single biblio number selected.
175         my $bib = $query->param('single_bib');
176         my $item = $query->param("checkitem_$bib");
177         if ($item eq 'any') {
178             $item = '';
179         }
180         my $branch = $query->param('branch');
181         $selectedItems = "$bib/$item/$branch/";
182     }
183
184     $selectedItems =~ s!/$!!;
185     my @selectedItems = split /\//, $selectedItems, -1;
186
187     # Make sure there is a biblionum/itemnum/branch triplet for each item.
188     # The itemnum can be 'any', meaning next available.
189     my $selectionCount = @selectedItems;
190     if (($selectionCount == 0) || (($selectionCount % 3) != 0)) {
191         $template->param(message=>1, bad_data=>1);
192         &get_out($query, $cookie, $template->output);
193     }
194
195     while (@selectedItems) {
196         my $biblioNum = shift(@selectedItems);
197         my $itemNum   = shift(@selectedItems);
198         my $branch    = shift(@selectedItems); # i.e., branch code, not name
199
200         my $singleBranchMode = $template->param('singleBranchMode');
201         if ($singleBranchMode || ! $OPACChooseBranch) { # single branch mode or disabled user choosing
202             $branch = $borr->{'branchcode'};
203         }
204
205         #item may belong to a host biblio, if yes change biblioNum to hosts bilbionumber
206         if ($itemNum ne '') {
207                 my $hostbiblioNum = GetBiblionumberFromItemnumber($itemNum);
208                 if ($hostbiblioNum ne $biblioNum) {
209                         $biblioNum = $hostbiblioNum;
210                 }
211         }
212
213         my $biblioData = $biblioDataHash{$biblioNum};
214         my $found;
215
216         # Check for user supplied reserve date
217         my $startdate;
218         if (
219             C4::Context->preference( 'AllowHoldDateInFuture' ) &&
220             C4::Context->preference( 'OPACAllowHoldDateInFuture' )
221             ) {
222             $startdate = $query->param("reserve_date_$biblioNum");
223         }
224         
225         my $expiration_date = $query->param("expiration_date_$biblioNum");
226
227         # If a specific item was selected and the pickup branch is the same as the
228         # holdingbranch, force the value $rank and $found.
229         my $rank = $biblioData->{rank};
230         if ($itemNum ne ''){
231                 $canreserve = 1 if CanItemBeReserved($borrowernumber,$itemNum);
232             $rank = '0' unless C4::Context->preference('ReservesNeedReturns');
233             my $item = GetItem($itemNum);
234             if ( $item->{'holdingbranch'} eq $branch ){
235                 $found = 'W' unless C4::Context->preference('ReservesNeedReturns');
236             }
237         }
238         else {
239                 $canreserve = 1 if CanBookBeReserved($borrowernumber,$biblioNum);
240             # Inserts a null into the 'itemnumber' field of 'reserves' table.
241             $itemNum = undef;
242         }
243
244         # Here we actually do the reserveration. Stage 3.
245         AddReserve($branch, $borrowernumber, $biblioNum, 'a', [$biblioNum], $rank, $startdate, $expiration_date, $notes,
246                    $biblioData->{'title'}, $itemNum, $found) if ($canreserve);
247     }
248
249     print $query->redirect("/cgi-bin/koha/opac-user.pl#opac-user-holds");
250     exit;
251 }
252
253 #
254 #
255 # Here we check that the borrower can actually make reserves Stage 1.
256 #
257 #
258 my $noreserves     = 0;
259 my $maxoutstanding = C4::Context->preference("maxoutstanding");
260 $template->param( noreserve => 1 ) unless $maxoutstanding;
261 if ( $borr->{'amountoutstanding'} && ($borr->{'amountoutstanding'} > $maxoutstanding) ) {
262     my $amount = sprintf "\$%.02f", $borr->{'amountoutstanding'};
263     $template->param( message => 1 );
264     $noreserves = 1;
265     $template->param( too_much_oweing => $amount );
266 }
267 if ( $borr->{gonenoaddress} && ($borr->{gonenoaddress} eq 1) ) {
268     $noreserves = 1;
269     $template->param(
270                      message => 1,
271                      GNA     => 1
272                     );
273 }
274 if ( $borr->{lost} && ($borr->{lost} eq 1) ) {
275     $noreserves = 1;
276     $template->param(
277                      message => 1,
278                      lost    => 1
279                     );
280 }
281 if ( $borr->{debarred} && ($borr->{debarred} eq 1) ) {
282     $noreserves = 1;
283     $template->param(
284                      message  => 1,
285                      debarred => 1
286                     );
287 }
288
289 my @reserves = GetReservesFromBorrowernumber( $borrowernumber );
290 $template->param( RESERVES => \@reserves );
291 if ( $MAXIMUM_NUMBER_OF_RESERVES && (scalar(@reserves) >= $MAXIMUM_NUMBER_OF_RESERVES) ) {
292     $template->param( message => 1 );
293     $noreserves = 1;
294     $template->param( too_many_reserves => scalar(@reserves));
295 }
296 foreach my $res (@reserves) {
297     foreach my $biblionumber (@biblionumbers) {
298         if ( $res->{'biblionumber'} == $biblionumber && $res->{'borrowernumber'} == $borrowernumber) {
299 #            $template->param( message => 1 );
300 #            $noreserves = 1;
301 #            $template->param( already_reserved => 1 );
302             $biblioDataHash{$biblionumber}->{already_reserved} = 1;
303         }
304     }
305 }
306
307 unless ($noreserves) {
308     $template->param( select_item_types => 1 );
309 }
310
311
312 #
313 #
314 # Build the template parameters that will show the info
315 # and items for each biblionumber.
316 #
317 #
318 my $notforloan_label_of = get_notforloan_label_of();
319
320 my $biblioLoop = [];
321 my $numBibsAvailable = 0;
322 my $itemdata_enumchron = 0;
323 my $anyholdable;
324 my $itemLevelTypes = C4::Context->preference('item-level_itypes');
325 $template->param('item_level_itypes' => $itemLevelTypes);
326
327 foreach my $biblioNum (@biblionumbers) {
328
329     my $record = GetMarcBiblio($biblioNum);
330     # Init the bib item with the choices for branch pickup
331     my %biblioLoopIter = ( branchChoicesLoop => $CGIbranchloop );
332
333     # Get relevant biblio data.
334     my $biblioData = $biblioDataHash{$biblioNum};
335     if (! $biblioData) {
336         $template->param(message=>1, bad_biblionumber=>$biblioNum);
337         &get_out($query, $cookie, $template->output);
338     }
339
340     $biblioLoopIter{biblionumber} = $biblioData->{biblionumber};
341     $biblioLoopIter{title} = $biblioData->{title};
342     $biblioLoopIter{subtitle} = GetRecordValue('subtitle', $record, GetFrameworkCode($biblioData->{biblionumber}));
343     $biblioLoopIter{author} = $biblioData->{author};
344     $biblioLoopIter{rank} = $biblioData->{rank};
345     $biblioLoopIter{reservecount} = $biblioData->{reservecount};
346     $biblioLoopIter{already_reserved} = $biblioData->{already_reserved};
347
348     if (!$itemLevelTypes && $biblioData->{itemtype}) {
349         $biblioLoopIter{description} = $itemTypes->{$biblioData->{itemtype}}{description};
350         $biblioLoopIter{imageurl} = getitemtypeimagesrc() . "/". $itemTypes->{$biblioData->{itemtype}}{imageurl};
351     }
352
353     foreach my $itemInfo (@{$biblioData->{itemInfos}}) {
354         $debug and warn $itemInfo->{'notforloan'};
355
356         # Get reserve fee.
357         my $fee = GetReserveFee(undef, $borrowernumber, $itemInfo->{'biblionumber'}, 'a',
358                                 ( $itemInfo->{'biblioitemnumber'} ) );
359         $itemInfo->{'reservefee'} = sprintf "%.02f", ($fee ? $fee : 0.0);
360
361         if ($itemLevelTypes && $itemInfo->{itype}) {
362             $itemInfo->{description} = $itemTypes->{$itemInfo->{itype}}{description};
363             $itemInfo->{imageurl} = getitemtypeimagesrc() . "/". $itemTypes->{$itemInfo->{itype}}{imageurl};
364         }
365
366         if (!$itemInfo->{'notforloan'} && !($itemInfo->{'itemnotforloan'} > 0)) {
367             $biblioLoopIter{forloan} = 1;
368         }
369     }
370
371     $biblioLoopIter{itemLoop} = [];
372     my $numCopiesAvailable = 0;
373     foreach my $itemInfo (@{$biblioData->{itemInfos}}) {
374         my $itemNum = $itemInfo->{itemnumber};
375         my $itemLoopIter = {};
376
377         $itemLoopIter->{itemnumber} = $itemNum;
378         $itemLoopIter->{barcode} = $itemInfo->{barcode};
379         $itemLoopIter->{homeBranchName} = $branches->{$itemInfo->{homebranch}}{branchname};
380         $itemLoopIter->{callNumber} = $itemInfo->{itemcallnumber};
381         $itemLoopIter->{enumchron} = $itemInfo->{enumchron};
382         $itemLoopIter->{copynumber} = $itemInfo->{copynumber};
383         if ($itemLevelTypes) {
384             $itemLoopIter->{description} = $itemInfo->{description};
385             $itemLoopIter->{imageurl} = $itemInfo->{imageurl};
386         }
387
388         # If the holdingbranch is different than the homebranch, we show the
389         # holdingbranch of the document too.
390         if ( $itemInfo->{homebranch} ne $itemInfo->{holdingbranch} ) {
391             $itemLoopIter->{holdingBranchName} =
392               $branches->{ $itemInfo->{holdingbranch} }{branchname};
393         }
394
395         # If the item is currently on loan, we display its return date and
396         # change the background color.
397         my $issues= GetItemIssue($itemNum);
398         if ( $issues->{'date_due'} ) {
399             $itemLoopIter->{dateDue} = format_date($issues->{'date_due'});
400             $itemLoopIter->{backgroundcolor} = 'onloan';
401         }
402
403         # checking reserve
404         my ($reservedate,$reservedfor,$expectedAt) = GetReservesFromItemnumber($itemNum);
405         my $ItemBorrowerReserveInfo = GetMemberDetails( $reservedfor, 0);
406
407         # the item could be reserved for this borrower vi a host record, flag this
408         if ($reservedfor eq $borrowernumber){
409                 $itemLoopIter->{already_reserved} = 1;
410         }
411
412         if ( defined $reservedate ) {
413             $itemLoopIter->{backgroundcolor} = 'reserved';
414             $itemLoopIter->{reservedate}     = format_date($reservedate);
415             $itemLoopIter->{ReservedForBorrowernumber} = $reservedfor;
416             $itemLoopIter->{ReservedForSurname}        = $ItemBorrowerReserveInfo->{'surname'};
417             $itemLoopIter->{ReservedForFirstname}      = $ItemBorrowerReserveInfo->{'firstname'};
418             $itemLoopIter->{ExpectedAtLibrary}         = $expectedAt;
419         }
420
421         $itemLoopIter->{notforloan} = $itemInfo->{notforloan};
422         $itemLoopIter->{itemnotforloan} = $itemInfo->{itemnotforloan};
423
424         # Management of the notforloan document
425         if ( $itemLoopIter->{notforloan} || $itemLoopIter->{itemnotforloan}) {
426             $itemLoopIter->{backgroundcolor} = 'other';
427             $itemLoopIter->{notforloanvalue} =
428               $notforloan_label_of->{ $itemLoopIter->{notforloan} };
429         }
430
431         # Management of lost or long overdue items
432         if ( $itemInfo->{itemlost} ) {
433
434             # FIXME localized strings should never be in Perl code
435             $itemLoopIter->{message} =
436                 $itemInfo->{itemlost} == 1 ? "(lost)"
437               : $itemInfo->{itemlost} == 2 ? "(long overdue)"
438               : "";
439             $itemInfo->{backgroundcolor} = 'other';
440         }
441
442         # Check of the transfered documents
443         my ( $transfertwhen, $transfertfrom, $transfertto ) =
444           GetTransfers($itemNum);
445         if ( $transfertwhen && ($transfertwhen ne '') ) {
446             $itemLoopIter->{transfertwhen} = format_date($transfertwhen);
447             $itemLoopIter->{transfertfrom} =
448               $branches->{$transfertfrom}{branchname};
449             $itemLoopIter->{transfertto} = $branches->{$transfertto}{branchname};
450             $itemLoopIter->{nocancel} = 1;
451         }
452
453         # if the items belongs to a host record, show link to host record
454         if ($itemInfo->{biblionumber} ne $biblioNum){
455                 $biblioLoopIter{hostitemsflag} = 1;
456                 $itemLoopIter->{hostbiblionumber} = $itemInfo->{biblionumber};
457                 $itemLoopIter->{hosttitle} = GetBiblioData($itemInfo->{biblionumber})->{title};
458         }
459
460         # If there is no loan, return and transfer, we show a checkbox.
461         $itemLoopIter->{notforloan} = $itemLoopIter->{notforloan} || 0;
462
463         my $branch = C4::Circulation::_GetCircControlBranch($itemLoopIter, $borr);
464
465         my $branchitemrule = GetBranchItemRule( $branch, $itemInfo->{'itype'} );
466         my $policy_holdallowed = 1;
467
468         if ( $branchitemrule->{'holdallowed'} == 0 ||
469                 ( $branchitemrule->{'holdallowed'} == 1 && $borr->{'branchcode'} ne $itemInfo->{'homebranch'} ) ) {
470             $policy_holdallowed = 0;
471         }
472
473         if (IsAvailableForItemLevelRequest($itemNum) and $policy_holdallowed and CanItemBeReserved($borrowernumber,$itemNum) and ($itemLoopIter->{already_reserved} ne 1)) {
474             $itemLoopIter->{available} = 1;
475             $numCopiesAvailable++;
476         }
477
478         # FIXME: move this to a pm
479         my $dbh = C4::Context->dbh;
480         my $sth2 = $dbh->prepare("SELECT * FROM reserves WHERE borrowernumber=? AND itemnumber=? AND found='W'");
481         $sth2->execute($itemLoopIter->{ReservedForBorrowernumber}, $itemNum);
482         while (my $wait_hashref = $sth2->fetchrow_hashref) {
483             $itemLoopIter->{waitingdate} = format_date($wait_hashref->{waitingdate});
484         }
485         $itemLoopIter->{imageurl} = getitemtypeimagelocation( 'opac', $itemTypes->{ $itemInfo->{itype} }{imageurl} );
486
487     # Show serial enumeration when needed
488         if ($itemLoopIter->{enumchron}) {
489             $itemdata_enumchron = 1;
490         }
491
492         push @{$biblioLoopIter{itemLoop}}, $itemLoopIter;
493     }
494     $template->param( itemdata_enumchron => $itemdata_enumchron );
495
496     if ($numCopiesAvailable > 0) {
497         $numBibsAvailable++;
498         $biblioLoopIter{bib_available} = 1;
499         $biblioLoopIter{holdable} = 1;
500         $anyholdable = 1;
501     }
502     if ($biblioLoopIter{already_reserved}) {
503         $biblioLoopIter{holdable} = undef;
504         $anyholdable = undef;
505     }
506     if(not CanBookBeReserved($borrowernumber,$biblioNum)){
507         $biblioLoopIter{holdable} = undef;
508         $anyholdable = undef;
509     }
510
511     push @$biblioLoop, \%biblioLoopIter;
512 }
513
514 if ( $numBibsAvailable == 0 || !$anyholdable) {
515     $template->param( none_available => 1 );
516 }
517
518 my $itemTableColspan = 7;
519 if (! $template->{VARS}->{'OPACItemHolds'}) {
520     $itemTableColspan--;
521 }
522 if (! $template->{VARS}->{'singleBranchMode'}) {
523     $itemTableColspan--;
524 }
525 $template->param(itemtable_colspan => $itemTableColspan);
526
527 # display infos
528 $template->param(bibitemloop => $biblioLoop);
529 $template->param( showpriority=>1 ) if $OPACDisplayRequestPriority;
530 # can set reserve date in future
531 if (
532     C4::Context->preference( 'AllowHoldDateInFuture' ) &&
533     C4::Context->preference( 'OPACAllowHoldDateInFuture' )
534     ) {
535     $template->param(
536             reserve_in_future         => 1,
537     );
538 }
539
540 $template->param( DHTMLcalendar_dateformat  => C4::Dates->DHTMLcalendar() );
541
542 output_html_with_http_headers $query, $cookie, $template->output;
543