Bug 19160: Move the code from controller to C4::Auth_with_cas
[koha.git] / opac / opac-user.pl
1 #!/usr/bin/perl
2
3 # This file is part of Koha.
4 # parts copyright 2010 BibLibre
5 #
6 # Koha is free software; you can redistribute it and/or modify it
7 # under the terms of the GNU General Public License as published by
8 # the Free Software Foundation; either version 3 of the License, or
9 # (at your option) any later version.
10 #
11 # Koha is distributed in the hope that it will be useful, but
12 # WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 # GNU General Public License for more details.
15 #
16 # You should have received a copy of the GNU General Public License
17 # along with Koha; if not, see <http://www.gnu.org/licenses>.
18
19
20 use strict;
21 #use warnings; FIXME - Bug 2505
22
23 use CGI qw ( -utf8 );
24
25 use C4::Auth;
26 use C4::Koha;
27 use C4::Circulation;
28 use C4::Reserves;
29 use C4::Members;
30 use C4::Members::AttributeTypes;
31 use C4::Members::Attributes qw/GetBorrowerAttributeValue/;
32 use C4::Output;
33 use C4::Biblio;
34 use C4::Items;
35 use C4::Letters;
36 use Koha::Account::Lines;
37 use Koha::Libraries;
38 use Koha::DateUtils;
39 use Koha::Holds;
40 use Koha::Database;
41 use Koha::ItemTypes;
42 use Koha::Patron::Attribute::Types;
43 use Koha::Patron::Messages;
44 use Koha::Patron::Discharge;
45 use Koha::Patrons;
46
47 use constant ATTRIBUTE_SHOW_BARCODE => 'SHOW_BCODE';
48
49 use Scalar::Util qw(looks_like_number);
50 use Date::Calc qw(
51   Today
52   Add_Delta_Days
53   Date_to_Days
54 );
55
56 my $query = new CGI;
57
58 BEGIN {
59     if (C4::Context->preference('BakerTaylorEnabled')) {
60         require C4::External::BakerTaylor;
61         import C4::External::BakerTaylor qw(&image_url &link_url);
62     }
63 }
64
65 my $cas_logout_required = C4::Context->preference('casAuthentication')
66   and C4::Auth_with_ldap::logout_required($query);
67
68 my ( $template, $borrowernumber, $cookie ) = get_template_and_user(
69     {
70         template_name   => "opac-user.tt",
71         query           => $query,
72         type            => "opac",
73         authnotrequired => 0,
74         debug           => 1,
75     }
76 );
77
78 if ($cas_logout_required){
79     print $query->header;
80     exit;
81 }
82
83
84 my %renewed = map { $_ => 1 } split( ':', $query->param('renewed') );
85
86 my $show_priority;
87 for ( C4::Context->preference("OPACShowHoldQueueDetails") ) {
88     m/priority/ and $show_priority = 1;
89 }
90
91 my $patronupdate = $query->param('patronupdate');
92 my $canrenew = 1;
93
94 $template->param( shibbolethAuthentication => C4::Context->config('useshibboleth') );
95
96 if (!$borrowernumber) {
97     $template->param( adminWarning => 1 );
98 }
99
100 # get borrower information ....
101 my $patron = Koha::Patrons->find( $borrowernumber );
102 my $borr = $patron->unblessed;
103
104 my (  $today_year,   $today_month,   $today_day) = Today();
105 my ($warning_year, $warning_month, $warning_day) = split /-/, $borr->{'dateexpiry'};
106
107 my $debar = Koha::Patrons->find( $borrowernumber )->is_debarred;
108 my $userdebarred;
109
110 if ($debar) {
111     $userdebarred = 1;
112     $template->param( 'userdebarred' => $userdebarred );
113     if ( $debar ne "9999-12-31" ) {
114         $borr->{'userdebarreddate'} = $debar;
115     }
116     # FIXME looks like $available is not needed
117     # If a user is discharged they have a validated discharge available
118     my $available = Koha::Patron::Discharge::count({
119         borrowernumber => $borrowernumber,
120         validated      => 1,
121     });
122     $template->param( 'discharge_available' => $available && Koha::Patron::Discharge::is_discharged({borrowernumber => $borrowernumber}) );
123 }
124
125 if ( $userdebarred || $borr->{'gonenoaddress'} || $borr->{'lost'} ) {
126     $borr->{'flagged'} = 1;
127     $canrenew = 0;
128 }
129
130 my $amountoutstanding = $patron->account->balance;
131 if ( $amountoutstanding > 5 ) {
132     $borr->{'amountoverfive'} = 1;
133 }
134 if ( 5 >= $amountoutstanding && $amountoutstanding > 0 ) {
135     $borr->{'amountoverzero'} = 1;
136 }
137 my $no_renewal_amt = C4::Context->preference( 'OPACFineNoRenewals' );
138 $no_renewal_amt = undef unless looks_like_number( $no_renewal_amt );
139
140 if (   C4::Context->preference('OpacRenewalAllowed')
141     && defined($no_renewal_amt)
142     && $amountoutstanding > $no_renewal_amt )
143 {
144     $borr->{'flagged'} = 1;
145     $canrenew = 0;
146     $template->param(
147         renewal_blocked_fines => $no_renewal_amt,
148         renewal_blocked_fines_amountoutstanding => $amountoutstanding,
149     );
150 }
151
152 if ( $amountoutstanding < 0 ) {
153     $borr->{'amountlessthanzero'} = 1;
154     $amountoutstanding = -1 * ( $amountoutstanding );
155 }
156
157 # Warningdate is the date that the warning starts appearing
158 if ( $borr->{'dateexpiry'} && C4::Context->preference('NotifyBorrowerDeparture') ) {
159     my $days_to_expiry = Date_to_Days( $warning_year, $warning_month, $warning_day ) - Date_to_Days( $today_year, $today_month, $today_day );
160     if ( $days_to_expiry < 0 ) {
161         #borrower card has expired, warn the borrower
162         $borr->{'warnexpired'} = $borr->{'dateexpiry'};
163     } elsif ( $days_to_expiry < C4::Context->preference('NotifyBorrowerDeparture') ) {
164         # borrower card soon to expire, warn the borrower
165         $borr->{'warndeparture'} = $borr->{dateexpiry};
166         if (C4::Context->preference('ReturnBeforeExpiry')){
167             $borr->{'returnbeforeexpiry'} = 1;
168         }
169     }
170 }
171
172 # pass on any renew errors to the template for displaying
173 my $renew_error = $query->param('renew_error');
174
175 $template->param(   BORROWER_INFO     => $borr,
176                     amountoutstanding => $amountoutstanding,
177                     borrowernumber    => $borrowernumber,
178                     patron_flagged    => $borr->{flagged},
179                     OPACMySummaryHTML => (C4::Context->preference("OPACMySummaryHTML")) ? 1 : 0,
180                     surname           => $borr->{surname},
181                     RENEW_ERROR       => $renew_error,
182                     borrower          => $borr,
183                 );
184
185 #get issued items ....
186
187 my $count          = 0;
188 my $overdues_count = 0;
189 my @overdues;
190 my @issuedat;
191 my $itemtypes = { map { $_->{itemtype} => $_ } @{ Koha::ItemTypes->search_with_localization->unblessed } };
192 my $issues = GetPendingIssues($borrowernumber);
193 if ($issues){
194     foreach my $issue ( sort { $b->{date_due}->datetime() cmp $a->{date_due}->datetime() } @{$issues} ) {
195         # check for reserves
196         my $restype = GetReserveStatus( $issue->{'itemnumber'} );
197         if ( $restype ) {
198             $issue->{'reserved'} = 1;
199         }
200
201         # Must be moved in a module if reused
202         my $charges = Koha::Account::Lines->search(
203             {
204                 borrowernumber    => $patron->borrowernumber,
205                 amountoutstanding => { '>' => 0 },
206                 accounttype       => [ 'F', 'FU', 'L' ],
207                 itemnumber        => $issue->{itemnumber}
208             },
209             { select => [ { sum => 'amountoutstanding' } ], as => ['charges'] }
210         );
211         $issue->{charges} = $charges->count ? $charges->next->get_column('charges') : 0;
212
213         my $rental_fines = Koha::Account::Lines->search(
214             {
215                 borrowernumber    => $patron->borrowernumber,
216                 amountoutstanding => { '>' => 0 },
217                 accounttype       => 'Rent',
218                 itemnumber        => $issue->{itemnumber}
219             },
220             {
221                 select => [ { sum => 'amountoutstanding' } ],
222                 as     => ['rental_fines']
223             }
224         );
225         $issue->{rentalfines} = $charges->count ? $charges->next->get_column('rental_fines') : 0;
226
227         my $marcrecord = GetMarcBiblio({ biblionumber => $issue->{'biblionumber'} });
228         $issue->{'subtitle'} = GetRecordValue('subtitle', $marcrecord, GetFrameworkCode($issue->{'biblionumber'}));
229         # check if item is renewable
230         my ($status,$renewerror) = CanBookBeRenewed( $borrowernumber, $issue->{'itemnumber'} );
231         ($issue->{'renewcount'},$issue->{'renewsallowed'},$issue->{'renewsleft'}) = GetRenewCount($borrowernumber, $issue->{'itemnumber'});
232         ( $issue->{'renewalfee'}, $issue->{'renewalitemtype'} ) = GetIssuingCharges( $issue->{'itemnumber'}, $borrowernumber );
233         if($status && C4::Context->preference("OpacRenewalAllowed")){
234             $issue->{'status'} = $status;
235         }
236
237         $issue->{'renewed'} = $renewed{ $issue->{'itemnumber'} };
238
239         if ($renewerror) {
240             $issue->{'too_many'}       = 1 if $renewerror eq 'too_many';
241             $issue->{'on_reserve'}     = 1 if $renewerror eq 'on_reserve';
242             $issue->{'norenew_overdue'} = 1 if $renewerror eq 'overdue';
243             $issue->{'auto_renew'}     = 1 if $renewerror eq 'auto_renew';
244             $issue->{'auto_too_soon'}  = 1 if $renewerror eq 'auto_too_soon';
245             $issue->{'auto_too_late'}  = 1 if $renewerror eq 'auto_too_late';
246             $issue->{'auto_too_much_oweing'}  = 1 if $renewerror eq 'auto_too_much_oweing';
247
248             if ( $renewerror eq 'too_soon' ) {
249                 $issue->{'too_soon'}         = 1;
250                 $issue->{'soonestrenewdate'} = output_pref(
251                     C4::Circulation::GetSoonestRenewDate(
252                         $issue->{borrowernumber},
253                         $issue->{itemnumber}
254                     )
255                 );
256             }
257         }
258
259         if ( $issue->{'overdue'} ) {
260             push @overdues, $issue;
261             $overdues_count++;
262             $issue->{'overdue'} = 1;
263         }
264         else {
265             $issue->{'issued'} = 1;
266         }
267         # imageurl:
268         my $itemtype = $issue->{'itemtype'};
269         if ( $itemtype ) {
270             $issue->{'imageurl'}    = getitemtypeimagelocation( 'opac', $itemtypes->{$itemtype}->{'imageurl'} );
271             $issue->{'description'} = $itemtypes->{$itemtype}->{'description'};
272         }
273         push @issuedat, $issue;
274         $count++;
275
276         my $isbn = GetNormalizedISBN($issue->{'isbn'});
277         $issue->{normalized_isbn} = $isbn;
278         $issue->{normalized_upc} = GetNormalizedUPC( $marcrecord, C4::Context->preference('marcflavour') );
279
280                 # My Summary HTML
281                 if (my $my_summary_html = C4::Context->preference('OPACMySummaryHTML')){
282                     $issue->{author} ? $my_summary_html =~ s/{AUTHOR}/$issue->{author}/g : $my_summary_html =~ s/{AUTHOR}//g;
283                     $issue->{title} =~ s/\/+$//; # remove trailing slash
284                     $issue->{title} =~ s/\s+$//; # remove trailing space
285                     $issue->{title} ? $my_summary_html =~ s/{TITLE}/$issue->{title}/g : $my_summary_html =~ s/{TITLE}//g;
286                     $issue->{isbn} ? $my_summary_html =~ s/{ISBN}/$isbn/g : $my_summary_html =~ s/{ISBN}//g;
287                     $issue->{biblionumber} ? $my_summary_html =~ s/{BIBLIONUMBER}/$issue->{biblionumber}/g : $my_summary_html =~ s/{BIBLIONUMBER}//g;
288                     $issue->{MySummaryHTML} = $my_summary_html;
289                 }
290     }
291 }
292 my $overduesblockrenewing = C4::Context->preference('OverduesBlockRenewing');
293 $canrenew = 0 if ($overduesblockrenewing ne 'allow' and $overdues_count == $count);
294
295 $template->param( ISSUES       => \@issuedat );
296 $template->param( issues_count => $count );
297 $template->param( canrenew     => $canrenew );
298 $template->param( OVERDUES       => \@overdues );
299 $template->param( overdues_count => $overdues_count );
300
301 my $show_barcode = Koha::Patron::Attribute::Types->search(
302     { code => ATTRIBUTE_SHOW_BARCODE } )->count;
303 if ($show_barcode) {
304     my $patron_show_barcode = GetBorrowerAttributeValue($borrowernumber, ATTRIBUTE_SHOW_BARCODE);
305     undef $show_barcode if defined($patron_show_barcode) && !$patron_show_barcode;
306 }
307 $template->param( show_barcode => 1 ) if $show_barcode;
308
309 # now the reserved items....
310 my $reserves = Koha::Holds->search( { borrowernumber => $borrowernumber } );
311
312 $template->param(
313     RESERVES       => $reserves,
314     showpriority   => $show_priority,
315 );
316
317 # current alert subscriptions
318 my $alerts = getalert($borrowernumber);
319 foreach ( @$alerts ) {
320     $_->{ $_->{type} } = 1;
321     $_->{relatedto} = findrelatedto( $_->{type}, $_->{externalid} );
322 }
323
324 if (C4::Context->preference('BakerTaylorEnabled')) {
325     $template->param(
326         BakerTaylorEnabled  => 1,
327         BakerTaylorImageURL => &image_url(),
328         BakerTaylorLinkURL  => &link_url(),
329         BakerTaylorBookstoreURL => C4::Context->preference('BakerTaylorBookstoreURL'),
330     );
331 }
332
333 if (C4::Context->preference("OPACAmazonCoverImages") or 
334     C4::Context->preference("GoogleJackets") or
335     C4::Context->preference("BakerTaylorEnabled") or
336     C4::Context->preference("SyndeticsCoverImages")) {
337         $template->param(JacketImages=>1);
338 }
339
340 $template->param(
341     OverDriveCirculation => C4::Context->preference('OverDriveCirculation') || 0,
342     overdrive_error      => scalar $query->param('overdrive_error') || undef,
343     overdrive_tab        => scalar $query->param('overdrive_tab') || 0,
344 );
345
346 my $patron_messages = Koha::Patron::Messages->search(
347     {
348         borrowernumber => $borrowernumber,
349         message_type => 'B',
350     }
351 );
352
353 if (   C4::Context->preference('AllowPatronToSetCheckoutsVisibilityForGuarantor')
354     || C4::Context->preference('AllowStaffToSetCheckoutsVisibilityForGuarantor') )
355 {
356     my @relatives =
357       Koha::Database->new()->schema()->resultset("Borrower")->search(
358         {
359             privacy_guarantor_checkouts => 1,
360             'me.guarantorid'           => $borrowernumber
361         },
362         { prefetch => [ { 'issues' => { 'item' => 'biblio' } } ] }
363       );
364     $template->param( relatives => \@relatives );
365 }
366
367 $template->param(
368     borrower                 => scalar Koha::Patrons->find($borrowernumber),
369     patron_messages          => $patron_messages,
370     opacnote                 => $borr->{opacnote},
371     patronupdate             => $patronupdate,
372     OpacRenewalAllowed       => C4::Context->preference("OpacRenewalAllowed"),
373     userview                 => 1,
374     SuspendHoldsOpac         => C4::Context->preference('SuspendHoldsOpac'),
375     AutoResumeSuspendedHolds => C4::Context->preference('AutoResumeSuspendedHolds'),
376     OpacHoldNotes            => C4::Context->preference('OpacHoldNotes'),
377     failed_holds             => scalar $query->param('failed_holds'),
378 );
379
380 output_html_with_http_headers $query, $cookie, $template->output, undef, { force_no_caching => 1 };