Completed
Push — branch-5.8-built ( 327068...93ad53 )
by
unknown
83:37 queued 74:56
created

Jetpack_Lazy_Images::allow_lazy_attributes()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 16
Code Lines 9

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 9
nc 2
nop 1
dl 0
loc 16
rs 9.4285
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
	}
51
52 View Code Duplication
	public function setup_filters() {
53
		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
54
		add_filter( 'post_thumbnail_html', array( $this, 'add_image_placeholders' ), PHP_INT_MAX );
55
		add_filter( 'get_avatar', array( $this, 'add_image_placeholders' ), PHP_INT_MAX );
56
		add_filter( 'widget_text', array( $this, 'add_image_placeholders' ), PHP_INT_MAX );
57
		add_filter( 'get_image_tag', array( $this, 'add_image_placeholders' ), PHP_INT_MAX);
58
		add_filter( 'wp_get_attachment_image_attributes', array( __CLASS__, 'process_image_attributes' ), PHP_INT_MAX );
59
	}
60
61 View Code Duplication
	public function remove_filters() {
62
		remove_filter( 'the_content', array( $this, 'add_image_placeholders' ), PHP_INT_MAX );
63
		remove_filter( 'post_thumbnail_html', array( $this, 'add_image_placeholders' ), PHP_INT_MAX );
64
		remove_filter( 'get_avatar', array( $this, 'add_image_placeholders' ), PHP_INT_MAX );
65
		remove_filter( 'widget_text', array( $this, 'add_image_placeholders' ), PHP_INT_MAX );
66
		remove_filter( 'get_image_tag', array( $this, 'add_image_placeholders' ), PHP_INT_MAX);
67
		remove_filter( 'wp_get_attachment_image_attributes', array( __CLASS__, 'process_image_attributes' ), PHP_INT_MAX );
68
	}
69
70
	/**
71
	 * Ensure that our lazy image attributes are not filtered out of image tags.
72
	 *
73
	 * @param array $allowed_tags The allowed tags and their attributes.
74
	 * @return array
75
	 */
76
	public function allow_lazy_attributes( $allowed_tags ) {
77
		if ( ! isset( $allowed_tags['img'] ) ) {
78
			return $allowed_tags;
79
		}
80
81
		// But, if images are allowed, ensure that our attributes are allowed!
82
		$img_attributes = array_merge( $allowed_tags['img'], array(
83
			'data-lazy-src' => 1,
84
			'data-lazy-srcset' => 1,
85
			'data-lazy-sizes' => 1,
86
		) );
87
88
		$allowed_tags['img'] = $img_attributes;
89
90
		return $allowed_tags;
91
	}
92
93
	public function add_image_placeholders( $content ) {
94
		// Don't lazyload for feeds, previews
95
		if ( is_feed() || is_preview() ) {
96
			return $content;
97
		}
98
99
		// Don't lazy-load if the content has already been run through previously
100
		if ( false !== strpos( $content, 'data-lazy-src' ) ) {
101
			return $content;
102
		}
103
104
		// Don't lazyload for amp-wp content
105
		if ( function_exists( 'is_amp_endpoint' ) && is_amp_endpoint() ) {
106
			return $content;
107
		}
108
109
		// This is a pretty simple regex, but it works
110
		$content = preg_replace_callback( '#<(img)([^>]+?)(>(.*?)</\\1>|[\/]?>)#si', array( __CLASS__, 'process_image' ), $content );
111
112
		return $content;
113
	}
114
115
	/**
116
	 * Processes images in content by acting as the preg_replace_callback
117
	 *
118
	 * @since 5.6.0
119
	 *
120
	 * @param array $matches
121
	 *
122
	 * @return string The image with updated lazy attributes
123
	 */
124
	static function process_image( $matches ) {
125
		$old_attributes_str = $matches[2];
126
		$old_attributes_kses_hair = wp_kses_hair( $old_attributes_str, wp_allowed_protocols() );
127
128
		if ( empty( $old_attributes_kses_hair['src'] ) ) {
129
			return $matches[0];
130
		}
131
132
		$old_attributes = self::flatten_kses_hair_data( $old_attributes_kses_hair );
133
		$new_attributes = self::process_image_attributes( $old_attributes );
134
		$new_attributes_str = self::build_attributes_string( $new_attributes );
135
136
		return sprintf( '<img %1$s><noscript>%2$s</noscript>', $new_attributes_str, $matches[0] );
137
	}
