Completed
Push — story-block/fix/external-media... ( cf2e30...889c72 )
by
unknown
239:43 queued 228:24
created

story.php ➔ render_video()   A

Complexity

Conditions 5
Paths 3

Size

Total Lines 30

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 5
nc 3
nop 1
dl 0
loc 30
rs 9.1288
c 0
b 0
f 0
1
<?php
2
/**
3
 * Story Block.
4
 *
5
 * @since 8.6.1
6
 *
7
 * @package automattic/jetpack
8
 */
9
10
namespace Automattic\Jetpack\Extensions\Story;
11
12
use Automattic\Jetpack\Blocks;
13
use Jetpack;
14
use Jetpack_Gutenberg;
15
16
const FEATURE_NAME = 'story';
17
const BLOCK_NAME   = 'jetpack/' . FEATURE_NAME;
18
19
const EMBED_SIZE        = array( 180, 320 );
20
const CROP_UP_TO        = 0.2;
21
const MAX_BULLETS       = 7;
22
const IMAGE_BREAKPOINTS = '(max-width: 460px) 576w, (max-width: 614px) 768w, 120vw'; // 120vw to match the 20% CROP_UP_TO ratio
23
24
/**
25
 * Registers the block for use in Gutenberg
26
 * This is done via an action so that we can disable
27
 * registration if we need to.
28
 */
29
function register_block() {
30
	Blocks::jetpack_register_block(
31
		BLOCK_NAME,
32
		array( 'render_callback' => __NAMESPACE__ . '\render_block' )
33
	);
34
}
35
add_action( 'init', __NAMESPACE__ . '\register_block' );
36
37
/**
38
 * Compare 2 urls and return true if they likely correspond to the same resource.
39
 * Ignore scheme, ports, query params and hashes and only compare hostname and pathname.
40
 *
41
 * @param string $url1  - First url used in comparison.
42
 * @param string $url2  - Second url used in comparison.
43
 *
44
 * @returns boolean
45
 */
46
function is_same_resource( $url1, $url2 ) {
47
	$url1_parsed = wp_parse_url( $url1 );
48
	$url2_parsed = wp_parse_url( $url2 );
49
	return isset( $url1_parsed['host'] ) &&
50
		isset( $url2_parsed['host'] ) &&
51
		isset( $url1_parsed['path'] ) &&
52
		isset( $url2_parsed['path'] ) &&
53
		$url1_parsed['host'] === $url2_parsed['host'] &&
54
		$url1_parsed['path'] === $url2_parsed['path'];
55
}
56
57
/**
58
 * Enrich media files with extra information we can retrieve from the media library.
59
 * Add missing `width`, `height`, `srcset` and `sizes` properties to images of the mediaFiles block attributes.
60
 * Add missing `width`, `height`, `poster` properties to videos of the mediaFiles block attributes.
61
 *
62
 * @param array $media_files  - List of media, each as an array containing the media attributes.
63
 *
64
 * @returns array $media_files
65
 */
