Completed
Push — master ( c92350...ab0c5b )
by frank
01:42
created

autoptimizeExtra   F

Complexity

Total Complexity 111

Size/Duplication

Total Lines 562
Duplicated Lines 3.91 %

Coupling/Cohesion

Components 2
Dependencies 4

Importance

Changes 0
Metric Value
dl 22
loc 562
rs 2
c 0
b 0
f 0
wmc 111
lcom 2
cbo 4

20 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 8 2
A instance() 0 8 2
A run() 13 13 5
A set_options() 0 6 1
A fetch_options() 0 10 2
A disable_emojis() 0 17 1
A filter_disable_emojis_tinymce() 0 8 2
A filter_remove_qs() 0 8 2
A extra_async_js() 3 19 3
B run_on_frontend() 0 38 10
A filter_remove_emoji_dns_prefetch() 0 6 1
A filter_remove_gfonts_dnsprefetch() 0 4 1
A filter_remove_dns_prefetch() 0 16 5
F filter_optimize_google_fonts() 0 118 24
C filter_preconnect() 3 40 12
A filter_preconnect_google_fonts() 0 15 3
C filter_preload() 3 48 16
A admin_menu() 0 15 2
A add_extra_tab() 0 8 2
F options_page() 0 108 15

How to fix   Duplicated Code    Complexity   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

Complex Class

 Tip:   Before tackling complexity, make sure that you eliminate any duplication first. This often can reduce the size of classes significantly.

Complex classes like autoptimizeExtra often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use autoptimizeExtra, and based on these observations, apply Extract Interface, too.

1
<?php
2
/**
3
 * Handles autoptimizeExtra frontend features + admin options page
4
 */
5
6
if ( ! defined( 'ABSPATH' ) ) {
7
    exit;
8
}
9
10
class autoptimizeExtra
11
{
12
    /**
13
     * Options
14
     *
15
     * @var array
16
     */
17
    protected $options = array();
18
19
    /**
20
     * Singleton instance.
21
     *
22
     * @var self|null
23
     */
24
    protected static $instance = null;
25
26
    /**
27
     * Creates an instance and calls run().
28
     *
29
     * @param array $options Optional. Allows overriding options without having to specify them via admin options page.
30
     */
31
    public function __construct( $options = array() )
32
    {
33
        if ( empty( $options ) ) {
34
            $options = self::fetch_options();
35
        }
36
37
        $this->options = $options;
0 ignored issues
show
Documentation Bug introduced by
It seems like $options of type * is incompatible with the declared type array of property $options.

Our type inference engine has found an assignment to a property that is incompatible with the declared type of that property.

Either this assignment is in error or the assigned type should be added to the documentation/type hint for that property..

Loading history...
38
    }
39
40
    /**
41
     * Helper for getting a singleton instance. While being an
42
     * anti-pattern generally, it comes in handy for now from a
43
     * readability/maintainability perspective, until we get some
44
     * proper dependency injection going.
45
     *
46
     * @return self
47
     */
48
    public static function instance()
49
    {
50
        if ( null === self::$instance ) {
51
            self::$instance = new self();
52
        }
53
54
        return self::$instance;
55
    }
56
57 View Code Duplication
    public function run()
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
58
    {
59
        if ( is_admin() ) {
60
            if ( is_multisite() && is_network_admin() && autoptimizeOptionWrapper::is_ao_active_for_network() ) {
61
                add_action( 'network_admin_menu', array( $this, 'admin_menu' ) );
62
            } else {
63
                add_action( 'admin_menu', array( $this, 'admin_menu' ) );
64
            }
65
            add_filter( 'autoptimize_filter_settingsscreen_tabs', array( $this, 'add_extra_tab' ) );
66
        } else {
67
            $this->run_on_frontend();
68
        }
69
    }
70
71
    public function set_options( array $options )
72
    {
73
        $this->options = $options;
74
75
        return $this;
76
    }
77
78
    public static function fetch_options()
79
    {
80
        $value = autoptimizeOptionWrapper::get_option( 'autoptimize_extra_settings' );
81
        if ( empty( $value ) ) {
82
            // Fallback to returning defaults when no stored option exists yet.
83
            $value = autoptimizeConfig::get_ao_extra_default_options();
84
        }
85
86
        return $value;
87
    }
88
89
    public function disable_emojis()
90
    {
91
        // Removing all actions related to emojis!
92
        remove_action( 'admin_print_styles', 'print_emoji_styles' );
93
        remove_action( 'wp_head', 'print_emoji_detection_script', 7 );
94
        remove_action( 'admin_print_scripts', 'print_emoji_detection_script' );
95
        remove_action( 'wp_print_styles', 'print_emoji_styles' );
96
        remove_filter( 'wp_mail', 'wp_staticize_emoji_for_email' );
97
        remove_filter( 'the_content_feed', 'wp_staticize_emoji' );
98
        remove_filter( 'comment_text_rss', 'wp_staticize_emoji' );
99
100
        // Removes TinyMCE emojis.
101
        add_filter( 'tiny_mce_plugins', array( $this, 'filter_disable_emojis_tinymce' ) );
102
103
        // Removes emoji dns-preftech.
104
        add_filter( 'wp_resource_hints', array( $this, 'filter_remove_emoji_dns_prefetch' ), 10, 2 );
105
    }
106
107
    public function filter_disable_emojis_tinymce( $plugins )
108
    {
109
        if ( is_array( $plugins ) ) {
110
            return array_diff( $plugins, array( 'wpemoji' ) );
111
        } else {
112
            return array();
113
        }
114
    }
115
116
    public function filter_remove_qs( $src )
117
    {
118
        if ( strpos( $src, '?ver=' ) ) {
119
            $src = remove_query_arg( 'ver', $src );
120
        }
121
122
        return $src;
123
    }
124
125
    public function extra_async_js( $in )
126
    {
127
        $exclusions = array();
128 View Code Duplication
        if ( ! empty( $in ) ) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
129
            $exclusions = array_fill_keys( array_filter( array_map( 'trim', explode( ',', $in ) ) ), '' );
130
        }
131
132
        $settings = $this->options['autoptimize_extra_text_field_3'];
133
        $async    = array_fill_keys( array_filter( array_map( 'trim', explode( ',', $settings ) ) ), '' );
134
        $attr     = apply_filters( 'autoptimize_filter_extra_async', 'async' );
135
        foreach ( $async as $k => $v ) {
136
            $async[ $k ] = $attr;
137
        }
138
139
        // Merge exclusions & asyncs in one array and return to AO API.
140
        $merged = array_merge( $exclusions, $async );
141
142
        return $merged;
143
    }
