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