Bug 30714: Unit test
[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 Modern::Perl;
21
22 use CGI qw ( -utf8 );
23
24 use C4::Auth qw( get_template_and_user );
25 use C4::Koha qw(
26     getitemtypeimagelocation
27     GetNormalizedISBN
28     GetNormalizedUPC
29 );
30 use C4::Circulation qw( CanBookBeRenewed GetRenewCount GetIssuingCharges );
31 use C4::External::BakerTaylor qw( image_url link_url );
32 use C4::Reserves qw( GetReserveStatus );
33 use C4::Members;
34 use C4::Output qw( output_html_with_http_headers );
35 use C4::Biblio qw( GetMarcBiblio );
36 use Koha::Account::Lines;
37 use Koha::Biblios;
38 use Koha::Libraries;
39 use Koha::DateUtils qw( output_pref );
40 use Koha::Holds;
41 use Koha::Database;
42 use Koha::ItemTypes;
43 use Koha::Patron::Attribute::Types;
44 use Koha::Patrons;
45 use Koha::Patron::Messages;
46 use Koha::Patron::Discharge;
47 use Koha::Patrons;
48 use Koha::Ratings;
49 use Koha::Recalls;
50 use Koha::Token;
51
52 use constant ATTRIBUTE_SHOW_BARCODE => 'SHOW_BCODE';
53
54 use Scalar::Util qw( looks_like_number );
55 use Date::Calc qw( Date_to_Days Today );
56
57 my $query = CGI->new;
58
59 # CAS single logout handling
60 # Will print header and exit
61 if ( C4::Context->preference('casAuthentication') ) {
62     require C4::Auth_with_cas;
63     C4::Auth_with_cas::logout_if_required($query);
64 }
65
66 my ( $template, $borrowernumber, $cookie ) = get_template_and_user(
67     {
68         template_name   => "opac-user.tt",
69         query           => $query,
70         type            => "opac",
71     }
72 );
73
74 my %renewed = map { $_ => 1 } split( ':', $query->param('renewed') || '' );
75
76 my $show_priority;
77 for ( C4::Context->preference("OPACShowHoldQueueDetails") ) {
78     m/priority/ and $show_priority = 1;
79 }
80
81 my $patronupdate = $query->param('patronupdate');
82 my $canrenew = 1;
83
84 $template->param( shibbolethAuthentication => C4::Context->config('useshibboleth') );
85
86 # get borrower information ....
87 my $patron = Koha::Patrons->find( $borrowernumber );
88
89 if( $query->param('update_arc') && C4::Context->preference("AllowPatronToControlAutorenewal") ){
90     die "Wrong CSRF token"
91         unless Koha::Token->new->check_csrf({
92             session_id => scalar $query->cookie('CGISESSID'),
93             token  => scalar $query->param('csrf_token'),
94         });
95
96     my $autorenew_checkouts = $query->param('borrower_autorenew_checkouts');
97     $patron->autorenew_checkouts( $autorenew_checkouts )->store() if defined $autorenew_checkouts;
98 }
99
100 my $borr = $patron->unblessed;
101 # unblessed is a hash vs. object/undef. Hence the use of curly braces here.
102 my $borcat = $borr ? $borr->{categorycode} : q{};
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 my $no_renewal_amt = C4::Context->preference( 'OPACFineNoRenewals' );
132 $no_renewal_amt = undef unless looks_like_number( $no_renewal_amt );
133 my $amountoutstandingfornewal =
134   C4::Context->preference("OPACFineNoRenewalsIncludeCredit")
135   ? $amountoutstanding
136   : $patron->account->outstanding_debits->total_outstanding;
137
138 if (   C4::Context->preference('OpacRenewalAllowed')
139     && defined($no_renewal_amt)
140     && $amountoutstandingfornewal > $no_renewal_amt )
141 {
142     $borr->{'flagged'} = 1;
143     $canrenew = 0;
144     $template->param(
145         renewal_blocked_fines => $no_renewal_amt,
146         renewal_blocked_fines_amountoutstanding => $amountoutstandingfornewal,
147     );
148 }
149
150 my $maxoutstanding = C4::Context->preference('maxoutstanding');
151 if ( $amountoutstanding && ( $amountoutstanding > $maxoutstanding ) ){
152     $borr->{blockedonfines} = 1;
153 }
154
155 # Warningdate is the date that the warning starts appearing
156 if ( $borr->{'dateexpiry'} && C4::Context->preference('NotifyBorrowerDeparture') ) {
157     my $days_to_expiry = Date_to_Days( $warning_year, $warning_month, $warning_day ) - Date_to_Days( $today_year, $today_month, $today_day );
158     if ( $days_to_expiry < 0 ) {
159         #borrower card has expired, warn the borrower
160         $borr->{'warnexpired'} = $borr->{'dateexpiry'};
161     } elsif ( $days_to_expiry < C4::Context->preference('NotifyBorrowerDeparture') ) {
162         # borrower card soon to expire, warn the borrower
163         $borr->{'warndeparture'} = $borr->{dateexpiry};
164         if (C4::Context->preference('ReturnBeforeExpiry')){
165             $borr->{'returnbeforeexpiry'} = 1;
166         }
167     }
168 }
169
170 # pass on any renew errors to the template for displaying
171 my $renew_error = $query->param('renew_error');
172
173 $template->param(
174                     amountoutstanding => $amountoutstanding,
175                     borrowernumber    => $borrowernumber,
176                     patron_flagged    => $borr->{flagged},
177                     OPACMySummaryHTML => (C4::Context->preference("OPACMySummaryHTML")) ? 1 : 0,
178                     surname           => $borr->{surname},
179                     RENEW_ERROR       => $renew_error,
180                     borrower          => $borr,
181                     csrf_token             => Koha::Token->new->generate_csrf({
182                         session_id => scalar $query->cookie('CGISESSID'),
183                     }),
184                 );
185
186 #get issued items ....
187
188 my $count          = 0;
189 my $overdues_count = 0;
190 my @overdues;
191 my @issuedat;
192 my $itemtypes = { map { $_->{itemtype} => $_ } @{ Koha::ItemTypes->search_with_localization->unblessed } };
193 my $pending_checkouts = $patron->pending_checkouts->search({}, { order_by => [ { -desc => 'date_due' }, { -asc => 'issue_id' } ] });
194 my $are_renewable_items = 0;
195 if ( $pending_checkouts->count ) { # Useless test
196     while ( my $c = $pending_checkouts->next ) {
197         my $issue = $c->unblessed_all_relateds;
198         # check for reserves
199         my $restype = GetReserveStatus( $issue->{'itemnumber'} );
200         if ( $restype ) {
201             $issue->{'reserved'} = 1;
202         }
203
204         # Must be moved in a module if reused
205         my $charges = Koha::Account::Lines->search(
206             {
207                 borrowernumber    => $patron->borrowernumber,
208                 amountoutstanding => { '>' => 0 },
209                 debit_type_code   => [ 'OVERDUE', 'LOST' ],
210                 itemnumber        => $issue->{itemnumber}
211             },
212         );
213         $issue->{charges} = $charges->total_outstanding;
214
215         my $rental_fines = Koha::Account::Lines->search(
216             {
217                 borrowernumber    => $patron->borrowernumber,
218                 amountoutstanding => { '>' => 0 },
219                 debit_type_code   => { 'LIKE' => 'RENT_%' },
220                 itemnumber        => $issue->{itemnumber}
221             }
222         );
223         $issue->{rentalfines} = $rental_fines->total_outstanding;
224
225         # check if item is renewable
226         my ($status,$renewerror,$info) = CanBookBeRenewed( $borrowernumber, $issue->{'itemnumber'} );
227         (
228             $issue->{'renewcount'},
229             $issue->{'renewsallowed'},
230             $issue->{'renewsleft'},
231             $issue->{'unseencount'},
232             $issue->{'unseenallowed'},
233             $issue->{'unseenleft'}
234         ) = GetRenewCount($borrowernumber, $issue->{'itemnumber'});
235         ( $issue->{'renewalfee'}, $issue->{'renewalitemtype'} ) = GetIssuingCharges( $issue->{'itemnumber'}, $borrowernumber );
236         $issue->{itemtype_object} = Koha::ItemTypes->find( Koha::Items->find( $issue->{itemnumber} )->effective_itemtype );
237         if($status && C4::Context->preference("OpacRenewalAllowed")){
238             $are_renewable_items = 1;
239             $issue->{'status'} = $status;
240         }
241
242         $issue->{'renewed'} = $renewed{ $issue->{'itemnumber'} };
243
244         if ($renewerror) {
245             $issue->{'too_many'}       = 1 if $renewerror eq 'too_many';
246             $issue->{'too_unseen'}     = 1 if $renewerror eq 'too_unseen';
247             $issue->{'on_reserve'}     = 1 if $renewerror eq 'on_reserve';
248             $issue->{'norenew_overdue'} = 1 if $renewerror eq 'overdue';
249             $issue->{'auto_renew'}     = 1 if $renewerror eq 'auto_renew';
250             $issue->{'auto_too_soon'}  = 1 if $renewerror eq 'auto_too_soon';
251             $issue->{'auto_too_late'}  = 1 if $renewerror eq 'auto_too_late';
252             $issue->{'auto_too_much_oweing'}  = 1 if $renewerror eq 'auto_too_much_oweing';
253             $issue->{'item_denied_renewal'}  = 1 if $renewerror eq 'item_denied_renewal';
254
255             if ( $renewerror eq 'too_soon' ) {
256                 $issue->{'too_soon'}         = 1;
257                 $issue->{'soonestrenewdate'} = $info->{soonest_renew_date};
258             }
259         }
260
261         if ( $c->is_overdue ) {
262             push @overdues, $issue;
263             $overdues_count++;
264             $issue->{'overdue'} = 1;
265         }
266         else {
267             $issue->{'issued'} = 1;
268         }
269         # imageurl:
270         my $itemtype = $issue->{'itemtype'};
271         if ( $itemtype ) {
272             $issue->{'imageurl'}    = getitemtypeimagelocation( 'opac', $itemtypes->{$itemtype}->{'imageurl'} );
273             $issue->{'description'} = $itemtypes->{$itemtype}->{'description'};
274         }
275
276         if ( C4::Context->preference('OpacStarRatings') eq 'all' ) {
277             my $ratings = Koha::Ratings->search({ biblionumber => $issue->{biblionumber} });
278             $issue->{ratings} = $ratings;
279             $issue->{my_rating} = $borrowernumber ? $ratings->search({ borrowernumber => $borrowernumber })->next : undef;
280         }
281
282         $issue->{biblio_object} = Koha::Biblios->find($issue->{biblionumber});
283         push @issuedat, $issue;
284         $count++;
285
286         my $isbn = GetNormalizedISBN($issue->{'isbn'});
287         $issue->{normalized_isbn} = $isbn;
288         my $marcrecord = GetMarcBiblio({
289             biblionumber => $issue->{'biblionumber'},
290             embed_items  => 1,
291             opac         => 1,
292             borcat       => $borcat });
293         $issue->{normalized_upc} = GetNormalizedUPC( $marcrecord, C4::Context->preference('marcflavour') );
294
295                 # My Summary HTML
296                 if (my $my_summary_html = C4::Context->preference('OPACMySummaryHTML')){
297                     $issue->{author} ? $my_summary_html =~ s/{AUTHOR}/$issue->{author}/g : $my_summary_html =~ s/{AUTHOR}//g;
298                     $issue->{title} =~ s/\/+$//; # remove trailing slash
299                     $issue->{title} =~ s/\s+$//; # remove trailing space
300                     $issue->{title} ? $my_summary_html =~ s/{TITLE}/$issue->{title}/g : $my_summary_html =~ s/{TITLE}//g;
301                     $issue->{isbn} ? $my_summary_html =~ s/{ISBN}/$isbn/g : $my_summary_html =~ s/{ISBN}//g;
302                     $issue->{biblionumber} ? $my_summary_html =~ s/{BIBLIONUMBER}/$issue->{biblionumber}/g : $my_summary_html =~ s/{BIBLIONUMBER}//g;
303                     $issue->{MySummaryHTML} = $my_summary_html;
304                 }
305
306         if ( C4::Context->preference('UseRecalls') ) {
307             my $maybe_recalls = Koha::Recalls->search({ biblio_id => $issue->{biblionumber}, item_id => [ undef, $issue->{itemnumber} ], completed => 0 });
308             while( my $recall = $maybe_recalls->next ) {
309                 if ( $recall->checkout and $recall->checkout->issue_id == $issue->{issue_id} ) {
310                     $issue->{recall} = 1;
311                     last;
312                 }
313             }
314         }
315     }
316 }
317 my $overduesblockrenewing = C4::Context->preference('OverduesBlockRenewing');
318 $canrenew = 0 if ($overduesblockrenewing ne 'allow' and $overdues_count == $count) || !$are_renewable_items;
319
320 $template->param( ISSUES       => \@issuedat );
321 $template->param( issues_count => $count );
322 $template->param( canrenew     => $canrenew );
323 $template->param( OVERDUES       => \@overdues );
324 $template->param( overdues_count => $overdues_count );
325
326 my $show_barcode = Koha::Patron::Attribute::Types->search( # FIXME we should not need this search
327     { code => ATTRIBUTE_SHOW_BARCODE } )->count;
328 if ($show_barcode) {
329     my $patron_show_barcode = $patron->get_extended_attribute(ATTRIBUTE_SHOW_BARCODE);
330     undef $show_barcode if $patron_show_barcode and not $patron_show_barcode->attribute;
331 }
332 $template->param( show_barcode => 1 ) if $show_barcode;
333
334 # now the reserved items....
335 my $reserves = Koha::Holds->search( { borrowernumber => $borrowernumber } );
336
337 $template->param(
338     RESERVES       => $reserves,
339     showpriority   => $show_priority,
340 );
341
342 if ( C4::Context->preference('UseRecalls') ) {
343     my $recalls = Koha::Recalls->search( { patron_id => $borrowernumber, completed => 0 } );
344     $template->param( RECALLS => $recalls );
345 }
346
347 if (C4::Context->preference('BakerTaylorEnabled')) {
348     $template->param(
349         BakerTaylorEnabled  => 1,
350         BakerTaylorImageURL => &image_url(),
351         BakerTaylorLinkURL  => &link_url(),
352         BakerTaylorBookstoreURL => C4::Context->preference('BakerTaylorBookstoreURL'),
353     );
354 }
355
356 if (C4::Context->preference("OPACAmazonCoverImages") or 
357     C4::Context->preference("GoogleJackets") or
358     C4::Context->preference("BakerTaylorEnabled") or
359     C4::Context->preference("SyndeticsCoverImages") or
360     ( C4::Context->preference('OPACCustomCoverImages') and C4::Context->preference('CustomCoverImagesURL') )
361 ) {
362         $template->param(JacketImages=>1);
363 }
364
365 $template->param(
366     OverDriveCirculation => C4::Context->preference('OverDriveCirculation') || 0,
367     overdrive_error      => scalar $query->param('overdrive_error') || undef,
368     overdrive_tab        => scalar $query->param('overdrive_tab') || 0,
369     RecordedBooksCirculation => C4::Context->preference('RecordedBooksClientSecret') && C4::Context->preference('RecordedBooksLibraryID'),
370 );
371
372 my $patron_messages = Koha::Patron::Messages->search(
373     {
374         borrowernumber => $borrowernumber,
375         message_type => 'B',
376     }
377 );
378
379 if (   C4::Context->preference('AllowPatronToSetCheckoutsVisibilityForGuarantor')
380     || C4::Context->preference('AllowStaffToSetCheckoutsVisibilityForGuarantor') )
381 {
382     my @relatives;
383     # Filter out guarantees that don't want guarantor to see checkouts
384     foreach my $gr ( $patron->guarantee_relationships->as_list ) {
385         my $g = $gr->guarantee;
386         push( @relatives, $g ) if $g->privacy_guarantor_checkouts;
387     }
388     $template->param( relatives => \@relatives );
389 }
390
391 if (   C4::Context->preference('AllowPatronToSetFinesVisibilityForGuarantor')
392     || C4::Context->preference('AllowStaffToSetFinesVisibilityForGuarantor') )
393 {
394     my @relatives_with_fines;
395     # Filter out guarantees that don't want guarantor to see checkouts
396     foreach my $gr ( $patron->guarantee_relationships->as_list ) {
397         my $g = $gr->guarantee;
398         push( @relatives_with_fines, $g ) if $g->privacy_guarantor_fines;
399     }
400     $template->param( relatives_with_fines => \@relatives_with_fines );
401 }
402
403 if ( C4::Context->preference("ArticleRequests") ) {
404     $template->param(
405         current_article_requests => [$patron->article_requests->filter_by_current->as_list],
406     );
407 }
408
409 $template->param(
410     patron_messages          => $patron_messages,
411     opacnote                 => $borr->{opacnote},
412     patronupdate             => $patronupdate,
413     OpacRenewalAllowed       => C4::Context->preference("OpacRenewalAllowed"),
414     userview                 => 1,
415     SuspendHoldsOpac         => C4::Context->preference('SuspendHoldsOpac'),
416     AutoResumeSuspendedHolds => C4::Context->preference('AutoResumeSuspendedHolds'),
417     OpacHoldNotes            => C4::Context->preference('OpacHoldNotes'),
418     failed_holds             => scalar $query->param('failed_holds'),
419 );
420
421 # if not an empty string this indicates to return
422 # back to the opac-results page
423 my $search_query = $query->param('has-search-query');
424
425 if ($search_query) {
426
427     print $query->redirect(
428         -uri    => "/cgi-bin/koha/opac-search.pl?$search_query",
429         -cookie => $cookie,
430     );
431 }
432
433 output_html_with_http_headers $query, $cookie, $template->output, undef, { force_no_caching => 1 };