66
function enrich_media_files( $media_files ) {
67
	return array_filter(
68
		array_map(
69
			function ( $media_file ) {
70
				$attachment_id = isset( $media_file['id'] ) ? $media_file['id'] : null;
71
				if ( 'image' === $media_file['type'] ) {
72
					$image = wp_get_attachment_image_src( $attachment_id, 'full', false );
73
					if ( ! $image ) {
74
						return $media_file;
75
					}
76
					list( $src, $width, $height ) = $image;
77
					// Bail if url stored in block attributes is different than the media library one for that id.
78
					if ( isset( $media_file['url'] ) && ! is_same_resource( $media_file['url'], $src ) ) {
79
						return $media_file;
80
					}
81
					$image_meta = wp_get_attachment_metadata( $attachment_id );
82
					if ( ! is_array( $image_meta ) ) {
83
						return $media_file;
84
					}
85
					$size_array = array( absint( $width ), absint( $height ) );
86
					return array_merge(
87
						$media_file,
88
						array(
89
							'width'   => absint( $width ),
90
							'height'  => absint( $height ),
91
							'srcset'  => wp_calculate_image_srcset( $size_array, $src, $image_meta, $attachment_id ),
92
							'sizes'   => IMAGE_BREAKPOINTS,
93
							'title'   => get_the_title( $attachment_id ),
94
							'alt'     => get_post_meta( $attachment_id, '_wp_attachment_image_alt', true ),
95
							'caption' => wp_get_attachment_caption( $attachment_id ),
96
						)
97
					);
98
				}
99
				// VideoPress videos can sometimes have type 'file', and mime 'video/videopress' or 'video/mp4'.
100
				// Let's fix `type` for those.
101
				if ( 'file' === $media_file['type'] && 'video' === substr( $media_file['mime'], 0, 5 ) ) {
102
					$media_file['type'] = 'video';
103
				}
104
				if ( 'video' !== $media_file['type'] ) { // we only support images and videos at this point.
105
					return null;
106
				}
107
				$video_meta = wp_get_attachment_metadata( $attachment_id );
108
				if ( ! $video_meta ) {
109
					return $media_file;
110
				}
111
				$media_file = array_merge(
112
					$media_file,
113
					array(
114
						'width'   => absint( ! empty( $video_meta['width'] ) ? $video_meta['width'] : $media_file['width'] ),
115
						'height'  => absint( ! empty( $video_meta['height'] ) ? $video_meta['height'] : $media_file['height'] ),
116
						'alt'     => ! empty( $video_meta['videopress']['description'] ) ? $video_meta['videopress']['description'] : $media_file['alt'],
117
						'url'     => ! empty( $video_meta['original']['url'] ) ? $video_meta['original']['url'] : $media_file['url'],
118
						'title'   => get_the_title( $attachment_id ),
119
						'caption' => wp_get_attachment_caption( $attachment_id ),
120
					)
121
				);
122
123
				$poster_url = null;
124
				// Set the poster attribute for the video tag if a poster image is available.
125
				if ( ! empty( $video_meta['videopress']['poster'] ) ) {
126
					$poster_url = $video_meta['videopress']['poster'];
127
				} elseif ( ! empty( $video_meta['thumb'] ) ) {
128
					$video_url  = wp_get_attachment_url( $attachment_id );
129
					$poster_url = str_replace( wp_basename( $video_url ), $video_meta['thumb'], $video_url );
130
				}
131
132
				if ( $poster_url ) {
133
					$poster_width  = esc_attr( $media_file['width'] );
134
					$poster_height = esc_attr( $media_file['height'] );
135
					$content_width = (int) Jetpack::get_content_width();
136
					if ( is_numeric( $content_width ) ) {
137
						$poster_height = round( ( $content_width * $poster_height ) / $poster_width );
138
						$poster_width  = $content_width;
139
					}
140
					$media_file = array_merge(
141
						$media_file,
142
						array(
143
							'poster' => add_query_arg( 'resize', rawurlencode( $poster_width . ',' . $poster_height ), $poster_url ),
144
						)
145
					);
146
				}
147
148
				return $media_file;
149
			},
150
			$media_files
151
		)
152
	);
153
}
154
155
/**
156
 * Render an image inside a slide
157
 *
158
 * @param array $media  - Image information.
159
 *
160
 * @returns string
161
 */
