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