144
145
    protected function run_on_frontend()
146
    {
147
        $options = $this->options;
148
149
        // Disable emojis if specified.
150
        if ( ! empty( $options['autoptimize_extra_checkbox_field_1'] ) ) {
151
            $this->disable_emojis();
152
        }
153
154
        // Remove version query parameters.
155
        if ( ! empty( $options['autoptimize_extra_checkbox_field_0'] ) ) {
156
            add_filter( 'script_loader_src', array( $this, 'filter_remove_qs' ), 15, 1 );
157
            add_filter( 'style_loader_src', array( $this, 'filter_remove_qs' ), 15, 1 );
158
        }
159
160
        // Avoiding conflicts of interest when async-javascript plugin is active!
161
        $async_js_plugin_active = autoptimizeUtils::is_plugin_active( 'async-javascript/async-javascript.php' );
162
        if ( ! empty( $options['autoptimize_extra_text_field_3'] ) && ! $async_js_plugin_active ) {
163
            add_filter( 'autoptimize_filter_js_exclude', array( $this, 'extra_async_js' ), 10, 1 );
164
        }
165
166
        // Optimize google fonts!
167
        if ( ! empty( $options['autoptimize_extra_radio_field_4'] ) && ( '1' !== $options['autoptimize_extra_radio_field_4'] ) ) {
168
            add_filter( 'wp_resource_hints', array( $this, 'filter_remove_gfonts_dnsprefetch' ), 10, 2 );
169
            add_filter( 'autoptimize_html_after_minify', array( $this, 'filter_optimize_google_fonts' ), 10, 1 );
170
            add_filter( 'autoptimize_extra_filter_tobepreconn', array( $this, 'filter_preconnect_google_fonts' ), 10, 1 );
171
        }
172
173
        // Preconnect!
174
        if ( ! empty( $options['autoptimize_extra_text_field_2'] ) || has_filter( 'autoptimize_extra_filter_tobepreconn' ) ) {
175
            add_filter( 'wp_resource_hints', array( $this, 'filter_preconnect' ), 10, 2 );
176
        }
177
178
        // Preload!
179
        if ( ! empty( $options['autoptimize_extra_text_field_7'] ) ) {
180
            add_filter( 'autoptimize_html_after_minify', array( $this, 'filter_preload' ), 10, 2 );
181
        }
182
    }
183
184
    public function filter_remove_emoji_dns_prefetch( $urls, $relation_type )