162
function render_image( $media ) {
163
	if ( empty( $media['id'] ) || empty( $media['url'] ) ) {
164
		return __( 'Error retrieving media', 'jetpack' );
165
	}
166
	$image = wp_get_attachment_image_src( $media['id'], 'full', false );
167
	if ( $image ) {
168
		list( $src, $width, $height ) = $image;
169
	}
170
171
	// if image does not match.
172
	if ( ! $image || isset( $media['url'] ) && ! is_same_resource( $media['url'], $src ) ) {
0 ignored issues
show
Bug introduced by
The variable $src does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
173
		$width  = isset( $media['width'] ) ? $media['width'] : null;
174
		$height = isset( $media['height'] ) ? $media['height'] : null;
175
		return sprintf(
176
			'<img
177
				title="%1$s"
178
				alt="%2$s"
179
				class="wp-block-jetpack-story_image wp-story-image %3$s"
180
				src="%4$s"
181
			/>',
182
			esc_attr( $media['title'] ),
183
			esc_attr( $media['alt'] ),
184
			$width && $height ? get_image_crop_class( $width, $height ) : '',
185
			esc_attr( $media['url'] )
186
		);
187
	}
188
189
	$crop_class = get_image_crop_class( $width, $height );
0 ignored issues
show
Bug introduced by
The variable $height does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
Bug introduced by
The variable $width does not seem to be defined for all execution paths leading up to this point.

If you define a variable conditionally, it can happen that it is not defined for all execution paths.

Let’s take a look at an example:

function myFunction($a) {
    switch ($a) {
        case 'foo':
            $x = 1;
            break;

        case 'bar':
            $x = 2;
            break;
    }

    // $x is potentially undefined here.
    echo $x;
}

In the above example, the variable $x is defined if you pass “foo” or “bar” as argument for $a. However, since the switch statement has no default case statement, if you pass any other value, the variable $x would be undefined.

Available Fixes

  1. Check for existence of the variable explicitly:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        if (isset($x)) { // Make sure it's always set.
            echo $x;
        }
    }
    
  2. Define a default value for the variable:

    function myFunction($a) {
        $x = ''; // Set a default which gets overridden for certain paths.
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
        }
    
        echo $x;
    }
    
  3. Add a value for the missing path:

    function myFunction($a) {
        switch ($a) {
            case 'foo':
                $x = 1;
                break;
    
            case 'bar':
                $x = 2;
                break;
    
            // We add support for the missing case.
            default:
                $x = '';
                break;
        }
    
        echo $x;
    }
    
Loading history...
190
	// need to specify the size of the embed so it picks an image that is large enough for the `src` attribute
191
	// `sizes` is optimized for 1080x1920 (9:16) images
192
	// Note that the Story block does not have thumbnail support, it will load the right
193
	// image based on the viewport size only.
194
	return wp_get_attachment_image(
195
		$media['id'],
196
		EMBED_SIZE,
197
		false,
198
		array(
199
			'class' => sprintf( 'wp-story-image wp-image-%d %s', $media['id'], $crop_class ),
200
			'sizes' => IMAGE_BREAKPOINTS,
201
			'title' => get_the_title( $media['id'] ),
202
		)
203
	);
204
}
205
206
/**
207
 * Return the css crop class if image width and height requires it
208
 *
209
 * @param int $width   - Image width.
210
 * @param int $height  - Image height.
211
 *
212
 * @returns string The CSS class which will display a cropped image
213
 */
214
function get_image_crop_class( $width, $height ) {
215
	$crop_class          = '';
216
	$media_aspect_ratio  = $width / $height;
217
	$target_aspect_ratio = EMBED_SIZE[0] / EMBED_SIZE[1];
218
	if ( $media_aspect_ratio >= $target_aspect_ratio ) {
219
		// image wider than canvas.
220
		$media_too_wide_to_crop = $media_aspect_ratio > $target_aspect_ratio / ( 1 - CROP_UP_TO );
221
		if ( ! $media_too_wide_to_crop ) {
222
			$crop_class = 'wp-story-crop-wide';
223
		}
224
	} else {
225
		// image narrower than canvas.
226
		$media_too_narrow_to_crop = $media_aspect_ratio < $target_aspect_ratio * ( 1 - CROP_UP_TO );
227
		if ( ! $media_too_narrow_to_crop ) {
228
			$crop_class = 'wp-story-crop-narrow';
229
		}
230
	}
231
	return $crop_class;
232
}
233
234
/**
235
 * Render a video inside a slide
236
 *
237
 * @param array $media  - Video information.
238
 *
239
 * @returns string
240
 */
