Bug 17825: Remove the use of AttributeTypeExists from opac-user.pl
[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::DateUtils;
37 use Koha::Holds;
38 use Koha::Database;
39 use Koha::Patron::Attribute::Types;
40 use Koha::Patron::Messages;
41 use Koha::Patron::Discharge;
42 use Koha::Patrons;
43
44 use constant ATTRIBUTE_SHOW_BARCODE => 'SHOW_BCODE';
45
46 use Scalar::Util qw(looks_like_number);
47 use Date::Calc qw(
48   Today
49   Add_Delta_Days
50   Date_to_Days
51 );
52
53 my $query = new CGI;
54
55 BEGIN {
56     if (C4::Context->preference('BakerTaylorEnabled')) {
57         require C4::External::BakerTaylor;
58         import C4::External::BakerTaylor qw(&image_url &link_url);
59     }
60 }
61
62 my ( $template, $borrowernumber, $cookie ) = get_template_and_user(
63     {
64         template_name   => "opac-user.tt",
65         query           => $query,
66         type            => "opac",
67         authnotrequired => 0,
68         debug           => 1,
69     }
70 );
71
72 my %renewed = map { $_ => 1 } split( ':', $query->param('renewed') );
73
74 my $show_priority;
75 for ( C4::Context->preference("OPACShowHoldQueueDetails") ) {
76     m/priority/ and $show_priority = 1;
77 }
78
79 my $patronupdate = $query->param('patronupdate');
80 my $canrenew = 1;
81
82 $template->param( shibbolethAuthentication => C4::Context->config('useshibboleth') );
83
84 if (!$borrowernumber) {
85     $template->param( adminWarning => 1 );
86 }
87
88 # get borrower information ....
89 my ( $borr ) = GetMember( borrowernumber => $borrowernumber );
90
91 my (  $today_year,   $today_month,   $today_day) = Today();
92 my ($warning_year, $warning_month, $warning_day) = split /-/, $borr->{'dateexpiry'};
93
94 my $debar = Koha::Patrons->find( $borrowernumber )->is_debarred;
95 my $userdebarred;
96
97 if ($debar) {
98     $userdebarred = 1;
99     $template->param( 'userdebarred' => $userdebarred );
100     if ( $debar ne "9999-12-31" ) {
101         $borr->{'userdebarreddate'} = $debar;
102     }
103     # FIXME looks like $available is not needed
104     # If a patron is discharged he has a validated discharge available
105     my $available = Koha::Patron::Discharge::count({
106         borrowernumber => $borrowernumber,
107         validated      => 1,
108     });
109     $template->param( 'discharge_available' => $available && Koha::Patron::Discharge::is_discharged({borrowernumber => $borrowernumber}) );
110 }
111
112 if ( $userdebarred || $borr->{'gonenoaddress'} || $borr->{'lost'} ) {
113     $borr->{'flagged'} = 1;
114     $canrenew = 0;
115 }
116
117 my ( $amountoutstanding ) = GetMemberAccountRecords($borrowernumber);
118 if ( $amountoutstanding > 5 ) {
119     $borr->{'amountoverfive'} = 1;
120 }
121 if ( 5 >= $amountoutstanding && $amountoutstanding > 0 ) {
122     $borr->{'amountoverzero'} = 1;
123 }
124 my $no_renewal_amt = C4::Context->preference( 'OPACFineNoRenewals' );
125 $no_renewal_amt = undef unless looks_like_number( $no_renewal_amt );
126
127 if (   C4::Context->preference('OpacRenewalAllowed')
128     && defined($no_renewal_amt)
129     && $amountoutstanding > $no_renewal_amt )
130 {
131     $borr->{'flagged'} = 1;
132     $canrenew = 0;
133     $template->param(
134         renewal_blocked_fines => $no_renewal_amt,
135         renewal_blocked_fines_amountoutstanding => $amountoutstanding,
136     );
137 }
138
139 if ( $amountoutstanding < 0 ) {
140     $borr->{'amountlessthanzero'} = 1;
141     $amountoutstanding = -1 * ( $amountoutstanding );
142 }
143
144 # Warningdate is the date that the warning starts appearing
145 if ( $borr->{'dateexpiry'} && C4::Context->preference('NotifyBorrowerDeparture') ) {
146     my $days_to_expiry = Date_to_Days( $warning_year, $warning_month, $warning_day ) - Date_to_Days( $today_year, $today_month, $today_day );
147     if ( $days_to_expiry < 0 ) {
148         #borrower card has expired, warn the borrower
149         $borr->{'warnexpired'} = $borr->{'dateexpiry'};
150     } elsif ( $days_to_expiry < C4::Context->preference('NotifyBorrowerDeparture') ) {
151         # borrower card soon to expire, warn the borrower
152         $borr->{'warndeparture'} = $borr->{dateexpiry};
153         if (C4::Context->preference('ReturnBeforeExpiry')){
154             $borr->{'returnbeforeexpiry'} = 1;
155         }
156     }
157 }
158
159 # pass on any renew errors to the template for displaying
160 my $renew_error = $query->param('renew_error');
161
162 $template->param(   BORROWER_INFO     => $borr,
163                     amountoutstanding => $amountoutstanding,
164                     borrowernumber    => $borrowernumber,
165                     patron_flagged    => $borr->{flagged},
166                     OPACMySummaryHTML => (C4::Context->preference("OPACMySummaryHTML")) ? 1 : 0,
167                     surname           => $borr->{surname},
168                     RENEW_ERROR       => $renew_error,
169                     borrower          => $borr,
170                 );
171
172 #get issued items ....
173
174 my $count          = 0;
175 my $overdues_count = 0;
176 my @overdues;
177 my @issuedat;
178 my $itemtypes = GetItemTypes();
179 my $issues = GetPendingIssues($borrowernumber);
180 if ($issues){
181     foreach my $issue ( sort { $b->{date_due}->datetime() cmp $a->{date_due}->datetime() } @{$issues} ) {
182         # check for reserves
183         my $restype = GetReserveStatus( $issue->{'itemnumber'} );
184         if ( $restype ) {
185             $issue->{'reserved'} = 1;
186         }
187
188         my ( $total , $accts, $numaccts) = GetMemberAccountRecords( $borrowernumber );
189         my $charges = 0;
190         foreach my $ac (@$accts) {
191             if ( $ac->{'itemnumber'} == $issue->{'itemnumber'} ) {
192                 $charges += $ac->{'amountoutstanding'}
193                   if $ac->{'accounttype'} eq 'F';
194                 $charges += $ac->{'amountoutstanding'}
195                   if $ac->{'accounttype'} eq 'FU';
196                 $charges += $ac->{'amountoutstanding'}
197                   if $ac->{'accounttype'} eq 'L';
198             }
199         }
200         $issue->{'charges'} = $charges;
201         my $marcrecord = GetMarcBiblio( $issue->{'biblionumber'} );
202         $issue->{'subtitle'} = GetRecordValue('subtitle', $marcrecord, GetFrameworkCode($issue->{'biblionumber'}));
203         # check if item is renewable
204         my ($status,$renewerror) = CanBookBeRenewed( $borrowernumber, $issue->{'itemnumber'} );
205         ($issue->{'renewcount'},$issue->{'renewsallowed'},$issue->{'renewsleft'}) = GetRenewCount($borrowernumber, $issue->{'itemnumber'});
206         if($status && C4::Context->preference("OpacRenewalAllowed")){
207             $issue->{'status'} = $status;
208         }
209
210         $issue->{'renewed'} = $renewed{ $issue->{'itemnumber'} };
211
212         if ($renewerror) {
213             $issue->{'too_many'}       = 1 if $renewerror eq 'too_many';
214             $issue->{'on_reserve'}     = 1 if $renewerror eq 'on_reserve';
215             $issue->{'norenew_overdue'} = 1 if $renewerror eq 'overdue';
216             $issue->{'auto_renew'}     = 1 if $renewerror eq 'auto_renew';
217             $issue->{'auto_too_soon'}  = 1 if $renewerror eq 'auto_too_soon';
218             $issue->{'auto_too_late'}  = 1 if $renewerror eq 'auto_too_late';
219
220             if ( $renewerror eq 'too_soon' ) {
221                 $issue->{'too_soon'}         = 1;
222                 $issue->{'soonestrenewdate'} = output_pref(
223                     C4::Circulation::GetSoonestRenewDate(
224                         $issue->{borrowernumber},
225                         $issue->{itemnumber}
226                     )
227                 );
228             }
229         }
230
231         if ( $issue->{'overdue'} ) {
232             push @overdues, $issue;
233             $overdues_count++;
234             $issue->{'overdue'} = 1;
235         }
236         else {
237             $issue->{'issued'} = 1;
238         }
239         # imageurl:
240         my $itemtype = $issue->{'itemtype'};
241         if ( $itemtype ) {
242             $issue->{'imageurl'}    = getitemtypeimagelocation( 'opac', $itemtypes->{$itemtype}->{'imageurl'} );
243             $issue->{'description'} = $itemtypes->{$itemtype}->{'description'};
244         }
245         push @issuedat, $issue;
246         $count++;
247
248         my $isbn = GetNormalizedISBN($issue->{'isbn'});
249         $issue->{normalized_isbn} = $isbn;
250         $issue->{normalized_upc} = GetNormalizedUPC( $marcrecord, C4::Context->preference('marcflavour') );
251
252                 # My Summary HTML
253                 if (my $my_summary_html = C4::Context->preference('OPACMySummaryHTML')){
254                     $issue->{author} ? $my_summary_html =~ s/{AUTHOR}/$issue->{author}/g : $my_summary_html =~ s/{AUTHOR}//g;
255                     $issue->{title} =~ s/\/+$//; # remove trailing slash
256                     $issue->{title} =~ s/\s+$//; # remove trailing space
257                     $issue->{title} ? $my_summary_html =~ s/{TITLE}/$issue->{title}/g : $my_summary_html =~ s/{TITLE}//g;
258                     $issue->{isbn} ? $my_summary_html =~ s/{ISBN}/$isbn/g : $my_summary_html =~ s/{ISBN}//g;
259                     $issue->{biblionumber} ? $my_summary_html =~ s/{BIBLIONUMBER}/$issue->{biblionumber}/g : $my_summary_html =~ s/{BIBLIONUMBER}//g;
260                     $issue->{MySummaryHTML} = $my_summary_html;
261                 }
262     }
263 }
264 my $overduesblockrenewing = C4::Context->preference('OverduesBlockRenewing');
265 $canrenew = 0 if ($overduesblockrenewing ne 'allow' and $overdues_count == $count);
266 $template->param( ISSUES       => \@issuedat );
267 $template->param( issues_count => $count );
268 $template->param( canrenew     => $canrenew );
269 $template->param( OVERDUES       => \@overdues );
270 $template->param( overdues_count => $overdues_count );
271
272 my $show_barcode = Koha::Patron::Attribute::Types->search(
273     { code => ATTRIBUTE_SHOW_BARCODE } )->count;
274 if ($show_barcode) {
275     my $patron_show_barcode = GetBorrowerAttributeValue($borrowernumber, ATTRIBUTE_SHOW_BARCODE);
276     undef $show_barcode if defined($patron_show_barcode) && !$patron_show_barcode;
277 }
278 $template->param( show_barcode => 1 ) if $show_barcode;
279
280 # now the reserved items....
281 my $reserves = Koha::Holds->search( { borrowernumber => $borrowernumber } );
282
283 $template->param(
284     RESERVES       => $reserves,
285     showpriority   => $show_priority,
286 );
287
288 # current alert subscriptions
289 my $alerts = getalert($borrowernumber);
290 foreach ( @$alerts ) {
291     $_->{ $_->{type} } = 1;
292     $_->{relatedto} = findrelatedto( $_->{type}, $_->{externalid} );
293 }
294
295 if (C4::Context->preference('BakerTaylorEnabled')) {
296     $template->param(
297         BakerTaylorEnabled  => 1,
298         BakerTaylorImageURL => &image_url(),
299         BakerTaylorLinkURL  => &link_url(),
300         BakerTaylorBookstoreURL => C4::Context->preference('BakerTaylorBookstoreURL'),
301     );
302 }
303
304 if (C4::Context->preference("OPACAmazonCoverImages") or 
305     C4::Context->preference("GoogleJackets") or
306     C4::Context->preference("BakerTaylorEnabled") or
307     C4::Context->preference("SyndeticsCoverImages")) {
308         $template->param(JacketImages=>1);
309 }
310
311 $template->param(
312     OverDriveCirculation => C4::Context->preference('OverDriveCirculation') || 0,
313     overdrive_error      => $query->param('overdrive_error') || undef,
314     overdrive_tab        => $query->param('overdrive_tab') || 0,
315 );
316
317 my $patron_messages = Koha::Patron::Messages->search(
318     {
319         borrowernumber => $borrowernumber,
320         message_type => 'B',
321     }
322 );
323
324 if (   C4::Context->preference('AllowPatronToSetCheckoutsVisibilityForGuarantor')
325     || C4::Context->preference('AllowStaffToSetCheckoutsVisibilityForGuarantor') )
326 {
327     my @relatives =
328       Koha::Database->new()->schema()->resultset("Borrower")->search(
329         {
330             privacy_guarantor_checkouts => 1,
331             'me.guarantorid'           => $borrowernumber
332         },
333         { prefetch => [ { 'issues' => { 'item' => 'biblio' } } ] }
334       );
335     $template->param( relatives => \@relatives );
336 }
337
338 $template->param(
339     borrower                 => Koha::Patrons->find($borrowernumber),
340     patron_messages          => $patron_messages,
341     opacnote                 => $borr->{opacnote},
342     patronupdate             => $patronupdate,
343     OpacRenewalAllowed       => C4::Context->preference("OpacRenewalAllowed"),
344     userview                 => 1,
345     SuspendHoldsOpac         => C4::Context->preference('SuspendHoldsOpac'),
346     AutoResumeSuspendedHolds => C4::Context->preference('AutoResumeSuspendedHolds'),
347     OpacHoldNotes            => C4::Context->preference('OpacHoldNotes'),
348     failed_holds             => scalar $query->param('failed_holds'),
349 );
350
351 output_html_with_http_headers $query, $cookie, $template->output, undef, { force_no_caching => 1 };