185
    {
186
        $emoji_svg_url = apply_filters( 'emoji_svg_url', 'https://s.w.org/images/core/emoji/' );
187
188
        return $this->filter_remove_dns_prefetch( $urls, $relation_type, $emoji_svg_url );
189
    }
190
191
    public function filter_remove_gfonts_dnsprefetch( $urls, $relation_type )
192
    {
193
        return $this->filter_remove_dns_prefetch( $urls, $relation_type, 'fonts.googleapis.com' );
194
    }
195
196
    public function filter_remove_dns_prefetch( $urls, $relation_type, $url_to_remove )
197
    {
198
        $url_to_remove = (string) $url_to_remove;
199
200
        if ( ! empty( $url_to_remove ) && 'dns-prefetch' === $relation_type ) {
201
            $cnt = 0;
202
            foreach ( $urls as $url ) {
203
                if ( false !== strpos( $url, $url_to_remove ) ) {
204
                    unset( $urls[ $cnt ] );
205
                }
206
                $cnt++;
207
            }
208
        }
209
210
        return $urls;
211
    }
212
213
    public function filter_optimize_google_fonts( $in )
214
    {
215
        // Extract fonts, partly based on wp rocket's extraction code.
216
        $markup = preg_replace( '/<!--(.*)-->/Uis', '', $in );
217
        preg_match_all( '#<link(?:\s+(?:(?!href\s*=\s*)[^>])+)?(?:\s+href\s*=\s*([\'"])((?:https?:)?\/\/fonts\.googleapis\.com\/css(?:(?!\1).)+)\1)(?:\s+[^>]*)?>#iU', $markup, $matches );
218
219
        $fonts_collection = array();
220
        if ( ! $matches[2] ) {
221
            return $in;
222
        }
223
224
        // Store them in $fonts array.
225
        $i = 0;
226
        foreach ( $matches[2] as $font ) {
227
            if ( ! preg_match( '/rel=["\']dns-prefetch["\']/', $matches[0][ $i ] ) ) {
228
                // Get fonts name.
229
                $font = str_replace( array( '%7C', '%7c' ), '|', $font );
230
                $font = explode( 'family=', $font );
231
                $font = ( isset( $font[1] ) ) ? explode( '&', $font[1] ) : array();
232
                // Add font to $fonts[$i] but make sure not to pollute with an empty family!
233
                $_thisfont = array_values( array_filter( explode( '|', reset( $font ) ) ) );
234
                if ( ! empty( $_thisfont ) ) {
235
                    $fonts_collection[ $i ]['fonts'] = $_thisfont;
236
                    // And add subset if any!
237
                    $subset = ( is_array( $font ) ) ? end( $font ) : '';
238
                    if ( false !== strpos( $subset, 'subset=' ) ) {
239
                        $subset                            = str_replace( array( '%2C', '%2c' ), ',', $subset );
240
                        $subset                            = explode( 'subset=', $subset );
241
                        $fonts_collection[ $i ]['subsets'] = explode( ',', $subset[1] );
242
                    }
243
                }
244
                // And remove Google Fonts.
245
                $in = str_replace( $matches[0][ $i ], '', $in );
246
            }
247
            $i++;
248
        }
249
250
        $options      = $this->options;
251
        $fonts_markup = '';
252
        if ( '2' === $options['autoptimize_extra_radio_field_4'] ) {
253
            // Remove Google Fonts.
254
            unset( $fonts_collection );
255
            return $in;
256
        } elseif ( '3' === $options['autoptimize_extra_radio_field_4'] || '5' === $options['autoptimize_extra_radio_field_4'] ) {
257
            // Aggregate & link!
258
            $fonts_string  = '';
259
            $subset_string = '';
260
            foreach ( $fonts_collection as $font ) {
261
                $fonts_string .= '|' . trim( implode( '|', $font['fonts'] ), '|' );
262
                if ( ! empty( $font['subsets'] ) ) {
263
                    $subset_string .= ',' . trim( implode( ',', $font['subsets'] ), ',' );
264
                }
265
            }
266
267
            if ( ! empty( $subset_string ) ) {
268
                $subset_string = str_replace( ',', '%2C', ltrim( $subset_string, ',' ) );
269
                $fonts_string  = $fonts_string . '&#038;subset=' . $subset_string;
270
            }
271
272
            $fonts_string = apply_filters( 'autoptimize_filter_extra_gfont_fontstring', str_replace( '|', '%7C', ltrim( $fonts_string, '|' ) ) );
273
            // only add display parameter if there is none in $fonts_string (by virtue of the filter).
274
            if ( strpos( $fonts_string, 'display=' ) === false ) {
275
                $fonts_string .= apply_filters( 'autoptimize_filter_extra_gfont_display', '&amp;display=swap' );
276
            }
277
278
            if ( ! empty( $fonts_string ) ) {
279
                if ( '5' === $options['autoptimize_extra_radio_field_4'] ) {
280
                    $rel_string = 'rel="preload" as="style" onload="' . autoptimizeConfig::get_ao_css_preload_onload() . '"';
281
                } else {
282
                    $rel_string = 'rel="stylesheet"';
283
                }
284
                $fonts_markup = '<link ' . $rel_string . ' id="ao_optimized_gfonts" href="https://fonts.googleapis.com/css?family=' . $fonts_string . '" />';
285
            }
286
        } elseif ( '4' === $options['autoptimize_extra_radio_field_4'] ) {
287
            // Aggregate & load async (webfont.js impl.)!
288
            $fonts_array = array();
289
            foreach ( $fonts_collection as $_fonts ) {
290
                if ( ! empty( $_fonts['subsets'] ) ) {
291
                    $_subset = implode( ',', $_fonts['subsets'] );
292
                    foreach ( $_fonts['fonts'] as $key => $_one_font ) {
293
                        $_one_font               = $_one_font . ':' . $_subset;
294
                        $_fonts['fonts'][ $key ] = $_one_font;
295
                    }
296
                }
297
                $fonts_array = array_merge( $fonts_array, $_fonts['fonts'] );
298
            }
299
300
            $fonts_array = array_map( 'urldecode', $fonts_array );
301
            $fonts_array = array_map(
302
                function( $_f ) {
303
                    return trim( $_f, ',' );
304
                },
305
                $fonts_array
306
            );
307
308
            // type attrib on <script not added by default.
309
            $type_js = '';
310
            if ( apply_filters( 'autoptimize_filter_cssjs_addtype', false ) ) {
311
                $type_js = 'type="text/javascript" ';
312
            }
313
314
            $fonts_markup         = '<script ' . $type_js . 'data-cfasync="false" id="ao_optimized_gfonts_config">WebFontConfig={google:{families:' . wp_json_encode( $fonts_array ) . ' },classes:false, events:false, timeout:1500};</script>';
315
            $fonts_library_markup = '<script ' . $type_js . 'data-cfasync="false" id="ao_optimized_gfonts_webfontloader">(function() {var wf = document.createElement(\'script\');wf.src=\'https://ajax.googleapis.com/ajax/libs/webfont/1/webfont.js\';wf.type=\'text/javascript\';wf.async=\'true\';var s=document.getElementsByTagName(\'script\')[0];s.parentNode.insertBefore(wf, s);})();</script>';
316
            $in                   = substr_replace( $in, $fonts_library_markup . '</head>', strpos( $in, '</head>' ), strlen( '</head>' ) );
317
        }
318
319
        // Replace back in markup.
320
        $inject_point = apply_filters( 'autoptimize_filter_extra_gfont_injectpoint', '<link' );
321
        $out          = substr_replace( $in, $fonts_markup . $inject_point, strpos( $in, $inject_point ), strlen( $inject_point ) );
322
        unset( $fonts_collection );
323
324
        // and insert preload polyfill if "link preload" and if the polyfill isn't there yet (courtesy of inline&defer).
325
        $preload_polyfill = autoptimizeConfig::get_ao_css_preload_polyfill();
326
        if ( '5' === $options['autoptimize_extra_radio_field_4'] && strpos( $out, $preload_polyfill ) === false ) {
327
            $out = str_replace( '</body>', $preload_polyfill . '</body>', $out );
328
        }
329
        return $out;
330
    }
