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