Completed
Push — renovate/babel-plugin-add-modu... ( 6e5406...4d1bee )
by
unknown
06:36
created

Jetpack_Lazy_Images::add_image_placeholders()   A

Complexity

Conditions 5
Paths 4

Size

Total Lines 21

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 5
nc 4
nop 1
dl 0
loc 21
rs 9.2728
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 ( Jetpack_AMP_Support::is_amp_request() ) {
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
174
		// If we didn't add lazy attributes, just return the original image source.
175
		if ( ! empty( $old_attributes['class'] ) && false !== strpos( $old_attributes['class'], 'jetpack-lazy-image' ) ) {
176
			return $matches[0];
177
		}
178
179
		$new_attributes     = self::process_image_attributes( $old_attributes );
180
		$new_attributes_str = self::build_attributes_string( $new_attributes );
181
182
		return sprintf( '<img %1$s><noscript>%2$s</noscript>', $new_attributes_str, $matches[0] );
183
	}
184
185
	/**
186
	 * Given an array of image attributes, updates the `src`, `srcset`, and `sizes` attributes so
187
	 * that they load lazily.
188
	 *
189
	 * @since 5.7.0
190
	 *
191
	 * @param array $attributes
192
	 *
193
	 * @return array The updated image attributes array with lazy load attributes
194
	 */
195
	static function process_image_attributes( $attributes ) {
196
		if ( empty( $attributes['src'] ) ) {
197
			return $attributes;
198
		}
199
200
		if ( ! empty( $attributes['class'] ) && self::should_skip_image_with_blacklisted_class( $attributes['class'] ) ) {
201
			return $attributes;
202
		}
203
204
		/**
205
		 * Allow plugins and themes to conditionally skip processing an image via its attributes.
206
		 *
207
		 * @module-lazy-images
208
		 *
209
		 * @deprecated 6.5.0 Use jetpack_lazy_images_skip_image_with_attributes instead.
210
		 *
211
		 * @since 5.9.0
212
		 *
213
		 * @param bool  Default to not skip processing the current image.
214
		 * @param array An array of attributes via wp_kses_hair() for the current image.
215
		 */
216
		if ( apply_filters( 'jetpack_lazy_images_skip_image_with_atttributes', false, $attributes ) ) {
217
			return $attributes;
218
		}
219
220
		/**
221
		 * Allow plugins and themes to conditionally skip processing an image via its attributes.
222
		 *
223
		 * @module-lazy-images
224
		 *
225
		 * @since 6.5.0 Filter name was updated from jetpack_lazy_images_skip_image_with_atttributes to correct typo.
226
		 * @since 5.9.0
227
		 *
228
		 * @param bool  Default to not skip processing the current image.
229
		 * @param array An array of attributes via wp_kses_hair() for the current image.
230
		 */
231
		if ( apply_filters( 'jetpack_lazy_images_skip_image_with_attributes', false, $attributes ) ) {
232
			return $attributes;
233
		}
234
235
		$old_attributes = $attributes;
236
237
		// Stash srcset and sizes in data attributes.
238
		foreach ( array( 'srcset', 'sizes' ) as $attribute ) {
239
			if ( isset( $old_attributes[ $attribute ] ) ) {
240
				$attributes[ "data-lazy-$attribute" ] = $old_attributes[ $attribute ];
241
				unset( $attributes[ $attribute ] );
242
			}
243
		}
244
245
		// We set this, adding the query arg so that it doesn't exactly equal the src attribute, so that photon JavaScript
246
		// will hold off on processing this image.
247
		$attributes['data-lazy-src'] = esc_url_raw( add_query_arg( 'is-pending-load', true, $attributes['src'] ) );
248
249
		$attributes['srcset'] = self::get_placeholder_image();
250
		$attributes['class']  = sprintf(
251
			'%s jetpack-lazy-image',
252
			empty( $old_attributes['class'] )
253
				? ''
254
				: $old_attributes['class']
255
		);
256
257
		/**
258
		 * Allow plugins and themes to override the attributes on the image before the content is updated.
259
		 *
260
		 * One potential use of this filter is for themes that set `height:auto` on the `img` tag.
261
		 * With this filter, the theme could get the width and height attributes from the
262
		 * $attributes array and then add a style tag that sets those values as well, which could
263
		 * minimize reflow as images load.
264
		 *
265
		 * @module lazy-images
266
		 *
267
		 * @since 5.6.0
268
		 *
269
		 * @param array An array containing the attributes for the image, where the key is the attribute name
270
		 *              and the value is the attribute value.
271
		 */
272
		return apply_filters( 'jetpack_lazy_images_new_attributes', $attributes );
273
	}
274
275
	/**
276
	 * Adds JavaScript to check if the current browser supports JavaScript as well as some styles to hide lazy
277
	 * images when the browser does not support JavaScript.
278
	 *
279
	 * @return void
280
	 */
281
	public function add_nojs_fallback() {
282
		?>
283
			<style type="text/css">
284
				html:not( .jetpack-lazy-images-js-enabled ) .jetpack-lazy-image {
285
					display: none;
286
				}
287
			</style>
288
			<script>
289
				document.documentElement.classList.add(
290
					'jetpack-lazy-images-js-enabled'
291
				);
292
			</script>
293
		<?php
294
	}
295
296
	/**
297
	 * Retrieves the placeholder image after running it through the lazyload_images_placeholder_image filter.
298
	 *
299
	 * @return string The placeholder image source.
300
	 */
301
	private static function get_placeholder_image() {
302
		/**
303
		 * Allows plugins and themes to modify the placeholder image.
304
		 *
305
		 * This filter is not prefixed with jetpack_ to provide a smoother migration
306
		 * process from the WordPress Lazy Load plugin.
307
		 *
308
		 * @module lazy-images
309
		 *
310
		 * @since 5.6.0
311
		 * @since 6.5.0 Default image is now a base64 encoded transparent gif.
312
		 *
313
		 * @param string The URL to the placeholder image
314
		 */
315
		return apply_filters(
316
			'lazyload_images_placeholder_image',
317
			'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7'
318
		);
319
	}
320
321
	private static function flatten_kses_hair_data( $attributes ) {
322
		$flattened_attributes = array();
323
		foreach ( $attributes as $name => $attribute ) {
324
			$flattened_attributes[ $name ] = $attribute['value'];
325
		}
326
		return $flattened_attributes;
327
	}
328
329
	private static function build_attributes_string( $attributes ) {
330
		$string = array();
331
		foreach ( $attributes as $name => $value ) {
332
			if ( '' === $value ) {
333
				$string[] = sprintf( '%s', $name );
334
			} else {
335
				$string[] = sprintf( '%s="%s"', $name, esc_attr( $value ) );
336
			}
337
		}
338
		return implode( ' ', $string );
339
	}
340
341 View Code Duplication
	public function enqueue_assets() {
342
		if ( Jetpack_AMP_Support::is_amp_request() ) {
343
			return;
344
		}
345
		wp_enqueue_script(
346
			'jetpack-lazy-images',
347
			Jetpack::get_file_url_for_environment(
348
				'_inc/build/lazy-images/js/lazy-images.min.js',
349
				'modules/lazy-images/js/lazy-images.js'
350
			),
351
			array( 'jquery' ),
352
			JETPACK__VERSION,
353
			true
354
		);
355
	}
356
}
357