331
332
    public function filter_preconnect( $hints, $relation_type )
333
    {
334
        $options  = $this->options;
335
        $preconns = array();
336
337
        // Get settings and store in array.
338 View Code Duplication
        if ( array_key_exists( 'autoptimize_extra_text_field_2', $options ) ) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
339
            $preconns = array_filter( array_map( 'trim', explode( ',', $options['autoptimize_extra_text_field_2'] ) ) );
340
        }
341
        $preconns = apply_filters( 'autoptimize_extra_filter_tobepreconn', $preconns );
342
343
        // Walk array, extract domain and add to new array with crossorigin attribute.
344
        foreach ( $preconns as $preconn ) {
345
            $domain = '';
346
            $parsed = parse_url( $preconn );
347
            if ( is_array( $parsed ) && ! empty( $parsed['host'] ) && empty( $parsed['scheme'] ) ) {
348
                $domain = '//' . $parsed['host'];
349
            } elseif ( is_array( $parsed ) && ! empty( $parsed['host'] ) ) {
350
                $domain = $parsed['scheme'] . '://' . $parsed['host'];
351
            }
352
353
            if ( ! empty( $domain ) ) {
354
                $hint = array( 'href' => $domain );
355
                // Fonts don't get preconnected unless crossorigin flag is set, non-fonts don't get preconnected if origin flag is set
356
                // so hardcode fonts.gstatic.com to come with crossorigin and have filter to add other domains if needed.
357
                $crossorigins = apply_filters( 'autoptimize_extra_filter_preconn_crossorigin', array( 'https://fonts.gstatic.com' ) );
358
                if ( in_array( $domain, $crossorigins ) ) {
359
                    $hint['crossorigin'] = 'anonymous';
360
                }
361
                $new_hints[] = $hint;
0 ignored issues
show
Coding Style Comprehensibility introduced by
$new_hints was never initialized. Although not strictly required by PHP, it is generally a good practice to add $new_hints = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
362
            }
363
        }
