Completed
Push — update/lazy-images-no-js-css-f... ( 246952...b9f95c )
by
unknown
28:31 queued 18:57
created

Jetpack_Lazy_Images::add_nojs_body_class()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 4

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
nc 1
nop 1
dl 0
loc 4
rs 10
c 0
b 0
f 0
1
<?php
2
3
class Jetpack_Lazy_Images {
4
	private static $__instance = null;
5
6
	/**
7
	 * Singleton implementation
8
	 *
9
	 * @return object
10
	 */
11
	public static function instance() {
12
		if ( is_null( self::$__instance ) ) {
13
			self::$__instance = new Jetpack_Lazy_Images();
14
		}
15
16
		return self::$__instance;
17
	}
18
19
	/**
20
	 * Registers actions
21
	 */
22
	private function __construct() {
23
		if ( is_admin() ) {
24
			return;
25
		}
26
27
		/**
28
		 * Whether the lazy-images module should load.
29
		 *
30
		 * This filter is not prefixed with jetpack_ to provide a smoother migration
31
		 * process from the WordPress Lazy Load plugin.
32
		 *
33
		 * @module lazy-images
34
		 *
35
		 * @since 5.6.0
36
		 *
37
		 * @param bool true Whether lazy image loading should occur.
38
		 */
39
		if ( ! apply_filters( 'lazyload_is_enabled', true ) ) {
40
			return;
41
		}
42
43
		add_action( 'wp_head', array( $this, 'setup_filters' ), 9999 ); // we don't really want to modify anything in <head> since it's mostly all metadata
44
		add_action( 'wp_enqueue_scripts', array( $this, 'enqueue_assets' ) );
45
46
		// Do not lazy load avatar in admin bar
47
		add_action( 'admin_bar_menu', array( $this, 'remove_filters' ), 0 );
48
49
		add_filter( 'wp_kses_allowed_html', array( $this, 'allow_lazy_attributes' ) );
50
		add_action( 'wp_head', array( $this, 'add_nojs_fallback' ) );
51
	}
52
53 View Code Duplication
	public function setup_filters() {
54
		add_filter( 'the_content', array( $this, 'add_image_placeholders' ), PHP_INT_MAX ); // run this later, so other content filters have run, including image_add_wh on WP.com
55
		add_filter( 'post_thumbnail_html', array( $this, 'add_image_placeholders' ), PHP_INT_MAX );
56
		add_filter( 'get_avatar', array( $this, 'add_image_placeholders' ), PHP_INT_MAX );
57
		add_filter( 'widget_text', array( $this, 'add_image_placeholders' ), PHP_INT_MAX );
58
		add_filter( 'get_image_tag', array( $this, 'add_image_placeholders' ), PHP_INT_MAX);
59
		add_filter( 'wp_get_attachment_image_attributes', array( __CLASS__, 'process_image_attributes' ), PHP_INT_MAX );
60
	}
61
62 View Code Duplication
	public function remove_filters() {
63
		remove_filter( 'the_content', array( $this, 'add_image_placeholders' ), PHP_INT_MAX );
64
		remove_filter( 'post_thumbnail_html', array( $this, 'add_image_placeholders' ), PHP_INT_MAX );
65
		remove_filter( 'get_avatar', array( $this, 'add_image_placeholders' ), PHP_INT_MAX );
66
		remove_filter( 'widget_text', array( $this, 'add_image_placeholders' ), PHP_INT_MAX );
67
		remove_filter( 'get_image_tag', array( $this, 'add_image_placeholders' ), PHP_INT_MAX);
68
		remove_filter( 'wp_get_attachment_image_attributes', array( __CLASS__, 'process_image_attributes' ), PHP_INT_MAX );
69
	}
70
71
	/**
72
	 * Ensure that our lazy image attributes are not filtered out of image tags.
73
	 *
74
	 * @param array $allowed_tags The allowed tags and their attributes.
75
	 * @return array
76
	 */
77
	public function allow_lazy_attributes( $allowed_tags ) {
78
		if ( ! isset( $allowed_tags['img'] ) ) {
79
			return $allowed_tags;
80
		}
81
82
		// But, if images are allowed, ensure that our attributes are allowed!
83
		$img_attributes = array_merge( $allowed_tags['img'], array(
84
			'data-lazy-src' => 1,
85
			'data-lazy-srcset' => 1,
86
			'data-lazy-sizes' => 1,
87
		) );
88
89
		$allowed_tags['img'] = $img_attributes;
90
91
		return $allowed_tags;
92
	}
93
94
	public function add_image_placeholders( $content ) {
95
		// Don't lazyload for feeds, previews
96
		if ( is_feed() || is_preview() ) {
97
			return $content;
98
		}
99
100
		// Don't lazy-load if the content has already been run through previously
101
		if ( false !== strpos( $content, 'data-lazy-src' ) ) {
102
			return $content;
103
		}
104
105
		// Don't lazyload for amp-wp content
106
		if ( function_exists( 'is_amp_endpoint' ) && is_amp_endpoint() ) {
107
			return $content;
108
		}
109
110
		// This is a pretty simple regex, but it works
111
		$content = preg_replace_callback( '#<(img)([^>]+?)(>(.*?)</\\1>|[\/]?>)#si', array( __CLASS__, 'process_image' ), $content );
112
113
		return $content;
114
	}
115
116
	/**
117
	 * Returns true when a given string of classes contains a class signifying lazy images
118
	 * should not process the image.
119
	 *
120
	 * @since 5.9.0
121
	 *
122
	 * @param string $classes A string of space-separated classes.
123
	 * @return bool
124
	 */
125
	public static function should_skip_image_with_blacklisted_class( $classes ) {
126
		$blacklisted_classes = array(
127
			'skip-lazy',
128
			'gazette-featured-content-thumbnail',
129
		);
130
131
		/**
132
		 * Allow plugins and themes to tell lazy images to skip an image with a given class.
133
		 *
134
		 * @module lazy-images
135
		 *
136
		 * @since 5.9.0
137
		 *
138
		 * @param array An array of strings where each string is a class.
139
		 */
140
		$blacklisted_classes = apply_filters( 'jetpack_lazy_images_blacklisted_classes', $blacklisted_classes );
141
142
		if ( ! is_array( $blacklisted_classes ) || empty( $blacklisted_classes ) ) {
143
			return false;
144
		}
145
146
		foreach ( $blacklisted_classes as $class ) {
147
			if ( false !== strpos( $classes, $class ) ) {
148
				return true;
149
			}
150
		}
151
152
		return false;
153
	}
154
155
	/**
156
	 * Processes images in content by acting as the preg_replace_callback
157
	 *
158
	 * @since 5.6.0
159
	 *
160
	 * @param array $matches
161
	 *
162
	 * @return string The image with updated lazy attributes
163
	 */
164
	static function process_image( $matches ) {
165
		$old_attributes_str = $matches[2];
166
		$old_attributes_kses_hair = wp_kses_hair( $old_attributes_str, wp_allowed_protocols() );
167
168
		if ( empty( $old_attributes_kses_hair['src'] ) ) {
169
			return $matches[0];
170
		}
171
172
		$old_attributes = self::flatten_kses_hair_data( $old_attributes_kses_hair );
173
		$new_attributes = self::process_image_attributes( $old_attributes );
174
175
		// If we didn't add lazy attributes, just return the original image source.
176
		if ( empty( $new_attributes['data-lazy-src'] ) ) {
177
			return $matches[0];
178
		}
179
180
		// Ensure we add the jetpack-lazy-image class to this image.
181
		$new_attributes['class'] = sprintf( '%s jetpack-lazy-image', empty( $new_attributes['class'] ) ? '' : $new_attributes['class'] );
182
183
		$new_attributes_str = self::build_attributes_string( $new_attributes );
184
185
		return sprintf( '<img %1$s><noscript>%2$s</noscript>', $new_attributes_str, $matches[0] );
186
	}
187
188
	/**
189
	 * Given an array of image attributes, updates the `src`, `srcset`, and `sizes` attributes so
190
	 * that they load lazily.
191
	 *
192
	 * @since 5.7.0
193
	 *
194
	 * @param array $attributes
195
	 *
196
	 * @return array The updated image attributes array with lazy load attributes
197
	 */
198
	static function process_image_attributes( $attributes ) {
199
		if ( empty( $attributes['src'] ) ) {
200
			return $attributes;
201
		}
202
203
		if ( ! empty( $attributes['class'] ) && self::should_skip_image_with_blacklisted_class( $attributes['class'] ) ) {
204
			return $attributes;
205
		}
206
207
		/**
208
		 * Allow plugins and themes to conditionally skip processing an image via its attributes.
209
		 *
210
		 * @module-lazy-images
211
		 *
212
		 * @since 5.9.0
213
		 *
214
		 * @param bool  Default to not skip processing the current image.
215
		 * @param array An array of attributes via wp_kses_hair() for the current image.
216
		 */
217
		if ( apply_filters( 'jetpack_lazy_images_skip_image_with_atttributes', false, $attributes ) ) {
218
			return $attributes;
219
		}
220
221
		$old_attributes = $attributes;
222
223
		// Set placeholder and lazy-src
224
		$attributes['src'] = self::get_placeholder_image();
225
		$attributes['data-lazy-src'] = $old_attributes['src'];
226
227
		// Handle `srcset`
228
		if ( ! empty( $attributes['srcset'] ) ) {
229
			$attributes['data-lazy-srcset'] = $old_attributes['srcset'];
230
			unset( $attributes['srcset'] );
231
		}
232
233
		// Handle `sizes`
234
		if ( ! empty( $attributes['sizes'] ) ) {
235
			$attributes['data-lazy-sizes'] = $old_attributes['sizes'];
236
			unset( $attributes['sizes'] );
237
		}
238
239
		/**
240
		 * Allow plugins and themes to override the attributes on the image before the content is updated.
241
		 *
242
		 * One potential use of this filter is for themes that set `height:auto` on the `img` tag.
243
		 * With this filter, the theme could get the width and height attributes from the
244
		 * $attributes array and then add a style tag that sets those values as well, which could
245
		 * minimize reflow as images load.
246
		 *
247
		 * @module lazy-images
248
		 *
249
		 * @since 5.6.0
250
		 *
251
		 * @param array An array containing the attributes for the image, where the key is the attribute name
252
		 *              and the value is the attribute value.
253
		 */
254
		return apply_filters( 'jetpack_lazy_images_new_attributes', $attributes );
255
	}
256
257
	/**
258
	 * Adds JavaScript to check if the current browser supports JavaScript as well as some styles to hide lazy
259
	 * images when the browser does not support JavaScript.
260
	 *
261
	 * @return void
262
	 */
263
	public function add_nojs_fallback() {
264
		?>
265
			<style type="text/css">
266
				html:not( .jetpack-lazy-images-js-enabled ) .jetpack-lazy-image {
267
					display: none;
268
				}
269
			</style>
270
			<script>
271
				document.documentElement.classList.add(
272
					'jetpack-lazy-images-js-enabled'
273
				);
274
			</script>
275
		<?php
276
	}
277
278
	private static function get_placeholder_image() {
279
		/**
280
		 * Allows plugins and themes to modify the placeholder image.
281
		 *
282
		 * This filter is not prefixed with jetpack_ to provide a smoother migration
283
		 * process from the WordPress Lazy Load plugin.
284
		 *
285
		 * @module lazy-images
286
		 *
287
		 * @since 5.6.0
288
		 *
289
		 * @param string The URL to the placeholder image
290
		 */
291
		return apply_filters(
292
			'lazyload_images_placeholder_image',
293
			plugins_url( 'modules/lazy-images/images/1x1.trans.gif', JETPACK__PLUGIN_FILE )
294
		);
295
	}
296
297
	private static function flatten_kses_hair_data( $attributes ) {
298
		$flattened_attributes = array();
299
		foreach ( $attributes as $name => $attribute ) {
300
			$flattened_attributes[ $name ] = $attribute['value'];
301
		}
302
		return $flattened_attributes;
303
	}
304
305
	private static function build_attributes_string( $attributes ) {
306
		$string = array();
307
		foreach ( $attributes as $name => $value ) {
308
			if ( '' === $value ) {
309
				$string[] = sprintf( '%s', $name );
310
			} else {
311
				$string[] = sprintf( '%s="%s"', $name, esc_attr( $value ) );
312
			}
313
		}
314
		return implode( ' ', $string );
315
	}
316
317 View Code Duplication
	public function enqueue_assets() {
318
		if ( Jetpack_AMP_Support::is_amp_request() ) {
319
			return;
320
		}
321
		wp_enqueue_script(
322
			'jetpack-lazy-images',
323
			Jetpack::get_file_url_for_environment(
324
				'_inc/build/lazy-images/js/lazy-images.min.js',
325
				'modules/lazy-images/js/lazy-images.js'
326
			),
327
			array( 'jquery' ),
328
			JETPACK__VERSION,
329
			true
330
		);
331
	}
332
}
333