assets-optimization.php
11.5 KB
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
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
<?php
namespace Getwid;
class AssetsOptimization {
/**
* @var AssetsOptimization
*/
private static $instance = null;
/**
* Flag to indicate if CSS is already minified
*
* @var bool
*/
private $alreadyoptimized = false;
/**
* @return AssetsOptimization
*/
public static function getInstance() {
if ( is_null( self::$instance ) ) {
self::$instance = new self();
}
return self::$instance;
}
/**
* AssetsOptimization constructor.
*/
public function __construct() {
getwid_maybe_add_option( 'getwid_load_assets_on_demand', false, true );
getwid_maybe_add_option( 'getwid_move_css_to_head', false, true );
if ( FALSE == $this->load_assets_on_demand() ||
FALSE == $this->move_css_to_head() ) {
return;
}
add_action( 'template_redirect', array( $this, 'buffer_start' ), 1 );
add_filter( 'getwid/html/output', array( $this, 'filter_css' ) );
add_filter( 'getwid/html/output', array( $this, 'filter_test' ) );
// Filter Autoptimize plugin output
add_filter( 'autoptimize_filter_html_before_minify', array( $this, 'filter_css' ) );
//TODO: add support for other plugins?
}
/**
* Setup output buffering if needed.
*
* @return void
*/
public function buffer_start() {
if ( $this->should_buffer() ) {
ob_start( array( $this, 'buffer_end' ) );
}
}
/**
* Processes/optimizes the output-buffered content and returns it.
* If the content is not processable, it is returned unmodified.
*
* @param string $html Buffered content.
*
* @return string
*/
public function buffer_end( $html ) {
// Bail early without modifying anything if we can't handle the content.
if ( ! $this->is_valid_buffer( $html ) ) {
return $html;
}
// Apply any filters to the final output
$html = apply_filters( 'getwid/html/output', $html );
return $html;
}
/*
* Test replacement
*
* @param string $html Buffered content.
*
* @return string
*/
public function filter_test( $html ) {
if ( $this->alreadyoptimized ) {
$html .= PHP_EOL . '<!-- getwid optimized -->';
}
return $html;
}
/*
* Find stylesheets of our blocks in original HTML and move them to Header
*
* @param string $html Buffered content.
*
* @return string
*
* Source \plugins\autoptimize\classes\autoptimizeStyles.php
*/
public function filter_css( $html ) {
if ( $this->alreadyoptimized ) {
return $html;
}
$css = array();
$blocks = getwid()->blocksManager()->getBlocks();
//var_dump($blocks);exit;
$optimize_more = apply_filters( 'getwid/optimize/assets', [] );
/*
* Blocks array example:
* ["getwid/anchor"] => object(Getwid\Blocks\Anchor) {}
*
* Style tag example:
* <link rel='stylesheet' id='getwid/banner-css' href='https://.../wp-content/plugins/getwid/assets/blocks/banner/style.css' type='text/css' media='all' />
*/
// Find stylesheets in original html
if ( preg_match_all( '#(<link[^>]*stylesheet[^>]*>)#Usmi', $html, $tag_matches ) ) {
foreach ( $tag_matches[0] as $tag ) {
if ( preg_match( '#<link.*id=("|\')(.*)-css("|\')#Usmi', $tag, $link_matches ) ) {
$link_id = $link_matches[2];
//var_dump($link_id);
// Check if this is a stylesheet of our block
if (
array_key_exists( $link_id, $blocks ) ||
in_array( $link_id, $optimize_more )
) {
//var_dump($link_id);
// Save tag for next steps
$css[ $link_id ] = $tag;
// Clear tag in original html
$html = str_replace( $tag, '<!-- #' . $link_id .' -->', $html );
}
}
}
}
// Process stylesheets if we found ones
if ( ! empty( $css ) ) {
// move stylesheet to a new positon
$replace_tag = array( '</title>', 'after' );
// Debug
$css_scope = PHP_EOL . '<!-- getwid styles -->' . PHP_EOL . "\t";
// Print stylesheets
$css_scope .= implode( PHP_EOL . "\t", $css );
// Debug
$css_scope .= PHP_EOL . '<!-- /getwid styles -->' . PHP_EOL;
//var_dump($css_scope);exit;
$html = $this->inject_in_html( $css_scope, $replace_tag, $html );
// Mark as optimized
$this->alreadyoptimized = true;
}
return $html;
}
/**
* Injects/replaces the given payload markup into `$html`
* at the specified location.
* If the specified tag cannot be found, the payload is appended into
* $html along with a warning wrapped inside <!--noptimize--> tags.
*
* @param string $payload Markup to inject.
* @param array $where Array specifying the tag name and method of injection.
* Index 0 is the tag name (i.e., `</body>`).
* Index 1 specifies ?'before', 'after' or 'replace'. Defaults to 'before'.
*
* @return void
*/
protected function inject_in_html( $payload, $where, $html )
{
$warned = false;
$position = $this->strpos( $html, $where[0] );
if ( false !== $position ) {
// Found the tag, setup content/injection as specified.
if ( 'after' === $where[1] ) {
$content = $where[0] . $payload;
} elseif ( 'replace' === $where[1] ) {
$content = $payload;
} else {
$content = $payload . $where[0];
}
// Place where specified.
$html = $this->substr_replace(
$html,
$content,
$position,
// Using plain strlen() should be safe here for now, since
// we're not searching for multibyte chars here still...
strlen( $where[0] )
);
} else {
// Couldn't find what was specified, just append and add a warning.
$html .= $payload;
if ( ! $warned ) {
$tag_display = str_replace( array( '<', '>' ), '', $where[0] );
$html .= '<!--noptimize--><!-- We found a problem with the HTML in your Theme, tag `' . $tag_display . '` missing --><!--/noptimize-->';
$warned = true;
}
}
return $html;
}
/**
* Returns true if all the conditions to start output buffering are satisfied.
*
* @return bool
*/
public function should_buffer() {
$do_buffering = false;
// Check for site being previewed in the Customizer (available since WP 4.0).
$is_customize_preview = false;
if ( function_exists( 'is_customize_preview' ) && is_customize_preview() ) {
$is_customize_preview = is_customize_preview();
}
/**
* We only buffer the frontend requests (and then only if not a feed
* and not turned off explicitly and not when being previewed in Customizer)!
*/
$do_buffering = ( ! is_admin() && ! is_feed() && ! is_embed() && ! $is_customize_preview );
return $do_buffering;
}
/**
* Returns true if given markup is considered valid/processable/optimizable.
*
* @param string $content Markup.
*
* @return bool
*/
public function is_valid_buffer( $content )
{
// Defaults to true.
$valid = true;
//TODO
return $valid;
}
/**
* Multibyte-capable strpos() if support is available on the server.
* If not, it falls back to using \strpos().
*
* @param string $haystack Haystack.
* @param string $needle Needle.
* @param int $offset Offset.
* @param string|null $encoding Encoding. Default null.
*
* @return int|false
*/
public function strpos( $haystack, $needle, $offset = 0, $encoding = null )
{
if ( $this->mbstring_available() ) {
return ( null === $encoding ) ? \mb_strpos( $haystack, $needle, $offset ) : \mb_strpos( $haystack, $needle, $offset, $encoding );
} else {
return \strpos( $haystack, $needle, $offset );
}
}
/**
* Our wrapper around implementations of \substr_replace()
* that attempts to not break things horribly if at all possible.
* Uses mbstring if available, before falling back to regular
* substr_replace() (which works just fine in the majority of cases).
*
* @param string $string String.
* @param string $replacement Replacement.
* @param int $start Start offset.
* @param int|null $length Length.
* @param string|null $encoding Encoding.
*
* @return string
*/
public function substr_replace( $string, $replacement, $start, $length = null, $encoding = null )
{
if ( $this->mbstring_available() ) {
$strlen = $this->strlen( $string, $encoding );
if ( $start < 0 ) {
if ( -$start < $strlen ) {
$start = $strlen + $start;
} else {
$start = 0;
}
} elseif ( $start > $strlen ) {
$start = $strlen;
}
if ( null === $length || '' === $length ) {
$start2 = $strlen;
} elseif ( $length < 0 ) {
$start2 = $strlen + $length;
if ( $start2 < $start ) {
$start2 = $start;
}
} else {
$start2 = $start + $length;
}
if ( null === $encoding ) {
$leader = $start ? \mb_substr( $string, 0, $start ) : '';
$trailer = ( $start2 < $strlen ) ? \mb_substr( $string, $start2, null ) : '';
} else {
$leader = $start ? \mb_substr( $string, 0, $start, $encoding ) : '';
$trailer = ( $start2 < $strlen ) ? \mb_substr( $string, $start2, null, $encoding ) : '';
}
return "{$leader}{$replacement}{$trailer}";
}
return ( null === $length ) ? \substr_replace( $string, $replacement, $start ) : \substr_replace( $string, $replacement, $start, $length );
}
/**
* Attempts to return the number of characters in the given $string if
* mbstring is available. Returns the number of bytes
* (instead of characters) as fallback.
*
* @param string $string String.
* @param string|null $encoding Encoding.
*
* @return int Number of characters or bytes in given $string
* (characters if/when supported, bytes otherwise).
*/
public function strlen( $string, $encoding = null )
{
if ( $this->mbstring_available() ) {
return ( null === $encoding ) ? \mb_strlen( $string ) : \mb_strlen( $string, $encoding );
} else {
return \strlen( $string );
}
}
/**
* Returns true when mbstring is available.
*
* @param bool|null $override Allows overriding the decision.
*
* @return bool
*/
public function mbstring_available()
{
$available = \extension_loaded( 'mbstring' );
return $available;
}
public function load_assets_on_demand()
{
return get_option( 'getwid_load_assets_on_demand', false );
}
public function move_css_to_head()
{
return get_option( 'getwid_move_css_to_head', false );
}
}