Completed
Push — master ( 2784cd...57846f )
by frank
01:55
created

autoptimizeExtra.php ➔ autoptimize_extra_gfonts_remove_dnsprefetch()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 5
Code Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
eloc 3
nc 1
nop 2
dl 0
loc 5
rs 9.4285
c 0
b 0
f 0
1
<?php
2
if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly
3
4
// initialize
5
if ( is_admin() ) {
6
    add_action( 'admin_menu', 'autoptimize_extra_admin' );
7
    add_filter( 'autoptimize_filter_settingsscreen_tabs','add_autoptimize_extra_tab' );
8
} else {
9
    autoptimize_extra_init();
10
}
11
12
// get option
13
function autoptimize_extra_get_options() {
14
    $_default_val = array("autoptimize_extra_checkbox_field_1"=>"0","autoptimize_extra_checkbox_field_0"=>"0","autoptimize_extra_radio_field_4"=>"1","autoptimize_extra_text_field_2"=>"","autoptimize_extra_text_field_3"=>"");
15
    $_option_val = get_option( 'autoptimize_extra_settings' );
16
    if (empty($_option_val)) {
17
        $_option_val = $_default_val;
18
    }
19
    return $_option_val;
20
}
21
22
// frontend init
23
function autoptimize_extra_init() {
24
    $autoptimize_extra_options = autoptimize_extra_get_options();
25
26
    /* disable emojis */
27
    if ( !empty($autoptimize_extra_options['autoptimize_extra_checkbox_field_1']) ) {
28
        autoptimize_extra_disable_emojis();
29
    }
30
    
31
    /* remove version from query string */
32
    if ( !empty($autoptimize_extra_options['autoptimize_extra_checkbox_field_0']) ) {
33
        add_filter( 'script_loader_src', 'autoptimize_extra_remove_qs', 15, 1 );
34
        add_filter( 'style_loader_src', 'autoptimize_extra_remove_qs', 15, 1 );
35
    }
36
37
    /* async JS */
38
    if (!empty($autoptimize_extra_options['autoptimize_extra_text_field_3'])) {
39
        add_filter('autoptimize_filter_js_exclude','autoptimize_extra_async_js',10,1);
40
    }
41
42
    /* optimize google fonts */
43
    if ( !empty( $autoptimize_extra_options['autoptimize_extra_radio_field_4'] ) && ( $autoptimize_extra_options['autoptimize_extra_radio_field_4'] != "1" ) ) {
44
        add_filter( 'wp_resource_hints', 'autoptimize_extra_gfonts_remove_dnsprefetch', 10, 2 );        
45
        if ( $autoptimize_extra_options['autoptimize_extra_radio_field_4'] == "2" ) {
46
            add_filter('autoptimize_filter_css_removables','autoptimize_extra_remove_gfonts',10,1);
47
        } else {
48
            add_filter('autoptimize_html_after_minify','autoptimize_extra_gfonts',10,1);
49
            add_filter('autoptimize_extra_filter_tobepreconn','autoptimize_extra_preconnectgooglefonts',10,1);
50
        }
51
    }
52
    
53
    /* preconnect */
54
    if ( !empty($autoptimize_extra_options['autoptimize_extra_text_field_2']) || has_filter('autoptimize_extra_filter_tobepreconn') ) {
55
        add_filter( 'wp_resource_hints', 'autoptimize_extra_preconnect', 10, 2 );
56
    }
57
}
58
59
// disable emoji's functions
60
function autoptimize_extra_disable_emojis() {
61
    // all actions related to emojis
62
    remove_action( 'admin_print_styles', 'print_emoji_styles' );
63
    remove_action( 'wp_head', 'print_emoji_detection_script', 7 );
64
    remove_action( 'admin_print_scripts', 'print_emoji_detection_script' );
65
    remove_action( 'wp_print_styles', 'print_emoji_styles' );
66
    remove_filter( 'wp_mail', 'wp_staticize_emoji_for_email' );
67
    remove_filter( 'the_content_feed', 'wp_staticize_emoji' );
68
    remove_filter( 'comment_text_rss', 'wp_staticize_emoji' );
69
70
    // filter to remove TinyMCE emojis
71
    add_filter( 'tiny_mce_plugins', 'autoptimize_extra_disable_emojis_tinymce' );
72
73
    // and remove dns-prefetch for emoji
74
    add_filter( 'wp_resource_hints', 'autoptimize_extra_emojis_remove_dns_prefetch', 10, 2 );
75
}
76
77
function autoptimize_extra_disable_emojis_tinymce( $plugins ) {
78
    if ( is_array( $plugins ) ) {
79
        return array_diff( $plugins, array( 'wpemoji' ) );
80
    } else {
81
        return array();
82
    }
83
}
84
85
function autoptimize_extra_emojis_remove_dns_prefetch( $urls, $relation_type ) {
86
    $_emoji_svg_url = apply_filters( 'emoji_svg_url', 'https://s.w.org/images/core/emoji/' );
87
88
    return autoptimize_extra_remove_dns_prefetch( $urls, $relation_type, $_emoji_svg_url );
89
}
90
91
// remove query string function
92
function autoptimize_extra_remove_qs( $src ) {
93
    if ( strpos($src, '?ver=') ) {
94
            $src = remove_query_arg( 'ver', $src );
95
    }
96
    return $src;
97
}
98
99
// async function
100
function autoptimize_extra_async_js($in) {
101
    $autoptimize_extra_options = autoptimize_extra_get_options();
102
    
103
    // get exclusions
104
    $AO_JSexclArrayIn = array();
105 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...
106
        $AO_JSexclArrayIn = array_fill_keys(array_filter(array_map('trim',explode(",",$in))),"");
107
    }
