-
Notifications
You must be signed in to change notification settings - Fork 0
/
TinyfierWP.php
299 lines (242 loc) · 9.76 KB
/
TinyfierWP.php
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
<?php
/**
* Plugin Name: tinyfier-wp
* Plugin URI: http://URI_Of_Page_Describing_Plugin_and_Updates
* Description: Make your wordpress instalation fly. Once enabled, this plugin will combine, compress and optimize JS, CSS and HTML files to improve page load time.
* Version: 0.1
* Author: ideatic
* Author URI: http://www.ideatic.net
* License: GPL2
*/
/*
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.
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. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*/
class TinyfierWP {
public $minify_css = TRUE;
public $minify_js = TRUE;
public $minify_html = FALSE;
/**
* Add async attribute to the last javascript block
* @var boolean
*/
public $async_js = TRUE;
/**
* Maintain CSS order (TRUE) or join all CSS even if that imply alter the order (FALSE, better performance, default)
* @var boolean
*/
public $safe_css_order = FALSE;
public function exec() {
//Disable when not necessary
if (defined('WP_ADMIN') || is_feed() || defined('DOING_AJAX') || defined('DOING_CRON') || defined('APP_REQUEST') || defined('XMLRPC_REQUEST') || defined('SHORTINIT') && SHORTINIT) {
return FALSE;
}
ob_start(array($this, 'ob_callback'));
}
public function ob_callback($buffer) {
$replaces = array();
$modes = array(
'css' => $this->minify_css,
'js' => $this->minify_js
);
foreach ($modes as $mode => $enabled) {
if (!$enabled) {
continue;
}
$join_queue = array();
$assets = $this->_find_assets($buffer, $mode);
end($assets);
$lastk = key($assets);
foreach ($assets as $k => $asset) {
$replacement = $asset['original'];
$join = $this->_suitable_for_join($asset, $mode);
if ($join) {
$join_queue[] = $asset['external'];
$replacement = '';
}
$context_change = !$join;
if ($context_change && $mode == 'css' && !$this->safe_css_order) {
$context_change = FALSE;
}
if (($context_change || $k == $lastk) && !empty($join_queue)) {
//Join all the previous assets
$url = $this->_tinyfier_url($mode, $join_queue);
if ($mode == 'css') {
$loader = '<link rel="stylesheet" type="text/css" href="' . $url . '" />';
} else {
if ($join && $k == $lastk && $this->async_js) {
$loader = '<script async src="' . $url . '"></script>';
} else {
$loader = '<script src="' . $url . '"></script>';
}
}
$replacement = $loader . $replacement;
$join_queue = array();
}
if ($replacement != $asset['original']) {
$replaces[$asset['original']] = $replacement;
}
}
}
$buffer = str_replace(array_keys($replaces), array_values($replaces), $buffer);
//Minify HTML
if ($this->minify_html) {
require_once dirname(__FILE__) . '/tinyfier/html/html.php';
$buffer = Tinyfier_HTML_Tool::process($buffer, array(
'external_services' => FALSE
));
}
return $buffer;
}
/**
* Find JS or CSS assets in the input HTML
* @param type $type
*/
private function _find_assets($html, $type) {
//Remove comments
$html = preg_replace('~<!--.*?-->~s', '', $html);
//Find tags
switch ($type) {
case 'js':
$tags = array('script');
$attr_external = 'src';
break;
case 'css':
$tags = array('link');
$attr_external = 'href';
break;
}
$found = array();
$matches = null;
$pattern = '<(?<tag>' . implode('|', $tags) . ')(?<attrs>[^>]*?)(/>|>(?<content>.*?)</\k<tag>>)';
$attr_pattern = '(\w+)\s*=\s*((["\']).*?\3|[^\'">\s]+?)';
if (preg_match_all("~$pattern~is", $html, $matches, PREG_SET_ORDER)) {
foreach ($matches as $match) {
$attrs = array();
//Parse attrs
if (preg_match_all("~$attr_pattern~is", $match['attrs'], $attr_matches, PREG_SET_ORDER)) {
foreach ($attr_matches as $attr_match) {
$attrs[$attr_match[1]] = trim($attr_match[2], '"\'');
}
}
$found[] = array(
'original' => $match[0],
'tag' => $match['tag'],
'attrs' => $attrs,
'content' => $match['content'],
'external' => isset($attrs[$attr_external]) ? $attrs[$attr_external] : NULL
);
}
}
return $found;
}
private function _suitable_for_join($asset, $mode) {
//Only join external assets
if (!isset($asset['external']) || !empty($asset['content'])) {
return FALSE;
}
$url = $asset['external'];
//Check if URL is in the current domain
if ($this->_is_absolute($url) && strpos($url, get_site_url()) === FALSE) {
return FALSE;
}
//Check if it is a stylesheet
if ($mode == 'css') {
if (!isset($asset['attrs']['rel']) || stristr($asset['attrs']['rel'], 'stylesheet') === FALSE || (isset($asset['attrs']['media']) && stristr($asset['attrs']['media'], 'print') !== FALSE)) {
return FALSE;
}
}
return TRUE;
}
private function _tinyfier_url($mode, $assets) {
$normalized_assets = array();
foreach ($assets as $asset) {
//Remove query
$asset = preg_replace('/\?.*$/', '', $asset);
//Remove blog url
$asset = ltrim(str_replace(get_site_url(), '', $asset), '/');
$normalized_assets[] = $asset;
}
return content_url('assets.php/' . implode(',', $normalized_assets), __FILE__);
}
private function _is_absolute($url) {
if (!empty($url)) {
if (strpos($url, '://') !== FALSE && preg_match('#^\w+:\/\/#', $url)) {
return TRUE;
}
if (strlen($url) > 2 && $url[0] == '/' && $url[1] == '/') {
return TRUE;
}
}
return FALSE;
}
/* Install/Uninstall routines */
private static function _get_paths(&$cache_dir, &$loader_path, &$tinyfier) {
$cache_dir = WP_CONTENT_DIR . DIRECTORY_SEPARATOR . 'tinyfier-cache'; //Store cache in wp-content/cache/tinyfier
$loader_path = WP_CONTENT_DIR . DIRECTORY_SEPARATOR . 'assets.php';
$tinyfier = dirname(__FILE__) . DIRECTORY_SEPARATOR . 'Tinyfier' . DIRECTORY_SEPARATOR . 'tinyfier.php';
}
public static function install() {
//Place assets loader
self::_get_paths($cache_dir, $loader_path, $tinyfier);
if (!is_dir($cache_dir)) {
mkdir($cache_dir, 0755);
}
$error_path = WP_CONTENT_DIR . DIRECTORY_SEPARATOR . 'tinyfier_error.txt';
$php = '<?php
$src_folder = ' . var_export(get_home_path(), TRUE) . '; //Wordpress root path
$cache_dir = ' . var_export($cache_dir, TRUE) . '; //Cache path
$error_log = ' . var_export($error_path, TRUE) . '; //Error log path
require ' . var_export($tinyfier, TRUE) . ';';
file_put_contents($loader_path, $php);
}
/**
* Tinyfier must be the last plugin, in order to process the ob_ buffer
* before any other caching plugin
*/
public static function set_plugin_order() {
// ensure path to this file is via main wp plugin path
$wp_path_to_this_file = preg_replace('/(.*)plugins\/(.*)$/', WP_PLUGIN_DIR . "/$2", __FILE__);
$this_plugin = plugin_basename(trim($wp_path_to_this_file));
$active_plugins = get_option('active_plugins');
$this_plugin_key = array_search($this_plugin, $active_plugins);
if ($this_plugin_key !== FALSE) {
array_splice($active_plugins, $this_plugin_key, 1);
array_push($active_plugins, $this_plugin);
update_option('active_plugins', $active_plugins);
}
}
public static function uninstall() {
//Remove assets loader
self::_get_paths($cache_dir, $loader_path, $tinyfier);
if (is_dir($cache_dir)) {
self::_rrmdir($cache_dir);
}
if (file_exists($loader_path)) {
unlink($loader_path);
}
}
private static function _rrmdir($dir) {
foreach (glob($dir . '/*') as $file) {
if (is_dir($file)) {
rrmdir($file);
} else {
unlink($file);
}
}
rmdir($dir);
}
}
$instance = new TinyfierWP();
$instance->exec();
register_activation_hook(__FILE__, array('TinyfierWP', 'install'));
register_deactivation_hook(__FILE__, array('TinyfierWP', 'uninstall'));
add_action('activated_plugin', array('TinyfierWP', 'set_plugin_order'));