Bug 16805: Log in with database admin user breaks OPAC
[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 C4::Branch; # GetBranches
37 use Koha::DateUtils;
38 use Koha::Borrower::Debarments qw(IsDebarred);
39
40 use constant ATTRIBUTE_SHOW_BARCODE => 'SHOW_BCODE';
41
42 use Scalar::Util qw(looks_like_number);
43 use Date::Calc qw(
44   Today
45   Add_Delta_Days
46   Date_to_Days
47 );
48
49 my $query = new CGI;
50
51 BEGIN {
52     if (C4::Context->preference('BakerTaylorEnabled')) {
53         require C4::External::BakerTaylor;
54         import C4::External::BakerTaylor qw(&image_url &link_url);
55     }
56 }
57
58 my ( $template, $borrowernumber, $cookie ) = get_template_and_user(
59     {
60         template_name   => "opac-user.tt",
61         query           => $query,
62         type            => "opac",
63         authnotrequired => 0,
64         debug           => 1,
65     }
66 );
67
68 my %renewed = map { $_ => 1 } split( ':', $query->param('renewed') );
69
70 my $show_priority;
71 for ( C4::Context->preference("OPACShowHoldQueueDetails") ) {
72     m/priority/ and $show_priority = 1;
73 }
74
75 my $patronupdate = $query->param('patronupdate');
76 my $canrenew = 1;
77
78 $template->param( shibbolethAuthentication => C4::Context->config('useshibboleth') );
79
80 if (!$borrowernumber) {
81     $template->param( adminWarning => 1 );
82 }
83
84 # get borrower information ....
85 my ( $borr ) = GetMemberDetails( $borrowernumber );
86
87 my (  $today_year,   $today_month,   $today_day) = Today();
88 my ($warning_year, $warning_month, $warning_day) = split /-/, $borr->{'dateexpiry'};
89
90 my $debar = IsDebarred($borrowernumber);
91 my $userdebarred;
92
93 if ($debar) {
94     $userdebarred = 1;
95     $template->param( 'userdebarred' => $userdebarred );
96     if ( $debar ne "9999-12-31" ) {
97         $borr->{'userdebarreddate'} = $debar;
98     }
99 }
100
101 if ( $userdebarred || $borr->{'gonenoaddress'} || $borr->{'lost'} ) {
102     $borr->{'flagged'} = 1;
103     $canrenew = 0;
104 }
105
106 if ( $borr->{'amountoutstanding'} > 5 ) {
107     $borr->{'amountoverfive'} = 1;
108 }
109 if ( 5 >= $borr->{'amountoutstanding'} && $borr->{'amountoutstanding'} > 0 ) {
110     $borr->{'amountoverzero'} = 1;
111 }
112 my $no_renewal_amt = C4::Context->preference( 'OPACFineNoRenewals' );
113 $no_renewal_amt = undef unless looks_like_number( $no_renewal_amt );
114
115 if (   C4::Context->preference('OpacRenewalAllowed')
116     && defined($no_renewal_amt)
117     && $borr->{amountoutstanding} > $no_renewal_amt )
118 {
119     $borr->{'flagged'} = 1;
120     $canrenew = 0;
121     $template->param(
122         renewal_blocked_fines => sprintf( '%.02f', $no_renewal_amt ),
123         renewal_blocked_fines_amountoutstanding =>
124           sprintf( '%.02f', $borr->{amountoutstanding} ),
125     );
126 }
127
128 if ( $borr->{'amountoutstanding'} < 0 ) {
129     $borr->{'amountlessthanzero'} = 1;
130     $borr->{'amountoutstanding'} = -1 * ( $borr->{'amountoutstanding'} );
131 }
132
133 $borr->{'amountoutstanding'} = sprintf "%.02f", $borr->{'amountoutstanding'};
134
135 # Warningdate is the date that the warning starts appearing
136 if ( $borr->{'dateexpiry'} && C4::Context->preference('NotifyBorrowerDeparture') ) {
137     my $days_to_expiry = Date_to_Days( $warning_year, $warning_month, $warning_day ) - Date_to_Days( $today_year, $today_month, $today_day );
138     if ( $days_to_expiry < 0 ) {
139         #borrower card has expired, warn the borrower
140         $borr->{'warnexpired'} = $borr->{'dateexpiry'};
141     } elsif ( $days_to_expiry < C4::Context->preference('NotifyBorrowerDeparture') ) {
142         # borrower card soon to expire, warn the borrower
143         $borr->{'warndeparture'} = $borr->{dateexpiry};
144         if (C4::Context->preference('ReturnBeforeExpiry')){
145             $borr->{'returnbeforeexpiry'} = 1;
146         }
147     }
148 }
149
150 # pass on any renew errors to the template for displaying
151 my $renew_error = $query->param('renew_error');
152
153 $template->param(   BORROWER_INFO     => $borr,
154                     borrowernumber    => $borrowernumber,
155                     patron_flagged    => $borr->{flagged},
156                     OPACMySummaryHTML => (C4::Context->preference("OPACMySummaryHTML")) ? 1 : 0,
157                     surname           => $borr->{surname},
158                     RENEW_ERROR       => $renew_error,
159                     borrower          => $borr,
160                 );
161
162 #get issued items ....
163
164 my $count          = 0;
165 my $overdues_count = 0;
166 my @overdues;
167 my @issuedat;
168 my $itemtypes = GetItemTypes();
169 my $issues = GetPendingIssues($borrowernumber);
170 if ($issues){
171     foreach my $issue ( sort { $b->{date_due}->datetime() cmp $a->{date_due}->datetime() } @{$issues} ) {
172         # check for reserves
173         my $restype = GetReserveStatus( $issue->{'itemnumber'} );
174         if ( $restype ) {
175             $issue->{'reserved'} = 1;
176         }
177
178         my ( $total , $accts, $numaccts) = GetMemberAccountRecords( $borrowernumber );
179         my $charges = 0;
180         foreach my $ac (@$accts) {
181             if ( $ac->{'itemnumber'} == $issue->{'itemnumber'} ) {
182                 $charges += $ac->{'amountoutstanding'}
183                   if $ac->{'accounttype'} eq 'F';
184                 $charges += $ac->{'amountoutstanding'}
185                   if $ac->{'accounttype'} eq 'FU';
186                 $charges += $ac->{'amountoutstanding'}
187                   if $ac->{'accounttype'} eq 'L';
188             }
189         }
190         $issue->{'charges'} = $charges;
191         my $marcrecord = GetMarcBiblio( $issue->{'biblionumber'} );
192         $issue->{'subtitle'} = GetRecordValue('subtitle', $marcrecord, GetFrameworkCode($issue->{'biblionumber'}));
193         # check if item is renewable
194         my ($status,$renewerror) = CanBookBeRenewed( $borrowernumber, $issue->{'itemnumber'} );
195         ($issue->{'renewcount'},$issue->{'renewsallowed'},$issue->{'renewsleft'}) = GetRenewCount($borrowernumber, $issue->{'itemnumber'});
196         if($status && C4::Context->preference("OpacRenewalAllowed")){
197             $issue->{'status'} = $status;
198         }
199
200         $issue->{'renewed'} = $renewed{ $issue->{'itemnumber'} };
201
202         if ($renewerror) {
203             $issue->{'too_many'}       = 1 if $renewerror eq 'too_many';
204             $issue->{'on_reserve'}     = 1 if $renewerror eq 'on_reserve';
205             $issue->{'norenew_overdue'} = 1 if $renewerror eq 'overdue';
206             $issue->{'auto_renew'}     = 1 if $renewerror eq 'auto_renew';
207             $issue->{'auto_too_soon'}  = 1 if $renewerror eq 'auto_too_soon';
208
209             if ( $renewerror eq 'too_soon' ) {
210                 $issue->{'too_soon'}         = 1;
211                 $issue->{'soonestrenewdate'} = output_pref(
212                     C4::Circulation::GetSoonestRenewDate(
213                         $issue->{borrowernumber},
214                         $issue->{itemnumber}
215                     )
216                 );
217             }
218         }
219
220         if ( $issue->{'overdue'} ) {
221             push @overdues, $issue;
222             $overdues_count++;
223             $issue->{'overdue'} = 1;
224         }
225         else {
226             $issue->{'issued'} = 1;
227         }
228         # imageurl:
229         my $itemtype = $issue->{'itemtype'};
230         if ( $itemtype ) {
231             $issue->{'imageurl'}    = getitemtypeimagelocation( 'opac', $itemtypes->{$itemtype}->{'imageurl'} );
232             $issue->{'description'} = $itemtypes->{$itemtype}->{'description'};
233         }
234         push @issuedat, $issue;
235         $count++;
236
237         my $isbn = GetNormalizedISBN($issue->{'isbn'});
238         $issue->{normalized_isbn} = $isbn;
239         $issue->{normalized_upc} = GetNormalizedUPC( $marcrecord, C4::Context->preference('marcflavour') );
240
241                 # My Summary HTML
242                 if (my $my_summary_html = C4::Context->preference('OPACMySummaryHTML')){
243                     $issue->{author} ? $my_summary_html =~ s/{AUTHOR}/$issue->{author}/g : $my_summary_html =~ s/{AUTHOR}//g;
244                     $issue->{title} =~ s/\/+$//; # remove trailing slash
245                     $issue->{title} =~ s/\s+$//; # remove trailing space
246                     $issue->{title} ? $my_summary_html =~ s/{TITLE}/$issue->{title}/g : $my_summary_html =~ s/{TITLE}//g;
247                     $issue->{isbn} ? $my_summary_html =~ s/{ISBN}/$isbn/g : $my_summary_html =~ s/{ISBN}//g;
248                     $issue->{biblionumber} ? $my_summary_html =~ s/{BIBLIONUMBER}/$issue->{biblionumber}/g : $my_summary_html =~ s/{BIBLIONUMBER}//g;
249                     $issue->{MySummaryHTML} = $my_summary_html;
250                 }
251     }
252 }
253 my $overduesblockrenewing = C4::Context->preference('OverduesBlockRenewing');
254 $canrenew = 0 if ($overduesblockrenewing ne 'allow' and $overdues_count == $count);
255 $template->param( ISSUES       => \@issuedat );
256 $template->param( issues_count => $count );
257 $template->param( canrenew     => $canrenew );
258 $template->param( OVERDUES       => \@overdues );
259 $template->param( overdues_count => $overdues_count );
260
261 my $show_barcode = C4::Members::AttributeTypes::AttributeTypeExists( ATTRIBUTE_SHOW_BARCODE );
262 if ($show_barcode) {
263     my $patron_show_barcode = GetBorrowerAttributeValue($borrowernumber, ATTRIBUTE_SHOW_BARCODE);
264     undef $show_barcode if defined($patron_show_barcode) && !$patron_show_barcode;
265 }
266 $template->param( show_barcode => 1 ) if $show_barcode;
267
268 # load the branches
269 my $branches = GetBranches();
270 my @branch_loop;
271 for my $branch_hash ( sort keys %{$branches} ) {
272     my $selected;
273     if ( C4::Context->preference('SearchMyLibraryFirst') ) {
274         $selected =
275           ( C4::Context->userenv
276               && ( $branch_hash eq C4::Context->userenv->{branch} ) );
277     }
278     push @branch_loop,
279       { value      => "branch: $branch_hash",
280         branchname => $branches->{$branch_hash}->{'branchname'},
281         selected   => $selected,
282       };
283 }
284 $template->param( branchloop => \@branch_loop );
285
286 # now the reserved items....
287 my @reserves  = GetReservesFromBorrowernumber( $borrowernumber );
288 foreach my $res (@reserves) {
289
290     if ( $res->{'expirationdate'} eq '0000-00-00' ) {
291       $res->{'expirationdate'} = '';
292     }
293     $res->{'subtitle'} = GetRecordValue('subtitle', GetMarcBiblio($res->{'biblionumber'}), GetFrameworkCode($res->{'biblionumber'}));
294     $res->{'waiting'} = 1 if $res->{'found'} eq 'W';
295     $res->{'branch'} = $branches->{ $res->{'branchcode'} }->{'branchname'};
296     my $biblioData = GetBiblioData($res->{'biblionumber'});
297     $res->{'reserves_title'} = $biblioData->{'title'};
298     $res->{'author'} = $biblioData->{'author'};
299
300     if ($show_priority) {
301         $res->{'priority'} ||= '';
302     }
303     if ( $res->{'suspend_until'} ) {
304         $res->{'suspend_until'} = output_pref({ dt => dt_from_string( $res->{'suspend_until'} , 'iso' ), dateonly => 1 });
305     }
306 }
307
308 # use Data::Dumper;
309 # warn Dumper(@reserves);
310
311 $template->param( RESERVES       => \@reserves );
312 $template->param( reserves_count => $#reserves+1 );
313 $template->param( showpriority=>$show_priority );
314
315 my @waiting;
316 my $wcount = 0;
317 foreach my $res (@reserves) {
318     if ( $res->{'itemnumber'} ) {
319         my $item = GetItem( $res->{'itemnumber'});
320         $res->{'holdingbranch'} =
321           $branches->{ $item->{'holdingbranch'} }->{'branchname'};
322         $res->{'branch'} = $branches->{ $res->{'branchcode'} }->{'branchname'};
323         $res->{'enumchron'} = $item->{'enumchron'} if $item->{'enumchron'};
324         # get document reserve status
325         my $biblioData = GetBiblioData($res->{'biblionumber'});
326         $res->{'waiting_title'} = $biblioData->{'title'};
327         if ( ( $res->{'found'} eq 'W' ) ) {
328             my $item = $res->{'itemnumber'};
329             $item = GetBiblioFromItemNumber($item,undef);
330             $res->{'wait'}= 1;
331             $res->{'holdingbranch'}=$item->{'holdingbranch'};
332             $res->{'biblionumber'}=$item->{'biblionumber'};
333             $res->{'barcode'} = $item->{'barcode'};
334             $res->{'wbrcode'} = $res->{'branchcode'};
335             $res->{'itemnumber'}    = $res->{'itemnumber'};
336             $res->{'wbrname'} = $branches->{$res->{'branchcode'}}->{'branchname'};
337             if($res->{'holdingbranch'} eq $res->{'wbrcode'}){
338                 $res->{'atdestination'} = 1;
339             }
340             # set found to 1 if reserve is waiting for patron pickup
341             $res->{'found'} = 1 if $res->{'found'} eq 'W';
342         } else {
343             my ($transfertwhen, $transfertfrom, $transfertto) = GetTransfers( $res->{'itemnumber'} );
344             if ($transfertwhen) {
345                 $res->{intransit} = 1;
346                 $res->{datesent}   = $transfertwhen;
347                 $res->{frombranch} = GetBranchName($transfertfrom);
348             }
349         }
350         push @waiting, $res;
351         $wcount++;
352     }
353     # can be cancelled
354     #$res->{'cancelable'} = 1 if ($res->{'wait'} && $res->{'atdestination'} && $res->{'found'} ne "1");
355     $res->{'cancelable'} = 1 if    ($res->{wait} and not $res->{found}) or (not $res->{wait} and not $res->{intransit});
356
357 }
358
359 $template->param( WAITING => \@waiting );
360
361 # current alert subscriptions
362 my $alerts = getalert($borrowernumber);
363 foreach ( @$alerts ) {
364     $_->{ $_->{type} } = 1;
365     $_->{relatedto} = findrelatedto( $_->{type}, $_->{externalid} );
366 }
367
368 if (C4::Context->preference('BakerTaylorEnabled')) {
369     $template->param(
370         BakerTaylorEnabled  => 1,
371         BakerTaylorImageURL => &image_url(),
372         BakerTaylorLinkURL  => &link_url(),
373         BakerTaylorBookstoreURL => C4::Context->preference('BakerTaylorBookstoreURL'),
374     );
375 }
376
377 if (C4::Context->preference("OPACAmazonCoverImages") or 
378     C4::Context->preference("GoogleJackets") or
379     C4::Context->preference("BakerTaylorEnabled") or
380     C4::Context->preference("SyndeticsCoverImages")) {
381         $template->param(JacketImages=>1);
382 }
383
384 if ( GetMessagesCount( $borrowernumber, 'B' ) ) {
385     $template->param( bor_messages => 1 );
386 }
387
388 if ( $borr->{'opacnote'} ) {
389   $template->param( 
390     bor_messages => 1,
391     opacnote => $borr->{'opacnote'},
392   );
393 }
394
395 $template->param(
396     bor_messages_loop        => GetMessages( $borrowernumber, 'B', 'NONE' ),
397     waiting_count            => $wcount,
398     patronupdate             => $patronupdate,
399     OpacRenewalAllowed       => C4::Context->preference("OpacRenewalAllowed"),
400     userview                 => 1,
401     SuspendHoldsOpac         => C4::Context->preference('SuspendHoldsOpac'),
402     AutoResumeSuspendedHolds => C4::Context->preference('AutoResumeSuspendedHolds'),
403     OpacHoldNotes            => C4::Context->preference('OpacHoldNotes'),
404     failed_holds             => scalar $query->param('failed_holds'),
405 );
406
407 output_html_with_http_headers $query, $cookie, $template->output, undef, { force_no_caching => 1 };