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