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