/
Core.pm
354 lines (265 loc) · 9.74 KB
/
Core.pm
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
# Plugin for Foswiki - The Free and Open Source Wiki, http://foswiki.org/
#
# Copyright (C) 2012-2016 Michael Daum http://michaeldaumconsulting.com
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# version 2 as published by the Free Software Foundation.
# For more details read LICENSE in the root of this distribution.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
#
# For licensing info read LICENSE file in the Foswiki root.
package Foswiki::Plugins::PageOptimizerPlugin::Core;
use strict;
use warnings;
use Foswiki::Func();
use Foswiki::Plugins::PageOptimizerPlugin ();
use constant TRACE => 0; # toggle me
###############################################################################
sub new {
my $class = shift;
my $this = bless({
cacheDir => $Foswiki::cfg{PageOptimizerPlugin}{CacheDir}
|| $Foswiki::cfg{PubDir} . '/' . $Foswiki::cfg{SystemWebName} . '/PageOptimizerPlugin/cache/',
cachePath => $Foswiki::cfg{PageOptimizerPlugin}{CachePath}
|| $Foswiki::cfg{PubUrlPath} . '/' . $Foswiki::cfg{SystemWebName} . '/PageOptimizerPlugin/cache/',
@_
},
$class
);
# make sure it has got a tailing slash
$this->{cacheDir} =~ s/\/?$/\//;
$this->{cachePath} =~ s/\/?$/\//;
mkdir $this->{cacheDir} unless -d $this->{cacheDir};
return $this;
}
###############################################################################
sub finish {
# nop for now
}
###############################################################################
sub optimizeJavaScript {
my ($this, $text) = @_;
# take out ie stuff
my @ieConditionals = ();
my $index = 0;
while ($text =~ s/(<!\-\- +\[if.*?<!\[endif\]\-\->)/\0ie$index/s) {
#_writeDebug("found ie conditional: $1");
push @ieConditionals, $1;
$index++;
}
# collect all javascript
my @jsUrls = ();
my $excludePattern = '';
# if we defined JQueryVersionForOldIEs then the jQuery core lib has to be excluded from the process
if (defined $Foswiki::cfg{PageOptimizerPlugin}{ExcludeJavaScript} || $Foswiki::cfg{JQueryPlugin}{JQueryVersionForOldIEs}) {
$excludePattern = '(?!.*(?:' . $Foswiki::cfg{PageOptimizerPlugin}{ExcludeJavaScript} . ($Foswiki::cfg{JQueryPlugin}{JQueryVersionForOldIEs} ? '|jquery\-\d\.\d' : '') . '))';
}
#_writeDebug("excludePattern=$excludePattern");
my %classes = ();
$classes{"script"} = 1;
while ($text =~ s/<script (?:class=["']([^"']+)["'])?.*?type=["']text\/javascript["'] .*?src=["'](\/$excludePattern(?:[^"']+))["'].*><\/script>/\0js\0/) {
#_writeDebug("found src $2 in script tag");
if ($1) {
$classes{$_} = 1 foreach split(/ /, $1);
}
push @jsUrls, $2;
}
# put back ie stuff
$index = 0;
foreach my $cond (@ieConditionals) {
$text =~ s/\0ie$index/$cond/;
}
return $text unless @jsUrls;
# check if there's a cache file already
my ($cacheFileName, $cacheUrl) = $this->getCacheEntry("js", \@jsUrls);
my $query = Foswiki::Func::getCgiQuery();
my $refresh = $query->param("refresh") || '';
my $cacheFileTime = _getModificationTime($cacheFileName);
my $needsUpdate = 0;
foreach my $url (@jsUrls) {
my $fileName = _url2FileName($url);
my $fileTime = _getModificationTime($fileName);
if ($cacheFileTime < $fileTime) {
$needsUpdate = 1;
_writeDebug("$fileName has been updated ... refreshing cache file");
last;
}
}
if ($needsUpdate || $refresh =~ /\b(on|all|cache|js)\b/ || !-f $cacheFileName) {
# TODO: compare timestamps of files
_writeDebug("creating cache at $cacheFileName");
my $cachedData = '';
foreach my $url (@jsUrls) {
#_writeDebug("url=$url");
my $fileName = _url2FileName($url);
if (-f $fileName) {
my $data = Foswiki::Func::readFile($fileName);
if ($data) {
# $cachedData .= "\n\n/* DEBUG: fileName=$fileName */\n"
# if TRACE;
$cachedData .= ";\n$data;\n";
}
} else {
print STDERR "woops, file $fileName does not exist for url=$url\n";
}
}
$cachedData =~ s/\/\/#\s+sourceMappingURL=.*?\.js\.map;//g;
# save the cached javascript
Foswiki::Func::saveFile($cacheFileName, $cachedData);
# create a gzip'ed version as well
$cachedData = Compress::Zlib::memGzip($cachedData);
Foswiki::Func::saveFile($cacheFileName . '.gz', $cachedData);
Foswiki::Plugins::PageOptimizerPlugin::getStats()->logJavaScript(\@jsUrls)
if $Foswiki::cfg{PageOptimizerPlugin}{GatherStatistics};
} else {
_writeDebug("found compressed javascript in cache at $cacheFileName");
}
my $classes = join(" ", sort keys %classes);
# insert the cached javascript at the first position we've found a js url
$text =~ s/\0js\0/<script class='$classes' type='text\/javascript' src='$cacheUrl'><\/script>/;
# remove the rest
$text =~ s/\0js\0//g;
return $text;
}
###############################################################################
sub optimizeStylesheets {
my ($this, $text) = @_;
# collect all css
$this->{_cssUrls} = [];
my %classes = ();
while ($text =~ s/((?:<(link) (?:class=["']([^"']+)["'])?.*?rel=["']stylesheet["']\s+href=["'](\/[^"']+)["'].*media=["']all["'](?:\s+type=["']text\/css["'])?[^\/>]*?\/?>)|(?:<(style)\s+.*?media=["']all["'][^>]*?>(.*?)<\/style>))/$this->_gatherCssUrls($2||$5, $4||$6)||$1/e) {
if ($3) {
$classes{$_} = 1 foreach split(/ /, $3);
}
}
return $text unless @{$this->{_cssUrls}};
my ($cacheFileName, $cacheUrl) = $this->getCacheEntry("css", $this->{_cssUrls});
my $query = Foswiki::Func::getCgiQuery();
my $refresh = $query->param("refresh") || '';
my $cacheFileTime = _getModificationTime($cacheFileName);
my $needsUpdate = 0;
foreach my $url (@{$this->{_cssUrls}}) {
my $fileName = _url2FileName($url);
my $fileTime = _getModificationTime($fileName);
if ($cacheFileTime < $fileTime) {
$needsUpdate = 1;
_writeDebug("$fileName has been updated ... refreshing cache file");
last;
}
}
if ($needsUpdate || $refresh =~ /\b(on|all|cache|css)\b/ || !-f $cacheFileName) {
_writeDebug("creating cache at $cacheFileName");
my $cachedData = '';
foreach my $url (@{$this->{_cssUrls}}) {
my $data = $this->parseStylesheet($url);
$cachedData .= $data if $data;
}
Foswiki::Func::saveFile($cacheFileName, $cachedData);
$cachedData = Compress::Zlib::memGzip($cachedData);
Foswiki::Func::saveFile($cacheFileName . '.gz', $cachedData);
Foswiki::Plugins::PageOptimizerPlugin::getStats()->logStylesheet($this->{_cssUrls})
if $Foswiki::cfg{PageOptimizerPlugin}{GatherStatistics};
} else {
_writeDebug("found compressed css in cache at $cacheFileName");
}
my $classes = join(" ", sort keys %classes);
$text =~ s/\0css\0/<link class='$classes' rel='stylesheet' href='$cacheUrl' media='all' \/>/;
$text =~ s/\0css\0//g;
return $text;
}
###############################
sub _getModificationTime {
my ($file) = @_;
return 0 unless $file;
my @stat = stat($file);
return $stat[9] || $stat[10] || 0;
}
###############################
sub _gatherCssUrls {
my ($this, $type, $data) = @_;
# link tag
if ($type eq 'link') {
my $excludePattern = $Foswiki::cfg{PageOptimizerPlugin}{ExcludeCss};
return if defined($excludePattern) && $data =~ /$excludePattern/;
#_writeDebug("found url $data in link tag");
push @{$this->{_cssUrls}}, $data;
return "\0css\0";
}
# style block
while ($data =~ s/\@import +url\(["']?(.*?)["']?\);//) {
push @{$this->{_cssUrls}}, $1;
#_writeDebug("found url $1 in style block");
}
# test for an empty style block
if ($data =~ /^\s*$/s) {
return "\0css\0";
}
# return the rest of the style block
return "\0css\0<style>$data</style>";
}
###############################
sub parseStylesheet {
my ($this, $url, $baseUrl) = @_;
$baseUrl ||= $url;
$baseUrl =~ s/\?.*?$//;
my $fileName = _url2FileName($url);
#_writeDebug("baseUrl=$baseUrl");
#_writeDebug("fileName=$fileName");
my $data = '';
if (-f $fileName) {
$data = Foswiki::Func::readFile($fileName);
$data =~ s/url\(["']?(.*?)["']?\)/"url("._rewriteUrl($1, $baseUrl).")"/ge;
$data =~ s/\@import +url\(["']?(.*?)["']?\);/$this->parseStylesheet($1)/ge;
} else {
print STDERR "woops file $fileName does not exist for url $url\n";
}
return $data;
}
###############################
sub purgeCache {
my $this = shift;
opendir(my $dh, $this->{cacheDir});
my @files = map { Foswiki::Sandbox::normalizeFileName($this->{cacheDir} . $_) } grep { !/^(\.|README)/ } readdir $dh;
closedir $dh;
_writeDebug("cleaning up ".scalar(@files)." files");
unlink @files;
return;
}
###############################
sub getCacheEntry {
my ($this, $type, $urls) = @_;
my $fileName = Digest::MD5::md5_hex(@$urls) . '.' . $type;
return ($this->{cacheDir} . $fileName, $this->{cachePath} . $fileName);
}
###############################################################################
# static
sub _writeDebug {
return unless TRACE;
print STDERR "- PageOptimizerPlugin - " . $_[0] . "\n";
}
###############################
# static
sub _url2FileName {
my $url = shift;
my $fileName = $url;
$fileName =~ s/$Foswiki::cfg{PubUrlPath}/$Foswiki::cfg{PubDir}/;
$fileName =~ s/^$Foswiki::cfg{DefaultUrlHost}//;
$fileName =~ s/\?.*$//;
return $fileName;
}
###############################
# static
sub _rewriteUrl {
my ($url, $baseUrl) = @_;
return $url if $url =~ /^(data|https?):/;
#_writeDebug("rewriteUrl($url, $baseUrl)");
my $uri = URI->new($url);
$url = $uri->abs($baseUrl);
#_writeDebug("... url=$url");
return $url;
}
1;