Bug 23846: Display degraded view when MARCXML is invalid (staff detail)
[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::Items;
47 use Koha::ItemTypes;
48 use Koha::Patrons;
49 use Koha::Virtualshelves;
50 use Koha::Plugins;
51
52 my $query = CGI->new();
53
54 my $analyze = $query->param('analyze');
55
56 my ( $template, $borrowernumber, $cookie, $flags ) = get_template_and_user(
57     {
58     template_name   =>  'catalogue/detail.tt',
59         query           => $query,
60         type            => "intranet",
61         authnotrequired => 0,
62         flagsrequired   => { catalogue => 1 },
63     }
64 );
65
66 # Determine if we should be offering any enhancement plugin buttons
67 if ( C4::Context->preference('UseKohaPlugins') &&
68      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 my $fw           = GetFrameworkCode($biblionumber);
130 my $showallitems = $query->param('showallitems');
131 my $marcflavour  = C4::Context->preference("marcflavour");
132
133 # XSLT processing of some stuff
134 my $xslfile = C4::Context->preference('XSLTDetailsDisplay') || "default";
135 my $lang   = $xslfile ? C4::Languages::getlanguage()  : undef;
136 my $sysxml = $xslfile ? C4::XSLT::get_xslt_sysprefs() : undef;
137
138 if ( $xslfile ) {
139     $template->param(
140         XSLTDetailsDisplay => '1',
141         XSLTBloc => XSLTParse4Display(
142                         $biblionumber, $record, "XSLTDetailsDisplay",
143                         1, undef, $sysxml, $xslfile, $lang
144                     )
145     );
146 }
147
148 $template->param( 'SpineLabelShowPrintOnBibDetails' => C4::Context->preference("SpineLabelShowPrintOnBibDetails") );
149
150 # Catch the exception as Koha::Biblio::Metadata->record can explode if the MARCXML is invalid
151 # Do not propagate it as we already deal with it previously in this script
152 my $coins = eval { $biblio->get_coins };
153 $template->param( ocoins => $coins );
154
155 # some useful variables for enhanced content;
156 # in each case, we're grabbing the first value we find in
157 # the record and normalizing it
158 my $upc = GetNormalizedUPC($record,$marcflavour);
159 my $ean = GetNormalizedEAN($record,$marcflavour);
160 my $oclc = GetNormalizedOCLCNumber($record,$marcflavour);
161 my $isbn = GetNormalizedISBN(undef,$record,$marcflavour);
162
163 $template->param(
164     normalized_upc => $upc,
165     normalized_ean => $ean,
166     normalized_oclc => $oclc,
167     normalized_isbn => $isbn,
168 );
169
170 my $marcnotesarray   = GetMarcNotes( $record, $marcflavour );
171 my $marcisbnsarray   = GetMarcISBN( $record, $marcflavour );
172 my $marcauthorsarray = GetMarcAuthors( $record, $marcflavour );
173 my $marcsubjctsarray = GetMarcSubjects( $record, $marcflavour );
174 my $marcseriesarray  = GetMarcSeries($record,$marcflavour);
175 my $marcurlsarray    = GetMarcUrls    ($record,$marcflavour);
176 my $marchostsarray   = GetMarcHosts($record,$marcflavour);
177
178 my $itemtypes = { map { $_->{itemtype} => $_ } @{ Koha::ItemTypes->search->unblessed } };
179
180 my $dbh = C4::Context->dbh;
181
182 my @all_items = GetItemsInfo( $biblionumber );
183 my @items;
184 my $patron = Koha::Patrons->find( $borrowernumber );
185 for my $itm (@all_items) {
186     push @items, $itm unless ( $itm->{itemlost} && $patron->category->hidelostitems && !$showallitems);
187 }
188
189 # flag indicating existence of at least one item linked via a host record
190 my $hostrecords;
191 # adding items linked via host biblios
192 my @hostitems = GetHostItemsInfo($record);
193 if (@hostitems){
194     $hostrecords =1;
195     push (@items,@hostitems);
196 }
197
198 my $dat = &GetBiblioData($biblionumber);
199
200 #coping with subscriptions
201 my $subscriptionsnumber = CountSubscriptionFromBiblionumber($biblionumber);
202 my @subscriptions       = SearchSubscriptions({ biblionumber => $biblionumber, orderby => 'title' });
203 my @subs;
204
205 foreach my $subscription (@subscriptions) {
206     my %cell;
207     my $serials_to_display;
208     $cell{subscriptionid}    = $subscription->{subscriptionid};
209     $cell{subscriptionnotes} = $subscription->{internalnotes};
210     $cell{missinglist}       = $subscription->{missinglist};
211     $cell{librariannote}     = $subscription->{librariannote};
212     $cell{branchcode}        = $subscription->{branchcode};
213     $cell{hasalert}          = $subscription->{hasalert};
214     $cell{callnumber}        = $subscription->{callnumber};
215     $cell{location}          = $subscription->{location};
216     $cell{closed}            = $subscription->{closed};
217     #get the three latest serials.
218     $serials_to_display = $subscription->{staffdisplaycount};
219     $serials_to_display = C4::Context->preference('StaffSerialIssueDisplayCount') unless $serials_to_display;
220     $cell{staffdisplaycount} = $serials_to_display;
221     $cell{latestserials} =
222       GetLatestSerials( $subscription->{subscriptionid}, $serials_to_display );
223     push @subs, \%cell;
224 }
225
226
227 # Get acquisition details
228 if ( C4::Context->preference('AcquisitionDetails') ) {
229     my $orders = Koha::Acquisition::Orders->search(
230         { biblionumber => $biblionumber },
231         {
232             join => 'basketno',
233             order_by => 'basketno.booksellerid'
234         }
235     );    # GetHistory sorted by aqbooksellerid, but does it make sense?
236
237     $template->param(
238         orders => $orders,
239     );
240 }
241
242 if ( defined $dat->{'itemtype'} ) {
243     $dat->{imageurl} = getitemtypeimagelocation( 'intranet', $itemtypes->{ $dat->{itemtype} }{imageurl} );
244 }
245
246 $dat->{'count'} = scalar @all_items + @hostitems;
247 $dat->{'showncount'} = scalar @items + @hostitems;
248 $dat->{'hiddencount'} = scalar @all_items + @hostitems - scalar @items;
249
250 my $shelflocations =
251   { map { $_->{authorised_value} => $_->{lib} } Koha::AuthorisedValues->get_descriptions_by_koha_field( { frameworkcode => $fw, kohafield => 'items.location' } ) };
252 my $collections =
253   { map { $_->{authorised_value} => $_->{lib} } Koha::AuthorisedValues->get_descriptions_by_koha_field( { frameworkcode => $fw, kohafield => 'items.ccode' } ) };
254 my $copynumbers =
255   { map { $_->{authorised_value} => $_->{lib} } Koha::AuthorisedValues->get_descriptions_by_koha_field( { frameworkcode => $fw, kohafield => 'items.copynumber' } ) };
256 my (@itemloop, @otheritemloop, %itemfields);
257 my $norequests = 1;
258
259 my $mss = Koha::MarcSubfieldStructures->search({ frameworkcode => $fw, kohafield => 'items.itemlost', authorised_value => [ -and => {'!=' => undef }, {'!=' => ''}] });
260 if ( $mss->count ) {
261     $template->param( itemlostloop => GetAuthorisedValues( $mss->next->authorised_value ) );
262 }
263 $mss = Koha::MarcSubfieldStructures->search({ frameworkcode => $fw, kohafield => 'items.damaged', authorised_value => [ -and => {'!=' => undef }, {'!=' => ''}] });
264 if ( $mss->count ) {
265     $template->param( itemdamagedloop => GetAuthorisedValues( $mss->next->authorised_value ) );
266 }
267 $mss = Koha::MarcSubfieldStructures->search({ frameworkcode => $fw, kohafield => 'items.withdrawn', authorised_value => { not => undef } });
268 if ( $mss->count ) {
269     $template->param( itemwithdrawnloop => GetAuthorisedValues( $mss->next->authorised_value) );
270 }
271
272 $mss = Koha::MarcSubfieldStructures->search({ frameworkcode => $fw, kohafield => 'items.materials', authorised_value => [ -and => {'!=' => undef }, {'!=' => ''}] });
273 my %materials_map;
274 if ($mss->count) {
275     my $materials_authvals = GetAuthorisedValues($mss->next->authorised_value);
276     if ($materials_authvals) {
277         foreach my $value (@$materials_authvals) {
278             $materials_map{$value->{authorised_value}} = $value->{lib};
279         }
280     }
281 }
282
283 my $analytics_flag;
284 my $materials_flag; # set this if the items have anything in the materials field
285 my $currentbranch = C4::Context->userenv ? C4::Context->userenv->{branch} : undef;
286 if ($currentbranch and C4::Context->preference('SeparateHoldings')) {
287     $template->param(SeparateHoldings => 1);
288 }
289 my $separatebranch = C4::Context->preference('SeparateHoldingsBranch') || 'homebranch';
290 foreach my $item (@items) {
291     my $itembranchcode = $item->{$separatebranch};
292
293     # can place holds defaults to yes
294     $norequests = 0 unless ( ( $item->{'notforloan'} > 0 ) || ( $item->{'itemnotforloan'} > 0 ) );
295
296     $item->{imageurl} = defined $item->{itype} ? getitemtypeimagelocation('intranet', $itemtypes->{ $item->{itype} }{imageurl})
297                                                : '';
298
299     $item->{datedue} = format_sqldatetime($item->{datedue});
300
301     #get shelf location and collection code description if they are authorised value.
302     # same thing for copy number
303     my $shelfcode = $item->{'location'};
304     $item->{'location'} = $shelflocations->{$shelfcode} if ( defined( $shelfcode ) && defined($shelflocations) && exists( $shelflocations->{$shelfcode} ) );
305     my $ccode = $item->{'ccode'};
306     $item->{'ccode'} = $collections->{$ccode} if ( defined( $ccode ) && defined($collections) && exists( $collections->{$ccode} ) );
307     my $copynumber = $item->{'copynumber'};
308     $item->{'copynumber'} = $copynumbers->{$copynumber} if ( defined($copynumber) && defined($copynumbers) && exists( $copynumbers->{$copynumber} ) );
309     foreach (qw(ccode enumchron copynumber stocknumber itemnotes itemnotes_nonpublic uri)) {
310         $itemfields{$_} = 1 if ( $item->{$_} );
311     }
312
313     # checking for holds
314     my $item_object = Koha::Items->find( $item->{itemnumber} );
315     my $holds = $item_object->current_holds;
316     if ( my $first_hold = $holds->next ) {
317         my $patron = Koha::Patrons->find( $first_hold->borrowernumber );
318         $item->{backgroundcolor} = 'reserved';
319         $item->{reservedate}     = $first_hold->reservedate;
320         $item->{ReservedFor}     = $patron,
321         $item->{ExpectedAtLibrary}      = $first_hold->branchcode;
322         # Check waiting status
323         $item->{waitingdate} = $first_hold->waitingdate;
324     }
325
326     if ( my $checkout = $item_object->checkout ) {
327         $item->{CheckedOutFor} = $checkout->patron;
328     }
329
330     # Check the transit status
331     my ( $transfertwhen, $transfertfrom, $transfertto ) = GetTransfers($item->{itemnumber});
332     if ( defined( $transfertwhen ) && ( $transfertwhen ne '' ) ) {
333         $item->{transfertwhen} = $transfertwhen;
334         $item->{transfertfrom} = $transfertfrom;
335         $item->{transfertto}   = $transfertto;
336         $item->{nocancel} = 1;
337     }
338
339     foreach my $f (qw( itemnotes )) {
340         if ($item->{$f}) {
341             $item->{$f} =~ s|\n|<br />|g;
342             $itemfields{$f} = 1;
343         }
344     }
345
346     #item has a host number if its biblio number does not match the current bib
347
348     if ($item->{biblionumber} ne $biblionumber){
349         $item->{hostbiblionumber} = $item->{biblionumber};
350         $item->{hosttitle} = GetBiblioData($item->{biblionumber})->{title};
351     }
352         
353
354     if ( $analyze ) {
355         # count if item is used in analytical bibliorecords
356         # The 'countanalytics' flag is only used in the templates if analyze is set
357         my $countanalytics = C4::Context->preference('EasyAnalyticalRecords') ? GetAnalyticsCount($item->{itemnumber}) : 0;
358         if ($countanalytics > 0){
359             $analytics_flag=1;
360             $item->{countanalytics} = $countanalytics;
361         }
362     }
363
364     if (defined($item->{'materials'}) && $item->{'materials'} =~ /\S/){
365         $materials_flag = 1;
366         if (defined $materials_map{ $item->{materials} }) {
367             $item->{materials} = $materials_map{ $item->{materials} };
368         }
369     }
370
371     if ( C4::Context->preference('UseCourseReserves') ) {
372         $item->{'course_reserves'} = GetItemCourseReservesInfo( itemnumber => $item->{'itemnumber'} );
373     }
374
375     if ( C4::Context->preference('IndependentBranches') ) {
376         my $userenv = C4::Context->userenv();
377         if ( not C4::Context->IsSuperLibrarian()
378             and $userenv->{branch} ne $item->{homebranch} ) {
379             $item->{cannot_be_edited} = 1;
380         }
381     }
382
383     if ($currentbranch and $currentbranch ne "NO_LIBRARY_SET"
384     and C4::Context->preference('SeparateHoldings')) {
385         if ($itembranchcode and $itembranchcode eq $currentbranch) {
386             push @itemloop, $item;
387         } else {
388             push @otheritemloop, $item;
389         }
390     } else {
391         push @itemloop, $item;
392     }
393 }
394
395 # Display only one tab if one items list is empty
396 if (scalar(@itemloop) == 0 || scalar(@otheritemloop) == 0) {
397     $template->param(SeparateHoldings => 0);
398     if (scalar(@itemloop) == 0) {
399         @itemloop = @otheritemloop;
400     }
401 }
402
403 $template->param( norequests => $norequests );
404 $template->param(
405     MARCNOTES   => $marcnotesarray,
406     MARCSUBJCTS => $marcsubjctsarray,
407     MARCAUTHORS => $marcauthorsarray,
408     MARCSERIES  => $marcseriesarray,
409     MARCURLS => $marcurlsarray,
410     MARCISBNS => $marcisbnsarray,
411     MARCHOSTS => $marchostsarray,
412     itemdata_ccode      => $itemfields{ccode},
413     itemdata_enumchron  => $itemfields{enumchron},
414     itemdata_uri        => $itemfields{uri},
415     itemdata_copynumber => $itemfields{copynumber},
416     itemdata_stocknumber => $itemfields{stocknumber},
417     volinfo                => $itemfields{enumchron},
418         itemdata_itemnotes  => $itemfields{itemnotes},
419         itemdata_nonpublicnotes => $itemfields{itemnotes_nonpublic},
420     z3950_search_params    => C4::Search::z3950_search_args($dat),
421         hostrecords         => $hostrecords,
422     analytics_flag    => $analytics_flag,
423     C4::Search::enabled_staff_search_views,
424         materials       => $materials_flag,
425 );
426
427 if (C4::Context->preference("AlternateHoldingsField") && scalar @items == 0) {
428     my $fieldspec = C4::Context->preference("AlternateHoldingsField");
429     my $subfields = substr $fieldspec, 3;
430     my $holdingsep = C4::Context->preference("AlternateHoldingsSeparator") || ' ';
431     my @alternateholdingsinfo = ();
432     my @holdingsfields = $record->field(substr $fieldspec, 0, 3);
433
434     for my $field (@holdingsfields) {
435         my %holding = ( holding => '' );
436         my $havesubfield = 0;
437         for my $subfield ($field->subfields()) {
438             if ((index $subfields, $$subfield[0]) >= 0) {
439                 $holding{'holding'} .= $holdingsep if (length $holding{'holding'} > 0);
440                 $holding{'holding'} .= $$subfield[1];
441                 $havesubfield++;
442             }
443         }
444         if ($havesubfield) {
445             push(@alternateholdingsinfo, \%holding);
446         }
447     }
448
449     $template->param(
450         ALTERNATEHOLDINGS   => \@alternateholdingsinfo,
451         );
452 }
453
454 my @results = ( $dat, );
455 foreach ( keys %{$dat} ) {
456     $template->param( "$_" => defined $dat->{$_} ? $dat->{$_} : '' );
457 }
458
459 # does not work: my %views_enabled = map { $_ => 1 } $template->query(loop => 'EnableViews');
460 # method query not found?!?!
461 $template->param( AmazonTld => get_amazon_tld() ) if ( C4::Context->preference("AmazonCoverImages"));
462 $template->param(
463     itemloop        => \@itemloop,
464     otheritemloop   => \@otheritemloop,
465     biblionumber        => $biblionumber,
466     ($analyze? 'analyze':'detailview') =>1,
467     subscriptions       => \@subs,
468     subscriptionsnumber => $subscriptionsnumber,
469     subscriptiontitle   => $dat->{title},
470     searchid            => scalar $query->param('searchid'),
471 );
472
473 # $debug and $template->param(debug_display => 1);
474
475 # Lists
476
477 if (C4::Context->preference("virtualshelves") ) {
478     my $shelves = Koha::Virtualshelves->search(
479         {
480             biblionumber => $biblionumber,
481             category => 2,
482         },
483         {
484             join => 'virtualshelfcontents',
485         }
486     );
487     $template->param( 'shelves' => $shelves );
488 }
489
490 # XISBN Stuff
491 if (C4::Context->preference("FRBRizeEditions")==1) {
492     eval {
493         $template->param(
494             XISBNS => scalar get_xisbns($isbn, $biblionumber)
495         );
496     };
497     if ($@) { warn "XISBN Failed $@"; }
498 }
499
500 if ( C4::Context->preference("LocalCoverImages") == 1 ) {
501     my @images = ListImagesForBiblio($biblionumber);
502     $template->{VARS}->{localimages} = \@images;
503 }
504
505 # HTML5 Media
506 if ( (C4::Context->preference("HTML5MediaEnabled") eq 'both') or (C4::Context->preference("HTML5MediaEnabled") eq 'staff') ) {
507     $template->param( C4::HTML5Media->gethtml5media($record));
508 }
509
510 # Displaying tags
511
512 my $tag_quantity;
513 if (C4::Context->preference('TagsEnabled') and $tag_quantity = C4::Context->preference('TagsShowOnDetail')) {
514     $template->param(
515         TagsEnabled => 1,
516         TagsShowOnDetail => $tag_quantity
517     );
518     $template->param(TagLoop => get_tags({biblionumber=>$biblionumber, approved=>1,
519                                 'sort'=>'-weight', limit=>$tag_quantity}));
520 }
521
522 #we only need to pass the number of holds to the template
523 my $holds = $biblio->holds;
524 $template->param( holdcount => $holds->count );
525
526 my $StaffDetailItemSelection = C4::Context->preference('StaffDetailItemSelection');
527 if ($StaffDetailItemSelection) {
528     # Only enable item selection if user can execute at least one action
529     if (
530         $flags->{superlibrarian}
531         || (
532             ref $flags->{tools} eq 'HASH' && (
533                 $flags->{tools}->{items_batchmod}       # Modify selected items
534                 || $flags->{tools}->{items_batchdel}    # Delete selected items
535             )
536         )
537         || ( ref $flags->{tools} eq '' && $flags->{tools} )
538       )
539     {
540         $template->param(
541             StaffDetailItemSelection => $StaffDetailItemSelection );
542     }
543 }
544
545 my @allorders_using_biblio = GetOrdersByBiblionumber ($biblionumber);
546 my @deletedorders_using_biblio;
547 my @orders_using_biblio;
548 my @baskets_orders;
549 my @baskets_deletedorders;
550
551 foreach my $myorder (@allorders_using_biblio) {
552     my $basket = $myorder->{'basketno'};
553     if ((defined $myorder->{'datecancellationprinted'}) and  ($myorder->{'datecancellationprinted'} ne '0000-00-00') ){
554         push @deletedorders_using_biblio, $myorder;
555         unless (grep(/^$basket$/, @baskets_deletedorders)){
556             push @baskets_deletedorders,$myorder->{'basketno'};
557         }
558     }
559     else {
560         push @orders_using_biblio, $myorder;
561         unless (grep(/^$basket$/, @baskets_orders)){
562             push @baskets_orders,$myorder->{'basketno'};
563             }
564     }
565 }
566
567 $template->param(biblio => $biblio);
568
569 my $count_orders_using_biblio = scalar @orders_using_biblio ;
570 $template->param (countorders => $count_orders_using_biblio);
571
572 my $count_deletedorders_using_biblio = scalar @deletedorders_using_biblio ;
573 $template->param (countdeletedorders => $count_deletedorders_using_biblio);
574
575 $template->param (basketsorders => \@baskets_orders);
576 $template->param (basketsdeletedorders => \@baskets_deletedorders);
577
578 output_html_with_http_headers $query, $cookie, $template->output;