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