Bug 643: QA Followup - server-side verification of permissions
[koha.git] / circ / circulation.pl
1 #!/usr/bin/perl
2
3 # script to execute issuing of books
4
5 # Copyright 2000-2002 Katipo Communications
6 # copyright 2010 BibLibre
7 # Copyright 2011 PTFS-Europe Ltd.
8 # Copyright 2012 software.coop and MJ Ray
9 #
10 # This file is part of Koha.
11 #
12 # Koha is free software; you can redistribute it and/or modify it under the
13 # terms of the GNU General Public License as published by the Free Software
14 # Foundation; either version 2 of the License, or (at your option) any later
15 # version.
16 #
17 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
18 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
19 # A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
20 #
21 # You should have received a copy of the GNU General Public License along
22 # with Koha; if not, write to the Free Software Foundation, Inc.,
23 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
24
25 use strict;
26 use warnings;
27 use CGI;
28 use C4::Output;
29 use C4::Print;
30 use C4::Auth qw/:DEFAULT get_session haspermission/;
31 use C4::Dates qw/format_date/;
32 use C4::Branch; # GetBranches
33 use C4::Koha;   # GetPrinter
34 use C4::Circulation;
35 use C4::Members;
36 use C4::Biblio;
37 use C4::Search;
38 use MARC::Record;
39 use C4::Reserves;
40 use C4::Context;
41 use CGI::Session;
42 use C4::Members::Attributes qw(GetBorrowerAttributes);
43 use Koha::Borrower::Debarments qw(GetDebarments IsDebarred);
44 use Koha::DateUtils;
45 use Koha::Database;
46
47 use Date::Calc qw(
48   Today
49   Add_Delta_YM
50   Add_Delta_Days
51   Date_to_Days
52 );
53 use List::MoreUtils qw/uniq/;
54
55
56 #
57 # PARAMETERS READING
58 #
59 my $query = new CGI;
60
61 my $sessionID = $query->cookie("CGISESSID") ;
62 my $session = get_session($sessionID);
63
64 # branch and printer are now defined by the userenv
65 # but first we have to check if someone has tried to change them
66
67 my $branch = $query->param('branch');
68 if ($branch){
69     # update our session so the userenv is updated
70     $session->param('branch', $branch);
71     $session->param('branchname', GetBranchName($branch));
72 }
73
74 my $printer = $query->param('printer');
75 if ($printer){
76     # update our session so the userenv is updated
77     $session->param('branchprinter', $printer);
78 }
79
80 if (!C4::Context->userenv && !$branch){
81     if ($session->param('branch') eq 'NO_LIBRARY_SET'){
82         # no branch set we can't issue
83         print $query->redirect("/cgi-bin/koha/circ/selectbranchprinter.pl");
84         exit;
85     }
86 }
87
88 my ( $template, $loggedinuser, $cookie ) = get_template_and_user (
89     {
90         template_name   => 'circ/circulation.tt',
91         query           => $query,
92         type            => "intranet",
93         authnotrequired => 0,
94         flagsrequired   => { circulate => 'circulate_remaining_permissions' },
95     }
96 );
97
98 my $branches = GetBranches();
99
100 my $force_allow_issue = $query->param('forceallow') || 0;
101 if (!C4::Auth::haspermission( C4::Context->userenv->{id} , { circulate => 'force_checkout' } )) {
102     $force_allow_issue = 0;
103 }
104
105 my @failedrenews = $query->param('failedrenew');    # expected to be itemnumbers
106 our %renew_failed = ();
107 for (@failedrenews) { $renew_failed{$_} = 1; }
108
109 my @failedreturns = $query->param('failedreturn');
110 our %return_failed = ();
111 for (@failedreturns) { $return_failed{$_} = 1; }
112
113 my $findborrower = $query->param('findborrower') || q{};
114 $findborrower =~ s|,| |g;
115 my $borrowernumber = $query->param('borrowernumber');
116
117 $branch  = C4::Context->userenv->{'branch'};  
118 $printer = C4::Context->userenv->{'branchprinter'};
119
120
121 # If AutoLocation is not activated, we show the Circulation Parameters to chage settings of librarian
122 if (C4::Context->preference("AutoLocation") != 1) {
123     $template->param(ManualLocation => 1);
124 }
125
126 if (C4::Context->preference("DisplayClearScreenButton")) {
127     $template->param(DisplayClearScreenButton => 1);
128 }
129
130 my $barcode        = $query->param('barcode') || q{};
131 $barcode =~  s/^\s*|\s*$//g; # remove leading/trailing whitespace
132
133 $barcode = barcodedecode($barcode) if( $barcode && C4::Context->preference('itemBarcodeInputFilter'));
134 my $stickyduedate  = $query->param('stickyduedate') || $session->param('stickyduedate');
135 my $duedatespec    = $query->param('duedatespec')   || $session->param('stickyduedate');
136 my $issueconfirmed = $query->param('issueconfirmed');
137 my $cancelreserve  = $query->param('cancelreserve');
138 my $print          = $query->param('print') || q{};
139 my $debt_confirmed = $query->param('debt_confirmed') || 0; # Don't show the debt error dialog twice
140 my $charges        = $query->param('charges') || q{};
141
142 # Check if stickyduedate is turned off
143 if ( $barcode ) {
144     # was stickyduedate loaded from session?
145     if ( $stickyduedate && ! $query->param("stickyduedate") ) {
146         $session->clear( 'stickyduedate' );
147         $stickyduedate  = $query->param('stickyduedate');
148         $duedatespec    = $query->param('duedatespec');
149     }
150     $session->param('auto_renew', $query->param('auto_renew'));
151 }
152 else {
153     $session->clear('auto_renew');
154 }
155
156 my ($datedue,$invalidduedate);
157
158 my $duedatespec_allow = C4::Context->preference('SpecifyDueDate');
159 if($duedatespec_allow){
160     if ($duedatespec) {
161         if ($duedatespec =~ C4::Dates->regexp('syspref')) {
162                 $datedue = dt_from_string($duedatespec);
163         } else {
164             $invalidduedate = 1;
165             $template->param(IMPOSSIBLE=>1, INVALID_DATE=>$duedatespec);
166         }
167     }
168 }
169
170 our $todaysdate = C4::Dates->new->output('iso');
171
172 # check and see if we should print
173 if ( $barcode eq '' && $print eq 'maybe' ) {
174     $print = 'yes';
175 }
176
177 my $inprocess = ($barcode eq '') ? '' : $query->param('inprocess');
178 if ( $barcode eq '' && $charges eq 'yes' ) {
179     $template->param(
180         PAYCHARGES     => 'yes',
181         borrowernumber => $borrowernumber
182     );
183 }
184
185 if ( $print eq 'yes' && $borrowernumber ne '' ) {
186     if ( C4::Context->boolean_preference('printcirculationslips') ) {
187         my $letter = IssueSlip($branch, $borrowernumber, "QUICK");
188         NetworkPrint($letter->{content});
189     }
190     $query->param( 'borrowernumber', '' );
191     $borrowernumber = '';
192 }
193
194 #
195 # STEP 2 : FIND BORROWER
196 # if there is a list of find borrowers....
197 #
198 my $borrowerslist;
199 my $message;
200 if ($findborrower) {
201     my $borrowers = Search($findborrower, 'cardnumber') || [];
202     if (C4::Context->preference("AddPatronLists")) {
203         $template->param(
204             "AddPatronLists_".C4::Context->preference("AddPatronLists")=> "1",
205         );
206         if (C4::Context->preference("AddPatronLists")=~/code/){
207             my $categories = GetBorrowercategoryList;
208             $categories->[0]->{'first'} = 1;
209             $template->param(categories=>$categories);
210         }
211     }
212     if ( @$borrowers == 0 ) {
213         $query->param( 'findborrower', '' );
214         $message = "'$findborrower'";
215     }
216     elsif ( @$borrowers == 1 ) {
217         $borrowernumber = $borrowers->[0]->{'borrowernumber'};
218         $query->param( 'borrowernumber', $borrowernumber );
219         $query->param( 'barcode',           '' );
220     }
221     else {
222         $borrowerslist = $borrowers;
223     }
224 }
225
226 # get the borrower information.....
227 my $borrower;
228 if ($borrowernumber) {
229     $borrower = GetMemberDetails( $borrowernumber, 0 );
230     my ( $od, $issue, $fines ) = GetMemberIssuesAndFines( $borrowernumber );
231
232     # Warningdate is the date that the warning starts appearing
233     my (  $today_year,   $today_month,   $today_day) = Today();
234     my ($warning_year, $warning_month, $warning_day) = split /-/, $borrower->{'dateexpiry'};
235     my (  $enrol_year,   $enrol_month,   $enrol_day) = split /-/, $borrower->{'dateenrolled'};
236     # Renew day is calculated by adding the enrolment period to today
237     my (  $renew_year,   $renew_month,   $renew_day);
238     if ($enrol_year*$enrol_month*$enrol_day>0) {
239         (  $renew_year,   $renew_month,   $renew_day) =
240         Add_Delta_YM( $enrol_year, $enrol_month, $enrol_day,
241             0 , $borrower->{'enrolmentperiod'});
242     }
243     # if the expiry date is before today ie they have expired
244     if ( !$borrower->{'dateexpiry'} || $warning_year*$warning_month*$warning_day==0
245         || Date_to_Days($today_year,     $today_month, $today_day  ) 
246          > Date_to_Days($warning_year, $warning_month, $warning_day) )
247     {
248         #borrowercard expired, no issues
249         $template->param(
250             flagged  => "1",
251             noissues => ($force_allow_issue) ? 0 : "1",
252             forceallow => $force_allow_issue,
253             expired => "1",
254             renewaldate => format_date("$renew_year-$renew_month-$renew_day")
255         );
256     }
257     # check for NotifyBorrowerDeparture
258     elsif ( C4::Context->preference('NotifyBorrowerDeparture') &&
259             Date_to_Days(Add_Delta_Days($warning_year,$warning_month,$warning_day,- C4::Context->preference('NotifyBorrowerDeparture'))) <
260             Date_to_Days( $today_year, $today_month, $today_day ) ) 
261     {
262         # borrower card soon to expire warn librarian
263         $template->param("warndeparture" => format_date($borrower->{dateexpiry}),
264         flagged       => "1",);
265         if (C4::Context->preference('ReturnBeforeExpiry')){
266             $template->param("returnbeforeexpiry" => 1);
267         }
268     }
269     $template->param(
270         overduecount => $od,
271         issuecount   => $issue,
272         finetotal    => $fines
273     );
274
275     if ( IsDebarred($borrowernumber) ) {
276         $template->param(
277             'userdebarred'    => $borrower->{debarred},
278             'debarredcomment' => $borrower->{debarredcomment},
279         );
280
281         if ( $borrower->{debarred} ne "9999-12-31" ) {
282             $template->param( 'userdebarreddate' =>
283                   C4::Dates::format_date( $borrower->{debarred} ) );
284         }
285     }
286
287 }
288
289 #
290 # STEP 3 : ISSUING
291 #
292 #
293 if ($barcode) {
294     # always check for blockers on issuing
295     my ( $error, $question, $alerts ) =
296     CanBookBeIssued( $borrower, $barcode, $datedue , $inprocess );
297     my $blocker = $invalidduedate ? 1 : 0;
298
299     $template->param( alert => $alerts );
300
301     #  Get the item title for more information
302     my $getmessageiteminfo = GetBiblioFromItemNumber(undef,$barcode);
303     $template->param(
304         authvalcode_notforloan => C4::Koha::GetAuthValCode('items.notforloan', $getmessageiteminfo->{'frameworkcode'}),
305     );
306     # Fix for bug 7494: optional checkout-time fallback search for a book
307
308     if ( $error->{'UNKNOWN_BARCODE'}
309         && C4::Context->preference("itemBarcodeFallbackSearch") )
310     {
311      $template->param( FALLBACK => 1 );
312
313         my $query = "kw=" . $barcode;
314         my ( $searcherror, $results, $total_hits ) = SimpleSearch($query);
315
316         # if multiple hits, offer options to librarian
317         if ( $total_hits > 0 ) {
318             my @options = ();
319             foreach my $hit ( @{$results} ) {
320                 my $chosen =
321                   TransformMarcToKoha( C4::Context->dbh,
322                     C4::Search::new_record_from_zebra('biblioserver',$hit) );
323
324                 # offer all barcodes individually
325                 if ( $chosen->{barcode} ) {
326                     foreach my $barcode ( sort split(/\s*\|\s*/, $chosen->{barcode}) ) {
327                         my %chosen_single = %{$chosen};
328                         $chosen_single{barcode} = $barcode;
329                         push( @options, \%chosen_single );
330                     }
331                 }
332             }
333             $template->param( options => \@options );
334         }
335     }
336
337     delete $question->{'DEBT'} if ($debt_confirmed);
338     foreach my $impossible ( keys %$error ) {
339         $template->param(
340             $impossible => $$error{$impossible},
341             IMPOSSIBLE  => 1
342         );
343         $blocker = 1;
344     }
345     if( !$blocker || $force_allow_issue ){
346         my $confirm_required = 0;
347         unless($issueconfirmed){
348             #  Get the item title for more information
349             my $getmessageiteminfo  = GetBiblioFromItemNumber(undef,$barcode);
350             $template->{VARS}->{'additional_materials'} = $getmessageiteminfo->{'materials'};
351             $template->param( itemhomebranch => $getmessageiteminfo->{'homebranch'} );
352
353             # pass needsconfirmation to template if issuing is possible and user hasn't yet confirmed.
354             foreach my $needsconfirmation ( keys %$question ) {
355                 $template->param(
356                     $needsconfirmation => $$question{$needsconfirmation},
357                     getTitleMessageIteminfo => $getmessageiteminfo->{'title'},
358                     getBarcodeMessageIteminfo => $getmessageiteminfo->{'barcode'},
359                     NEEDSCONFIRMATION  => 1
360                 );
361                 $confirm_required = 1;
362             }
363         }
364         unless($confirm_required) {
365             AddIssue( $borrower, $barcode, $datedue, $cancelreserve, undef, undef, $session->param('auto_renew') );
366             $session->clear('auto_renew');
367             $inprocess = 1;
368         }
369     }
370     
371     my ( $od, $issue, $fines ) = GetMemberIssuesAndFines($borrowernumber);
372     $template->param( issuecount => $issue );
373 }
374
375 # reload the borrower info for the sake of reseting the flags.....
376 if ($borrowernumber) {
377     $borrower = GetMemberDetails( $borrowernumber, 0 );
378 }
379
380 ##################################################################################
381 # BUILD HTML
382 # show all reserves of this borrower, and the position of the reservation ....
383 if ($borrowernumber) {
384     $template->param(
385         holds_count => Koha::Database->new()->schema()->resultset('Reserve')
386           ->count( { borrowernumber => $borrowernumber } ) );
387
388     $template->param( adultborrower => 1 ) if ( $borrower->{'category_type'} eq 'A' );
389 }
390
391 my @values;
392 my %labels;
393 my $selectborrower;
394 if ($borrowerslist) {
395     foreach (
396         sort {(lc $a->{'surname'} cmp lc $b->{'surname'} || lc $a->{'firstname'} cmp lc $b->{'firstname'})
397         } @$borrowerslist
398       )
399     {
400         push @values, $_->{'borrowernumber'};
401         $labels{ $_->{'borrowernumber'} } =
402 "$_->{'surname'}, $_->{'firstname'} ... ($_->{'cardnumber'} - $_->{'categorycode'} - $_->{'branchcode'}) ...  $_->{'address'} ";
403     }
404     $selectborrower = {
405         values => \@values,
406         labels => \%labels,
407     };
408 }
409
410 #title
411 my $flags = $borrower->{'flags'};
412 foreach my $flag ( sort keys %$flags ) {
413     $template->param( flagged=> 1);
414     $flags->{$flag}->{'message'} =~ s#\n#<br />#g;
415     if ( $flags->{$flag}->{'noissues'} ) {
416         $template->param(
417             noissues => ($force_allow_issue) ? 0 : 'true',
418             forceallow => $force_allow_issue,
419         );
420         if ( $flag eq 'GNA' ) {
421             $template->param( gna => 'true' );
422         }
423         elsif ( $flag eq 'LOST' ) {
424             $template->param( lost => 'true' );
425         }
426         elsif ( $flag eq 'DBARRED' ) {
427             $template->param( dbarred => 'true' );
428         }
429         elsif ( $flag eq 'CHARGES' ) {
430             $template->param(
431                 charges    => 'true',
432                 chargesmsg => $flags->{'CHARGES'}->{'message'},
433                 chargesamount => $flags->{'CHARGES'}->{'amount'},
434                 charges_is_blocker => 1
435             );
436         }
437         elsif ( $flag eq 'CREDITS' ) {
438             $template->param(
439                 credits    => 'true',
440                 creditsmsg => $flags->{'CREDITS'}->{'message'},
441                 creditsamount => sprintf("%.02f", -($flags->{'CREDITS'}->{'amount'})), # from patron's pov
442             );
443         }
444     }
445     else {
446         if ( $flag eq 'CHARGES' ) {
447             $template->param(
448                 charges    => 'true',
449                 chargesmsg => $flags->{'CHARGES'}->{'message'},
450                 chargesamount => $flags->{'CHARGES'}->{'amount'},
451             );
452         }
453         elsif ( $flag eq 'CREDITS' ) {
454             $template->param(
455                 credits    => 'true',
456                 creditsmsg => $flags->{'CREDITS'}->{'message'},
457                 creditsamount => sprintf("%.02f", -($flags->{'CREDITS'}->{'amount'})), # from patron's pov
458             );
459         }
460         elsif ( $flag eq 'ODUES' ) {
461             $template->param(
462                 odues    => 'true',
463                 oduesmsg => $flags->{'ODUES'}->{'message'}
464             );
465
466             my $items = $flags->{$flag}->{'itemlist'};
467             if ( ! $query->param('module') || $query->param('module') ne 'returns' ) {
468                 $template->param( nonreturns => 'true' );
469             }
470         }
471         elsif ( $flag eq 'NOTES' ) {
472             $template->param(
473                 notes    => 'true',
474                 notesmsg => $flags->{'NOTES'}->{'message'}
475             );
476         }
477     }
478 }
479
480 my $amountold = $borrower->{flags}->{'CHARGES'}->{'message'} || 0;
481 $amountold =~ s/^.*\$//;    # remove upto the $, if any
482
483 my ( $total, $accts, $numaccts) = GetMemberAccountRecords( $borrowernumber );
484
485 if ( $borrowernumber && $borrower->{'category_type'} eq 'C') {
486     my  ( $catcodes, $labels ) =  GetborCatFromCatType( 'A', 'WHERE category_type = ?' );
487     my $cnt = scalar(@$catcodes);
488     $template->param( 'CATCODE_MULTI' => 1) if $cnt > 1;
489     $template->param( 'catcode' =>    $catcodes->[0])  if $cnt == 1;
490 }
491
492 my $lib_messages_loop = GetMessages( $borrowernumber, 'L', $branch );
493 if($lib_messages_loop){ $template->param(flagged => 1 ); }
494
495 my $bor_messages_loop = GetMessages( $borrowernumber, 'B', $branch );
496 if($bor_messages_loop){ $template->param(flagged => 1 ); }
497
498 # Computes full borrower address
499 my @fulladdress;
500 push @fulladdress, $borrower->{'streetnumber'} if ( $borrower->{'streetnumber'} );
501 push @fulladdress, C4::Koha::GetAuthorisedValueByCode( 'ROADTYPE', $borrower->{'streettype'} ) if ( $borrower->{'streettype'} );
502 push @fulladdress, $borrower->{'address'} if ( $borrower->{'address'} );
503
504 my $fast_cataloging = 0;
505 if (defined getframeworkinfo('FA')) {
506     $fast_cataloging = 1 
507 }
508
509 if (C4::Context->preference('ExtendedPatronAttributes')) {
510     my $attributes = GetBorrowerAttributes($borrowernumber);
511     $template->param(
512         ExtendedPatronAttributes => 1,
513         extendedattributes => $attributes
514     );
515 }
516
517 my @relatives = GetMemberRelatives( $borrower->{'borrowernumber'} );
518 my $relatives_issues_count =
519   Koha::Database->new()->schema()->resultset('Issue')
520   ->count( { borrowernumber => \@relatives } );
521
522 $template->param(
523     lib_messages_loop => $lib_messages_loop,
524     bor_messages_loop => $bor_messages_loop,
525     all_messages_del  => C4::Context->preference('AllowAllMessageDeletion'),
526     findborrower      => $findborrower,
527     borrower          => $borrower,
528     borrowernumber    => $borrowernumber,
529     branch            => $branch,
530     branchname        => GetBranchName($borrower->{'branchcode'}),
531     printer           => $printer,
532     printername       => $printer,
533     firstname         => $borrower->{'firstname'},
534     surname           => $borrower->{'surname'},
535     showname          => $borrower->{'showname'},
536     category_type     => $borrower->{'category_type'},
537     was_renewed       => $query->param('was_renewed') ? 1 : 0,
538     expiry            => format_date($borrower->{'dateexpiry'}),
539     categorycode      => $borrower->{'categorycode'},
540     categoryname      => $borrower->{description},
541     address           => join(' ', @fulladdress),
542     address2          => $borrower->{'address2'},
543     email             => $borrower->{'email'},
544     emailpro          => $borrower->{'emailpro'},
545     borrowernotes     => $borrower->{'borrowernotes'},
546     city              => $borrower->{'city'},
547     state              => $borrower->{'state'},
548     zipcode           => $borrower->{'zipcode'},
549     country           => $borrower->{'country'},
550     phone             => $borrower->{'phone'},
551     mobile            => $borrower->{'mobile'},
552     phonepro          => $borrower->{'phonepro'},
553     cardnumber        => $borrower->{'cardnumber'},
554     othernames        => $borrower->{'othernames'},
555     amountold         => $amountold,
556     barcode           => $barcode,
557     stickyduedate     => $stickyduedate,
558     duedatespec       => $duedatespec,
559     message           => $message,
560     selectborrower    => $selectborrower,
561     totaldue          => sprintf('%.2f', $total),
562     inprocess         => $inprocess,
563     is_child          => ($borrowernumber && $borrower->{'category_type'} eq 'C'),
564     circview => 1,
565     soundon           => C4::Context->preference("SoundOn"),
566     fast_cataloging   => $fast_cataloging,
567     CircAutoPrintQuickSlip   => C4::Context->preference("CircAutoPrintQuickSlip"),
568     activeBorrowerRelationship => (C4::Context->preference('borrowerRelationship') ne ''),
569     SuspendHoldsIntranet => C4::Context->preference('SuspendHoldsIntranet'),
570     AutoResumeSuspendedHolds => C4::Context->preference('AutoResumeSuspendedHolds'),
571     RoutingSerials => C4::Context->preference('RoutingSerials'),
572     relatives_issues_count => $relatives_issues_count,
573     relatives_borrowernumbers => \@relatives,
574 );
575
576 # save stickyduedate to session
577 if ($stickyduedate) {
578     $session->param( 'stickyduedate', $duedatespec );
579 }
580
581 my ($picture, $dberror) = GetPatronImage($borrower->{'borrowernumber'});
582 $template->param( picture => 1 ) if $picture;
583
584 # get authorised values with type of BOR_NOTES
585
586 my $canned_notes = GetAuthorisedValues("BOR_NOTES");
587
588 $template->param(
589     debt_confirmed            => $debt_confirmed,
590     SpecifyDueDate            => $duedatespec_allow,
591     CircAutocompl             => C4::Context->preference("CircAutocompl"),
592     AllowRenewalLimitOverride => C4::Context->preference("AllowRenewalLimitOverride"),
593     export_remove_fields      => C4::Context->preference("ExportRemoveFields"),
594     export_with_csv_profile   => C4::Context->preference("ExportWithCsvProfile"),
595     canned_bor_notes_loop     => $canned_notes,
596     debarments                => GetDebarments({ borrowernumber => $borrowernumber }),
597 );
598
599 output_html_with_http_headers $query, $cookie, $template->output;