Completed
Push — master ( 62d0c5...6852ce )
by
unknown
03:03
created

Images_Via_Imgix::prefetch_cdn()   A

Complexity

Conditions 2
Paths 2

Size

Total Lines 10
Code Lines 6

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 2
eloc 6
nc 2
nop 0
dl 0
loc 10
rs 9.4285
c 0
b 0
f 0
1
<?php
2
3
class Images_Via_Imgix {
4
5
	/**
6
	 * The instance of the class.
7
	 *
8
	 * @var Images_Via_Imgix
9
	 */
10
	protected static $instance;
11
12
	/**
13
	 * Plugin options
14
	 *
15
	 * @var array
16
	 */
17
	protected $options = [];
18
19
	/**
20
	 * Buffer is started by plugin and should be ended on shutdown.
21
	 *
22
	 * @var bool
23
	 */
24
	protected $buffer_started = false;
25
26
	/**
27
	 * ImagesViaImgix constructor.
28
	 */
29
	public function __construct() {
30
		$this->options = get_option( 'imgix_settings', [] );
31
32
		// Change filter load order to ensure it loads after other CDN url transformations i.e. Amazon S3 which loads at position 99.
33
		add_filter( 'wp_get_attachment_url', [ $this, 'replace_image_url' ], 100 );
34
		add_filter( 'imgix/add-image-url', [ $this, 'replace_image_url' ] );
35
36
		add_filter( 'image_downsize', [ $this, 'image_downsize' ], 10, 3 );
37
38
		add_filter( 'wp_calculate_image_srcset', [ $this, 'calculate_image_srcset' ], 10, 5 );
39
40
		add_filter( 'the_content', [ $this, 'replace_images_in_content' ] );
41
		add_action( 'wp_head', [ $this, 'prefetch_cdn' ], 1 );
42
43
		add_action( 'after_setup_theme', [ $this, 'buffer_start_for_retina' ] );
44
		add_action( 'shutdown', [ $this, 'buffer_end_for_retina' ], 0 );
45
	}
46
47
	/**
48
	 * Plugin loader instance.
49
	 *
50
	 * @return Images_Via_Imgix
51
	 */
52
	public static function instance() {
53
		if ( ! isset( self::$instance ) ) {
54
			self::$instance = new self;
55
		}
56
57
		return self::$instance;
58
	}
59
60
	/**
61
	 * Override options from settings.
62
	 * Used in unit tests.
63
	 *
64
	 * @param array $options
65
	 */
66
	public function set_options( $options ) {
67
		$this->options = $options;
68
	}
69
70
	/**
71
	 * Find all img tags with sources matching "imgix.net" without the parameter
72
	 * "srcset" and add the "srcset" parameter to all those images, appending a new
73
	 * source using the "dpr=2" modifier.
74
	 *
75
	 * @param $content
76
	 *
77
	 * @return string Content with retina-enriched image tags.
78
	 */
79
	public function add_retina( $content ) {
80
		$pattern = '/<img((?![^>]+srcset )([^>]*)';
81
		$pattern .= 'src=[\'"]([^\'"]*imgix.net[^\'"]*\?[^\'"]*w=[^\'"]*)[\'"]([^>]*)*?)>/i';
82
		$repl    = '<img$2src="$3" srcset="${3}, ${3}&amp;dpr=2 2x, ${3}&amp;dpr=3 3x,"$4>';
83
		$content = preg_replace( $pattern, $repl, $content );
84
85
		return preg_replace( $pattern, $repl, $content );
86
	}
87
88
	/**
89
	 * Modify image urls for attachments to use imgix host.
90
	 *
91
	 * @param string $url
92
	 *
93
	 * @return string
94
	 */
95
	public function replace_image_url( $url ) {
96
		if ( ! empty ( $this->options['cdn_link'] ) ) {
97
			$parsed_url = parse_url( $url );
98
99
			//Check if image is hosted on current site url -OR- the CDN url specified. Using strpos because we're comparing the host to a full CDN url.
100
            if (
101
                isset( $parsed_url['host'], $parsed_url['path'] )
102
                && ($parsed_url['host'] === parse_url( home_url( '/' ), PHP_URL_HOST ) || ( isset($this->options['external_cdn_link']) && ! empty($this->options['external_cdn_link']) && strpos( $this->options['external_cdn_link'], $parsed_url['host']) !== false ) )
103
                && preg_match( '/\.(jpg|jpeg|gif|png)$/i', $parsed_url['path'] )
104
            ) {
105
				$cdn = parse_url( $this->options['cdn_link'] );
106
				foreach ( [ 'scheme', 'host', 'port' ] as $url_part ) {
107
					if ( isset( $cdn[ $url_part ] ) ) {
108
						$parsed_url[ $url_part ] = $cdn[ $url_part ];
109
					} else {
110
						unset( $parsed_url[ $url_part ] );
111
					}
112
				}
113
				if ( ! empty( $this->options['external_cdn_link'] ) ) {
114
                    //Modify the CDN URL, we won't need any parts after the host.
115
                    $parsed_cdn_url = parse_url( $this->options['external_cdn_link'] );
116
                    $parsed_url['path'] = str_replace( $parsed_cdn_url['path'], "", $parsed_url['path'] );
117
                }
118
119
				$url = http_build_url( $parsed_url );
0 ignored issues
show
Security Bug introduced by
It seems like $parsed_url defined by parse_url($url) on line 97 can also be of type false; however, http_build_url() does only seem to accept array, did you maybe forget to handle an error condition?

This check looks for type mismatches where the missing type is false. This is usually indicative of an error condtion.

Consider the follow example

<?php

function getDate($date)
{
    if ($date !== null) {
        return new DateTime($date);
    }

    return false;
}

This function either returns a new DateTime object or false, if there was an error. This is a typical pattern in PHP programming to show that an error has occurred without raising an exception. The calling code should check for this returned false before passing on the value to another function or method that may not be able to handle a false.

Loading history...
120
121
				$url = add_query_arg( $this->get_global_params(), $url );
122
			}
123
		}
124
125
		return $url;
126
	}
127
128
	/**
129
	 * Set params when running image_downsize
130
	 *
131
	 * @param false|array  $return
132
	 * @param int          $attachment_id
133
	 * @param string|array $size
134
	 *
135
	 * @return false|array
136
	 */
137
	public function image_downsize( $return, $attachment_id, $size ) {
138
		if ( ! empty ( $this->options['cdn_link'] ) ) {
139
			$img_url = wp_get_attachment_url( $attachment_id );
140
141
			$params = [];
142
			if ( is_array( $size ) ) {
143
				$params['w'] = $width = isset( $size[0] ) ? $size[0] : 0;
144
				$params['h'] = $height = isset( $size[1] ) ? $size[1] : 0;
145
			} else {
146
				$available_sizes = $this->get_all_defined_sizes();
147
				if ( isset( $available_sizes[ $size ] ) ) {
148
					$size        = $available_sizes[ $size ];
149
					$params['w'] = $width = $size['width'];
150
					$params['h'] = $height = $size['height'];
151
				}
152
			}
153
154
			$params = array_filter( $params );
155
156
			$img_url = add_query_arg( $params, $img_url );
157
158
			if ( ! isset( $width ) || ! isset( $height ) ) {
159
				// any other type: use the real image
160
				$meta   = wp_get_attachment_metadata( $attachment_id );
161
				
162
				// Image sizes is missing for pdf thumbnails
163
				$meta['width']  = isset( $meta['width'] ) ? $meta['width'] : 0;
164
				$meta['height'] = isset( $meta['height'] ) ? $meta['height'] : 0;
165
				
166
				$width  = isset( $width ) ? $width : $meta['width'];
167
				$height = isset( $height ) ? $height : $meta['height'];
168
			}
169
170
			$return = [ $img_url, $width, $height, true ];
171
		}
172
173
		return $return;
174
	}
175
176
	/**
177
	 * Change url for images in srcset
178
	 *
179
	 * @param array  $sources
180
	 * @param array  $size_array
181
	 * @param string $image_src
182
	 * @param array  $image_meta
183
	 * @param int    $attachment_id
184
	 *
185
	 * @return array
186
	 */
187
	public function calculate_image_srcset( $sources, $size_array, $image_src, $image_meta, $attachment_id ) {
188
		if ( ! empty ( $this->options['cdn_link'] ) ) {
189
			foreach ( $sources as $i => $image_size ) {
190
				if ( $image_size['descriptor'] === 'w' ) {
191
					if ( $attachment_id ) {
192
						$image_src = wp_get_attachment_url( $attachment_id );
193
					}
194
195
					$image_src            = remove_query_arg( 'h', $image_src );
196
					$sources[ $i ]['url'] = add_query_arg( 'w', $image_size['value'], $image_src );
197
				}
198
			}
199
		}
200
201
		return $sources;
202
	}
203
204
	/**
205
	 * Modify image urls in content to use imgix host.
206
	 *
207
	 * @param $content
208
	 *
209
	 * @return string
210
	 */
211
	public function replace_images_in_content( $content ) {
212
	    // Added null to apply filters wp_get_attachment_url to improve compatibility with https://en-gb.wordpress.org/plugins/amazon-s3-and-cloudfront/ - does not break wordpress if the plugin isn't present.
213
		if ( ! empty ( $this->options['cdn_link'] ) ) {
214 View Code Duplication
			if ( preg_match_all( '/<img\s[^>]*src=([\"\']??)([^\" >]*?)\1[^>]*>/iU', $content, $matches ) ) {
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...
215
				foreach ( $matches[2] as $image_src ) {
216
					$content = str_replace( $image_src, apply_filters( 'wp_get_attachment_url', $image_src, null ), $content );
217
				}
218
			}
219
220
			if ( preg_match_all( '/<img\s[^>]*srcset=([\"\']??)([^\">]*?)\1[^>]*\/?>/iU', $content, $matches ) ) {
221
222
				foreach ( $matches[2] as $image_srcset ) {
223
					$new_image_srcset = preg_replace_callback( '/(\S+)(\s\d+\w)/', function ( $srcset_matches ) {
224
						return apply_filters( 'wp_get_attachment_url', $srcset_matches[1], null ) . $srcset_matches[2];
225
					}, $image_srcset );
226
227
					$content = str_replace( $image_srcset, $new_image_srcset, $content );
228
				}
229
			}
230
231 View Code Duplication
			if ( preg_match_all( '/<a\s[^>]*href=([\"\']??)([^\" >]*?)\1[^>]*>(.*)<\/a>/iU', $content, $matches ) ) {
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...
232
				foreach ( $matches[0] as $link ) {
233
					$content = str_replace( $link[2], apply_filters( 'wp_get_attachment_url', $link[2], null ), $content );
234
				}
235
			}
236
		}
237
		return $content;
238
	}
239
240
	/**
241
	 * Add tag to dns prefetch cdn host
242
	 */
243
	public function prefetch_cdn() {
244
		if ( ! empty ( $this->options['cdn_link'] ) ) {
245
			$host = parse_url( $this->options['cdn_link'], PHP_URL_HOST );
246
247
			printf(
248
				'<link rel="dns-prefetch" href="%s"/>',
249
				esc_attr( '//' . $host )
250
			);
251
		}
252
	}
253
254
	/**
255
	 * Start output buffer if auto retina is enabled
256
	 */
257
	public function buffer_start_for_retina() {
258
		if ( ! empty ( $this->options['add_dpi2_srcset'] ) ) {
259
			$this->buffer_started = ob_start( [ $this, 'add_retina' ] );
260
		}
261
	}
262
263
	/**
264
	 * Stop output buffer if it was enabled by the plugin
265
	 */
266
	public function buffer_end_for_retina() {
267
		if ( $this->buffer_started && ob_get_level() ) {
268
			ob_end_flush();
269
		}
270
	}
271
272
	/**
273
	 * Returns a array of global parameters to be applied in all images,
274
	 * according to plugin's settings.
275
	 *
276
	 * @return array Global parameters to be appened at the end of each img URL.
277
	 */
278
	protected function get_global_params() {
279
		$params = [];
280
281
		// For now, only "auto" is supported.
282
		$auto = [];
283
		if ( ! empty ( $this->options['auto_format'] ) ) {
284
			array_push( $auto, 'format' );
285
		}
286
287
		if ( ! empty ( $this->options['auto_enhance'] ) ) {
288
			array_push( $auto, 'enhance' );
289
		}
290
291
		if ( ! empty ( $this->options['auto_compress'] ) ) {
292
			array_push( $auto, 'compress' );
293
		}
294
295
		if ( ! empty( $auto ) ) {
296
			$params['auto'] = implode( '%2C', $auto );
297
		}
298
299
		return $params;
300
	}
301
302
	/**
303
	 * Get all defined image sizes
304
	 *
305
	 * @return array
306
	 */
307
	protected function get_all_defined_sizes() {
308
		// Make thumbnails and other intermediate sizes.
309
		$theme_image_sizes = wp_get_additional_image_sizes();
310
311
		$sizes = [];
312
		foreach ( get_intermediate_image_sizes() as $s ) {
313
			$sizes[ $s ] = [ 'width' => '', 'height' => '', 'crop' => false ];
314
			if ( isset( $theme_image_sizes[ $s ] ) ) {
315
				// For theme-added sizes
316
				$sizes[ $s ]['width']  = intval( $theme_image_sizes[ $s ]['width'] );
317
				$sizes[ $s ]['height'] = intval( $theme_image_sizes[ $s ]['height'] );
318
				$sizes[ $s ]['crop']   = $theme_image_sizes[ $s ]['crop'];
319
			} else {
320
				// For default sizes set in options
321
				$sizes[ $s ]['width']  = get_option( "{$s}_size_w" );
322
				$sizes[ $s ]['height'] = get_option( "{$s}_size_h" );
323
				$sizes[ $s ]['crop']   = get_option( "{$s}_crop" );
324
			}
325
		}
326
327
		return $sizes;
328
	}
329
}
330
331
Images_Via_Imgix::instance();
332