Completed
Push — add/cxn-tests ( 3fded5...58073e )
by
unknown
28:41 queued 22:02
created

Jetpack_Photon_Static_Assets_CDN::go()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
nc 1
nop 0
dl 0
loc 8
rs 10
c 0
b 0
f 0
1
<?php
2
/**
3
 * Module Name: Asset CDN
4
 * Module Description: Serve static assets from our servers
5
 * Sort Order: 26
6
 * Recommendation Order: 1
7
 * First Introduced: 6.6
8
 * Requires Connection: No
9
 * Auto Activate: No
10
 * Module Tags: Photos and Videos, Appearance, Recommended
11
 * Feature: Recommended, Appearance
12
 * Additional Search Queries: photon, image, cdn, performance, speed, assets
13
 */
14
15
$GLOBALS['concatenate_scripts'] = false;
16
17
Jetpack::dns_prefetch( array(
18
	'//c0.wp.com',
19
) );
20
21
class Jetpack_Photon_Static_Assets_CDN {
22
	const CDN = 'https://c0.wp.com/';
23
24
	/**
25
	 * Sets up action handlers needed for Jetpack CDN.
26
	 */
27
	public static function go() {
28
		add_action( 'wp_print_scripts', array( __CLASS__, 'cdnize_assets' ) );
29
		add_action( 'wp_print_styles', array( __CLASS__, 'cdnize_assets' ) );
30
		add_action( 'admin_print_scripts', array( __CLASS__, 'cdnize_assets' ) );
31
		add_action( 'admin_print_styles', array( __CLASS__, 'cdnize_assets' ) );
32
		add_action( 'wp_footer', array( __CLASS__, 'cdnize_assets' ) );
33
		add_filter( 'load_script_textdomain_relative_path', array( __CLASS__, 'fix_script_relative_path' ), 10, 2 );
34
	}
35
36
	/**
37
	 * Sets up CDN URLs for assets that are enqueued by the WordPress Core.
38
	 */
39
	public static function cdnize_assets() {
40
		global $wp_scripts, $wp_styles, $wp_version;
41
42
		/**
43
		 * Filters Jetpack CDN's Core version number and locale. Can be used to override the values
44
		 * that Jetpack uses to retrieve assets. Expects the values to be returned in an array.
45
		 *
46
		 * @module photon-cdn
47
		 *
48
		 * @since 6.6.0
49
		 *
50
		 * @param array $values array( $version  = core assets version, i.e. 4.9.8, $locale = desired locale )
51
		 */
52
		list( $version, $locale ) = apply_filters(
0 ignored issues
show
Unused Code introduced by
The assignment to $locale is unused. Consider omitting it like so list($first,,$third).

This checks looks for assignemnts to variables using the list(...) function, where not all assigned variables are subsequently used.

Consider the following code example.

<?php

function returnThreeValues() {
    return array('a', 'b', 'c');
}

list($a, $b, $c) = returnThreeValues();

print $a . " - " . $c;

Only the variables $a and $c are used. There was no need to assign $b.

Instead, the list call could have been.

list($a,, $c) = returnThreeValues();
Loading history...
53
			'jetpack_cdn_core_version_and_locale',
54
			array( $wp_version, get_locale() )
55
		);
56
57
		if ( self::is_public_version( $version ) ) {
58
			$site_url = trailingslashit( site_url() );
59 View Code Duplication
			foreach ( $wp_scripts->registered as $handle => $thing ) {
60
				if ( wp_startswith( $thing->src, self::CDN ) ) {
61
					continue;
62
				}
63
				$src = ltrim( str_replace( $site_url, '', $thing->src ), '/' );
64
				if ( self::is_js_or_css_file( $src ) && in_array( substr( $src, 0, 9 ), array( 'wp-admin/', 'wp-includ' ) ) ) {
65
					$wp_scripts->registered[ $handle ]->src = sprintf( self::CDN . 'c/%1$s/%2$s', $version, $src );
66
					$wp_scripts->registered[ $handle ]->ver = null;
67
				}
68
			}
69 View Code Duplication
			foreach ( $wp_styles->registered as $handle => $thing ) {
70
				if ( wp_startswith( $thing->src, self::CDN ) ) {
71
					continue;
72
				}
73
				$src = ltrim( str_replace( $site_url, '', $thing->src ), '/' );
74
				if ( self::is_js_or_css_file( $src ) && in_array( substr( $src, 0, 9 ), array( 'wp-admin/', 'wp-includ' ) ) ) {
75
					$wp_styles->registered[ $handle ]->src = sprintf( self::CDN . 'c/%1$s/%2$s', $version, $src );
76
					$wp_styles->registered[ $handle ]->ver = null;
77
				}
78
			}
79
		}
80
81
		self::cdnize_plugin_assets( 'jetpack', JETPACK__VERSION );
82
		if ( class_exists( 'WooCommerce' ) ) {
83
			self::cdnize_plugin_assets( 'woocommerce', WC_VERSION );
84
		}
85
	}
86
87
	/**
88
	 * Ensure use of the correct relative path when determining the JavaScript file names.
89
	 *
90
	 * @param string $relative The relative path of the script. False if it could not be determined.
91
	 * @param string $src      The full source url of the script.
92
	 * @return string The expected relative path for the CDN-ed URL.
93
	 */
94
	public static function fix_script_relative_path( $relative, $src ) {
95
		$strpos = strpos( $src, '/wp-includes/' );
96
97
		// We only treat URLs that have wp-includes in them. Cases like language textdomains
98
		// can also use this filter, they don't need to be touched because they are local paths.
99
		if ( false === $strpos ) {
100
			return $relative;
101
		}
102
		return substr( $src, 1 + $strpos );
103
	}
104
105
	/**
106
	 * Sets up CDN URLs for supported plugin assets.
107
	 *
108
	 * @param String $plugin_slug plugin slug string.
109
	 * @param String $current_version plugin version string.
110
	 * @return null|bool
111
	 */
112
	public static function cdnize_plugin_assets( $plugin_slug, $current_version ) {
113
		global $wp_scripts, $wp_styles;
114
115
		/**
116
		 * Filters Jetpack CDN's plugin slug and version number. Can be used to override the values
117
		 * that Jetpack uses to retrieve assets. For example, when testing a development version of Jetpack
118
		 * the assets are not yet published, so you may need to override the version value to either
119
		 * trunk, or the latest available version. Expects the values to be returned in an array.
120
		 *
121
		 * @module photon-cdn
122
		 *
123
		 * @since 6.6.0
124
		 *
125
		 * @param array $values array( $slug = the plugin repository slug, i.e. jetpack, $version = the plugin version, i.e. 6.6 )
126
		 */
127
		list( $plugin_slug, $current_version ) = apply_filters(
128
			'jetpack_cdn_plugin_slug_and_version',
129
			array( $plugin_slug, $current_version )
130
		);
131
132
		$assets               = self::get_plugin_assets( $plugin_slug, $current_version );
133
		$plugin_directory_url = plugins_url() . '/' . $plugin_slug . '/';
134
135
		if ( is_wp_error( $assets ) || ! is_array( $assets ) ) {
136
			return false;
137
		}
138
139 View Code Duplication
		foreach ( $wp_scripts->registered as $handle => $thing ) {
140
			if ( wp_startswith( $thing->src, self::CDN ) ) {
141
				continue;
142
			}
143
			if ( wp_startswith( $thing->src, $plugin_directory_url ) ) {
144
				$local_path = substr( $thing->src, strlen( $plugin_directory_url ) );
145
				if ( in_array( $local_path, $assets, true ) ) {
146
					$wp_scripts->registered[ $handle ]->src = sprintf( self::CDN . 'p/%1$s/%2$s/%3$s', $plugin_slug, $current_version, $local_path );
147
					$wp_scripts->registered[ $handle ]->ver = null;
148
				}
149
			}
150
		}
151 View Code Duplication
		foreach ( $wp_styles->registered as $handle => $thing ) {
152
			if ( wp_startswith( $thing->src, self::CDN ) ) {
153
				continue;
154
			}
155
			if ( wp_startswith( $thing->src, $plugin_directory_url ) ) {
156
				$local_path = substr( $thing->src, strlen( $plugin_directory_url ) );
157
				if ( in_array( $local_path, $assets, true ) ) {
158
					$wp_styles->registered[ $handle ]->src = sprintf( self::CDN . 'p/%1$s/%2$s/%3$s', $plugin_slug, $current_version, $local_path );
159
					$wp_styles->registered[ $handle ]->ver = null;
160
				}
161
			}
162
		}
163
	}
164
165
	/**
166
	 * Returns cdn-able assets for a given plugin.
167
	 *
168
	 * @param string $plugin plugin slug string.
169
	 * @param string $version plugin version number string.
170
	 * @return array|bool Will return false if not a public version.
171
	 */
172
	public static function get_plugin_assets( $plugin, $version ) {
173
		if ( 'jetpack' === $plugin && JETPACK__VERSION === $version ) {
174
			if ( ! self::is_public_version( $version ) ) {
175
				return false;
176
			}
177
178
			$assets = array(); // The variable will be redefined in the included file.
179
180
			include JETPACK__PLUGIN_DIR . 'modules/photon-cdn/jetpack-manifest.php';
181
			return $assets;
182
		}
183
184
		/**
185
		 * Used for other plugins to provide their bundled assets via filter to
186
		 * prevent the need of storing them in an option or an external api request
187
		 * to w.org.
188
		 *
189
		 * @module photon-cdn
190
		 *
191
		 * @since 6.6.0
192
		 *
193
		 * @param array $assets The assets array for the plugin.
194
		 * @param string $version The version of the plugin being requested.
195
		 */
196
		$assets = apply_filters( "jetpack_cdn_plugin_assets-{$plugin}", null, $version );
197
		if ( is_array( $assets ) ) {
198
			return $assets;
199
		}
200
201
		if ( ! self::is_public_version( $version ) ) {
202
			return false;
203
		}
204
205
		$cache = Jetpack_Options::get_option( 'static_asset_cdn_files', array() );
206
		if ( isset( $cache[ $plugin ][ $version ] ) ) {
207
			if ( is_array( $cache[ $plugin ][ $version ] ) ) {
208
				return $cache[ $plugin ][ $version ];
209
			}
210
			if ( is_numeric( $cache[ $plugin ][ $version ] ) ) {
211
				// Cache an empty result for up to 24h.
212
				if ( intval( $cache[ $plugin ][ $version ] ) + DAY_IN_SECONDS > time() ) {
213
					return array();
214
				}
215
			}
216
		}
217
218
		$url = sprintf( 'http://downloads.wordpress.org/plugin-checksums/%s/%s.json', $plugin, $version );
219
220
		if ( wp_http_supports( array( 'ssl' ) ) ) {
221
			$url = set_url_scheme( $url, 'https' );
222
		}
223
224
		$response = wp_remote_get( $url );
225
226
		$body = trim( wp_remote_retrieve_body( $response ) );
227
		$body = json_decode( $body, true );
228
229
		$return = time();
230
		if ( is_array( $body ) ) {
231
			$return = array_filter( array_keys( $body['files'] ), array( __CLASS__, 'is_js_or_css_file' ) );
232
		}
233
234
		$cache[ $plugin ]             = array();
235
		$cache[ $plugin ][ $version ] = $return;
236
		Jetpack_Options::update_option( 'static_asset_cdn_files', $cache, true );
0 ignored issues
show
Documentation introduced by
true is of type boolean, but the function expects a string|null.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
237
238
		return $return;
239
	}
240
241
	/**
242
	 * Checks a path whether it is a JS or CSS file.
243
	 *
244
	 * @param String $path file path.
245
	 * @return Boolean whether the file is a JS or CSS.
246
	 */
247
	public static function is_js_or_css_file( $path ) {
248
		return ( false === strpos( $path, '?' ) ) && in_array( substr( $path, -3 ), array( 'css', '.js' ), true );
249
	}
250
251
	/**
252
	 * Checks whether the version string indicates a production version.
253
	 *
254
	 * @param String  $version the version string.
255
	 * @param Boolean $include_beta_and_rc whether to count beta and RC versions as production.
256
	 * @return Boolean
257
	 */
258
	public static function is_public_version( $version, $include_beta_and_rc = false ) {
259
		if ( preg_match( '/^\d+(\.\d+)+$/', $version ) ) {
260
			// matches `1` `1.2` `1.2.3`.
261
			return true;
262
		} elseif ( $include_beta_and_rc && preg_match( '/^\d+(\.\d+)+(-(beta|rc|pressable)\d?)$/i', $version ) ) {
263
			// matches `1.2.3` `1.2.3-beta` `1.2.3-pressable` `1.2.3-beta1` `1.2.3-rc` `1.2.3-rc2`.
264
			return true;
265
		}
266
		// unrecognized version.
267
		return false;
268
	}
269
}
270
/**
271
 * Allow plugins to short-circuit the Asset CDN, even when the module is on.
272
 *
273
 * @module photon-cdn
274
 *
275
 * @since 6.7.0
276
 *
277
 * @param false bool Should the Asset CDN be blocked? False by default.
278
 */
279
if ( true !== apply_filters( 'jetpack_force_disable_site_accelerator', false ) ) {
280
	Jetpack_Photon_Static_Assets_CDN::go();
281
}
282