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