241
function render_video( $media ) {
242
	if ( empty( $media['id'] ) || empty( $media['mime'] ) || empty( $media['url'] ) ) {
243
		return __( 'Error retrieving media', 'jetpack' );
244
	}
245
246
	if ( ! empty( $media['poster'] ) ) {
247
		return render_image(
248
			array_merge(
249
				$media,
250
				array(
251
					'url' => $media['poster'],
252
				)
253
			)
254
		);
255
	}
256
257
	return sprintf(
258
		'<video
259
			title="%1$s"
260
			type="%2$s"
261
			class="wp-story-video intrinsic-ignore wp-video-%3$s"
262
			data-id="%3$s"
263
			src="%4$s">
264
		</video>',
265
		esc_attr( get_the_title( $media['id'] ) ),
266
		esc_attr( $media['mime'] ),
267
		$media['id'],
268
		esc_attr( $media['url'] )
269
	);
270
}
271
272
/**
273
 * Render a static embed story picking a thumbnail
274
 *
275
 * @param array $media_files  - list of Media files.
276
 *
277
 * @returns string
278
 */
279
function render_static_slide( $media_files ) {
280
	$media_template = '';
281
	if ( empty( $media_files ) ) {
282
		return '';
283
	}
284
285
	// find an image to showcase.
286
	foreach ( $media_files as $media ) {
287
		switch ( $media['type'] ) {
288
			case 'image':
289
				$media_template = render_image( $media );
290
				break 2;
291
			case 'video':
292
				// ignore videos without a poster image.
293
				if ( empty( $media['poster'] ) ) {
294
					continue 2;
295
				}
296
				$media_template = render_video( $media );
297
				break 2;
298
		}
299
	}
300
301
	// if no media was found try to render a video tag without poster.
302
	if ( empty( $media_template ) ) {
303
		foreach ( $media_files as $media ) {
304
			switch ( $media['type'] ) {
305
				case 'video':
306
					$media_template = render_video( $media );
307
					break 2;
308
			}
309
		}
310
	}
311
312
	return sprintf(
313
		'<div class="wp-story-slide" style="display: block;">
314
			<figure>%s</figure>
315
		</div>',
316
		$media_template
317
	);
318
}
319
320
/**
321
 * Render the top right icon on top of the story embed
322
 *
323
 * @param array $settings  - The block settings.
324
 *
325
 * @returns string
326
 */
327
function render_top_right_icon( $settings ) {
328
	$show_slide_count = isset( $settings['showSlideCount'] ) ? $settings['showSlideCount'] : false;
329
	$slide_count      = isset( $settings['slides'] ) ? count( $settings['slides'] ) : 0;
330
	if ( $show_slide_count ) {
331
		// Render the story block icon along with the slide count.
332
		return sprintf(
333
			'<div class="wp-story-embed-icon">
334
				<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" role="img" aria-hidden="true" focusable="false">
335
					<path d="M0 0h24v24H0z" fill="none"></path>
336
					<path fill-rule="evenodd" clip-rule="evenodd" d="M6 3H14V17H6L6 3ZM4 3C4 1.89543 4.89543 1 6 1H14C15.1046 1 16 1.89543 16 3V17C16 18.1046 15.1046 19 14 19H6C4.89543 19 4 18.1046 4 17V3ZM18 5C19.1046 5 20 5.89543 20 7V21C20 22.1046 19.1046 23 18 23H10C8.89543 23 8 22.1046 8 21H18V5Z"></path>
337
				</svg>
338
				<span>%d</span>
339
			</div>',
340
			$slide_count
341
		);
342
	} else {
343
		// Render the Fullscreen Gridicon.
344
		return (
345
			'<div class="wp-story-embed-icon-expand">
346
				<svg class="gridicon gridicons-fullscreen" role="img" height="24" width="24" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
347
					<g>
348
						<path d="M21 3v6h-2V6.41l-3.29 3.3-1.42-1.42L17.59 5H15V3zM3 3v6h2V6.41l3.29 3.3 1.42-1.42L6.41 5H9V3zm18 18v-6h-2v2.59l-3.29-3.29-1.41 1.41L17.59 19H15v2zM9 21v-2H6.41l3.29-3.29-1.41-1.42L5 17.59V15H3v6z"></path>
349
					</g>
350
				</svg>
351
			</div>'
352
		);
353
	}
354
}
355
356
/**
357
 * Render a pagination bullet
358
 *
359
 * @param int    $slide_index  - The slide index it corresponds to.
360
 * @param string $class_name   - Optional css class name(s) to customize the bullet element.
361
 *
362
 * @returns string
363
 */
