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