108
    
109
    // get asyncs
110
    $_fromSetting = $autoptimize_extra_options['autoptimize_extra_text_field_3'];
111
    $AO_asynced_JS = array_fill_keys(array_filter(array_map('trim',explode(",",$_fromSetting))),"");
112
    foreach ($AO_asynced_JS as $JSkey => $JSvalue) {
113
        $AO_asynced_JS[$JSkey] = "async";
114
    }
115
    
116
    // merge exclusions & asyncs in one array and return to AO API
117
    $AO_excl_w_async = array_merge( $AO_JSexclArrayIn, $AO_asynced_JS );
118
    return $AO_excl_w_async;
119
}
120
121
// preconnect function
122
function autoptimize_extra_preconnect($hints, $relation_type) {
123
    $autoptimize_extra_options = autoptimize_extra_get_options();
124
    
125
    // get setting and store in array
126
    $_to_be_preconnected = array_filter(array_map('trim',explode(",",$autoptimize_extra_options['autoptimize_extra_text_field_2'])));
127
    $_to_be_preconnected = apply_filters( 'autoptimize_extra_filter_tobepreconn', $_to_be_preconnected );
128
129
    // walk array, extract domain and add to new array with crossorigin attribute
130
    foreach ($_to_be_preconnected as $_preconn_single) {
131
        $_preconn_parsed = parse_url($_preconn_single);
132
        
133
        if ( is_array($_preconn_parsed) && empty($_preconn_parsed['scheme']) ) {
134
            $_preconn_domain = "//".$_preconn_parsed['host'];
135
        } else if ( is_array($_preconn_parsed) ) {
136
            $_preconn_domain = $_preconn_parsed['scheme']."://".$_preconn_parsed['host'];
137
        }
138
        
139
        if ( !empty($_preconn_domain) ) {
140
            $_preconn_hint = array('href' => $_preconn_domain);
141
            // fonts don't get preconnected unless crossorigin flag is set, non-fonts don't get preconnected if origin flag is set
142
            // so hardcode fonts.gstatic.com to come with crossorigin and have filter to add other domains if needed
143
            $_preconn_crossorigin = apply_filters( 'autoptimize_extra_filter_preconn_crossorigin', array('https://fonts.gstatic.com') );
144
            if ( in_array( $_preconn_domain, $_preconn_crossorigin ) ) {
145
                $_preconn_hint['crossorigin'] = 'anonymous';
146
            }
147
            $_new_hints[] = $_preconn_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...
148
        }
149
    }
150
151
    // merge in wordpress' preconnect hints
152
    if ( 'preconnect' === $relation_type && !empty($_new_hints) ) {
153
        $hints = array_merge($hints, $_new_hints);      
154
    }
155
    
156
    return $hints;
157
}
158
159
// google font functions
160
function autoptimize_extra_gfonts_remove_dnsprefetch ( $urls, $relation_type ) {
161
    $_gfonts_url = "fonts.googleapis.com";
162
    
163
    return autoptimize_extra_remove_dns_prefetch( $urls, $relation_type, $_gfonts_url );
164
}
165
166
function autoptimize_extra_remove_gfonts($in) { 
167
    // simply remove google fonts
168
    return $in.", fonts.googleapis.com"; 
169
}
170
171
function autoptimize_extra_gfonts($in) {
172
    $autoptimize_extra_options = autoptimize_extra_get_options();
173
    
174
    // extract fonts, partly based on wp rocket's extraction code
175
    $_without_comments = preg_replace( '/<!--(.*)-->/Uis', '', $in );
176
    preg_match_all( '#<link(?:\s+(?:(?!href\s*=\s*)[^>])+)?(?:\s+href\s*=\s*([\'"])((?:https?:)?\/\/fonts\.googleapis\.com\/css(?:(?!\1).)+)\1)(?:\s+[^>]*)?>#iU', $_without_comments, $matches );
177
178
    $i = 0;
179
    $fontsCollection = array();
180
    if ( ! $matches[2] ) {
181
        return $in;
182
    }
183
    
184
    // store them in $fonts array
185
    foreach ( $matches[2] as $font ) {
186
        if ( ! preg_match( '/rel=["\']dns-prefetch["\']/', $matches[0][ $i ] ) ) {
187
            // Get fonts name.
188
            $font = str_replace( array( '%7C', '%7c' ) , '|', $font );
189
            $font = explode( 'family=', $font );
190
            $font = ( isset( $font[1] ) ) ? explode( '&', $font[1] ) : array();
191
            // Add font to $fonts[$i] but make sure not to pollute with an empty family
192
            $_thisfont = array_values( array_filter( explode( '|', reset( $font ) ) ) );
193
            if ( !empty($_thisfont) ) {
194
                $fontsCollection[$i]["fonts"] = $_thisfont;
195
                // And add subset if any
196
                $subset = ( is_array( $font ) ) ? end( $font ) : '';
197
                if ( false !== strpos( $subset, 'subset=' ) ) {
198
                    $subset = explode( 'subset=', $subset );
199
                    $fontsCollection[$i]["subsets"] = explode( ',', $subset[1] );
200
                }
201
            }
202
            // And remove Google Fonts.
203
            $in = str_replace( $matches[0][ $i ], '', $in );
204
        }
205
        $i++;
206
    }
207
208
    $_fontsOut="";
209
    if ( $autoptimize_extra_options['autoptimize_extra_radio_field_4'] == "3" ) {
210
        // aggregate & link
211
        $_fontsString="";
212
        $_subsetString="";
213
        foreach ($fontsCollection as $font) {
214
            $_fontsString .= '|'.trim( implode( '|' , $font["fonts"] ), '|' );
215
            if ( !empty( $font["subsets"] ) ) {
216
                $_subsetString .= implode( ',', $font["subsets"] ); 
217
            }
218
        }
219
                    
220
        if (!empty($_subsetString)) {
221
            $_fontsString = $_fontsString."#038;subset=".$_subsetString;
222
        }
223
224
        $_fontsString = str_replace( '|', '%7C', ltrim($_fontsString,'|') );
225
        
226
        if ( ! empty( $_fontsString ) ) {
227
            $_fontsOut = '<link rel="stylesheet" id="ao_optimized_gfonts" href="https://fonts.googleapis.com/css?family=' . $_fontsString . '" />';
228
        }
229
    } else if ( $autoptimize_extra_options['autoptimize_extra_radio_field_4'] == "4" ) {
230
        // aggregate & load async (webfont.js impl.)
231
        $_fontsArray = array();
232
        foreach ($fontsCollection as $_fonts) {
233
            if ( !empty( $_fonts["subsets"] ) ) {
234
                $_subset = implode(",",$_fonts["subsets"]);
235
                foreach ($_fonts["fonts"] as $key => $_one_font) {
236
                    $_one_font = $_one_font.":".$_subset;
237
                    $_fonts["fonts"][$key] = $_one_font;
238
                } 
239
            }
240
            $_fontsArray = array_merge($_fontsArray, $_fonts["fonts"]);
241
        }
242
        
243
        $_fontsOut = '<script data-cfasync="false" type="text/javascript">WebFontConfig={google:{families:[\'';
244
        foreach ($_fontsArray as $_font) {
245
            $_fontsOut .= $_font."','";
246
        }
247
        $_fontsOut = trim(trim($_fontsOut,"'"),",");
248
        $_fontsOut .= '] },classes:false, events:false, timeout:1500};(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>';
249
    }
250
 
251
    // inject in HTML
252
    $out = substr_replace($in, $_fontsOut."<link", strpos($in, "<link"), strlen("<link"));
253
    return $out;
254
}
255
256
function autoptimize_extra_preconnectgooglefonts($in) {
257
    $autoptimize_extra_options = autoptimize_extra_get_options();
258
259
    // preconnect to fonts.gstatic.com speed up download of static font-files
260
    $in[] = "https://fonts.gstatic.com";
261
    if ( $autoptimize_extra_options['autoptimize_extra_radio_field_4'] == "4" ) {
262
        // and more preconnects for webfont.js
263
        $in[] = "https://ajax.googleapis.com";
264
        $in[] = "https://fonts.googleapis.com";
265
    }
266
    return $in;
267
}
268
269
function autoptimize_extra_remove_dns_prefetch( $urls, $relation_type, $_remove_url ) {
270
        if ( 'dns-prefetch' == $relation_type ) {
271
        $_count=0;
272
        foreach ($urls as $_url) {
273
            if ( strpos($_url, $_remove_url) !== false ) {
274
                unset($urls[$_count]);
275
            }
276
            $_count++;
277
        }
278
    }
279
280
    return $urls;
281
}
282
283
/* admin page functions */
284
function autoptimize_extra_admin() { 
285
    add_submenu_page( null, 'autoptimize_extra', 'autoptimize_extra', 'manage_options', 'autoptimize_extra', 'autoptimize_extra_options_page' );
286
    register_setting( 'autoptimize_extra_settings', 'autoptimize_extra_settings' );
287
}
288
289
function add_autoptimize_extra_tab($in) {
290
    $in=array_merge($in,array('autoptimize_extra' => __('Extra','autoptimize')));
291
    return $in;
292
}
293
294
function autoptimize_extra_options_page() { 
295
    $autoptimize_extra_options = autoptimize_extra_get_options();
296
    $_googlef = $autoptimize_extra_options['autoptimize_extra_radio_field_4'];
297
    ?>
298
    <style>
299
        #ao_settings_form {background: white;border: 1px solid #ccc;padding: 1px 15px;margin: 15px 10px 10px 0;}
300
        #ao_settings_form .form-table th {font-weight: 100;}
301
        #autoptimize_extra_descr{font-size: 120%;}
302
    </style>
303
    <div class="wrap">
304
    <h1><?php _e('Autoptimize Settings','autoptimize'); ?></h1>
305
    <?php echo autoptimizeConfig::ao_admin_tabs(); ?>
306
    <form id='ao_settings_form' action='options.php' method='post'>
307
        <?php settings_fields('autoptimize_extra_settings'); ?>
308
        <h2><?php _e('Extra Auto-Optimizations','autoptimize'); ?></h2>
309
        <span id='autoptimize_extra_descr'><?php _e('The following settings can improve your site\'s performance even more.','autoptimize'); ?></span>
310
        <table class="form-table">
311
            <tr>
312
                <th scope="row"><?php _e('Remove emojis','autoptimize'); ?></th>
313
                <td>
314
                    <label><input type='checkbox' name='autoptimize_extra_settings[autoptimize_extra_checkbox_field_1]' <?php if (!empty($autoptimize_extra_options['autoptimize_extra_checkbox_field_1']) && 1 == $autoptimize_extra_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>
315
                </td>
316
            </tr>
317
            <tr>
318
                <th scope="row"><?php _e('Remove query strings from static resources','autoptimize'); ?></th>
319
                <td>
320
                    <label><input type='checkbox' name='autoptimize_extra_settings[autoptimize_extra_checkbox_field_0]' <?php if (!empty( $autoptimize_extra_options['autoptimize_extra_checkbox_field_0']) && 1 == $autoptimize_extra_options['autoptimize_extra_checkbox_field_0']) echo 'checked="checked"'; ?> value='1'><?php _e('Removing query strings (or more specificaly the <code>ver</code> parameter) will not improve load time, but might improve performance scores.','autoptimize'); ?></label>
321
                </td>
322
            </tr>
323
            <tr>
324
                <th scope="row"><?php _e('Google Fonts','autoptimize'); ?></th>
325
                <td>
326
                    <input type="radio" name="autoptimize_extra_settings[autoptimize_extra_radio_field_4]" value="1" <?php if (!in_array($_googlef,array(2,3,4))) {echo "checked"; } ?> ><?php _e('Leave as is','autoptimize'); ?><br/>
327
                    <input type="radio" name="autoptimize_extra_settings[autoptimize_extra_radio_field_4]" value="2" <?php checked(2, $_googlef, true); ?> ><?php _e('Remove Google Fonts','autoptimize'); ?><br/>
328
                    <input type="radio" name="autoptimize_extra_settings[autoptimize_extra_radio_field_4]" value="3" <?php checked(3, $_googlef, true); ?> ><?php _e('Combine and link in head','autoptimize'); ?><br/>
329
                    <input type="radio" name="autoptimize_extra_settings[autoptimize_extra_radio_field_4]" value="4" <?php checked(4, $_googlef, true); ?> ><?php _e('Combine and load fonts asynchronously with <a href="https://github.com/typekit/webfontloader#readme" target="_blank">webfont.js</a>','autoptimize'); ?><br/>
330
                </td>
331
            </tr>
332
            <tr>
333
                <th scope="row"><?php _e('Preconnect to 3rd party domains <em>(advanced users)</em>','autoptimize'); ?></th>
334
                <td>
335
                    <label><input type='text' style='width:80%' name='autoptimize_extra_settings[autoptimize_extra_text_field_2]' value='<?php echo $autoptimize_extra_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>
336
                </td>
337
            </tr>
338
            <tr>
339
                <th scope="row"><?php _e('Async Javascript-files <em>(advanced users)</em>','autoptimize'); ?></th>
340
                <td>
341
                    <input type='text' style='width:80%' name='autoptimize_extra_settings[autoptimize_extra_text_field_3]' value='<?php echo $autoptimize_extra_options['autoptimize_extra_text_field_3']; ?>'>
342
                    <br />
343
                    <?php _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'); ?>
344
                </td>
345
            </tr>
346
        </table>
347
        <p class="submit"><input type="submit" name="submit" id="submit" class="button button-primary" value="Save Changes"  /></p>
348
    </form>
349
    <?php
350
}
351