Bug 24663: Remove authnotrequired if set to 0
[koha.git] / catalogue / detail.pl
1 #!/usr/bin/perl
2
3 # This file is part of Koha.
4 #
5 # Koha is free software; you can redistribute it and/or modify it
6 # under the terms of the GNU General Public License as published by
7 # the Free Software Foundation; either version 3 of the License, or
8 # (at your option) any later version.
9 #
10 # Koha is distributed in the hope that it will be useful, but
11 # WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU General Public License for more details.
14 #
15 # You should have received a copy of the GNU General Public License
16 # along with Koha; if not, see <http://www.gnu.org/licenses>.
17
18
19 use Modern::Perl;
20
21 use CGI qw ( -utf8 );
22 use HTML::Entities;
23 use Try::Tiny;
24 use C4::Auth;
25 use C4::Context;
26 use C4::Koha;
27 use C4::Serials;    #uses getsubscriptionfrom biblionumber
28 use C4::Output;
29 use C4::Biblio;
30 use C4::Items;
31 use C4::Circulation;
32 use C4::Reserves;
33 use C4::Serials;
34 use C4::XISBN qw(get_xisbns);
35 use C4::External::Amazon;
36 use C4::Search;        # enabled_staff_search_views
37 use C4::Tags qw(get_tags);
38 use C4::XSLT;
39 use C4::Images;
40 use Koha::DateUtils;
41 use C4::HTML5Media;
42 use C4::CourseReserves qw(GetItemCourseReservesInfo);
43 use C4::Acquisition qw(GetOrdersByBiblionumber);
44 use Koha::AuthorisedValues;
45 use Koha::Biblios;
46 use Koha::Illrequests;
47 use Koha::Items;
48 use Koha::ItemTypes;
49 use Koha::Patrons;
50 use Koha::Virtualshelves;
51 use Koha::Plugins;
52
53 my $query = CGI->new();
54
55 my $analyze = $query->param('analyze');
56
57 my ( $template, $borrowernumber, $cookie, $flags ) = get_template_and_user(
58     {
59     template_name   =>  'catalogue/detail.tt',
60         query           => $query,
61         type            => "intranet",
62         flagsrequired   => { catalogue => 1 },
63     }
64 );
65
66 # Determine if we should be offering any enhancement plugin buttons
67 if ( C4::Context->config('enable_plugins') ) {
68     # Only pass plugins that can offer a toolbar button
69     my @plugins = Koha::Plugins->new()->GetPlugins({
70         method => 'intranet_catalog_biblio_enhancements_toolbar_button'
71     });
72
73     my @tab_plugins = Koha::Plugins->new()->GetPlugins({
74         method => 'intranet_catalog_biblio_tab',
75     });
76     my @tabs;
77     foreach my $tab_plugin (@tab_plugins) {
78         my @biblio_tabs;
79
80         try {
81             @biblio_tabs = $tab_plugin->intranet_catalog_biblio_tab();
82             foreach my $tab (@biblio_tabs) {
83                 my $tab_id = 'tab-' . $tab->title;
84                 $tab_id =~ s/[^0-9A-Za-z]+/-/g;
85                 $tab->id( $tab_id );
86                 push @tabs, $tab,
87             }
88         }
89         catch {
90             warn "Error calling 'intranet_catalog_biblio_tab' on the " . $tab_plugin->{class} . "plugin ($_)";
91         };
92     }
93
94     $template->param(
95         plugins => \@plugins,
96         tabs => \@tabs,
97     );
98 }
99
100 my $biblionumber = $query->param('biblionumber');
101 $biblionumber = HTML::Entities::encode($biblionumber);
102 my $record       = GetMarcBiblio({ biblionumber => $biblionumber });
103 my $biblio = Koha::Biblios->find( $biblionumber );
104 $template->param( 'biblio', $biblio );
105
106 if ( not defined $record ) {
107     # biblionumber invalid -> report and exit
108     $template->param( unknownbiblionumber => 1,
109                       biblionumber => $biblionumber );
110     output_html_with_http_headers $query, $cookie, $template->output;
111     exit;
112 }
113
114 eval { $biblio->metadata->record };
115 $template->param( decoding_error => $@ );
116
117 if($query->cookie("holdfor")){ 
118     my $holdfor_patron = Koha::Patrons->find( $query->cookie("holdfor") );
119     $template->param(
120         # FIXME Should pass the patron object
121         holdfor => $query->cookie("holdfor"),
122         holdfor_surname => $holdfor_patron->surname,
123         holdfor_firstname => $holdfor_patron->firstname,
124         holdfor_cardnumber => $holdfor_patron->cardnumber,
125     );
126 }
127
128 if($query->cookie("searchToOrder")){
129     my ( $basketno, $vendorid ) = split( /\//, $query->cookie("searchToOrder") );
130     $template->param(
131         searchtoorder_basketno => $basketno,
132         searchtoorder_vendorid => $vendorid
133     );
134 }
135
136 my $fw           = GetFrameworkCode($biblionumber);
137 my $showallitems = $query->param('showallitems');
138 my $marcflavour  = C4::Context->preference("marcflavour");
139
140 # XSLT processing of some stuff
141 my $xslfile = C4::Context->preference('XSLTDetailsDisplay') || "default";
142 my $lang   = $xslfile ? C4::Languages::getlanguage()  : undef;
143 my $sysxml = $xslfile ? C4::XSLT::get_xslt_sysprefs() : undef;
144
145 if ( $xslfile ) {
146     $template->param(
147         XSLTDetailsDisplay => '1',
148         XSLTBloc => XSLTParse4Display(
149                         $biblionumber, $record, "XSLTDetailsDisplay",
150                         1, undef, $sysxml, $xslfile, $lang
151                     )
152     );
153 }
154
155 $template->param( 'SpineLabelShowPrintOnBibDetails' => C4::Context->preference("SpineLabelShowPrintOnBibDetails") );
156
157 # Catch the exception as Koha::Biblio::Metadata->record can explode if the MARCXML is invalid
158 # Do not propagate it as we already deal with it previously in this script
159 my $coins = eval { $biblio->get_coins };
160 $template->param( ocoins => $coins );
161
162 # some useful variables for enhanced content;
163 # in each case, we're grabbing the first value we find in
164 # the record and normalizing it
165 my $upc = GetNormalizedUPC($record,$marcflavour);
166 my $ean = GetNormalizedEAN($record,$marcflavour);
167 my $oclc = GetNormalizedOCLCNumber($record,$marcflavour);
168 my $isbn = GetNormalizedISBN(undef,$record,$marcflavour);
169
170 $template->param(
171     normalized_upc => $upc,
172     normalized_ean => $ean,
173     normalized_oclc => $oclc,
174     normalized_isbn => $isbn,
175 );
176
177 my $marcnotesarray   = GetMarcNotes( $record, $marcflavour );
178
179 my $itemtypes = { map { $_->{itemtype} => $_ } @{ Koha::ItemTypes->search->unblessed } };
180
181 my $dbh = C4::Context->dbh;
182
183 my @all_items = GetItemsInfo( $biblionumber );
184 my @items;
185 my $patron = Koha::Patrons->find( $borrowernumber );
186 for my $itm (@all_items) {
187     push @items, $itm unless ( $itm->{itemlost} && $patron->category->hidelostitems && !$showallitems);
188 }
189
190 # flag indicating existence of at least one item linked via a host record
191 my $hostrecords;
192 # adding items linked via host biblios
193 my @hostitems = GetHostItemsInfo($record);
194 if (@hostitems){
195     $hostrecords =1;
196     push (@items,@hostitems);
197 }
198
199 my $dat = &GetBiblioData($biblionumber);
200
201 #coping with subscriptions
202 my $subscriptionsnumber = CountSubscriptionFromBiblionumber($biblionumber);
203 my @subscriptions       = SearchSubscriptions({ biblionumber => $biblionumber, orderby => 'title' });
204 my @subs;
205
206 foreach my $subscription (@subscriptions) {
207     my %cell;
208     my $serials_to_display;
209     $cell{subscriptionid}    = $subscription->{subscriptionid};
210     $cell{subscriptionnotes} = $subscription->{internalnotes};
211     $cell{missinglist}       = $subscription->{missinglist};
212     $cell{librariannote}     = $subscription->{librariannote};
213     $cell{branchcode}        = $subscription->{branchcode};
214     $cell{hasalert}          = $subscription->{hasalert};
215     $cell{callnumber}        = $subscription->{callnumber};
216     $cell{location}          = $subscription->{location};
217     $cell{closed}            = $subscription->{closed};
218     #get the three latest serials.
219     $serials_to_display = $subscription->{staffdisplaycount};
220     $serials_to_display = C4::Context->preference('StaffSerialIssueDisplayCount') unless $serials_to_display;
221     $cell{staffdisplaycount} = $serials_to_display;
222     $cell{latestserials} =
223       GetLatestSerials( $subscription->{subscriptionid}, $serials_to_display );
224     push @subs, \%cell;
225 }
226
227
228 # Get acquisition details
229 if ( C4::Context->preference('AcquisitionDetails') ) {
230     my $orders = Koha::Acquisition::Orders->search(
231         { biblionumber => $biblionumber },
232         {
233             join => 'basketno',
234             order_by => 'basketno.booksellerid'
235         }
236     );    # GetHistory sorted by aqbooksellerid, but does it make sense?
237
238     $template->param(
239         orders => $orders,
240     );
241 }
242
243 if ( C4::Context->preference('suggestion') ) {
244     my $suggestions = Koha::Suggestions->search(
245         {
246             biblionumber => $biblionumber,
247             archived     => 0,
248         },
249         {
250             order_by => { -desc => 'suggesteddate' }
251         }
252     );
253     my $nb_archived_suggestions = Koha::Suggestions->search({ biblionumber => $biblionumber, archived => 1 })->count;
254     $template->param( suggestions => $suggestions, nb_archived_suggestions => $nb_archived_suggestions );
255 }
256
257 if ( defined $dat->{'itemtype'} ) {
258     $dat->{imageurl} = getitemtypeimagelocation( 'intranet', $itemtypes->{ $dat->{itemtype} }{imageurl} );
259 }
260
261 $dat->{'count'} = scalar @all_items + @hostitems;
262 $dat->{'showncount'} = scalar @items + @hostitems;
263 $dat->{'hiddencount'} = scalar @all_items + @hostitems - scalar @items;
264
265 my $shelflocations =
266   { map { $_->{authorised_value} => $_->{lib} } Koha::AuthorisedValues->get_descriptions_by_koha_field( { frameworkcode => $fw, kohafield => 'items.location' } ) };
267 my $collections =
268   { map { $_->{authorised_value} => $_->{lib} } Koha::AuthorisedValues->get_descriptions_by_koha_field( { frameworkcode => $fw, kohafield => 'items.ccode' } ) };
269 my $copynumbers =
270   { map { $_->{authorised_value} => $_->{lib} } Koha::AuthorisedValues->get_descriptions_by_koha_field( { frameworkcode => $fw, kohafield => 'items.copynumber' } ) };
271 my (@itemloop, @otheritemloop, %itemfields);
272
273 my $mss = Koha::MarcSubfieldStructures->search({ frameworkcode => $fw, kohafield => 'items.itemlost', authorised_value => [ -and => {'!=' => undef }, {'!=' => ''}] });
274 if ( $mss->count ) {
275     $template->param( itemlostloop => GetAuthorisedValues( $mss->next->authorised_value ) );
276 }
277 $mss = Koha::MarcSubfieldStructures->search({ frameworkcode => $fw, kohafield => 'items.damaged', authorised_value => [ -and => {'!=' => undef }, {'!=' => ''}] });
278 if ( $mss->count ) {
279     $template->param( itemdamagedloop => GetAuthorisedValues( $mss->next->authorised_value ) );
280 }
281 $mss = Koha::MarcSubfieldStructures->search({ frameworkcode => $fw, kohafield => 'items.withdrawn', authorised_value => { not => undef } });
282 if ( $mss->count ) {
283     $template->param( itemwithdrawnloop => GetAuthorisedValues( $mss->next->authorised_value) );
284 }
285
286 $mss = Koha::MarcSubfieldStructures->search({ frameworkcode => $fw, kohafield => 'items.materials', authorised_value => [ -and => {'!=' => undef }, {'!=' => ''}] });
287 my %materials_map;
288 if ($mss->count) {
289     my $materials_authvals = GetAuthorisedValues($mss->next->authorised_value);
290     if ($materials_authvals) {
291         foreach my $value (@$materials_authvals) {
292             $materials_map{$value->{authorised_value}} = $value->{lib};
293         }
294     }
295 }
296
297 my $analytics_flag;
298 my $materials_flag; # set this if the items have anything in the materials field
299 my $currentbranch = C4::Context->userenv ? C4::Context->userenv->{branch} : undef;
300 if ($currentbranch and C4::Context->preference('SeparateHoldings')) {
301     $template->param(SeparateHoldings => 1);
302 }
303 my $separatebranch = C4::Context->preference('SeparateHoldingsBranch') || 'homebranch';
304 foreach my $item (@items) {
305     my $itembranchcode = $item->{$separatebranch};
306
307     $item->{imageurl} = defined $item->{itype} ? getitemtypeimagelocation('intranet', $itemtypes->{ $item->{itype} }{imageurl})
308                                                : '';
309
310     $item->{datedue} = format_sqldatetime($item->{datedue});
311
312     #get shelf location and collection code description if they are authorised value.
313     # same thing for copy number
314     my $shelfcode = $item->{'location'};
315     $item->{'location'} = $shelflocations->{$shelfcode} if ( defined( $shelfcode ) && defined($shelflocations) && exists( $shelflocations->{$shelfcode} ) );
316     my $ccode = $item->{'ccode'};
317     $item->{'ccode'} = $collections->{$ccode} if ( defined( $ccode ) && defined($collections) && exists( $collections->{$ccode} ) );
318     my $copynumber = $item->{'copynumber'};
319     $item->{'copynumber'} = $copynumbers->{$copynumber} if ( defined($copynumber) && defined($copynumbers) && exists( $copynumbers->{$copynumber} ) );
320     foreach (qw(ccode enumchron copynumber stocknumber itemnotes itemnotes_nonpublic uri publisheddate)) { # Warning when removing GetItemsInfo - publisheddate (at least) is not part of the items table
321         $itemfields{$_} = 1 if ( $item->{$_} );
322     }
323
324     # checking for holds
325     my $item_object = Koha::Items->find( $item->{itemnumber} );
326     my $holds = $item_object->current_holds;
327     if ( my $first_hold = $holds->next ) {
328         $item->{first_hold} = $first_hold;
329     }
330
331     if ( my $checkout = $item_object->checkout ) {
332         $item->{CheckedOutFor} = $checkout->patron;
333     }
334
335     # Check the transit status
336     my ( $transfertwhen, $transfertfrom, $transfertto ) = GetTransfers($item->{itemnumber});
337     if ( defined( $transfertwhen ) && ( $transfertwhen ne '' ) ) {
338         $item->{transfertwhen} = $transfertwhen;
339         $item->{transfertfrom} = $transfertfrom;
340         $item->{transfertto}   = $transfertto;
341         $item->{nocancel} = 1;
342     }
343
344     foreach my $f (qw( itemnotes )) {
345         if ($item->{$f}) {
346             $item->{$f} =~ s|\n|<br />|g;
347             $itemfields{$f} = 1;
348         }
349     }
350
351     #item has a host number if its biblio number does not match the current bib
352
353     if ($item->{biblionumber} ne $biblionumber){
354         $item->{hostbiblionumber} = $item->{biblionumber};
355         $item->{hosttitle} = GetBiblioData($item->{biblionumber})->{title};
356     }
357         
358
359     if ( $analyze ) {
360         # count if item is used in analytical bibliorecords
361         # The 'countanalytics' flag is only used in the templates if analyze is set
362         my $countanalytics = C4::Context->preference('EasyAnalyticalRecords') ? GetAnalyticsCount($item->{itemnumber}) : 0;
363         if ($countanalytics > 0){
364             $analytics_flag=1;
365             $item->{countanalytics} = $countanalytics;
366         }
367     }
368
369     if (defined($item->{'materials'}) && $item->{'materials'} =~ /\S/){
370         $materials_flag = 1;
371         if (defined $materials_map{ $item->{materials} }) {
372             $item->{materials} = $materials_map{ $item->{materials} };
373         }
374     }
375
376     if ( C4::Context->preference('UseCourseReserves') ) {
377         $item->{'course_reserves'} = GetItemCourseReservesInfo( itemnumber => $item->{'itemnumber'} );
378     }
379
380     if ( C4::Context->preference('IndependentBranches') ) {
381         my $userenv = C4::Context->userenv();
382         if ( not C4::Context->IsSuperLibrarian()
383             and $userenv->{branch} ne $item->{homebranch} ) {
384             $item->{cannot_be_edited} = 1;
385         }
386     }
387
388     if ($currentbranch and C4::Context->preference('SeparateHoldings')) {
389         if ($itembranchcode and $itembranchcode eq $currentbranch) {
390             push @itemloop, $item;
391         } else {
392             push @otheritemloop, $item;
393         }
394     } else {
395         push @itemloop, $item;
396     }
397 }
398
399 # Display only one tab if one items list is empty
400 if (scalar(@itemloop) == 0 || scalar(@otheritemloop) == 0) {
401     $template->param(SeparateHoldings => 0);
402     if (scalar(@itemloop) == 0) {
403         @itemloop = @otheritemloop;
404     }
405 }
406
407 $template->param(
408     MARCNOTES   => $marcnotesarray,
409     itemdata_ccode      => $itemfields{ccode},
410     itemdata_enumchron  => $itemfields{enumchron},
411     itemdata_uri        => $itemfields{uri},
412     itemdata_copynumber => $itemfields{copynumber},
413     itemdata_stocknumber => $itemfields{stocknumber},
414     itemdata_publisheddate => $itemfields{publisheddate},
415     volinfo                => $itemfields{enumchron},
416         itemdata_itemnotes  => $itemfields{itemnotes},
417         itemdata_nonpublicnotes => $itemfields{itemnotes_nonpublic},
418     z3950_search_params    => C4::Search::z3950_search_args($dat),
419         hostrecords         => $hostrecords,
420     analytics_flag    => $analytics_flag,
421     C4::Search::enabled_staff_search_views,
422         materials       => $materials_flag,
423 );
424
425 if (C4::Context->preference("AlternateHoldingsField") && scalar @items == 0) {
426     my $fieldspec = C4::Context->preference("AlternateHoldingsField");
427     my $subfields = substr $fieldspec, 3;
428     my $holdingsep = C4::Context->preference("AlternateHoldingsSeparator") || ' ';
429     my @alternateholdingsinfo = ();
430     my @holdingsfields = $record->field(substr $fieldspec, 0, 3);
431
432     for my $field (@holdingsfields) {
433         my %holding = ( holding => '' );
434         my $havesubfield = 0;
435         for my $subfield ($field->subfields()) {
436             if ((index $subfields, $$subfield[0]) >= 0) {
437                 $holding{'holding'} .= $holdingsep if (length $holding{'holding'} > 0);
438                 $holding{'holding'} .= $$subfield[1];
439                 $havesubfield++;
440             }
441         }
442         if ($havesubfield) {
443             push(@alternateholdingsinfo, \%holding);
444         }
445     }
446
447     $template->param(
448         ALTERNATEHOLDINGS   => \@alternateholdingsinfo,
449         );
450 }
451
452 my @results = ( $dat, );
453 foreach ( keys %{$dat} ) {
454     $template->param( "$_" => defined $dat->{$_} ? $dat->{$_} : '' );
455 }
456
457 # does not work: my %views_enabled = map { $_ => 1 } $template->query(loop => 'EnableViews');
458 # method query not found?!?!
459 $template->param( AmazonTld => get_amazon_tld() ) if ( C4::Context->preference("AmazonCoverImages"));
460 $template->param(
461     itemloop        => \@itemloop,
462     otheritemloop   => \@otheritemloop,
463     biblionumber        => $biblionumber,
464     ($analyze? 'analyze':'detailview') =>1,
465     subscriptions       => \@subs,
466     subscriptionsnumber => $subscriptionsnumber,
467     subscriptiontitle   => $dat->{title},
468     searchid            => scalar $query->param('searchid'),
469 );
470
471 # $debug and $template->param(debug_display => 1);
472
473 # Lists
474
475 if (C4::Context->preference("virtualshelves") ) {
476     my $shelves = Koha::Virtualshelves->search(
477         {
478             biblionumber => $biblionumber,
479             category => 2,
480         },
481         {
482             join => 'virtualshelfcontents',
483         }
484     );
485     $template->param( 'shelves' => $shelves );
486 }
487
488 # XISBN Stuff
489 if (C4::Context->preference("FRBRizeEditions")==1) {
490     eval {
491         $template->param(
492             XISBNS => scalar get_xisbns($isbn, $biblionumber)
493         );
494     };
495     if ($@) { warn "XISBN Failed $@"; }
496 }
497
498 if ( C4::Context->preference("LocalCoverImages") == 1 ) {
499     my @images = ListImagesForBiblio($biblionumber);
500     $template->{VARS}->{localimages} = \@images;
501 }
502
503 # HTML5 Media
504 if ( (C4::Context->preference("HTML5MediaEnabled") eq 'both') or (C4::Context->preference("HTML5MediaEnabled") eq 'staff') ) {
505     $template->param( C4::HTML5Media->gethtml5media($record));
506 }
507
508 # Displaying tags
509 my $tag_quantity;
510 if (C4::Context->preference('TagsEnabled') and $tag_quantity = C4::Context->preference('TagsShowOnDetail')) {
511     $template->param(
512         TagsEnabled => 1,
513         TagsShowOnDetail => $tag_quantity
514     );
515     $template->param(TagLoop => get_tags({biblionumber=>$biblionumber, approved=>1,
516                                 'sort'=>'-weight', limit=>$tag_quantity}));
517 }
518
519 #we only need to pass the number of holds to the template
520 my $holds = $biblio->holds;
521 $template->param( holdcount => $holds->count );
522
523 # Check if there are any ILL requests connected to the biblio
524 my $illrequests =
525     C4::Context->preference('ILLModule')
526   ? Koha::Illrequests->search( { biblio_id => $biblionumber } )
527   : [];
528 $template->param( illrequests => $illrequests );
529
530 my $StaffDetailItemSelection = C4::Context->preference('StaffDetailItemSelection');
531 if ($StaffDetailItemSelection) {
532     # Only enable item selection if user can execute at least one action
533     if (
534         $flags->{superlibrarian}
535         || (
536             ref $flags->{tools} eq 'HASH' && (
537                 $flags->{tools}->{items_batchmod}       # Modify selected items
538                 || $flags->{tools}->{items_batchdel}    # Delete selected items
539             )
540         )
541         || ( ref $flags->{tools} eq '' && $flags->{tools} )
542       )
543     {
544         $template->param(
545             StaffDetailItemSelection => $StaffDetailItemSelection );
546     }
547 }
548
549 $template->param(biblio => $biblio);
550
551 output_html_with_http_headers $query, $cookie, $template->output;