364
365
        // Merge in WP's preconnect hints.
366
        if ( 'preconnect' === $relation_type && ! empty( $new_hints ) ) {
367
            $hints = array_merge( $hints, $new_hints );
368
        }
369
370
        return $hints;
371
    }
372
373
    public function filter_preconnect_google_fonts( $in )
374
    {
375
        if ( '2' !== $this->options['autoptimize_extra_radio_field_4'] ) {
376
            // Preconnect to fonts.gstatic.com unless we remove gfonts.
377
            $in[] = 'https://fonts.gstatic.com';
378
        }
379
380
        if ( '4' === $this->options['autoptimize_extra_radio_field_4'] ) {
381
            // Preconnect even more hosts for webfont.js!
382
            $in[] = 'https://ajax.googleapis.com';
383
            $in[] = 'https://fonts.googleapis.com';
384
        }
385
386
        return $in;
387
    }
388
389
    public function filter_preload( $in ) {
390
        // make array from comma separated list.
391
        $options  = $this->options;
392
        $preloads = array();
393 View Code Duplication
        if ( array_key_exists( 'autoptimize_extra_text_field_7', $options ) ) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
394
            $preloads = array_filter( array_map( 'trim', explode( ',', $options['autoptimize_extra_text_field_7'] ) ) );
395
        }
396
        $preloads = apply_filters( 'autoptimize_filter_extra_tobepreloaded', $preloads );
397
398
        // immediately return if nothing to be preloaded.
399
        if ( empty( $preloads ) ) {
400
            return $in;
401
        }
402
403
        // iterate through array and add preload link to tmp string.
404
        $preload_output = '';
405
        foreach ( $preloads as $preload ) {
406
            $crossorigin = '';
407
            $preload_as  = '';
0 ignored issues
show
Unused Code introduced by
$preload_as is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
408
            $mime_type   = '';
409
410
            if ( autoptimizeUtils::str_ends_in( $preload, '.css' ) ) {
411
                $preload_as = 'style';
412
            } elseif ( autoptimizeUtils::str_ends_in( $preload, '.js' ) ) {
413
                $preload_as = 'script';
414
            } elseif ( autoptimizeUtils::str_ends_in( $preload, '.woff' ) || autoptimizeUtils::str_ends_in( $preload, '.woff2' ) || autoptimizeUtils::str_ends_in( $preload, '.ttf' ) || autoptimizeUtils::str_ends_in( $preload, '.eot' ) ) {
415
                $preload_as  = 'font';
416
                $crossorigin = ' crossorigin';
417
                $mime_type   = ' type="font/' . pathinfo( $preload, PATHINFO_EXTENSION ) . '"';
418
                if ( ' type="font/eot"' === $mime_type ) {
419
                    $mime_type = 'application/vnd.ms-fontobject';
420
                }
421
            } elseif ( autoptimizeUtils::str_ends_in( $preload, '.jpeg' ) || autoptimizeUtils::str_ends_in( $preload, '.jpg' ) || autoptimizeUtils::str_ends_in( $preload, '.webp' ) || autoptimizeUtils::str_ends_in( $preload, '.png' ) || autoptimizeUtils::str_ends_in( $preload, '.gif' ) ) {
422
                $preload_as = 'image';
423
            } else {
424
                $preload_as = 'other';
425
            }
426
427
            $preload_output .= '<link rel="preload" href="' . $preload . '" as="' . $preload_as . '"' . $mime_type . $crossorigin . '>';
428
        }
