Bug 17600: Standardize our EXPORT_OK
[srvgit] / C4 / XSLT.pm
1 package C4::XSLT;
2
3 # Copyright (C) 2006 LibLime
4 # <jmf at liblime dot com>
5 # Parts Copyright Katrin Fischer 2011
6 # Parts Copyright ByWater Solutions 2011
7 # Parts Copyright Biblibre 2012
8 #
9 # This file is part of Koha.
10 #
11 # Koha is free software; you can redistribute it and/or modify it
12 # under the terms of the GNU General Public License as published by
13 # the Free Software Foundation; either version 3 of the License, or
14 # (at your option) any later version.
15 #
16 # Koha is distributed in the hope that it will be useful, but
17 # WITHOUT ANY WARRANTY; without even the implied warranty of
18 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 # GNU General Public License for more details.
20 #
21 # You should have received a copy of the GNU General Public License
22 # along with Koha; if not, see <http://www.gnu.org/licenses>.
23
24 use Modern::Perl;
25
26 use C4::Context;
27 use C4::Koha qw( xml_escape );
28 use C4::Biblio qw( GetAuthorisedValueDesc GetFrameworkCode GetMarcStructure );
29 use Koha::AuthorisedValues;
30 use Koha::ItemTypes;
31 use Koha::XSLT::Base;
32 use Koha::Libraries;
33
34
35
36 my $engine; #XSLT Handler object
37 my %authval_per_framework;
38     # Cache for tagfield-tagsubfield to decode per framework.
39     # Should be preferably be placed in Koha-core...
40
41 our (@ISA, @EXPORT_OK);
42 BEGIN {
43     require Exporter;
44     @ISA = qw(Exporter);
45     @EXPORT_OK = qw(
46         transformMARCXML4XSLT
47         getAuthorisedValues4MARCSubfields
48         buildKohaItemsNamespace
49         XSLTParse4Display
50     );
51     $engine=Koha::XSLT::Base->new( { do_not_return_source => 1 } );
52 }
53
54 =head1 NAME
55
56 C4::XSLT - Functions for displaying XSLT-generated content
57
58 =head1 FUNCTIONS
59
60 =head2 transformMARCXML4XSLT
61
62 Replaces codes with authorized values in a MARC::Record object
63 Is only used in this module currently.
64
65 =cut
66
67 sub transformMARCXML4XSLT {
68     my ($biblionumber, $record) = @_;
69     my $frameworkcode = GetFrameworkCode($biblionumber) || '';
70     my $tagslib = &GetMarcStructure(1, $frameworkcode, { unsafe => 1 });
71     my @fields;
72     # FIXME: wish there was a better way to handle exceptions
73     eval {
74         @fields = $record->fields();
75     };
76     if ($@) { warn "PROBLEM WITH RECORD"; next; }
77     my $marcflavour = C4::Context->preference('marcflavour');
78     my $av = getAuthorisedValues4MARCSubfields($frameworkcode);
79     foreach my $tag ( keys %$av ) {
80         foreach my $field ( $record->field( $tag ) ) {
81             if ( $av->{ $tag } ) {
82                 my @new_subfields = ();
83                 for my $subfield ( $field->subfields() ) {
84                     my ( $letter, $value ) = @$subfield;
85                     # Replace the field value with the authorised value *except* for MARC21/NORMARC field 942$n (suppression in opac)
86                     if ( !( $tag eq '942' && $subfield->[0] eq 'n' ) || $marcflavour eq 'UNIMARC' ) {
87                         $value = GetAuthorisedValueDesc( $tag, $letter, $value, '', $tagslib )
88                             if $av->{ $tag }->{ $letter };
89                     }
90                     push( @new_subfields, $letter, $value );
91                 } 
92                 $field ->replace_with( MARC::Field->new(
93                     $tag,
94                     $field->indicator(1),
95                     $field->indicator(2),
96                     @new_subfields
97                 ) );
98             }
99         }
100     }
101     return $record;
102 }
103
104 =head2 getAuthorisedValues4MARCSubfields
105
106 Returns a ref of hash of ref of hash for tag -> letter controlled by authorised values
107 Is only used in this module currently.
108
109 =cut
110
111 sub getAuthorisedValues4MARCSubfields {
112     my ($frameworkcode) = @_;
113     unless ( $authval_per_framework{ $frameworkcode } ) {
114         my $dbh = C4::Context->dbh;
115         my $sth = $dbh->prepare("SELECT DISTINCT tagfield, tagsubfield
116                                  FROM marc_subfield_structure
117                                  WHERE authorised_value IS NOT NULL
118                                    AND authorised_value!=''
119                                    AND frameworkcode=?");
120         $sth->execute( $frameworkcode );
121         my $av = { };
122         while ( my ( $tag, $letter ) = $sth->fetchrow() ) {
123             $av->{ $tag }->{ $letter } = 1;
124         }
125         $authval_per_framework{ $frameworkcode } = $av;
126     }
127     return $authval_per_framework{ $frameworkcode };
128 }
129
130 =head2 XSLTParse4Display
131
132 Returns xml for biblionumber and requested XSLT transformation.
133 Returns undef if the transform fails.
134
135 Used in OPAC results and detail, intranet results and detail, list display.
136 (Depending on the settings of your XSLT preferences.)
137
138 The helper function _get_best_default_xslt_filename is used in a unit test.
139
140 =cut
141
142 sub _get_best_default_xslt_filename {
143     my ($htdocs, $theme, $lang, $base_xslfile) = @_;
144
145     my @candidates = (
146         "$htdocs/$theme/$lang/xslt/${base_xslfile}", # exact match
147         "$htdocs/$theme/en/xslt/${base_xslfile}",    # if not, preferred theme in English
148         "$htdocs/prog/$lang/xslt/${base_xslfile}",   # if not, 'prog' theme in preferred language
149         "$htdocs/prog/en/xslt/${base_xslfile}",      # otherwise, prog theme in English; should always
150                                                      # exist
151     );
152     my $xslfilename;
153     foreach my $filename (@candidates) {
154         $xslfilename = $filename;
155         if (-f $filename) {
156             last; # we have a winner!
157         }
158     }
159     return $xslfilename;
160 }
161
162 sub get_xslt_sysprefs {
163     my $sysxml = "<sysprefs>\n";
164     foreach my $syspref ( qw/ hidelostitems OPACURLOpenInNewWindow
165                               DisplayOPACiconsXSLT URLLinkText viewISBD
166                               OPACBaseURL TraceCompleteSubfields UseICUStyleQuotes
167                               UseAuthoritiesForTracings TraceSubjectSubdivisions
168                               Display856uAsImage OPACDisplay856uAsImage 
169                               UseControlNumber IntranetBiblioDefaultView BiblioDefaultView
170                               OPACItemLocation DisplayIconsXSLT
171                               AlternateHoldingsField AlternateHoldingsSeparator
172                               TrackClicks opacthemes IdRef OpacSuppression
173                               OPACResultsLibrary OPACShowOpenURL
174                               OpenURLResolverURL OpenURLImageLocation
175                               OpenURLText OPACShowMusicalInscripts OPACPlayMusicalInscripts / )
176     {
177         my $sp = C4::Context->preference( $syspref );
178         next unless defined($sp);
179         $sysxml .= "<syspref name=\"$syspref\">$sp</syspref>\n";
180     }
181
182     # singleBranchMode was a system preference, but no longer is
183     # we can retain it here for compatibility
184     my $singleBranchMode = Koha::Libraries->search->count == 1 ? 1 : 0;
185     $sysxml .= "<syspref name=\"singleBranchMode\">$singleBranchMode</syspref>\n";
186
187     $sysxml .= "</sysprefs>\n";
188     return $sysxml;
189 }
190
191 sub XSLTParse4Display {
192     my ( $biblionumber, $orig_record, $xslsyspref, $fixamps, $hidden_items, $sysxml, $xslfilename, $lang, $variables, $items_rs ) = @_;
193
194     $sysxml ||= C4::Context->preference($xslsyspref);
195     $xslfilename ||= C4::Context->preference($xslsyspref);
196     $lang ||= C4::Languages::getlanguage();
197
198     if ( $xslfilename =~ /^\s*"?default"?\s*$/i ) {
199         my $htdocs;
200         my $theme;
201         my $xslfile;
202         if ($xslsyspref eq "XSLTDetailsDisplay") {
203             $htdocs  = C4::Context->config('intrahtdocs');
204             $theme   = C4::Context->preference("template");
205             $xslfile = C4::Context->preference('marcflavour') .
206                        "slim2intranetDetail.xsl";
207         } elsif ($xslsyspref eq "XSLTResultsDisplay") {
208             $htdocs  = C4::Context->config('intrahtdocs');
209             $theme   = C4::Context->preference("template");
210             $xslfile = C4::Context->preference('marcflavour') .
211                         "slim2intranetResults.xsl";
212         } elsif ($xslsyspref eq "OPACXSLTDetailsDisplay") {
213             $htdocs  = C4::Context->config('opachtdocs');
214             $theme   = C4::Context->preference("opacthemes");
215             $xslfile = C4::Context->preference('marcflavour') .
216                        "slim2OPACDetail.xsl";
217         } elsif ($xslsyspref eq "OPACXSLTResultsDisplay") {
218             $htdocs  = C4::Context->config('opachtdocs');
219             $theme   = C4::Context->preference("opacthemes");
220             $xslfile = C4::Context->preference('marcflavour') .
221                        "slim2OPACResults.xsl";
222         } elsif ($xslsyspref eq 'XSLTListsDisplay') {
223             # Lists default to *Results.xslt
224             $htdocs  = C4::Context->config('intrahtdocs');
225             $theme   = C4::Context->preference("template");
226             $xslfile = C4::Context->preference('marcflavour') .
227                         "slim2intranetResults.xsl";
228         } elsif ($xslsyspref eq 'OPACXSLTListsDisplay') {
229             # Lists default to *Results.xslt
230             $htdocs  = C4::Context->config('opachtdocs');
231             $theme   = C4::Context->preference("opacthemes");
232             $xslfile = C4::Context->preference('marcflavour') .
233                        "slim2OPACResults.xsl";
234         }
235         $xslfilename = _get_best_default_xslt_filename($htdocs, $theme, $lang, $xslfile);
236     }
237
238     if ( $xslfilename =~ m/\{langcode\}/ ) {
239         $xslfilename =~ s/\{langcode\}/$lang/;
240     }
241
242     # grab the XML, run it through our stylesheet, push it out to the browser
243     my $record = transformMARCXML4XSLT($biblionumber, $orig_record);
244     my $itemsxml;
245     if ( $xslsyspref eq "OPACXSLTDetailsDisplay" || $xslsyspref eq "XSLTDetailsDisplay" || $xslsyspref eq "XSLTResultsDisplay" ) {
246         $itemsxml = ""; #We don't use XSLT for items display on these pages
247     } else {
248         $itemsxml = buildKohaItemsNamespace($biblionumber, $hidden_items, $items_rs);
249     }
250     my $xmlrecord = $record->as_xml(C4::Context->preference('marcflavour'));
251
252     $variables ||= {};
253     if (C4::Context->preference('OPACShowOpenURL')) {
254         my @biblio_itemtypes;
255         my $biblio = Koha::Biblios->find($biblionumber);
256         if (C4::Context->preference('item-level_itypes')) {
257             @biblio_itemtypes = $biblio->items->get_column("itype");
258         } else {
259             push @biblio_itemtypes, $biblio->itemtype;
260         }
261         my @itypes = split( /\s/, C4::Context->preference('OPACOpenURLItemTypes') );
262         my %original = ();
263         map { $original{$_} = 1 } @biblio_itemtypes;
264         if ( grep { $original{$_} } @itypes ) {
265             $variables->{OpenURLResolverURL} = $biblio->get_openurl;
266         }
267     }
268     my $varxml = "<variables>\n";
269     while (my ($key, $value) = each %$variables) {
270         $varxml .= "<variable name=\"$key\">$value</variable>\n";
271     }
272     $varxml .= "</variables>\n";
273
274     $xmlrecord =~ s/\<\/record\>/$itemsxml$sysxml$varxml\<\/record\>/;
275     if ($fixamps) { # We need to correct the ampersand entities that Zebra outputs
276         $xmlrecord =~ s/\&amp;amp;/\&amp;/g;
277         $xmlrecord =~ s/\&amp\;lt\;/\&lt\;/g;
278         $xmlrecord =~ s/\&amp\;gt\;/\&gt\;/g;
279     }
280     $xmlrecord =~ s/\& /\&amp\; /;
281     $xmlrecord =~ s/\&amp\;amp\; /\&amp\; /;
282
283     #If the xslt should fail, we will return undef (old behavior was
284     #raw MARC)
285     #Note that we did set do_not_return_source at object construction
286     return $engine->transform($xmlrecord, $xslfilename ); #file or URL
287 }
288
289 =head2 buildKohaItemsNamespace
290
291     my $items_xml = buildKohaItemsNamespace( $biblionumber, [ $hidden_items, $items ] );
292
293 Returns XML for items. It accepts two optional parameters:
294 - I<$hidden_items>: An arrayref of itemnumber values, for items that should be hidden
295 - I<$items>: A Koha::Items resultset, for the items to be returned
296
297 If both parameters are passed, I<$items> is used as the basis resultset, and I<$hidden_items>
298 are filtered out of it.
299
300 Is only used in this module currently.
301
302 =cut
303
304 sub buildKohaItemsNamespace {
305     my ($biblionumber, $hidden_items, $items_rs) = @_;
306
307     $hidden_items ||= [];
308
309     my $query = {};
310     $query = { 'me.itemnumber' => { not_in => $hidden_items } }
311       if $hidden_items;
312
313     unless ( $items_rs && ref($items_rs) eq 'Koha::Items' ) {
314         $query->{'me.biblionumber'} = $biblionumber;
315         $items_rs = Koha::Items->new;
316     }
317
318     my $items = $items_rs->search( $query, { prefetch => [ 'branchtransfers', 'reserves' ] } );
319
320     my $shelflocations =
321       { map { $_->{authorised_value} => $_->{opac_description} } Koha::AuthorisedValues->get_descriptions_by_koha_field( { frameworkcode => "", kohafield => 'items.location' } ) };
322     my $ccodes =
323       { map { $_->{authorised_value} => $_->{opac_description} } Koha::AuthorisedValues->get_descriptions_by_koha_field( { frameworkcode => "", kohafield => 'items.ccode' } ) };
324
325     my %branches = map { $_->branchcode => $_->branchname } Koha::Libraries->search({}, { order_by => 'branchname' });
326
327     my $itemtypes = { map { $_->{itemtype} => $_ } @{ Koha::ItemTypes->search->unblessed } };
328     my $xml = '';
329     my %descs = map { $_->{authorised_value} => $_ } Koha::AuthorisedValues->get_descriptions_by_koha_field( { kohafield => 'items.notforloan' } );
330     my $ref_status = C4::Context->preference('Reference_NFL_Statuses') || '1|2';
331
332     while ( my $item = $items->next ) {
333         my $status;
334         my $substatus = '';
335
336         if ($item->has_pending_hold) {
337             $status = 'Pending hold';
338         }
339         elsif ( $item->holds->waiting->count ) {
340             $status = 'Waiting';
341         }
342         elsif ($item->get_transfer) {
343             $status = 'In transit';
344         }
345         elsif ($item->damaged) {
346             $status = "Damaged";
347         }
348         elsif ($item->itemlost) {
349             $status = "Lost";
350         }
351         elsif ( $item->withdrawn) {
352             $status = "Withdrawn";
353         }
354         elsif ($item->onloan) {
355             $status = "Checked out";
356         }
357         elsif ( $item->notforloan ) {
358             $status = $item->notforloan =~ /^($ref_status)$/
359                 ? "reference"
360                 : "reallynotforloan";
361             $substatus = exists $descs{$item->notforloan} ? $descs{$item->notforloan}->{opac_description} : "Not for loan";
362         }
363         elsif ( exists $itemtypes->{ $item->effective_itemtype }
364             && $itemtypes->{ $item->effective_itemtype }->{notforloan}
365             && $itemtypes->{ $item->effective_itemtype }->{notforloan} == 1 )
366         {
367             $status = "1" =~ /^($ref_status)$/
368                 ? "reference"
369                 : "reallynotforloan";
370             $substatus = "Not for loan";
371         }
372         else {
373             $status = "available";
374         }
375         my $homebranch     = xml_escape($branches{$item->homebranch});
376         my $holdingbranch  = xml_escape($branches{$item->holdingbranch});
377         my $location       = xml_escape($item->location && exists $shelflocations->{$item->location} ? $shelflocations->{$item->location} : $item->location);
378         my $ccode          = xml_escape($item->ccode    && exists $ccodes->{$item->ccode}            ? $ccodes->{$item->ccode}            : $item->ccode);
379         my $itemcallnumber = xml_escape($item->itemcallnumber);
380         my $stocknumber    = xml_escape($item->stocknumber);
381         $xml .=
382             "<item>"
383           . "<homebranch>$homebranch</homebranch>"
384           . "<holdingbranch>$holdingbranch</holdingbranch>"
385           . "<location>$location</location>"
386           . "<ccode>$ccode</ccode>"
387           . "<status>".( $status // q{} )."</status>"
388           . "<substatus>$substatus</substatus>"
389           . "<itemcallnumber>$itemcallnumber</itemcallnumber>"
390           . "<stocknumber>$stocknumber</stocknumber>"
391           . "</item>";
392     }
393     $xml = "<items xmlns=\"http://www.koha-community.org/items\">".$xml."</items>";
394     return $xml;
395 }
396
397 =head2 engine
398
399 Returns reference to XSLT handler object.
400
401 =cut
402
403 sub engine {
404     return $engine;
405 }
406
407 1;
408
409 __END__
410
411 =head1 AUTHOR
412
413 Joshua Ferraro <jmf@liblime.com>
414
415 Koha Development Team <http://koha-community.org/>
416
417 =cut