Bug 23794: (RM follow-up) Make DB update consistent
[koha.git] / catalogue / detail.pl
blobc968e33dc9976ce57a20da0569016e27352ae37e
1 #!/usr/bin/perl
3 # This file is part of Koha.
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.
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.
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>.
19 use Modern::Perl;
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::Items;
47 use Koha::ItemTypes;
48 use Koha::Patrons;
49 use Koha::Virtualshelves;
50 use Koha::Plugins;
52 my $query = CGI->new();
54 my $analyze = $query->param('analyze');
56 my ( $template, $borrowernumber, $cookie, $flags ) = get_template_and_user(
58 template_name => 'catalogue/detail.tt',
59 query => $query,
60 type => "intranet",
61 authnotrequired => 0,
62 flagsrequired => { catalogue => 1 },
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 });
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;
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,
89 catch {
90 warn "Error calling 'intranet_catalog_biblio_tab' on the " . $tab_plugin->{class} . "plugin ($_)";
94 $template->param(
95 plugins => \@plugins,
96 tabs => \@tabs,
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 );
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;
114 eval { $biblio->metadata->record };
115 $template->param( decoding_error => $@ );
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,
128 if($query->cookie("searchToOrder")){
129 my ( $basketno, $vendorid ) = split( /\//, $query->cookie("searchToOrder") );
130 $template->param(
131 searchtoorder_basketno => $basketno,
132 searchtoorder_vendorid => $vendorid
136 my $fw = GetFrameworkCode($biblionumber);
137 my $showallitems = $query->param('showallitems');
138 my $marcflavour = C4::Context->preference("marcflavour");
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;
145 if ( $xslfile ) {
146 $template->param(
147 XSLTDetailsDisplay => '1',
148 XSLTBloc => XSLTParse4Display(
149 $biblionumber, $record, "XSLTDetailsDisplay",
150 1, undef, $sysxml, $xslfile, $lang
155 $template->param( 'SpineLabelShowPrintOnBibDetails' => C4::Context->preference("SpineLabelShowPrintOnBibDetails") );
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 );
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);
170 $template->param(
171 normalized_upc => $upc,
172 normalized_ean => $ean,
173 normalized_oclc => $oclc,
174 normalized_isbn => $isbn,
177 my $marcnotesarray = GetMarcNotes( $record, $marcflavour );
178 my $marcisbnsarray = GetMarcISBN( $record, $marcflavour );
179 my $marcauthorsarray = GetMarcAuthors( $record, $marcflavour );
180 my $marcsubjctsarray = GetMarcSubjects( $record, $marcflavour );
181 my $marcseriesarray = GetMarcSeries($record,$marcflavour);
182 my $marcurlsarray = GetMarcUrls ($record,$marcflavour);
183 my $marchostsarray = GetMarcHosts($record,$marcflavour);
185 my $itemtypes = { map { $_->{itemtype} => $_ } @{ Koha::ItemTypes->search->unblessed } };
187 my $dbh = C4::Context->dbh;
189 my @all_items = GetItemsInfo( $biblionumber );
190 my @items;
191 my $patron = Koha::Patrons->find( $borrowernumber );
192 for my $itm (@all_items) {
193 push @items, $itm unless ( $itm->{itemlost} && $patron->category->hidelostitems && !$showallitems);
196 # flag indicating existence of at least one item linked via a host record
197 my $hostrecords;
198 # adding items linked via host biblios
199 my @hostitems = GetHostItemsInfo($record);
200 if (@hostitems){
201 $hostrecords =1;
202 push (@items,@hostitems);
205 my $dat = &GetBiblioData($biblionumber);
207 #coping with subscriptions
208 my $subscriptionsnumber = CountSubscriptionFromBiblionumber($biblionumber);
209 my @subscriptions = SearchSubscriptions({ biblionumber => $biblionumber, orderby => 'title' });
210 my @subs;
212 foreach my $subscription (@subscriptions) {
213 my %cell;
214 my $serials_to_display;
215 $cell{subscriptionid} = $subscription->{subscriptionid};
216 $cell{subscriptionnotes} = $subscription->{internalnotes};
217 $cell{missinglist} = $subscription->{missinglist};
218 $cell{librariannote} = $subscription->{librariannote};
219 $cell{branchcode} = $subscription->{branchcode};
220 $cell{hasalert} = $subscription->{hasalert};
221 $cell{callnumber} = $subscription->{callnumber};
222 $cell{location} = $subscription->{location};
223 $cell{closed} = $subscription->{closed};
224 #get the three latest serials.
225 $serials_to_display = $subscription->{staffdisplaycount};
226 $serials_to_display = C4::Context->preference('StaffSerialIssueDisplayCount') unless $serials_to_display;
227 $cell{staffdisplaycount} = $serials_to_display;
228 $cell{latestserials} =
229 GetLatestSerials( $subscription->{subscriptionid}, $serials_to_display );
230 push @subs, \%cell;
234 # Get acquisition details
235 if ( C4::Context->preference('AcquisitionDetails') ) {
236 my $orders = Koha::Acquisition::Orders->search(
237 { biblionumber => $biblionumber },
239 join => 'basketno',
240 order_by => 'basketno.booksellerid'
242 ); # GetHistory sorted by aqbooksellerid, but does it make sense?
244 $template->param(
245 orders => $orders,
249 if ( C4::Context->preference('suggestion') ) {
250 my $suggestions = Koha::Suggestions->search(
252 biblionumber => $biblionumber,
253 archived => 0,
256 order_by => { -desc => 'suggesteddate' }
259 my $nb_archived_suggestions = Koha::Suggestions->search({ biblionumber => $biblionumber, archived => 1 })->count;
260 $template->param( suggestions => $suggestions, nb_archived_suggestions => $nb_archived_suggestions );
263 if ( defined $dat->{'itemtype'} ) {
264 $dat->{imageurl} = getitemtypeimagelocation( 'intranet', $itemtypes->{ $dat->{itemtype} }{imageurl} );
267 $dat->{'count'} = scalar @all_items + @hostitems;
268 $dat->{'showncount'} = scalar @items + @hostitems;
269 $dat->{'hiddencount'} = scalar @all_items + @hostitems - scalar @items;
271 my $shelflocations =
272 { map { $_->{authorised_value} => $_->{lib} } Koha::AuthorisedValues->get_descriptions_by_koha_field( { frameworkcode => $fw, kohafield => 'items.location' } ) };
273 my $collections =
274 { map { $_->{authorised_value} => $_->{lib} } Koha::AuthorisedValues->get_descriptions_by_koha_field( { frameworkcode => $fw, kohafield => 'items.ccode' } ) };
275 my $copynumbers =
276 { map { $_->{authorised_value} => $_->{lib} } Koha::AuthorisedValues->get_descriptions_by_koha_field( { frameworkcode => $fw, kohafield => 'items.copynumber' } ) };
277 my (@itemloop, @otheritemloop, %itemfields);
278 my $norequests = 1;
280 my $mss = Koha::MarcSubfieldStructures->search({ frameworkcode => $fw, kohafield => 'items.itemlost', authorised_value => [ -and => {'!=' => undef }, {'!=' => ''}] });
281 if ( $mss->count ) {
282 $template->param( itemlostloop => GetAuthorisedValues( $mss->next->authorised_value ) );
284 $mss = Koha::MarcSubfieldStructures->search({ frameworkcode => $fw, kohafield => 'items.damaged', authorised_value => [ -and => {'!=' => undef }, {'!=' => ''}] });
285 if ( $mss->count ) {
286 $template->param( itemdamagedloop => GetAuthorisedValues( $mss->next->authorised_value ) );
288 $mss = Koha::MarcSubfieldStructures->search({ frameworkcode => $fw, kohafield => 'items.withdrawn', authorised_value => { not => undef } });
289 if ( $mss->count ) {
290 $template->param( itemwithdrawnloop => GetAuthorisedValues( $mss->next->authorised_value) );
293 $mss = Koha::MarcSubfieldStructures->search({ frameworkcode => $fw, kohafield => 'items.materials', authorised_value => [ -and => {'!=' => undef }, {'!=' => ''}] });
294 my %materials_map;
295 if ($mss->count) {
296 my $materials_authvals = GetAuthorisedValues($mss->next->authorised_value);
297 if ($materials_authvals) {
298 foreach my $value (@$materials_authvals) {
299 $materials_map{$value->{authorised_value}} = $value->{lib};
304 my $analytics_flag;
305 my $materials_flag; # set this if the items have anything in the materials field
306 my $currentbranch = C4::Context->userenv ? C4::Context->userenv->{branch} : undef;
307 if ($currentbranch and C4::Context->preference('SeparateHoldings')) {
308 $template->param(SeparateHoldings => 1);
310 my $separatebranch = C4::Context->preference('SeparateHoldingsBranch') || 'homebranch';
311 foreach my $item (@items) {
312 my $itembranchcode = $item->{$separatebranch};
314 # can place holds defaults to yes
315 $norequests = 0 unless ( ( $item->{'notforloan'} > 0 ) || ( $item->{'itemnotforloan'} > 0 ) );
317 $item->{imageurl} = defined $item->{itype} ? getitemtypeimagelocation('intranet', $itemtypes->{ $item->{itype} }{imageurl})
318 : '';
320 $item->{datedue} = format_sqldatetime($item->{datedue});
322 #get shelf location and collection code description if they are authorised value.
323 # same thing for copy number
324 my $shelfcode = $item->{'location'};
325 $item->{'location'} = $shelflocations->{$shelfcode} if ( defined( $shelfcode ) && defined($shelflocations) && exists( $shelflocations->{$shelfcode} ) );
326 my $ccode = $item->{'ccode'};
327 $item->{'ccode'} = $collections->{$ccode} if ( defined( $ccode ) && defined($collections) && exists( $collections->{$ccode} ) );
328 my $copynumber = $item->{'copynumber'};
329 $item->{'copynumber'} = $copynumbers->{$copynumber} if ( defined($copynumber) && defined($copynumbers) && exists( $copynumbers->{$copynumber} ) );
330 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
331 $itemfields{$_} = 1 if ( $item->{$_} );
334 # checking for holds
335 my $item_object = Koha::Items->find( $item->{itemnumber} );
336 my $holds = $item_object->current_holds;
337 if ( my $first_hold = $holds->next ) {
338 $item->{first_hold} = $first_hold;
341 if ( my $checkout = $item_object->checkout ) {
342 $item->{CheckedOutFor} = $checkout->patron;
345 # Check the transit status
346 my ( $transfertwhen, $transfertfrom, $transfertto ) = GetTransfers($item->{itemnumber});
347 if ( defined( $transfertwhen ) && ( $transfertwhen ne '' ) ) {
348 $item->{transfertwhen} = $transfertwhen;
349 $item->{transfertfrom} = $transfertfrom;
350 $item->{transfertto} = $transfertto;
351 $item->{nocancel} = 1;
354 foreach my $f (qw( itemnotes )) {
355 if ($item->{$f}) {
356 $item->{$f} =~ s|\n|<br />|g;
357 $itemfields{$f} = 1;
361 #item has a host number if its biblio number does not match the current bib
363 if ($item->{biblionumber} ne $biblionumber){
364 $item->{hostbiblionumber} = $item->{biblionumber};
365 $item->{hosttitle} = GetBiblioData($item->{biblionumber})->{title};
369 if ( $analyze ) {
370 # count if item is used in analytical bibliorecords
371 # The 'countanalytics' flag is only used in the templates if analyze is set
372 my $countanalytics = C4::Context->preference('EasyAnalyticalRecords') ? GetAnalyticsCount($item->{itemnumber}) : 0;
373 if ($countanalytics > 0){
374 $analytics_flag=1;
375 $item->{countanalytics} = $countanalytics;
379 if (defined($item->{'materials'}) && $item->{'materials'} =~ /\S/){
380 $materials_flag = 1;
381 if (defined $materials_map{ $item->{materials} }) {
382 $item->{materials} = $materials_map{ $item->{materials} };
386 if ( C4::Context->preference('UseCourseReserves') ) {
387 $item->{'course_reserves'} = GetItemCourseReservesInfo( itemnumber => $item->{'itemnumber'} );
390 if ( C4::Context->preference('IndependentBranches') ) {
391 my $userenv = C4::Context->userenv();
392 if ( not C4::Context->IsSuperLibrarian()
393 and $userenv->{branch} ne $item->{homebranch} ) {
394 $item->{cannot_be_edited} = 1;
398 if ($currentbranch and C4::Context->preference('SeparateHoldings')) {
399 if ($itembranchcode and $itembranchcode eq $currentbranch) {
400 push @itemloop, $item;
401 } else {
402 push @otheritemloop, $item;
404 } else {
405 push @itemloop, $item;
409 # Display only one tab if one items list is empty
410 if (scalar(@itemloop) == 0 || scalar(@otheritemloop) == 0) {
411 $template->param(SeparateHoldings => 0);
412 if (scalar(@itemloop) == 0) {
413 @itemloop = @otheritemloop;
417 $template->param( norequests => $norequests );
418 $template->param(
419 MARCNOTES => $marcnotesarray,
420 MARCSUBJCTS => $marcsubjctsarray,
421 MARCAUTHORS => $marcauthorsarray,
422 MARCSERIES => $marcseriesarray,
423 MARCURLS => $marcurlsarray,
424 MARCISBNS => $marcisbnsarray,
425 MARCHOSTS => $marchostsarray,
426 itemdata_ccode => $itemfields{ccode},
427 itemdata_enumchron => $itemfields{enumchron},
428 itemdata_uri => $itemfields{uri},
429 itemdata_copynumber => $itemfields{copynumber},
430 itemdata_stocknumber => $itemfields{stocknumber},
431 itemdata_publisheddate => $itemfields{publisheddate},
432 volinfo => $itemfields{enumchron},
433 itemdata_itemnotes => $itemfields{itemnotes},
434 itemdata_nonpublicnotes => $itemfields{itemnotes_nonpublic},
435 z3950_search_params => C4::Search::z3950_search_args($dat),
436 hostrecords => $hostrecords,
437 analytics_flag => $analytics_flag,
438 C4::Search::enabled_staff_search_views,
439 materials => $materials_flag,
442 if (C4::Context->preference("AlternateHoldingsField") && scalar @items == 0) {
443 my $fieldspec = C4::Context->preference("AlternateHoldingsField");
444 my $subfields = substr $fieldspec, 3;
445 my $holdingsep = C4::Context->preference("AlternateHoldingsSeparator") || ' ';
446 my @alternateholdingsinfo = ();
447 my @holdingsfields = $record->field(substr $fieldspec, 0, 3);
449 for my $field (@holdingsfields) {
450 my %holding = ( holding => '' );
451 my $havesubfield = 0;
452 for my $subfield ($field->subfields()) {
453 if ((index $subfields, $$subfield[0]) >= 0) {
454 $holding{'holding'} .= $holdingsep if (length $holding{'holding'} > 0);
455 $holding{'holding'} .= $$subfield[1];
456 $havesubfield++;
459 if ($havesubfield) {
460 push(@alternateholdingsinfo, \%holding);
464 $template->param(
465 ALTERNATEHOLDINGS => \@alternateholdingsinfo,
469 my @results = ( $dat, );
470 foreach ( keys %{$dat} ) {
471 $template->param( "$_" => defined $dat->{$_} ? $dat->{$_} : '' );
474 # does not work: my %views_enabled = map { $_ => 1 } $template->query(loop => 'EnableViews');
475 # method query not found?!?!
476 $template->param( AmazonTld => get_amazon_tld() ) if ( C4::Context->preference("AmazonCoverImages"));
477 $template->param(
478 itemloop => \@itemloop,
479 otheritemloop => \@otheritemloop,
480 biblionumber => $biblionumber,
481 ($analyze? 'analyze':'detailview') =>1,
482 subscriptions => \@subs,
483 subscriptionsnumber => $subscriptionsnumber,
484 subscriptiontitle => $dat->{title},
485 searchid => scalar $query->param('searchid'),
488 # $debug and $template->param(debug_display => 1);
490 # Lists
492 if (C4::Context->preference("virtualshelves") ) {
493 my $shelves = Koha::Virtualshelves->search(
495 biblionumber => $biblionumber,
496 category => 2,
499 join => 'virtualshelfcontents',
502 $template->param( 'shelves' => $shelves );
505 # XISBN Stuff
506 if (C4::Context->preference("FRBRizeEditions")==1) {
507 eval {
508 $template->param(
509 XISBNS => scalar get_xisbns($isbn, $biblionumber)
512 if ($@) { warn "XISBN Failed $@"; }
515 if ( C4::Context->preference("LocalCoverImages") == 1 ) {
516 my @images = ListImagesForBiblio($biblionumber);
517 $template->{VARS}->{localimages} = \@images;
520 # HTML5 Media
521 if ( (C4::Context->preference("HTML5MediaEnabled") eq 'both') or (C4::Context->preference("HTML5MediaEnabled") eq 'staff') ) {
522 $template->param( C4::HTML5Media->gethtml5media($record));
525 # Displaying tags
527 my $tag_quantity;
528 if (C4::Context->preference('TagsEnabled') and $tag_quantity = C4::Context->preference('TagsShowOnDetail')) {
529 $template->param(
530 TagsEnabled => 1,
531 TagsShowOnDetail => $tag_quantity
533 $template->param(TagLoop => get_tags({biblionumber=>$biblionumber, approved=>1,
534 'sort'=>'-weight', limit=>$tag_quantity}));
537 #we only need to pass the number of holds to the template
538 my $holds = $biblio->holds;
539 $template->param( holdcount => $holds->count );
541 my $StaffDetailItemSelection = C4::Context->preference('StaffDetailItemSelection');
542 if ($StaffDetailItemSelection) {
543 # Only enable item selection if user can execute at least one action
544 if (
545 $flags->{superlibrarian}
546 || (
547 ref $flags->{tools} eq 'HASH' && (
548 $flags->{tools}->{items_batchmod} # Modify selected items
549 || $flags->{tools}->{items_batchdel} # Delete selected items
552 || ( ref $flags->{tools} eq '' && $flags->{tools} )
555 $template->param(
556 StaffDetailItemSelection => $StaffDetailItemSelection );
560 my @allorders_using_biblio = GetOrdersByBiblionumber ($biblionumber);
561 my @deletedorders_using_biblio;
562 my @orders_using_biblio;
563 my @baskets_orders;
564 my @baskets_deletedorders;
566 foreach my $myorder (@allorders_using_biblio) {
567 my $basket = $myorder->{'basketno'};
568 if ((defined $myorder->{'datecancellationprinted'}) and ($myorder->{'datecancellationprinted'} ne '0000-00-00') ){
569 push @deletedorders_using_biblio, $myorder;
570 unless (grep{ $_ eq $basket } @baskets_deletedorders){
571 push @baskets_deletedorders,$myorder->{'basketno'};
574 else {
575 push @orders_using_biblio, $myorder;
576 unless (grep{ $_ eq $basket } @baskets_orders){
577 push @baskets_orders,$myorder->{'basketno'};
582 $template->param(biblio => $biblio);
584 my $count_orders_using_biblio = scalar @orders_using_biblio ;
585 $template->param (countorders => $count_orders_using_biblio);
587 my $count_deletedorders_using_biblio = scalar @deletedorders_using_biblio ;
588 $template->param (countdeletedorders => $count_deletedorders_using_biblio);
590 $template->param (basketsorders => \@baskets_orders);
591 $template->param (basketsdeletedorders => \@baskets_deletedorders);
593 output_html_with_http_headers $query, $cookie, $template->output;