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