Bug 15263: XSLT display fetches sysprefs for every result processed
[koha.git] / 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 under the
12 # terms of the GNU General Public License as published by the Free Software
13 # Foundation; either version 3 of the License, or (at your option) any later
14 # version.
15 #
16 # Koha is distributed in the hope that it will be useful, but WITHOUT ANY
17 # WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
18 # A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
19 #
20 # You should have received a copy of the GNU General Public License along
21 # with Koha; if not, write to the Free Software Foundation, Inc.,
22 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
23
24 use strict;
25 use warnings;
26
27 use C4::Context;
28 use C4::Branch;
29 use C4::Items;
30 use C4::Koha;
31 use C4::Biblio;
32 use C4::Circulation;
33 use C4::Reserves;
34 use Koha::XSLT_Handler;
35 use Koha::Libraries;
36
37 use Encode;
38
39 use vars qw(@ISA @EXPORT);
40
41 my $engine; #XSLT Handler object
42 my %authval_per_framework;
43     # Cache for tagfield-tagsubfield to decode per framework.
44     # Should be preferably be placed in Koha-core...
45
46 BEGIN {
47     require Exporter;
48     @ISA = qw(Exporter);
49     @EXPORT = qw(
50         &XSLTParse4Display
51     );
52     $engine=Koha::XSLT_Handler->new( { do_not_return_source => 1 } );
53 }
54
55 =head1 NAME
56
57 C4::XSLT - Functions for displaying XSLT-generated content
58
59 =head1 FUNCTIONS
60
61 =head2 transformMARCXML4XSLT
62
63 Replaces codes with authorized values in a MARC::Record object
64 Is only used in this module currently.
65
66 =cut
67
68 sub transformMARCXML4XSLT {
69     my ($biblionumber, $record) = @_;
70     my $frameworkcode = GetFrameworkCode($biblionumber) || '';
71     my $tagslib = &GetMarcStructure(1,$frameworkcode);
72     my @fields;
73     # FIXME: wish there was a better way to handle exceptions
74     eval {
75         @fields = $record->fields();
76     };
77     if ($@) { warn "PROBLEM WITH RECORD"; next; }
78     my $marcflavour = C4::Context->preference('marcflavour');
79     my $av = getAuthorisedValues4MARCSubfields($frameworkcode);
80     foreach my $tag ( keys %$av ) {
81         foreach my $field ( $record->field( $tag ) ) {
82             if ( $av->{ $tag } ) {
83                 my @new_subfields = ();
84                 for my $subfield ( $field->subfields() ) {
85                     my ( $letter, $value ) = @$subfield;
86                     # Replace the field value with the authorised value *except* for MARC21/NORMARC field 942$n (suppression in opac)
87                     if ( !( $tag eq '942' && $subfield eq 'n' ) || $marcflavour eq 'UNIMARC' ) {
88                         $value = GetAuthorisedValueDesc( $tag, $letter, $value, '', $tagslib )
89                             if $av->{ $tag }->{ $letter };
90                     }
91                     push( @new_subfields, $letter, $value );
92                 } 
93                 $field ->replace_with( MARC::Field->new(
94                     $tag,
95                     $field->indicator(1),
96                     $field->indicator(2),
97                     @new_subfields
98                 ) );
99             }
100         }
101     }
102     return $record;
103 }
104
105 =head2 getAuthorisedValues4MARCSubfields
106
107 Returns a ref of hash of ref of hash for tag -> letter controlled by authorised values
108 Is only used in this module currently.
109
110 =cut
111
112 sub getAuthorisedValues4MARCSubfields {
113     my ($frameworkcode) = @_;
114     unless ( $authval_per_framework{ $frameworkcode } ) {
115         my $dbh = C4::Context->dbh;
116         my $sth = $dbh->prepare("SELECT DISTINCT tagfield, tagsubfield
117                                  FROM marc_subfield_structure
118                                  WHERE authorised_value IS NOT NULL
119                                    AND authorised_value!=''
120                                    AND frameworkcode=?");
121         $sth->execute( $frameworkcode );
122         my $av = { };
123         while ( my ( $tag, $letter ) = $sth->fetchrow() ) {
124             $av->{ $tag }->{ $letter } = 1;
125         }
126         $authval_per_framework{ $frameworkcode } = $av;
127     }
128     return $authval_per_framework{ $frameworkcode };
129 }
130
131 =head2 XSLTParse4Display
132
133 Returns xml for biblionumber and requested XSLT transformation.
134 Returns undef if the transform fails.
135
136 Used in OPAC results and detail, intranet results and detail, list display.
137 (Depending on the settings of your XSLT preferences.)
138
139 The helper function _get_best_default_xslt_filename is used in a unit test.
140
141 =cut
142
143 sub _get_best_default_xslt_filename {
144     my ($htdocs, $theme, $lang, $base_xslfile) = @_;
145
146     my @candidates = (
147         "$htdocs/$theme/$lang/xslt/${base_xslfile}", # exact match
148         "$htdocs/$theme/en/xslt/${base_xslfile}",    # if not, preferred theme in English
149         "$htdocs/prog/$lang/xslt/${base_xslfile}",   # if not, 'prog' theme in preferred language
150         "$htdocs/prog/en/xslt/${base_xslfile}",      # otherwise, prog theme in English; should always
151                                                      # exist
152     );
153     my $xslfilename;
154     foreach my $filename (@candidates) {
155         $xslfilename = $filename;
156         if (-f $filename) {
157             last; # we have a winner!
158         }
159     }
160     return $xslfilename;
161 }
162
163 sub _get_xslt_sysprefs {
164     my $sysxml = "<sysprefs>\n";
165     foreach my $syspref ( qw/ hidelostitems OPACURLOpenInNewWindow
166                               DisplayOPACiconsXSLT URLLinkText viewISBD
167                               OPACBaseURL TraceCompleteSubfields UseICU
168                               UseAuthoritiesForTracings TraceSubjectSubdivisions
169                               Display856uAsImage OPACDisplay856uAsImage 
170                               UseControlNumber IntranetBiblioDefaultView BiblioDefaultView
171                               OPACItemLocation DisplayIconsXSLT
172                               AlternateHoldingsField AlternateHoldingsSeparator
173                               TrackClicks opacthemes IdRef OpacSuppression / )
174     {
175         my $sp = C4::Context->preference( $syspref );
176         next unless defined($sp);
177         $sysxml .= "<syspref name=\"$syspref\">$sp</syspref>\n";
178     }
179
180     # singleBranchMode was a system preference, but no longer is
181     # we can retain it here for compatibility
182     my $singleBranchMode = Koha::Libraries->search->count == 1;
183     $sysxml .= "<syspref name=\"singleBranchMode\">$singleBranchMode</syspref>\n";
184
185     $sysxml .= "</sysprefs>\n";
186     return $sysxml;
187 }
188
189 sub XSLTParse4Display {
190     my ( $biblionumber, $orig_record, $xslsyspref, $fixamps, $hidden_items, $sysxml, $xslfilename, $lang ) = @_;
191     #my $xslfilename = C4::Context->preference($xslsyspref);
192     if ( $xslfilename =~ /^\s*"?default"?\s*$/i ) {
193         my $htdocs;
194         my $theme;
195         # my $lang = C4::Languages::getlanguage();
196         my $xslfile;
197         if ($xslsyspref eq "XSLTDetailsDisplay") {
198             $htdocs  = C4::Context->config('intrahtdocs');
199             $theme   = C4::Context->preference("template");
200             $xslfile = C4::Context->preference('marcflavour') .
201                        "slim2intranetDetail.xsl";
202         } elsif ($xslsyspref eq "XSLTResultsDisplay") {
203             $htdocs  = C4::Context->config('intrahtdocs');
204             $theme   = C4::Context->preference("template");
205             $xslfile = C4::Context->preference('marcflavour') .
206                         "slim2intranetResults.xsl";
207         } elsif ($xslsyspref eq "OPACXSLTDetailsDisplay") {
208             $htdocs  = C4::Context->config('opachtdocs');
209             $theme   = C4::Context->preference("opacthemes");
210             $xslfile = C4::Context->preference('marcflavour') .
211                        "slim2OPACDetail.xsl";
212         } elsif ($xslsyspref eq "OPACXSLTResultsDisplay") {
213             $htdocs  = C4::Context->config('opachtdocs');
214             $theme   = C4::Context->preference("opacthemes");
215             $xslfile = C4::Context->preference('marcflavour') .
216                        "slim2OPACResults.xsl";
217         }
218         $xslfilename = _get_best_default_xslt_filename($htdocs, $theme, $lang, $xslfile);
219     }
220
221     if ( $xslfilename =~ m/\{langcode\}/ ) {
222         my $lang = C4::Languages::getlanguage();
223         $xslfilename =~ s/\{langcode\}/$lang/;
224     }
225
226     # grab the XML, run it through our stylesheet, push it out to the browser
227     my $record = transformMARCXML4XSLT($biblionumber, $orig_record);
228     my $itemsxml  = buildKohaItemsNamespace($biblionumber, $hidden_items);
229     my $xmlrecord = $record->as_xml(C4::Context->preference('marcflavour'));
230
231     $xmlrecord =~ s/\<\/record\>/$itemsxml$sysxml\<\/record\>/;
232     if ($fixamps) { # We need to correct the HTML entities that Zebra outputs
233         $xmlrecord =~ s/\&amp;amp;/\&amp;/g;
234         $xmlrecord =~ s/\&amp\;lt\;/\&lt\;/g;
235         $xmlrecord =~ s/\&amp\;gt\;/\&gt\;/g;
236     }
237     $xmlrecord =~ s/\& /\&amp\; /;
238     $xmlrecord =~ s/\&amp\;amp\; /\&amp\; /;
239
240     #If the xslt should fail, we will return undef (old behavior was
241     #raw MARC)
242     #Note that we did set do_not_return_source at object construction
243     return $engine->transform($xmlrecord, $xslfilename ); #file or URL
244 }
245
246 =head2 buildKohaItemsNamespace
247
248 Returns XML for items.
249 Is only used in this module currently.
250
251 =cut
252
253 sub buildKohaItemsNamespace {
254     my ($biblionumber, $hidden_items) = @_;
255
256     my @items = C4::Items::GetItemsInfo($biblionumber);
257     if ($hidden_items && @$hidden_items) {
258         my %hi = map {$_ => 1} @$hidden_items;
259         @items = grep { !$hi{$_->{itemnumber}} } @items;
260     }
261
262     my $shelflocations = GetKohaAuthorisedValues('items.location',GetFrameworkCode($biblionumber), 'opac');
263     my $ccodes         = GetKohaAuthorisedValues('items.ccode',GetFrameworkCode($biblionumber), 'opac');
264
265     my $branches = GetBranches();
266     my $itemtypes = GetItemTypes();
267     my $location = "";
268     my $ccode = "";
269     my $xml = '';
270     for my $item (@items) {
271         my $status;
272
273         my ( $transfertwhen, $transfertfrom, $transfertto ) = C4::Circulation::GetTransfers($item->{itemnumber});
274
275         my $reservestatus = C4::Reserves::GetReserveStatus( $item->{itemnumber} );
276
277         if ( $itemtypes->{ $item->{itype} }->{notforloan} || $item->{notforloan} || $item->{onloan} || $item->{withdrawn} || $item->{itemlost} || $item->{damaged} ||
278              (defined $transfertwhen && $transfertwhen ne '') || $item->{itemnotforloan} || (defined $reservestatus && $reservestatus eq "Waiting") ){ 
279             if ( $item->{notforloan} < 0) {
280                 $status = "On order";
281             } 
282             if ( $item->{itemnotforloan} > 0 || $item->{notforloan} > 0 || $itemtypes->{ $item->{itype} }->{notforloan} == 1 ) {
283                 $status = "reference";
284             }
285             if ($item->{onloan}) {
286                 $status = "Checked out";
287             }
288             if ( $item->{withdrawn}) {
289                 $status = "Withdrawn";
290             }
291             if ($item->{itemlost}) {
292                 $status = "Lost";
293             }
294             if ($item->{damaged}) {
295                 $status = "Damaged"; 
296             }
297             if (defined $transfertwhen && $transfertwhen ne '') {
298                 $status = 'In transit';
299             }
300             if (defined $reservestatus && $reservestatus eq "Waiting") {
301                 $status = 'Waiting';
302             }
303         } else {
304             $status = "available";
305         }
306         my $homebranch = $item->{homebranch}? xml_escape($branches->{$item->{homebranch}}->{'branchname'}):'';
307         my $holdingbranch = $item->{holdingbranch}? xml_escape($branches->{$item->{holdingbranch}}->{'branchname'}):'';
308         $location = $item->{location}? xml_escape($shelflocations->{$item->{location}}||$item->{location}):'';
309         $ccode = $item->{ccode}? xml_escape($ccodes->{$item->{ccode}}||$item->{ccode}):'';
310         my $itemcallnumber = xml_escape($item->{itemcallnumber});
311         $xml.= "<item><homebranch>$homebranch</homebranch>".
312                 "<holdingbranch>$holdingbranch</holdingbranch>".
313                 "<location>$location</location>".
314                 "<ccode>$ccode</ccode>".
315                 "<status>$status</status>".
316                 "<itemcallnumber>".$itemcallnumber."</itemcallnumber>".
317                 "</item>";
318     }
319     $xml = "<items xmlns=\"http://www.koha-community.org/items\">".$xml."</items>";
320     return $xml;
321 }
322
323 =head2 engine
324
325 Returns reference to XSLT handler object.
326
327 =cut
328
329 sub engine {
330     return $engine;
331 }
332
333 1;
334
335 __END__
336
337 =head1 AUTHOR
338
339 Joshua Ferraro <jmf@liblime.com>
340
341 Koha Development Team <http://koha-community.org/>
342
343 =cut