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