138
139
	/**
140
	 * Given an array of image attributes, updates the `src`, `srcset`, and `sizes` attributes so
141
	 * that they load lazily.
142
	 *
143
	 * @since 5.7.0
144
	 *
145
	 * @param array $attributes
146
	 *
147
	 * @return array The updated image attributes array with lazy load attributes
148
	 */
149
	static function process_image_attributes( $attributes ) {
150
		if ( empty( $attributes['src'] ) ) {
151
			return $attributes;
152
		}
153
154
		// check for gazette featured images, which are incompatible
155
		if ( isset( $attributes['class'] ) && false !== strpos( $attributes['class'], 'gazette-featured-content-thumbnail' ) ) {
156
			return $attributes;
157
		}
158
159
		$old_attributes = $attributes;
160
161
		// Set placeholder and lazy-src
162
		$attributes['src'] = self::get_placeholder_image();
163
		$attributes['data-lazy-src'] = $old_attributes['src'];
164
165
		// Handle `srcset`
166
		if ( ! empty( $attributes['srcset'] ) ) {
167
			$attributes['data-lazy-srcset'] = $old_attributes['srcset'];
168
			unset( $attributes['srcset'] );
169
		}
170
171
		// Handle `sizes`
172
		if ( ! empty( $attributes['sizes'] ) ) {
173
			$attributes['data-lazy-sizes'] = $old_attributes['sizes'];
174
			unset( $attributes['sizes'] );
175
		}
176
177
		/**
178
		 * Allow plugins and themes to override the attributes on the image before the content is updated.
179
		 *
180
		 * One potential use of this filter is for themes that set `height:auto` on the `img` tag.
181
		 * With this filter, the theme could get the width and height attributes from the
182
		 * $attributes array and then add a style tag that sets those values as well, which could
183
		 * minimize reflow as images load.
184
		 *
185
		 * @module lazy-images
186
		 *
187
		 * @since 5.6.0
188
		 *
189
		 * @param array An array containing the attributes for the image, where the key is the attribute name
190
		 *              and the value is the attribute value.
191
		 */
192
		return apply_filters( 'jetpack_lazy_images_new_attributes', $attributes );
193
	}
194
195
	private static function get_placeholder_image() {
196
		/**
197
		 * Allows plugins and themes to modify the placeholder image.
198
		 *
199
		 * This filter is not prefixed with jetpack_ to provide a smoother migration
200
		 * process from the WordPress Lazy Load plugin.
201
		 *
202
		 * @module lazy-images
203
		 *
204
		 * @since 5.6.0
205
		 *
206
		 * @param string The URL to the placeholder image
207
		 */
208
		return apply_filters(
209
			'lazyload_images_placeholder_image',
210
			plugins_url( 'modules/lazy-images/images/1x1.trans.gif', JETPACK__PLUGIN_FILE )
211
		);
212
	}
213
214
	private static function flatten_kses_hair_data( $attributes ) {
215
		$flattened_attributes = array();
216
		foreach ( $attributes as $name => $attribute ) {
217
			$flattened_attributes[ $name ] = $attribute['value'];
218
		}
219
		return $flattened_attributes;
220
	}
221
222
	private static function build_attributes_string( $attributes ) {
223
		$string = array();
224
		foreach ( $attributes as $name => $value ) {
225
			if ( '' === $value ) {
226
				$string[] = sprintf( '%s', $name );
227
			} else {
228
				$string[] = sprintf( '%s="%s"', $name, esc_attr( $value ) );
229
			}
230
		}
231
		return implode( ' ', $string );
232
	}
233
234
	public function enqueue_assets() {
235
		wp_enqueue_script(
236
			'jetpack-lazy-images',
237
			Jetpack::get_file_url_for_environment(
238
				'_inc/build/lazy-images/js/lazy-images.min.js',
239
				'modules/lazy-images/js/lazy-images.js'
240
			),
241
			array( 'jquery' ),
242
			JETPACK__VERSION,
243
			true
244
		);
245
	}
246
}
247