364
function render_pagination_bullet( $slide_index, $class_name = '' ) {
365
	return sprintf(
366
		'<div class="wp-story-pagination-bullet %s" aria-label="%s">
367
			<div class="wp-story-pagination-bullet-bar"></div>
368
		</div>',
369
		esc_attr( $class_name ),
370
		/* translators: %d is the slide number (1, 2, 3...) */
371
		sprintf( __( 'Go to slide %d', 'jetpack' ), $slide_index )
372
	);
373
}
374
375
/**
376
 * Render pagination on top of the story embed
377
 *
378
 * @param array $settings  - The block settings.
379
 *
380
 * @returns string
381
 */
382
function render_pagination( $settings ) {
383
	$show_slide_count = isset( $settings['showSlideCount'] ) ? $settings['showSlideCount'] : false;
384
	if ( $show_slide_count ) {
385
		return '';
386
	}
387
	$slide_count     = isset( $settings['slides'] ) ? count( $settings['slides'] ) : 0;
388
	$bullet_count    = min( $slide_count, MAX_BULLETS );
389
	$bullet_ellipsis = $slide_count > $bullet_count
390
		? render_pagination_bullet( $bullet_count + 1, 'wp-story-pagination-ellipsis' )
391
		: '';
392
	return sprintf(
393
		'<div class="wp-story-pagination wp-story-pagination-bullets">
394
			%s
395
		</div>',
396
		join( "\n", array_map( __NAMESPACE__ . '\render_pagination_bullet', range( 1, $bullet_count ) ) ) . $bullet_ellipsis
397
	);
398
}
399
400
/**
401
 * Render story block
402
 *
403
 * @param array $attributes  - Block attributes.
404
 *
405
 * @returns string
406
 */
407
function render_block( $attributes ) {
408
	Jetpack_Gutenberg::load_assets_as_required( FEATURE_NAME );
409
410
	$media_files              = isset( $attributes['mediaFiles'] ) ? enrich_media_files( $attributes['mediaFiles'] ) : array();
411
	$settings_from_attributes = isset( $attributes['settings'] ) ? $attributes['settings'] : array();
412
413
	$settings = array_merge(
414
		$settings_from_attributes,
415
		array(
416
			'slides' => $media_files,
417
		)
418
	);
419
420
	return sprintf(
421
		'<div class="%1$s" data-id="%2$s" data-settings="%3$s">
422
			<div class="wp-story-app">
423
				<div class="wp-story-display-contents" style="display: contents;">
424
					<a class="wp-story-container" href="%4$s" title="%5$s">
425
						<div class="wp-story-meta">
426
							<div class="wp-story-icon">
427
								<img alt="%6$s" src="%7$s" width="40" height="40">
428
							</div>
429
							<div>
430
								<div class="wp-story-title">
431
									%8$s
432
								</div>
433
							</div>
434
						</div>
435
						<div class="wp-story-wrapper">
436
							%9$s
437
						</div>
438
						<div class="wp-story-overlay">
439
							%10$s
440
						</div>
441
						%11$s
442
					</a>
443
				</div>
444
			</div>
445
		</div>',
446
		esc_attr( Blocks::classes( FEATURE_NAME, $attributes, array( 'wp-story', 'aligncenter' ) ) ),
447
		esc_attr( 'wp-story-' . get_the_ID() ),
448
		filter_var( wp_json_encode( $settings ), FILTER_SANITIZE_SPECIAL_CHARS ),
449
		get_permalink() . '?wp-story-load-in-fullscreen=true&amp;wp-story-play-on-load=true',
450
		__( 'Play story in new tab', 'jetpack' ),
451
		__( 'Site icon', 'jetpack' ),
452
		esc_attr( get_site_icon_url( 80, includes_url( 'images/w-logo-blue.png' ) ) ),
453
		esc_html( get_the_title() ),
454
		render_static_slide( $media_files ),
455
		render_top_right_icon( $settings ),
456
		render_pagination( $settings )
457
	);
458
}
459