429
        $preload_output = apply_filters( 'autoptimize_filter_extra_preload_output', $preload_output );
430
431
        // add string to head (before first link node by default).
432
        $preload_inject = apply_filters( 'autoptimize_filter_extra_preload_inject', '<link' );
433
        $position       = autoptimizeUtils::strpos( $in, $preload_inject );
434
435
        return autoptimizeUtils::substr_replace( $in, $preload_output . $preload_inject, $position, strlen( $preload_inject ) );
0 ignored issues
show
Security Bug introduced by
It seems like $position defined by \autoptimizeUtils::strpos($in, $preload_inject) on line 433 can also be of type false; however, autoptimizeUtils::substr_replace() does only seem to accept integer, did you maybe forget to handle an error condition?

This check looks for type mismatches where the missing type is false. This is usually indicative of an error condtion.

Consider the follow example

<?php

function getDate($date)
{
    if ($date !== null) {
        return new DateTime($date);
    }

    return false;
}

This function either returns a new DateTime object or false, if there was an error. This is a typical pattern in PHP programming to show that an error has occurred without raising an exception. The calling code should check for this returned false before passing on the value to another function or method that may not be able to handle a false.

Loading history...
436
    }
437
438
    public function admin_menu()
439
    {
440
        // no acces if multisite and not network admin and no site config allowed.
441
        if ( autoptimizeConfig::should_show_menu_tabs() ) {
442
            add_submenu_page(
443
                null,
444
                'autoptimize_extra',
445
                'autoptimize_extra',
446
                'manage_options',
447
                'autoptimize_extra',
448
                array( $this, 'options_page' )
449
            );
450
            register_setting( 'autoptimize_extra_settings', 'autoptimize_extra_settings' );
451
        }
452
    }
453
454
    public function add_extra_tab( $in )
455
    {
456
        if ( autoptimizeConfig::should_show_menu_tabs() ) {
457
            $in = array_merge( $in, array( 'autoptimize_extra' => __( 'Extra', 'autoptimize' ) ) );
458
        }
459
460
        return $in;
461
    }
462
463
    public function options_page()
