Completed
Push — story-block/fix/external-media... ( 8adc62...fb99b5 )
by
unknown
09:46
created

story.php ➔ render_video()   B

Complexity

Conditions 6
Paths 4

Size

Total Lines 48

Duplication

Lines 4
Ratio 8.33 %

Importance

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