Bug 14407: Allow restricting SCO to IP or IP range
[koha.git] / opac / sco / sco-main.pl
1 #!/usr/bin/perl
2 #
3 # This code has been modified by Trendsetters (originally from opac-user.pl)
4 # This code has been modified by rch
5 # Parts Copyright 2010-2011, ByWater Solutions (those related to username/password auth)
6 #
7 # This file is part of Koha.
8 #
9 # Koha is free software; you can redistribute it and/or modify it
10 # under the terms of the GNU General Public License as published by
11 # the Free Software Foundation; either version 3 of the License, or
12 # (at your option) any later version.
13 #
14 # Koha is distributed in the hope that it will be useful, but
15 # WITHOUT ANY WARRANTY; without even the implied warranty of
16 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 # GNU General Public License for more details.
18 #
19 # You should have received a copy of the GNU General Public License
20 # along with Koha; if not, see <http://www.gnu.org/licenses>.
21
22 # We're going to authenticate a self-check user.  we'll add a flag to borrowers 'selfcheck'
23 #
24 # We're in a controlled environment; we trust the user.
25 # So the selfcheck station will accept a patronid and issue items to that borrower.
26 # FIXME: NOT really a controlled environment...  We're on the internet!
27 #
28 # The checkout permission comes form the CGI cookie/session of a staff user.
29 # The patron is not really logging in here in the same way as they do on the
30 # rest of the OPAC.  So don't confuse loggedinuser with the patron user.
31 #
32 # FIXME: inputfocus not really used in TMPL
33
34 use Modern::Perl;
35
36 use CGI qw ( -utf8 );
37
38 use C4::Auth qw(get_template_and_user checkpw in_ipset);
39 use C4::Koha;
40 use C4::Circulation;
41 use C4::Reserves;
42 use C4::Output;
43 use C4::Members;
44 use C4::Biblio;
45 use C4::Items;
46 use Koha::DateUtils qw( dt_from_string );
47 use Koha::Acquisition::Currencies;
48 use Koha::Items;
49 use Koha::Patrons;
50 use Koha::Patron::Images;
51 use Koha::Patron::Messages;
52 use Koha::Token;
53
54 my $query = new CGI;
55
56 unless (C4::Context->preference('WebBasedSelfCheck')) {
57     # redirect to OPAC home if self-check is not enabled
58     print $query->redirect("/cgi-bin/koha/opac-main.pl");
59     exit;
60 }
61
62 unless ( in_ipset(C4::Context->preference('SelfCheckAllowByIPRanges')) ) {
63     # redirect to OPAC home if self-checkout not permitted from current IP
64     print $query->redirect("/cgi-bin/koha/opac-main.pl");
65     exit;
66 }
67
68 if (C4::Context->preference('AutoSelfCheckAllowed'))
69 {
70     my $AutoSelfCheckID = C4::Context->preference('AutoSelfCheckID');
71     my $AutoSelfCheckPass = C4::Context->preference('AutoSelfCheckPass');
72     $query->param(-name=>'userid',-values=>[$AutoSelfCheckID]);
73     $query->param(-name=>'password',-values=>[$AutoSelfCheckPass]);
74     $query->param(-name=>'koha_login_context',-values=>['sco']);
75 }
76 $query->param(-name=>'sco_user_login',-values=>[1]);
77
78 my ( $template, $loggedinuser, $cookie ) = get_template_and_user(
79     {
80         template_name   => "sco/sco-main.tt",
81         authnotrequired => 0,
82         flagsrequired   => { self_check => "self_checkout_module" },
83         query           => $query,
84         type            => "opac",
85         debug           => 1,
86     }
87 );
88
89 # Get the self checkout timeout preference, or use 120 seconds as a default
90 my $selfchecktimeout = 120000;
91 if (C4::Context->preference('SelfCheckTimeout')) { 
92     $selfchecktimeout = C4::Context->preference('SelfCheckTimeout') * 1000;
93 }
94 $template->param( SelfCheckTimeout => $selfchecktimeout );
95
96 # Checks policy laid out by AllowSelfCheckReturns, defaults to 'on' if preference is undefined
97 my $allowselfcheckreturns = 1;
98 if (defined C4::Context->preference('AllowSelfCheckReturns')) {
99     $allowselfcheckreturns = C4::Context->preference('AllowSelfCheckReturns');
100 }
101
102 my $issuerid = $loggedinuser;
103 my ($op, $patronid, $patronlogin, $patronpw, $barcode, $confirmed, $newissues) = (
104     $query->param("op")         || '',
105     $query->param("patronid")   || '',
106     $query->param("patronlogin")|| '',
107     $query->param("patronpw")   || '',
108     $query->param("barcode")    || '',
109     $query->param("confirmed")  || '',
110     $query->param("newissues")  || '',
111 );
112
113 my @newissueslist = split /,/, $newissues;
114 my $issuenoconfirm = 1; #don't need to confirm on issue.
115 my $issuer   = Koha::Patrons->find( $issuerid )->unblessed;
116 my $item     = Koha::Items->find({ barcode => $barcode });
117 if (C4::Context->preference('SelfCheckoutByLogin') && !$patronid) {
118     my $dbh = C4::Context->dbh;
119     my $resval;
120     ($resval, $patronid) = checkpw($dbh, $patronlogin, $patronpw);
121 }
122
123 my ( $borrower, $patron );
124 if ( $patronid ) {
125     $patron = Koha::Patrons->find( { cardnumber => $patronid } );
126     $borrower = $patron->unblessed if $patron;
127 }
128
129 my $branch = $issuer->{branchcode};
130 my $confirm_required = 0;
131 my $return_only = 0;
132 #warn "issuer cardnumber: " .   $issuer->{cardnumber};
133 #warn "patron cardnumber: " . $borrower->{cardnumber};
134 if ($op eq "logout") {
135     $template->param( loggedout => 1 );
136     $query->param( patronid => undef, patronlogin => undef, patronpw => undef );
137 }
138 elsif ( $op eq "returnbook" && $allowselfcheckreturns ) {
139     my ($doreturn) = AddReturn( $barcode, $branch );
140     $template->param( returned => $doreturn );
141 }
142 elsif ( $patron && ( $op eq 'checkout' || $op eq 'renew' ) ) {
143     my $impossible  = {};
144     my $needconfirm = {};
145     ( $impossible, $needconfirm ) = CanBookBeIssued(
146         $patron,
147         $barcode,
148         undef,
149         0,
150         C4::Context->preference("AllowItemsOnHoldCheckoutSCO")
151     );
152     my $issue_error;
153     if ( $confirm_required = scalar keys %$needconfirm ) {
154         for my $error ( qw( UNKNOWN_BARCODE max_loans_allowed ISSUED_TO_ANOTHER NO_MORE_RENEWALS NOT_FOR_LOAN DEBT WTHDRAWN RESTRICTED RESERVED ITEMNOTSAMEBRANCH EXPIRED DEBARRED CARD_LOST GNA INVALID_DATE UNKNOWN_BARCODE TOO_MANY DEBT_GUARANTEES USERBLOCKEDOVERDUE PATRON_CANT PREVISSUE NOT_FOR_LOAN_FORCING ITEM_LOST) ) {
155             if ( $needconfirm->{$error} ) {
156                 $issue_error = $error;
157                 $confirmed = 0;
158                 last;
159             }
160         }
161     }
162
163     #warn "confirm_required: " . $confirm_required ;
164     if (scalar keys %$impossible) {
165
166         my $issue_error = (keys %$impossible)[0]; # FIXME This is wrong, we assume only one error and keys are not ordered
167         my $title = ( $item ) ? $item->biblio->title : '';
168
169         $template->param(
170             impossible                => $issue_error,
171             "circ_error_$issue_error" => 1,
172             title                     => $title,
173             hide_main                 => 1,
174         );
175         if ($issue_error eq 'DEBT') {
176             $template->param(DEBT => $impossible->{DEBT});
177         }
178         #warn "issue_error: " . $issue_error ;
179         if ( $issue_error eq "NO_MORE_RENEWALS" ) {
180             $return_only = 1;
181             $template->param(
182                 returnitem => 1,
183                 barcode    => $barcode,
184             );
185         }
186     } elsif ( $needconfirm->{RENEW_ISSUE} || $op eq 'renew' ) {
187         if ($confirmed) {
188             #warn "renewing";
189             AddRenewal( $borrower->{borrowernumber}, $item->itemnumber );
190             push @newissueslist, $barcode;
191             $template->param( renewed => 1 );
192         } else {
193             #warn "renew confirmation";
194             $template->param(
195                 renew               => 1,
196                 barcode             => $barcode,
197                 confirm             => 1,
198                 confirm_renew_issue => 1,
199                 hide_main           => 1,
200             );
201         }
202     } elsif ( $confirm_required && !$confirmed ) {
203         #warn "failed confirmation";
204         $template->param(
205             impossible                => 1,
206             "circ_error_$issue_error" => 1,
207             hide_main                 => 1,
208         );
209         if ($issue_error eq 'DEBT') {
210             $template->param(DEBT => $needconfirm->{DEBT});
211         }
212     } else {
213         if ( $confirmed || $issuenoconfirm ) {    # we'll want to call getpatroninfo again to get updated issues.
214             my ( $hold_existed, $item );
215             if ( C4::Context->preference('HoldFeeMode') eq 'any_time_is_collected' ) {
216                 # There is no easy way to know if the patron has been charged for this item.
217                 # So we check if a hold existed for this item before the check in
218                 $item = Koha::Items->find({ barcode => $barcode });
219                 $hold_existed = Koha::Holds->search(
220                     {
221                         -and => {
222                             borrowernumber => $borrower->{borrowernumber},
223                             -or            => {
224                                 biblionumber => $item->biblionumber,
225                                 itemnumber   => $item->itemnumber
226                             }
227                         }
228                     }
229                 )->count;
230             }
231
232             AddIssue( $borrower, $barcode );
233             $template->param( issued => 1 );
234             push @newissueslist, $barcode;
235
236             if ( $hold_existed ) {
237                 my $dtf = Koha::Database->new->schema->storage->datetime_parser;
238                 $template->param(
239                     # If the hold existed before the check in, let's confirm that the charge line exists
240                     # Note that this should not be needed but since we do not have proper exception handling here we do it this way
241                     patron_has_hold_fee => Koha::Account::Lines->search(
242                         {
243                             borrowernumber => $borrower->{borrowernumber},
244                             accounttype    => 'Res',
245                             description    => $item->biblio->title,
246                             date           => $dtf->format_date(dt_from_string)
247                         }
248                       )->count,
249                 );
250             }
251         } else {
252             $confirm_required = 1;
253             #warn "issue confirmation";
254             $template->param(
255                 confirm    => "Issuing title: " . $item->biblio->title,
256                 barcode    => $barcode,
257                 hide_main  => 1,
258                 inputfocus => 'confirm',
259             );
260         }
261     }
262 } # $op
263
264 if ($borrower) {
265 #   warn "issuer's  branchcode: " .   $issuer->{branchcode};
266 #   warn   "user's  branchcode: " . $borrower->{branchcode};
267     my $borrowername = sprintf "%s %s", ($borrower->{firstname} || ''), ($borrower->{surname} || '');
268     my $pending_checkouts = $patron->pending_checkouts;
269     my @checkouts;
270     while ( my $c = $pending_checkouts->next ) {
271         my $checkout = $c->unblessed_all_relateds;
272         my ($can_be_renewed, $renew_error) = CanBookBeRenewed(
273             $borrower->{borrowernumber},
274             $checkout->{itemnumber},
275         );
276         $checkout->{can_be_renewed} = $can_be_renewed; # In the future this will be $checkout->can_be_renewed
277         $checkout->{renew_error} = $renew_error;
278         $checkout->{overdue} = $c->is_overdue;
279         push @checkouts, $checkout;
280     }
281
282     my $show_priority;
283     for ( C4::Context->preference("OPACShowHoldQueueDetails") ) {
284         m/priority/ and $show_priority = 1;
285     }
286
287     my $account = $patron->account;
288     my $total = $account->balance;
289     my $accountlines = $account->lines;
290
291     my $holds = $patron->holds;
292     my $waiting_holds_count = 0;
293
294     while(my $hold = $holds->next) {
295         $waiting_holds_count++ if $hold->is_waiting;
296     }
297
298     $template->param(
299         validuser => 1,
300         borrowername => $borrowername,
301         issues_count => scalar(@checkouts),
302         ISSUES => \@checkouts,
303         HOLDS => $holds,
304         newissues => join(',',@newissueslist),
305         patronid => $patronid,
306         patronlogin => $patronlogin,
307         patronpw => $patronpw,
308         waiting_holds_count => $waiting_holds_count,
309         noitemlinks => 1 ,
310         borrowernumber => $borrower->{'borrowernumber'},
311         SuspendHoldsOpac => C4::Context->preference('SuspendHoldsOpac'),
312         AutoResumeSuspendedHolds => C4::Context->preference('AutoResumeSuspendedHolds'),
313         howpriority   => $show_priority,
314         ACCOUNT_LINES => $accountlines,
315         total => $total,
316     );
317
318     my $patron_messages = Koha::Patron::Messages->search(
319         {
320             borrowernumber => $borrower->{'borrowernumber'},
321             message_type => 'B',
322         }
323     );
324     $template->param(
325         patron_messages => $patron_messages,
326         opacnote => $borrower->{opacnote},
327     );
328
329     my $inputfocus = ($return_only      == 1) ? 'returnbook' :
330                      ($confirm_required == 1) ? 'confirm'    : 'barcode' ;
331     $template->param(
332         inputfocus => $inputfocus,
333         nofines => 1,
334
335     );
336     if (C4::Context->preference('ShowPatronImageInWebBasedSelfCheck')) {
337         my $patron_image = Koha::Patron::Images->find($borrower->{borrowernumber});
338         $template->param(
339             display_patron_image => 1,
340             csrf_token           => Koha::Token->new->generate_csrf( { session_id => scalar $query->cookie('CGISESSID') . $borrower->{cardnumber}, id => $borrower->{userid}} ),
341         ) if $patron_image;
342     }
343 } else {
344     $template->param(
345         patronid   => $patronid,
346         nouser     => $patronid,
347     );
348 }
349
350 output_html_with_http_headers $query, $cookie, $template->output, undef, { force_no_caching => 1 };