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