464
    {
465
        // Working with actual option values from the database here.
466
        // That way any saves are still processed as expected, but we can still
467
        // override behavior by using `new autoptimizeExtra($custom_options)` and not have that custom
468
        // behavior being persisted in the DB even if save is done here.
469
        $options = $this->fetch_options();
470
        $gfonts  = $options['autoptimize_extra_radio_field_4'];
471
        ?>
472
    <style>
473
        #ao_settings_form {background: white;border: 1px solid #ccc;padding: 1px 15px;margin: 15px 10px 10px 0;}
474
        #ao_settings_form .form-table th {font-weight: normal;}
475
        #autoptimize_extra_descr{font-size: 120%;}
476
    </style>
477
    <script>document.title = "Autoptimize: <?php _e( 'Extra', 'autoptimize' ); ?> " + document.title;</script>
478
    <div class="wrap">
479
    <h1><?php _e( 'Autoptimize Settings', 'autoptimize' ); ?></h1>
480
        <?php echo autoptimizeConfig::ao_admin_tabs(); ?>
481
        <?php if ( 'on' !== autoptimizeOptionWrapper::get_option( 'autoptimize_js' ) && 'on' !== autoptimizeOptionWrapper::get_option( 'autoptimize_css' ) && 'on' !== autoptimizeOptionWrapper::get_option( 'autoptimize_html' ) && ! autoptimizeImages::imgopt_active() ) { ?>
0 ignored issues
show
Bug Best Practice introduced by
The expression \autoptimizeImages::imgopt_active() of type null|boolean is loosely compared to false; this is ambiguous if the boolean can be false. You might want to explicitly use !== null instead.

If an expression can have both false, and null as possible values. It is generally a good practice to always use strict comparison to clearly distinguish between those two values.

$a = canBeFalseAndNull();

// Instead of
if ( ! $a) { }

// Better use one of the explicit versions:
if ($a !== null) { }
if ($a !== false) { }
if ($a !== null && $a !== false) { }
Loading history...
482
            <div class="notice-warning notice"><p>
483
            <?php _e( 'Most of below Extra optimizations require at least one of HTML, JS, CSS or Image autoptimizations being active.', 'autoptimize' ); ?>
484
            </p></div>
485
        <?php } ?>
486
487
    <form id='ao_settings_form' action='<?php echo admin_url( 'options.php' ); ?>' method='post'>
488
        <?php settings_fields( 'autoptimize_extra_settings' ); ?>
489
        <h2><?php _e( 'Extra Auto-Optimizations', 'autoptimize' ); ?></h2>
490
        <span id='autoptimize_extra_descr'><?php _e( 'The following settings can improve your site\'s performance even more.', 'autoptimize' ); ?></span>
491
        <table class="form-table">
492
            <tr>
493
                <th scope="row"><?php _e( 'Google Fonts', 'autoptimize' ); ?></th>
494
                <td>
495
                    <input type="radio" name="autoptimize_extra_settings[autoptimize_extra_radio_field_4]" value="1" <?php if ( ! in_array( $gfonts, array( 2, 3, 4, 5 ) ) ) { echo 'checked'; } ?> ><?php _e( 'Leave as is', 'autoptimize' ); ?><br/>
496
                    <input type="radio" name="autoptimize_extra_settings[autoptimize_extra_radio_field_4]" value="2" <?php checked( 2, $gfonts, true ); ?> ><?php _e( 'Remove Google Fonts', 'autoptimize' ); ?><br/>
497
                    <?php // translators: "display:swap" should remain untranslated, will be shown in code tags. ?>
498
                    <input type="radio" name="autoptimize_extra_settings[autoptimize_extra_radio_field_4]" value="3" <?php checked( 3, $gfonts, true ); ?> ><?php echo __( 'Combine and link in head (fonts load fast but are render-blocking)', 'autoptimize' ) . ', ' . sprintf( __( 'includes %1$sdisplay:swap%2$s.', 'autoptimize' ), '<code>', '</code>' ); ?><br/>
499
                    <?php // translators: "display:swap" should remain untranslated, will be shown in code tags. ?>
500
                    <input type="radio" name="autoptimize_extra_settings[autoptimize_extra_radio_field_4]" value="5" <?php checked( 5, $gfonts, true ); ?> ><?php echo __( 'Combine and preload in head (fonts load late, but are not render-blocking)', 'autoptimize' ) . ', ' . sprintf( __( 'includes %1$sdisplay:swap%2$s.', 'autoptimize' ), '<code>', '</code>' ); ?><br/>
501
                    <input type="radio" name="autoptimize_extra_settings[autoptimize_extra_radio_field_4]" value="4" <?php checked( 4, $gfonts, true ); ?> ><?php _e( 'Combine and load fonts asynchronously with <a href="https://github.com/typekit/webfontloader#readme" target="_blank">webfont.js</a>', 'autoptimize' ); ?><br/>
502
                </td>
503
            </tr>
504
            <tr>
505
                <th scope="row"><?php _e( 'Remove emojis', 'autoptimize' ); ?></th>
506
                <td>
507
                    <label><input type='checkbox' name='autoptimize_extra_settings[autoptimize_extra_checkbox_field_1]' <?php if ( ! empty( $options['autoptimize_extra_checkbox_field_1'] ) && '1' === $options['autoptimize_extra_checkbox_field_1'] ) { echo 'checked="checked"'; } ?> value='1'><?php _e( 'Removes WordPress\' core emojis\' inline CSS, inline JavaScript, and an otherwise un-autoptimized JavaScript file.', 'autoptimize' ); ?></label>
508
                </td>
509
            </tr>
510
            <tr>
511
                <th scope="row"><?php _e( 'Remove query strings from static resources', 'autoptimize' ); ?></th>
512
                <td>
513
                    <label><input type='checkbox' name='autoptimize_extra_settings[autoptimize_extra_checkbox_field_0]' <?php if ( ! empty( $options['autoptimize_extra_checkbox_field_0'] ) && '1' === $options['autoptimize_extra_checkbox_field_0'] ) { echo 'checked="checked"'; } ?> value='1'><?php _e( 'Removing query strings (or more specifically the <code>ver</code> parameter) will not improve load time, but might improve performance scores.', 'autoptimize' ); ?></label>
514
                </td>
515
            </tr>
516
            <tr>
517
                <th scope="row"><?php _e( 'Preconnect to 3rd party domains <em>(advanced users)</em>', 'autoptimize' ); ?></th>
518
                <td>
519
                    <label><input type='text' style='width:80%' name='autoptimize_extra_settings[autoptimize_extra_text_field_2]' value='<?php if ( array_key_exists( 'autoptimize_extra_text_field_2', $options ) ) { echo esc_attr( $options['autoptimize_extra_text_field_2'] ); } ?>'><br /><?php _e( 'Add 3rd party domains you want the browser to <a href="https://www.keycdn.com/support/preconnect/#primary" target="_blank">preconnect</a> to, separated by comma\'s. Make sure to include the correct protocol (HTTP or HTTPS).', 'autoptimize' ); ?></label>
520
                </td>
521
            </tr>
522
            <tr>
523
                <th scope="row"><?php _e( 'Preload specific requests <em>(advanced users)</em>', 'autoptimize' ); ?></th>
524
                <td>
525
                    <label><input type='text' style='width:80%' name='autoptimize_extra_settings[autoptimize_extra_text_field_7]' value='<?php if ( array_key_exists( 'autoptimize_extra_text_field_7', $options ) ) { echo esc_attr( $options['autoptimize_extra_text_field_7'] ); } ?>'><br /><?php _e( 'Comma-separated list with full URL\'s of to to-be-preloaded resources. To be used sparingly!', 'autoptimize' ); ?></label>
526
                </td>
527
            </tr>
528
            <tr>
529
                <th scope="row"><?php _e( 'Async Javascript-files <em>(advanced users)</em>', 'autoptimize' ); ?></th>
530
                <td>
531
                    <?php
532
                    if ( autoptimizeUtils::is_plugin_active( 'async-javascript/async-javascript.php' ) ) {
533
                        // translators: link points Async Javascript settings page.
534
                        printf( __( 'You have "Async JavaScript" installed, %1$sconfiguration of async javascript is best done there%2$s.', 'autoptimize' ), '<a href="' . 'options-general.php?page=async-javascript' . '">', '</a>' );
535
                    } else {
536
                    ?>
537
                        <input type='text' style='width:80%' name='autoptimize_extra_settings[autoptimize_extra_text_field_3]' value='<?php if ( array_key_exists( 'autoptimize_extra_text_field_3', $options ) ) { echo esc_attr( $options['autoptimize_extra_text_field_3'] ); } ?>'>
538
                        <br />
539
                        <?php
540
                            _e( 'Comma-separated list of local or 3rd party JS-files that should loaded with the <code>async</code> flag. JS-files from your own site will be automatically excluded if added here. ', 'autoptimize' );
541
                            // translators: %s will be replaced by a link to the "async javascript" plugin.
542
                            echo sprintf( __( 'Configuration of async javascript is easier and more flexible using the %s plugin.', 'autoptimize' ), '"<a href="https://wordpress.org/plugins/async-javascript" target="_blank">Async Javascript</a>"' );
543
                            $asj_install_url = network_admin_url() . 'plugin-install.php?s=async+javascript&tab=search&type=term';
544
                            echo sprintf( ' <a href="' . $asj_install_url . '">%s</a>', __( 'Click here to install and activate it.', 'autoptimize' ) );
545
                    }
546
                    ?>
547
                </td>
548
            </tr>
549
            <tr>
550
                <th scope="row"><?php _e( 'Optimize YouTube videos', 'autoptimize' ); ?></th>
551
                <td>
552
                    <?php
553
                    if ( autoptimizeUtils::is_plugin_active( 'wp-youtube-lyte/wp-youtube-lyte.php' ) ) {
554
                        _e( 'Great, you have WP YouTube Lyte installed.', 'autoptimize' );
555
                        $lyte_config_url = 'options-general.php?page=lyte_settings_page';
556
                        echo sprintf( ' <a href="' . $lyte_config_url . '">%s</a>', __( 'Click here to configure it.', 'autoptimize' ) );
557
                    } else {
558
                        // translators: %s will be replaced by a link to "wp youtube lyte" plugin.
559
                        echo sprintf( __( '%s allows you to “lazy load” your videos, by inserting responsive “Lite YouTube Embeds". ', 'autoptimize' ), '<a href="https://wordpress.org/plugins/wp-youtube-lyte" target="_blank">WP YouTube Lyte</a>' );
560
                        $lyte_install_url = network_admin_url() . 'plugin-install.php?s=lyte&tab=search&type=term';
561
                        echo sprintf( ' <a href="' . $lyte_install_url . '">%s</a>', __( 'Click here to install and activate it.', 'autoptimize' ) );
562
                    }
563
                    ?>
564
                </td>
565
            </tr>
566
        </table>
567
        <p class="submit"><input type="submit" name="submit" id="submit" class="button button-primary" value="<?php _e( 'Save Changes', 'autoptimize' ); ?>" /></p>
568
    </form>
569
        <?php
570
    }
571
}
572