Completed
Push — fix/youtube-shortcode-amp-comp... ( 0aea78...87f47e )
by
unknown
08:56
created

Jetpack_Tweetstorm_Helper::generate_cards()   B

Complexity

Conditions 9
Paths 19

Size

Total Lines 72

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 9
nc 19
nop 1
dl 0
loc 72
rs 7.0553
c 0
b 0
f 0

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
/**
3
 * Tweetstorm block and API helper.
4
 *
5
 * @package jetpack
6
 * @since 8.7.0
7
 */
8
9
use Automattic\Jetpack\Connection\Client;
10
use Automattic\Jetpack\Status;
11
use Twitter\Text\Regex as Twitter_Regex;
12
use Twitter\Text\Validator as Twitter_Validator;
13
14
/**
15
 * Class Jetpack_Tweetstorm_Helper
16
 *
17
 * @since 8.7.0
18
 */
19
class Jetpack_Tweetstorm_Helper {
20
	/**
21
	 * Blocks that can be converted to tweets.
22
	 *
23
	 * @var array {
24
	 *     The key for each element must match the registered block name.
25
	 *
26
	 *     @type string $type Required. The type of content this block produces. Can be one of 'break', 'embed', 'image',
27
	 *                        'multiline', 'text', or 'video'.
28
	 *     @type string $content_location Optional. Where the block content can be found. Can be 'html', if we need to parse
29
	 *                           it out of the block HTML text, 'html-attributes', if the we need to parse it out of HTML attributes
30
	 *                           in the block HTML, or 'block-attributes', if the content can be found in the block attributes.
31
	 *                           Note that these attributes need to be available when the serialised block is
32
	 *                           parsed using `parse_blocks()`. If it isn't set, it's assumed the block doesn't add
33
	 *                           any content to the Twitter thread.
34
	 *     @type array $content Optional. Defines what parts of the block content need to be extracted. Behaviour can vary based on
35
	 *                          `$content_location`, and `$type`:
36
	 *
37
	 *                              - When `$content_location` is 'html', a value of `array()` or `array( 'content' )` have the same meaning:
38
	 *                                The entire block HTML should be used. In both cases, 'content' will be the corresponding tag in `$template`.
39
	 *                              - When `$content_location` is 'html', it should be formatted as `array( 'container' => 'tag' )`,
40
	 *                                where 'container' is the name of the corresponding RichText container in the block editor, and is also the name
41
	 *                                of the corresponding tag in the $template string. 'tag' is the HTML tag within the block that corresponds to this
42
	 *                                container. When `$type` is 'multiline', there must only be one element in the array, and tag should be set to the HTML
43
	 *                                tag that corresponds to each line, though the 'container' should still be the RichText container name. (Eg, in the core/list block, the tag is 'li'.)
44
	 *                              - When `$content_location` is 'html-attributes', the array should be formatted as `array( 'name' => array( 'tag', 'attribute') )`,
45
	 *                                where 'name' is the name of a particular value that different block types require, 'tag' is the name of the HTML tag where 'attribute'
46
	 *                                can be found, containing the value to use for 'name'. When `$type` is 'image', 'url' and 'alt' must be defined. When `$type` is 'video',
47
	 *                                'url' must be defined.
48
	 *                              - When `$content_location` is 'block-attributes', it must be an array of block attribute names. When `$type` is 'embed', there
49
	 *                                only be one element, corresponding to the URL for the embed.
50
	 *     @type string $template Required for 'text' and 'multiline' types, ignored for all other types. Describes how the block content will be formatted when tweeted.
51
	 *                            Tags should match the keys of `$content`, except for the special "{{content}}", which matches the entire HTML content of the block.
52
	 *                            For 'multiline' types, the template will be repeated for every line in the block.
53
	 *     @type boolean $force_new Required. Whether or not a new tweet should be started when this block is encountered.
54
	 *     @type boolean $force_finished Required. Whether or not a new tweet should be started after this block is finished.
55
	 * }
56
	 */
57
	private static $supported_blocks = array(
58
		'core/embed'     => array(
59
			'type'             => 'embed',
60
			'content_location' => 'block-attributes',
61
			'content'          => array( 'url' ),
62
			'force_new'        => false,
63
			'force_finished'   => true,
64
		),
65
		'core/gallery'   => array(
66
			'type'             => 'image',
67
			'content_location' => 'html-attributes',
68
			'content'          => array(
69
				'url' => array( 'img', 'src' ),
70
				'alt' => array( 'img', 'alt' ),
71
			),
72
			'force_new'        => false,
73
			'force_finished'   => true,
74
		),
75
		'core/heading'   => array(
76
			'type'             => 'text',
77
			'content_location' => 'html',
78
			'content'          => array(),
79
			'template'         => '{{content}}',
80
			'force_new'        => true,
81
			'force_finished'   => false,
82
		),
83
		'core/image'     => array(
84
			'type'             => 'image',
85
			'content_location' => 'html-attributes',
86
			'content'          => array(
87
				'url' => array( 'img', 'src' ),
88
				'alt' => array( 'img', 'alt' ),
89
			),
90
			'force_new'        => false,
91
			'force_finished'   => true,
92
		),
93
		'core/list'      => array(
94
			'type'             => 'multiline',
95
			'content_location' => 'html',
96
			// It looks a little weird to use the 'values' key for a single line,
97
			// but 'values' is the name of the RichText content area.
98
			'content'          => array(
99
				'values' => 'li',
100
			),
101
			'template'         => '- {{values}}',
102
			'force_new'        => false,
103
			'force_finished'   => false,
104
		),
105
		'core/paragraph' => array(
106
			'type'             => 'text',
107
			'content_location' => 'html',
108
			'content'          => array(),
109
			'template'         => '{{content}}',
110
			'force_new'        => false,
111
			'force_finished'   => false,
112
		),
113
		'core/quote'     => array(
114
			'type'             => 'text',
115
			'content_location' => 'html',
116
			// The quote content will always be inside <p> tags.
117
			'content'          => array(
118
				'value'    => 'p',
119
				'citation' => 'cite',
120
			),
121
			'template'         => '“{{value}}” – {{citation}}',
122
			'force_new'        => false,
123
			'force_finished'   => false,
124
		),
125
		'core/separator' => array(
126
			'type'           => 'break',
127
			'force_new'      => false,
128
			'force_finished' => true,
129
		),
130
		'core/spacer'    => array(
131
			'type'           => 'break',
132
			'force_new'      => false,
133
			'force_finished' => true,
134
		),
135
		'core/verse'     => array(
136
			'type'             => 'text',
137
			'content_location' => 'html',
138
			'content'          => array(),
139
			'template'         => '{{content}}',
140
			'force_new'        => false,
141
			'force_finished'   => false,
142
		),
143
		'core/video'     => array(
144
			'type'             => 'video',
145
			'content_location' => 'html-attributes',
146
			'content'          => array(
147
				'url' => array( 'video', 'src' ),
148
			),
149
			'force_new'        => false,
150
			'force_finished'   => true,
151
		),
152
		'jetpack/gif'    => array(
153
			'type'             => 'embed',
154
			'content_location' => 'block-attributes',
155
			'content'          => array( 'giphyUrl' ),
156
			'force_new'        => false,
157
			'force_finished'   => true,
158
		),
159
	);
160
161
	/**
162
	 * A cache of _wp_emoji_list( 'entities' ), after being run through html_entity_decode().
163
	 *
164
	 * Initialised in ::is_valid_tweet().
165
	 *
166
	 * @var array
167
	 */
168
	private static $emoji_list = array();
169
170
	/**
171
	 * Special line separator character, for multiline text.
172
	 *
173
	 * @var string
174
	 */
175
	private static $line_separator = "\xE2\x80\xA8";
176
177
	/**
178
	 * Special inline placeholder character, for inline tags that change content length in the RichText..
179
	 *
180
	 * @var string
181
	 */
182
	private static $inline_placeholder = "\xE2\x81\xA3";
183
184
	/**
185
	 * URLs always take up a fixed length from the text limit.
186
	 *
187
	 * @var int
188
	 */
189
	private static $characters_per_url = 24;
190
191
	/**
192
	 * Every media attachment takes up some space from the text limit.
193
	 *
194
	 * @var int
195
	 */
196
	private static $characters_per_media = 24;
197
198
	/**
199
	 * An array to store all the tweets in.
200
	 *
201
	 * @var array
202
	 */
203
	private static $tweets = array();
204
205
	/**
206
	 * While we're caching everything, we want to keep track of the URLs we're adding.
207
	 *
208
	 * @var array
209
	 */
210
	private static $urls = array();
211
212
	/**
213
	 * Gather the Tweetstorm.
214
	 *
215
	 * @param  string $url The tweet URL to gather from.
216
	 * @return mixed
217
	 */
218
	public static function gather( $url ) {
219
		if ( ( new Status() )->is_offline_mode() ) {
220
			return new WP_Error(
221
				'dev_mode',
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'dev_mode'.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
222
				__( 'Tweet unrolling is not available in offline mode.', 'jetpack' )
223
			);
224
		}
225
226
		$site_id = self::get_site_id();
227
		if ( is_wp_error( $site_id ) ) {
228
			return $site_id;
229
		}
230
231
		if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) {
232
			if ( ! class_exists( 'WPCOM_Gather_Tweetstorm' ) ) {
233
				\jetpack_require_lib( 'gather-tweetstorm' );
234
			}
235
236
			return WPCOM_Gather_Tweetstorm::gather( $url );
237
		}
238
239
		$response = Client::wpcom_json_api_request_as_blog(
240
			sprintf( '/sites/%d/tweetstorm/gather?url=%s', $site_id, rawurlencode( $url ) ),
241
			2,
242
			array( 'headers' => array( 'content-type' => 'application/json' ) ),
243
			null,
244
			'wpcom'
245
		);
246
		if ( is_wp_error( $response ) ) {
247
			return $response;
248
		}
249
250
		$data = json_decode( wp_remote_retrieve_body( $response ) );
251
252
		if ( wp_remote_retrieve_response_code( $response ) >= 400 ) {
253
			return new WP_Error( $data->code, $data->message, $data->data );
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with $data->code.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
254
		}
255
256
		return $data;
257
	}
258
259
	/**
260
	 * Parse blocks into an array of tweets.
261
	 *
262
	 * @param array $blocks {
263
	 *     An array of blocks, with optional editor-specific information, that need to be parsed into tweets.
264
	 *
265
	 *     @type array  $block      A single block, in the form produce by parse_blocks().
266
	 *     @type array  $attributes Optional. A list of block attributes and their values from the block editor.
267
	 *     @type string $clientId   Optional. The clientId of this block in the block editor.
268
	 * }
269
	 * @return array An array of tweets.
270
	 */
271
	public static function parse( $blocks ) {
272
		// Reset the tweets array.
273
		self::$tweets = array();
274
275
		$blocks = self::extract_blocks( $blocks );
276
277
		if ( empty( $blocks ) ) {
278
			return array();
279
		}
280
281
		// Initialise the tweets array with an empty tweet, so we don't need to check
282
		// if we're creating the first tweet while processing blocks.
283
		self::start_new_tweet();
284
285
		foreach ( $blocks as $block ) {
286
			$block_def = self::get_block_definition( $block['name'] );
287
288
			// Grab the most recent tweet.
289
			$current_tweet = self::get_current_tweet();
290
291
			// Break blocks have no content to add, so we can skip the rest of this loop.
292
			if ( 'break' === $block_def['type'] ) {
293
				self::save_current_tweet( $current_tweet, $block );
294
				continue;
295
			}
296
297
			// Check if we need to start a new tweet.
298
			if ( $current_tweet['finished'] || $block_def['force_new'] ) {
299
				self::start_new_tweet();
300
			}
301
302
			// Process the block.
303
			self::add_text_to_tweets( $block );
304
			self::add_media_to_tweets( $block );
305
			self::add_tweet_to_tweets( $block );
306
			self::add_embed_to_tweets( $block );
307
		}
308
309
		return self::clean_return_tweets();
310
	}
311
312
	/**
313
	 * If the passed block name is supported, return the block definition.
314
	 *
315
	 * @param string $block_name The registered block name.
316
	 * @return array|null The block definition, if it's supported.
317
	 */
318
	private static function get_block_definition( $block_name ) {
319
		if ( isset( self::$supported_blocks[ $block_name ] ) ) {
320
			return self::$supported_blocks[ $block_name ];
321
		}
322
323
		// @todo This is a fallback definition, it can be removed when WordPress 5.6 is the minimum supported version.
324
		if ( 0 === strpos( $block_name, 'core-embed/' ) ) {
325
			return self::$supported_blocks['core/embed'];
326
		}
327
328
		return null;
329
	}
330
331
	/**
332
	 * If the block has any text, process it, and add it to the tweet list.
333
	 *
334
	 * @param array $block The block to process.
335
	 */
336
	private static function add_text_to_tweets( $block ) {
337
		// This is a text block, is there any text?
338
		if ( 0 === strlen( $block['text'] ) ) {
339
			return;
340
		}
341
342
		$block_def = self::get_block_definition( $block['name'] );
343
344
		// Grab the most recent tweet, so we can append to that if we can.
345
		$current_tweet = self::get_current_tweet();
346
347
		// If the entire block can't be fit in this tweet, we need to start a new tweet.
348
		if ( $current_tweet['changed'] && ! self::is_valid_tweet( trim( $current_tweet['text'] ) . "\n\n{$block['text']}" ) ) {
349
			self::start_new_tweet();
350
		}
351
352
		// Multiline blocks prioritise splitting by line, but are otherwise identical to
353
		// normal text blocks. This means we can treat normal text blocks as being
354
		// "multiline", but with a single line.
355
		if ( 'multiline' === $block_def['type'] ) {
356
			$lines = explode( self::$line_separator, $block['text'] );
357
		} else {
358
			$lines = array( $block['text'] );
359
		}
360
		$line_total = count( $lines );
361
362
		// Keep track of how many characters from this block we've allocated to tweets.
363
		$current_character_count = 0;
364
365
		for ( $line_count = 0; $line_count < $line_total; $line_count++ ) {
366
			$line_text = $lines[ $line_count ];
367
368
			// Make sure we have the most recent tweet at the start of every loop.
369
			$current_tweet = self::get_current_tweet();
370
371
			if ( $current_tweet['changed'] ) {
372
				// When it's the first line, add an extra blank line to seperate
373
				// the tweet text from that of the previous block.
374
				$separator = "\n\n";
375
				if ( $line_count > 0 ) {
376
					$separator = "\n";
377
				}
378
379
				// Is this line short enough to append to the current tweet?
380
				if ( self::is_valid_tweet( trim( $current_tweet['text'] ) . "$separator$line_text" ) ) {
381
					// Don't trim the text yet, as we may need it for boundary calculations.
382
					$current_tweet['text'] = $current_tweet['text'] . "$separator$line_text";
383
384
					self::save_current_tweet( $current_tweet, $block );
385
					continue;
386
				}
387
388
				// This line is too long, and lines *must* be split to a new tweet if they don't fit
389
				// into the current tweet. If this isn't the first line, record where we split the block.
390 View Code Duplication
				if ( $line_count > 0 ) {
391
					// Increment by 1 to allow for the \n between lines to be counted by ::get_boundary().
392
					$current_character_count  += strlen( $current_tweet['text'] ) + 1;
393
					$current_tweet['boundary'] = self::get_boundary( $block, $current_character_count );
394
395
					self::save_current_tweet( $current_tweet );
396
				}
397
398
				// Start a new tweet.
399
				$current_tweet = self::start_new_tweet();
400
			}
401
402
			// Since we're now at the start of a new tweet, is this line short enough to be a tweet by itself?
403
			if ( self::is_valid_tweet( $line_text ) ) {
404
				$current_tweet['text'] = $line_text;
405
406
				self::save_current_tweet( $current_tweet, $block );
407
				continue;
408
			}
409
410
			// The line is too long for a single tweet, so split it by sentences.
411
			$sentences      = preg_split( '/(?<!\.\.\.)(?<=[.?!]|\.\)|\.["\'])(\s+)(?=[\p{L}\'"\(])/u', $line_text, -1, PREG_SPLIT_DELIM_CAPTURE );
412
			$sentence_total = count( $sentences );
413
414
			// preg_split() puts the blank space between sentences into a seperate entry in the result,
415
			// so we need to step through the result array by two, and append the blank space when needed.
416
			for ( $sentence_count = 0; $sentence_count < $sentence_total; $sentence_count += 2 ) {
417
				$current_sentence = $sentences[ $sentence_count ];
418
				if ( isset( $sentences[ $sentence_count + 1 ] ) ) {
419
					$current_sentence .= $sentences[ $sentence_count + 1 ];
420
				}
421
422
				// Make sure we have the most recent tweet.
423
				$current_tweet = self::get_current_tweet();
424
425
				// After the first sentence, we can try and append sentences to the previous sentence.
426
				if ( $current_tweet['changed'] && $sentence_count > 0 ) {
427
					// Is this sentence short enough for appending to the current tweet?
428
					if ( self::is_valid_tweet( $current_tweet['text'] . rtrim( $current_sentence ) ) ) {
429
						$current_tweet['text'] .= $current_sentence;
430
431
						self::save_current_tweet( $current_tweet, $block );
432
						continue;
433
					}
434
				}
435
436
				// Will this sentence fit in its own tweet?
437
				if ( self::is_valid_tweet( trim( $current_sentence ) ) ) {
438
					if ( $current_tweet['changed'] ) {
439
						// If we're already in the middle of a block, record the boundary
440
						// before creating a new tweet.
441 View Code Duplication
						if ( $line_count > 0 || $sentence_count > 0 ) {
442
							$current_character_count  += strlen( $current_tweet['text'] );
443
							$current_tweet['boundary'] = self::get_boundary( $block, $current_character_count );
444
445
							self::save_current_tweet( $current_tweet );
446
						}
447
448
						$current_tweet = self::start_new_tweet();
449
					}
450
					$current_tweet['text'] = $current_sentence;
451
452
					self::save_current_tweet( $current_tweet, $block );
453
					continue;
454
				}
455
456
				// This long sentence will start the next tweet that this block is going
457
				// to be turned into, so we need to record the boundary and start a new tweet.
458
				if ( $current_tweet['changed'] ) {
459
					$current_character_count  += strlen( $current_tweet['text'] );
460
					$current_tweet['boundary'] = self::get_boundary( $block, $current_character_count );
461
462
					self::save_current_tweet( $current_tweet );
463
464
					$current_tweet = self::start_new_tweet();
0 ignored issues
show
Unused Code introduced by
$current_tweet is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
465
				}
466
467
				// Split the long sentence into words.
468
				$words      = preg_split( '/(\p{Z})/u', $current_sentence, -1, PREG_SPLIT_DELIM_CAPTURE );
469
				$word_total = count( $words );
470
				for ( $word_count = 0; $word_count < $word_total; $word_count += 2 ) {
471
					// Make sure we have the most recent tweet.
472
					$current_tweet = self::get_current_tweet();
473
474
					// If we're on a new tweet, we don't want to add a space at the start.
475
					if ( ! $current_tweet['changed'] ) {
476
						$current_tweet['text'] = $words[ $word_count ];
477
478
						self::save_current_tweet( $current_tweet, $block );
479
						continue;
480
					}
481
482
					// Can we add this word to the current tweet?
483
					if ( self::is_valid_tweet( "{$current_tweet['text']} {$words[ $word_count ]}…" ) ) {
484
						$space = isset( $words[ $word_count - 1 ] ) ? $words[ $word_count - 1 ] : ' ';
485
486
						$current_tweet['text'] .= $space . $words[ $word_count ];
487
488
						self::save_current_tweet( $current_tweet, $block );
489
						continue;
490
					}
491
492
					// Add one for the space character that we won't include in the tweet text.
493
					$current_character_count += strlen( $current_tweet['text'] ) + 1;
494
495
					// We're starting a new tweet with this word. Append ellipsis to
496
					// the current tweet, then move on.
497
					$current_tweet['text'] .= '…';
498
499
					$current_tweet['boundary'] = self::get_boundary( $block, $current_character_count );
500
					self::save_current_tweet( $current_tweet );
501
502
					$current_tweet = self::start_new_tweet();
503
504
					// If this is the second tweet created by the split sentence, it'll start
505
					// with ellipsis, which we don't want to count, but we do want to count the space
506
					// that was replaced by this ellipsis.
507
					$current_tweet['text']    = "…{$words[ $word_count ]}";
508
					$current_character_count -= strlen( '…' );
509
510
					self::save_current_tweet( $current_tweet, $block );
511
				}
512
			}
513
		}
514
	}
515
516
	/**
517
	 * Check if the block has any media to add, and add it.
518
	 *
519
	 * @param array $block  The block to process.
520
	 */
521
	private static function add_media_to_tweets( $block ) {
522
		// There's some media to attach!
523
		$media_count = count( $block['media'] );
524
		if ( 0 === $media_count ) {
525
			return;
526
		}
527
528
		$current_tweet = self::get_current_tweet();
529
530
		// We can only attach media to the previous tweet if the previous tweet
531
		// doesn't already have media.
532
		if ( count( $current_tweet['media'] ) > 0 ) {
533
			$current_tweet = self::start_new_tweet();
534
		}
535
536
		// Would adding this media make the text of the previous tweet too long?
537
		if ( ! self::is_valid_tweet( $current_tweet['text'], $media_count * self::$characters_per_media ) ) {
538
			$current_tweet = self::start_new_tweet();
539
		}
540
541
		$media = array_values(
542
			array_filter(
543
				$block['media'],
544 View Code Duplication
				function ( $single ) {
545
					// Only images and videos can be uploaded.
546
					if ( 0 === strpos( $single['type'], 'image/' ) || 0 === strpos( $single['type'], 'video/' ) ) {
547
						return true;
548
					}
549
550
					return false;
551
				}
552
			)
553
		);
554
555
		if ( count( $media ) > 0 ) {
556
			if ( 0 === strpos( $media[0]['type'], 'video/' ) || 'image/gif' === $media[0]['type'] ) {
557
				// We can only attach a single video or GIF.
558
				$current_tweet['media'] = array_slice( $media, 0, 1 );
559
			} else {
560
				// Since a GIF or video isn't the first element, we can remove all of them from the array.
561
				$filtered_media = array_values(
562
					array_filter(
563
						$media,
564 View Code Duplication
						function ( $single ) {
565
							if ( 0 === strpos( $single['type'], 'video/' ) || 'image/gif' === $single['type'] ) {
566
								return false;
567
							}
568
569
							return true;
570
						}
571
					)
572
				);
573
				// We can only add the first four images found to the tweet.
574
				$current_tweet['media'] = array_slice( $filtered_media, 0, 4 );
575
			}
576
577
			self::save_current_tweet( $current_tweet, $block );
578
		}
579
	}
580
581
	/**
582
	 * Check if the block has a tweet that we can attach to the current tweet as a quote, and add it.
583
	 *
584
	 * @param array $block  The block to process.
585
	 */
586
	private static function add_tweet_to_tweets( $block ) {
587
		if ( 0 === strlen( $block['tweet'] ) ) {
588
			return;
589
		}
590
591
		$current_tweet = self::get_current_tweet();
592
593
		// We can only attach a tweet to the previous tweet if the previous tweet
594
		// doesn't already have a tweet quoted.
595
		if ( strlen( $current_tweet['tweet'] ) > 0 ) {
596
			$current_tweet = self::start_new_tweet();
597
		}
598
599
		$current_tweet['tweet'] = $block['tweet'];
600
601
		self::save_current_tweet( $current_tweet, $block );
602
	}
603
604
	/**
605
	 * Check if the block has an embed URL that we can append to the current tweet text.
606
	 *
607
	 * @param array $block  The block to process.
608
	 */
609
	private static function add_embed_to_tweets( $block ) {
610
		if ( 0 === strlen( $block['embed'] ) ) {
611
			return;
612
		}
613
614
		$current_tweet = self::get_current_tweet();
615
616
		$reserved_characters  = count( $current_tweet['media'] ) * self::$characters_per_media;
617
		$reserved_characters += 1 + self::$characters_per_url;
618
619
		// We can only attach an embed to the previous tweet if it doesn't already
620
		// have any URLs in it. Also, we can't attach it if it'll make the tweet too long.
621
		if ( preg_match( '/url-placeholder-\d+-*/', $current_tweet['text'] ) || ! self::is_valid_tweet( $current_tweet['text'], $reserved_characters ) ) {
622
			$current_tweet         = self::start_new_tweet();
623
			$current_tweet['text'] = self::generate_url_placeholder( $block['embed'] );
624
		} else {
625
			$current_tweet['text'] .= ' ' . self::generate_url_placeholder( $block['embed'] );
626
		}
627
628
		self::save_current_tweet( $current_tweet, $block );
629
	}
630
631
	/**
632
	 * Given an array of blocks and optional editor information, this will extract them into
633
	 * the internal representation used during parsing.
634
	 *
635
	 * @param array $blocks An array of blocks and optional editor-related information.
636
	 * @return array An array of blocks, in our internal representation.
637
	 */
638
	private static function extract_blocks( $blocks ) {
639
		if ( empty( $blocks ) ) {
640
			return array();
641
		}
642
643
		$block_count = count( $blocks );
644
645
		for ( $ii = 0; $ii < $block_count; $ii++ ) {
646
			if ( ! self::get_block_definition( $blocks[ $ii ]['block']['blockName'] ) ) {
647
				unset( $blocks[ $ii ] );
648
				continue;
649
			}
650
651
			$blocks[ $ii ]['name']  = $blocks[ $ii ]['block']['blockName'];
652
			$blocks[ $ii ]['text']  = self::extract_text_from_block( $blocks[ $ii ]['block'] );
653
			$blocks[ $ii ]['media'] = self::extract_media_from_block( $blocks[ $ii ]['block'] );
654
			$blocks[ $ii ]['tweet'] = self::extract_tweet_from_block( $blocks[ $ii ]['block'] );
655
			$blocks[ $ii ]['embed'] = self::extract_embed_from_block( $blocks[ $ii ]['block'] );
656
		}
657
658
		return array_values( $blocks );
659
	}
660
661
	/**
662
	 * Creates a blank tweet, appends it to the tweets array, and returns the tweet.
663
	 *
664
	 * @return array The blank tweet.
665
	 */
666
	private static function start_new_tweet() {
667
		self::$tweets[] = array(
668
			// An array of blocks that make up this tweet.
669
			'blocks'   => array(),
670
			// If this tweet only contains part of a block, the boundary contains
671
			// information about where in the block the tweet ends.
672
			'boundary' => false,
673
			// The text content of the tweet.
674
			'text'     => '',
675
			// The media content of the tweet.
676
			'media'    => array(),
677
			// The quoted tweet in this tweet.
678
			'tweet'    => '',
679
			// Some blocks force a hard finish to the tweet, even if subsequent blocks
680
			// could technically be appended. This flag shows when a tweet is finished.
681
			'finished' => false,
682
			// Flag if the current tweet already has content in it.
683
			'changed'  => false,
684
		);
685
686
		return self::get_current_tweet();
687
	}
688
689
	/**
690
	 * Get the last tweet in the array.
691
	 *
692
	 * @return array The tweet.
693
	 */
694
	private static function get_current_tweet() {
695
		return end( self::$tweets );
696
	}
697
698
	/**
699
	 * Saves the passed tweet array as the last tweet, overwriting the former last tweet.
700
	 *
701
	 * This method adds some last minute checks: marking the tweet as "changed", as well
702
	 * as adding the $block to the tweet (if it was passed, and hasn't already been added).
703
	 *
704
	 * @param array $tweet       The tweet being stored.
705
	 * @param array $block       Optional. The block that was used to modify this tweet.
0 ignored issues
show
Documentation introduced by
Should the type for parameter $block not be array|null?

This check looks for @param annotations where the type inferred by our type inference engine differs from the declared type.

It makes a suggestion as to what type it considers more descriptive.

Most often this is a case of a parameter that can be null in addition to its declared types.

Loading history...
706
	 * @return array The saved tweet, after the last minute checks have been done.
707
	 */
708
	private static function save_current_tweet( $tweet, $block = null ) {
709
		$tweet['changed'] = true;
710
711
		if ( isset( $block ) ) {
712
			$block_def = self::get_block_definition( $block['name'] );
713
714
			// Check if this block type will be forcing a new tweet.
715
			if ( $block_def['force_finished'] ) {
716
				$tweet['finished'] = true;
717
			}
718
719
			// Check if this block is already recorded against this tweet.
720
			$last_block = end( $tweet['blocks'] );
721
			if ( isset( $block['clientId'] ) && ( false === $last_block || $last_block['clientId'] !== $block['clientId'] ) ) {
722
				$tweet['blocks'][] = $block;
723
			}
724
		}
725
726
		// Find the index of the last tweet in the array.
727
		end( self::$tweets );
728
		$tweet_index = key( self::$tweets );
729
730
		self::$tweets[ $tweet_index ] = $tweet;
731
732
		return $tweet;
733
	}
734
735
	/**
736
	 * Checks if the passed text is valid for a tweet or not.
737
	 *
738
	 * @param string $text                The text to check.
739
	 * @param int    $reserved_characters Optional. The number of characters to reduce the maximum tweet length by.
740
	 * @return bool Whether or not the text is valid.
741
	 */
742
	private static function is_valid_tweet( $text, $reserved_characters = 0 ) {
743
		return self::is_within_twitter_length( $text, 280 - $reserved_characters );
744
	}
745
746
	/**
747
	 * Checks if the passed text is valid for image alt text.
748
	 *
749
	 * @param string $text The text to check.
750
	 * @return bool Whether or not the text is valid.
751
	 */
752
	private static function is_valid_alt_text( $text ) {
753
		return self::is_within_twitter_length( $text, 1000 );
754
	}
755
756
	/**
757
	 * Check if a string is shorter than a given length, according to Twitter's rules for counting string length.
758
	 *
759
	 * @param string $text       The text to check.
760
	 * @param int    $max_length The number of characters long this string can be.
761
	 * @return bool Whether or not the string is no longer than the length limit.
762
	 */
763
	private static function is_within_twitter_length( $text, $max_length ) {
764
		// Replace all multiline separators with a \n, since that's the
765
		// character we actually want to count.
766
		$text = str_replace( self::$line_separator, "\n", $text );
767
768
		// Keep a running total of characters we've removed.
769
		$stripped_characters = 0;
770
771
		// Since we use '…' a lot, strip it out, so we can still use the ASCII checks.
772
		$ellipsis_count = 0;
773
		$text           = str_replace( '…', '', $text, $ellipsis_count );
774
775
		// The ellipsis glyph counts for two characters.
776
		$stripped_characters += $ellipsis_count * 2;
777
778
		// Try filtering out emoji first, since ASCII text + emoji is a relatively common case.
779
		if ( ! self::is_ascii( $text ) ) {
780
			// Initialise the emoji cache.
781
			if ( 0 === count( self::$emoji_list ) ) {
782
				self::$emoji_list = array_map( 'html_entity_decode', _wp_emoji_list( 'entities' ) );
783
			}
784
785
			$emoji_count = 0;
786
			$text        = str_replace( self::$emoji_list, '', $text, $emoji_count );
787
788
			// Emoji graphemes count as 2 characters each.
789
			$stripped_characters += $emoji_count * 2;
790
		}
791
792
		if ( self::is_ascii( $text ) ) {
793
			$stripped_characters += strlen( $text );
794
			if ( $stripped_characters <= $max_length ) {
795
				return true;
796
			}
797
798
			return false;
799
		}
800
801
		// Remove any glyphs that count as 1 character.
802
		// Source: https://github.com/twitter/twitter-text/blob/master/config/v3.json .
803
		// Note that the source ranges are in decimal, the regex ranges are converted to hex.
804
		$single_character_count = 0;
805
		$text                   = preg_replace( '/[\x{0000}-\x{10FF}\x{2000}-\x{200D}\x{2010}-\x{201F}\x{2032}-\x{2037}]/uS', '', $text, -1, $single_character_count );
806
807
		$stripped_characters += $single_character_count;
808
809
		// Check if there's any text we haven't counted yet.
810
		// Any remaining glyphs count as 2 characters each.
811
		if ( 0 !== strlen( $text ) ) {
812
			// WP provides a compat version of mb_strlen(), no need to check if it exists.
813
			$stripped_characters += mb_strlen( $text, 'UTF-8' ) * 2;
814
		}
815
816
		if ( $stripped_characters <= $max_length ) {
817
			return true;
818
		}
819
820
		return false;
821
	}
822
823
	/**
824
	 * Checks if a string only contains ASCII characters.
825
	 *
826
	 * @param string $text The string to check.
827
	 * @return bool Whether or not the string is ASCII-only.
828
	 */
829
	private static function is_ascii( $text ) {
830
		if ( function_exists( 'mb_check_encoding' ) ) {
831
			if ( mb_check_encoding( $text, 'ASCII' ) ) {
832
				return true;
833
			}
834
		} elseif ( ! preg_match( '/[^\x00-\x7F]/', $text ) ) {
835
			return true;
836
		}
837
838
		return false;
839
	}
840
841
	/**
842
	 * A block will generate a certain amount of text to be inserted into a tweet. If that text is too
843
	 * long for a tweet, we already know where the text will be split when it's published as tweet, but
844
	 * we need to calculate where that corresponds to in the block edit UI.
845
	 *
846
	 * The tweet template for that block may add extra characters, extra characters are added for URL
847
	 * placeholders, and the block may contain multiple RichText areas (corresponding to attributes),
848
	 * so we need to keep track of both until the this function calculates which attribute area (in the
849
	 * block editor, the richTextIdentifier) that offset corresponds to, and how far into that attribute
850
	 * area it is.
851
	 *
852
	 * @param array   $block  The block being checked.
853
	 * @param integer $offset The position in the tweet text where it will be split.
854
	 * @return array|false `false` if the boundary can't be determined. Otherwise, returns the
855
	 *                     position in the block editor to insert the tweet boundary annotation.
856
	 */
857
	private static function get_boundary( $block, $offset ) {
858
		// If we don't have a clientId, there's no point in generating a boundary, since this
859
		// parse request doesn't have a way to map blocks back to editor UI.
860
		if ( ! isset( $block['clientId'] ) ) {
861
			return false;
862
		}
863
864
		$block_def = self::get_block_definition( $block['name'] );
865
866 View Code Duplication
		if ( isset( $block_def['content'] ) && count( $block_def['content'] ) > 0 ) {
867
			$tags = $block_def['content'];
868
		} else {
869
			$tags = array( 'content' );
870
		}
871
872
		$tag_content = self::extract_tag_content_from_html( $tags, $block['block']['innerHTML'] );
873
874
		// $tag_content is split up by tag first, then lines. We want to remap it to split it by lines
875
		// first, then tag.
876
		$lines = array();
877
		foreach ( $tag_content as $tag => $content ) {
878
			if ( 'content' === $tag ) {
879
				$attribute_name = 'content';
880
			} else {
881
				$attribute_name = array_search( $tag, $block_def['content'], true );
882
			}
883
884
			foreach ( $content as $id => $content_string ) {
885
				// Multiline blocks can have multiple lines, but other blocks will always only have 1.
886
				if ( 'multiline' === $block_def['type'] ) {
887
					$line_number = $id;
888
				} else {
889
					$line_number = 0;
890
				}
891
892
				if ( ! isset( $lines[ $line_number ] ) ) {
893
					$lines[ $line_number ] = array();
894
				}
895
896
				if ( ! isset( $lines[ $line_number ][ $attribute_name ] ) ) {
897
					// For multiline blocks, or the first time this attribute has been encountered
898
					// in single line blocks, assign the string to the line/attribute.
899
					$lines[ $line_number ][ $attribute_name ] = $content_string;
900
				} else {
901
					// For subsequent times this line/attribute is encountered (only in single line blocks),
902
					// append the string with a line break.
903
					$lines[ $line_number ][ $attribute_name ] .= "\n$content_string";
904
				}
905
			}
906
		}
907
908
		$line_count = count( $lines );
909
910
		$template_parts = preg_split( '/({{\w+}})/', $block_def['template'], -1, PREG_SPLIT_DELIM_CAPTURE );
911
912
		// Keep track of the total number of bytes we've processed from this block.
913
		$total_bytes_processed = 0;
914
915
		// Keep track of the number of characters that the processed data translates to in the editor.
916
		$characters_processed = 0;
917
918
		foreach ( $lines as $line_number => $line ) {
919
			// Add up the length of all the parts of this line.
920
			$line_byte_total = array_sum( array_map( 'strlen', $line ) );
921
922
			if ( $line_byte_total > 0 ) {
923
				// We have something to use in the template, so loop over each part of the template, and count it.
924
				foreach ( $template_parts as $template_part ) {
925
					$matches = array();
926
					if ( preg_match( '/{{(\w+)}}/', $template_part, $matches ) ) {
927
						$part_name = $matches[1];
928
929
						$line_part_data  = $line[ $part_name ];
930
						$line_part_bytes = strlen( $line_part_data );
931
932
						$cleaned_line_part_data = preg_replace( '/ \(url-placeholder-\d+-*\)/', '', $line_part_data );
933
934
						$cleaned_line_part_data = preg_replace_callback(
935
							'/url-placeholder-(\d+)-*/',
936
							function ( $matches ) {
937
								return self::$urls[ $matches[1] ];
938
							},
939
							$cleaned_line_part_data
940
						);
941
942
						if ( $total_bytes_processed + $line_part_bytes >= $offset ) {
943
							// We know that the offset is somewhere inside this part of the tweet, but we need to remove the length
944
							// of any URL placeholders that appear before the boundary, to be able to calculate the correct attribute offset.
945
946
							// $total_bytes_processed is the sum of everything we've processed so far, (including previous parts)
947
							// on this line. This makes it relatively easy to calculate the number of bytes into this part
948
							// that the boundary will occur.
949
							$line_part_byte_boundary = $offset - $total_bytes_processed;
950
951
							// Grab the data from this line part that appears before the boundary.
952
							$line_part_pre_boundary_data = substr( $line_part_data, 0, $line_part_byte_boundary );
953
954
							// Remove any URL placeholders, since these aren't shown in the editor.
955
							$line_part_pre_boundary_data = preg_replace( '/ \(url-placeholder-\d+-*\)/', '', $line_part_pre_boundary_data );
956
957
							$line_part_pre_boundary_data = preg_replace_callback(
958
								'/url-placeholder-(\d+)-*/',
959
								function ( $matches ) {
960
									return self::$urls[ $matches[1] ];
961
								},
962
								$line_part_pre_boundary_data
963
							);
964
965
							$boundary_start = self::utf_16_code_unit_length( $line_part_pre_boundary_data ) - 1;
966
967
							// Multiline blocks need to offset for the characters that are in the same content area,
968
							// but which were counted on previous lines.
969
							if ( 'multiline' === $block_def['type'] ) {
970
								$boundary_start += $characters_processed;
971
							}
972
973
							return array(
974
								'start'     => $boundary_start,
975
								'end'       => $boundary_start + 1,
976
								'container' => $part_name,
977
								'type'      => 'normal',
978
							);
979
						} else {
980
							$total_bytes_processed += $line_part_bytes;
981
							$characters_processed  += self::utf_16_code_unit_length( $cleaned_line_part_data );
982
							continue;
983
						}
984
					} else {
985
						$total_bytes_processed += strlen( $template_part );
986
					}
987
				}
988
989
				// Are we breaking at the end of this line?
990
				if ( $total_bytes_processed + 1 === $offset && $line_count > 1 ) {
991
					reset( $block_def['content'] );
992
					$container = key( $block_def['content'] );
993
					return array(
994
						'line'      => $line_number,
995
						'container' => $container,
996
						'type'      => 'end-of-line',
997
					);
998
				}
999
1000
				// The newline at the end of each line is 1 byte, but we don't need to count empty lines.
1001
				$total_bytes_processed++;
1002
			}
1003
1004
			// We do need to count empty lines in the editor, since they'll be displayed.
1005
			$characters_processed++;
1006
		}
1007
1008
		return false;
1009
	}
1010
1011
	/**
1012
	 * JavaScript uses UTF-16 for encoding strings, which means we need to provide UTF-16
1013
	 * based offsets for the block editor to render tweet boundaries in the correct location.
1014
	 *
1015
	 * UTF-16 is a variable-width character encoding: every code unit is 2 bytes, a single character
1016
	 * can be one or two code units long. Fortunately for us, JavaScript's String.charAt() is based
1017
	 * on the older UCS-2 character encoding, which only counts single code units. PHP's strlen()
1018
	 * counts a code unit as being 2 characters, so once a string is converted to UTF-16, we have
1019
	 * a fast way to determine how long it is in UTF-16 code units.
1020
	 *
1021
	 * @param string $text The natively encoded string to get the length of.
1022
	 * @return int The length of the string in UTF-16 code units. Returns -1 if the length could not
1023
	 *             be calculated.
1024
	 */
1025
	private static function utf_16_code_unit_length( $text ) {
1026
		// If mb_convert_encoding() exists, we can use that for conversion.
1027
		if ( function_exists( 'mb_convert_encoding' ) ) {
1028
			// UTF-16 can add an additional code unit to the start of the string, called the
1029
			// Byte Order Mark (BOM), which indicates whether the string is encoding as
1030
			// big-endian, or little-endian. Since we don't want to count code unit, and the endianness
1031
			// doesn't matter for our purposes, using PHP's UTF-16BE encoding uses big-endian
1032
			// encoding, and ensures the BOM *won't* be prepended to the string to the string.
1033
			return strlen( mb_convert_encoding( $text, 'UTF-16BE' ) ) / 2;
1034
		}
1035
1036
		// If we can't convert this string, return a result that will avoid an incorrect annotation being added.
1037
		return -1;
1038
	}
1039
1040
	/**
1041
	 * Extracts the tweetable text from a block.
1042
	 *
1043
	 * @param array $block A single block, as generated by parse_block().
1044
	 * @return string The tweetable text from the block, in the correct template form.
1045
	 */
1046
	private static function extract_text_from_block( $block ) {
1047
		// If the block doesn't have an innerHTMl, we're not going to get any text.
1048
		if ( empty( $block['innerHTML'] ) ) {
1049
			return '';
1050
		}
1051
1052
		$block_def = self::get_block_definition( $block['blockName'] );
1053
1054
		// We currently only support extracting text from HTML text nodes.
1055
		if ( ! isset( $block_def['content_location'] ) || 'html' !== $block_def['content_location'] ) {
1056
			return '';
1057
		}
1058
1059
		// Find out which tags we need to extract content from.
1060 View Code Duplication
		if ( isset( $block_def['content'] ) && count( $block_def['content'] ) > 0 ) {
1061
			$tags = $block_def['content'];
1062
		} else {
1063
			$tags = array( 'content' );
1064
		}
1065
1066
		$tag_values = self::extract_tag_content_from_html( $tags, $block['innerHTML'] );
1067
1068
		// We can treat single line blocks as "multiline", with only one line in them.
1069
		$lines = array();
1070
		foreach ( $tag_values as $tag => $values ) {
1071
			// For single-line blocks, we need to squash all the values for this tag into a single value.
1072
			if ( 'multiline' !== $block_def['type'] ) {
1073
				$values = array( trim( implode( "\n", $values ) ) );
1074
			}
1075
1076
			// Handle the special "content" tag.
1077
			if ( 'content' === $tag ) {
1078
				$placeholder = 'content';
1079
			} else {
1080
				$placeholder = array_search( $tag, $block_def['content'], true );
1081
			}
1082
1083
			// Loop over each instance of this value, appling that value to the corresponding line template.
1084
			foreach ( $values as $line_number => $value ) {
1085
				if ( ! isset( $lines[ $line_number ] ) ) {
1086
					$lines[ $line_number ] = $block_def['template'];
1087
				}
1088
1089
				$lines[ $line_number ] = str_replace( '{{' . $placeholder . '}}', $value, $lines[ $line_number ] );
1090
			}
1091
		}
1092
1093
		// Remove any lines that didn't apply any content.
1094
		$empty_template = preg_replace( '/{{.*?}}/', '', $block_def['template'] );
1095
		$lines          = array_filter(
1096
			$lines,
1097
			function ( $line ) use ( $empty_template ) {
1098
				return $line !== $empty_template;
1099
			}
1100
		);
1101
1102
		// Join the lines together into a single string.
1103
		$text = implode( self::$line_separator, $lines );
1104
1105
		// Trim off any extra whitespace that we no longer need.
1106
		$text = trim( $text );
1107
		$text = preg_replace( '/(' . self::$line_separator . ')+$/', '', $text );
1108
1109
		return $text;
1110
	}
1111
1112
	/**
1113
	 * Extracts the tweetable media from a block.
1114
	 *
1115
	 * @param array $block A single block, as generated by parse_block().
1116
	 * @return array {
1117
	 *     An array of media.
1118
	 *
1119
	 *     @type string url The URL of the media.
1120
	 *     @type string alt The alt text of the media.
1121
	 * }
1122
	 */
1123
	private static function extract_media_from_block( $block ) {
1124
		$block_def = self::get_block_definition( $block['blockName'] );
1125
1126
		$media = array();
1127
1128
		if ( 'image' === $block_def['type'] ) {
1129
			$url = self::extract_attr_content_from_html(
1130
				$block_def['content']['url'][0],
1131
				$block_def['content']['url'][1],
1132
				$block['innerHTML']
1133
			);
1134
			$alt = self::extract_attr_content_from_html(
1135
				$block_def['content']['alt'][0],
1136
				$block_def['content']['alt'][1],
1137
				$block['innerHTML']
1138
			);
1139
1140
			$img_count = count( $url );
1141
1142
			for ( $ii = 0; $ii < $img_count; $ii++ ) {
1143
				$filedata = wp_check_filetype( basename( wp_parse_url( $url[ $ii ], PHP_URL_PATH ) ) );
0 ignored issues
show
Unused Code introduced by
The call to wp_parse_url() has too many arguments starting with PHP_URL_PATH.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
1144
1145
				$media[] = array(
1146
					'url'  => $url[ $ii ],
1147
					'alt'  => self::is_valid_alt_text( $alt[ $ii ] ) ? $alt[ $ii ] : '',
1148
					'type' => $filedata['type'],
1149
				);
1150
			}
1151
		} elseif ( 'video' === $block_def['type'] ) {
1152
			// Handle VideoPress videos.
1153
			if ( isset( $block['attrs']['src'] ) && 0 === strpos( $block['attrs']['src'], 'https://videos.files.wordpress.com/' ) ) {
1154
				$url = array( $block['attrs']['src'] );
1155
			} else {
1156
				$url = self::extract_attr_content_from_html(
1157
					$block_def['content']['url'][0],
1158
					$block_def['content']['url'][1],
1159
					$block['innerHTML']
1160
				);
1161
			}
1162
1163
			// We can only ever use the first video found, no need to go through all of them.
1164
			if ( count( $url ) > 0 ) {
1165
				$filedata = wp_check_filetype( basename( wp_parse_url( $url[0], PHP_URL_PATH ) ) );
0 ignored issues
show
Unused Code introduced by
The call to wp_parse_url() has too many arguments starting with PHP_URL_PATH.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
1166
1167
				$media[] = array(
1168
					'url'  => $url[0],
1169
					'type' => $filedata['type'],
1170
				);
1171
			}
1172
		}
1173
1174
		return $media;
1175
	}
1176
1177
	/**
1178
	 * Extracts the tweet URL from a Twitter embed block.
1179
	 *
1180
	 * @param array $block A single block, as generated by parse_block().
1181
	 * @return string The tweet URL. Empty string if there is none available.
1182
	 */
1183
	private static function extract_tweet_from_block( $block ) {
1184 View Code Duplication
		if ( 'core/embed' === $block['blockName'] && 'twitter' === $block['attrs']['providerNameSlug'] ) {
1185
			return $block['attrs']['url'];
1186
		}
1187
1188
		// @todo This fallback can be removed when WordPress 5.6 is the minimum supported version.
1189
		if ( 'core-embed/twitter' === $block['blockName'] ) {
1190
			return $block['attrs']['url'];
1191
		}
1192
1193
		return '';
1194
	}
1195
1196
	/**
1197
	 * Extracts URL from an embed block.
1198
	 *
1199
	 * @param array $block A single block, as generated by parse_block().
1200
	 * @return string The URL. Empty string if there is none available.
1201
	 */
1202
	private static function extract_embed_from_block( $block ) {
1203
		$block_def = self::get_block_definition( $block['blockName'] );
1204
1205
		if ( 'embed' !== $block_def['type'] ) {
1206
			return '';
1207
		}
1208
1209
		// Twitter embeds are handled in ::extract_tweet_from_block().
1210 View Code Duplication
		if ( 'core/embed' === $block['blockName'] && 'twitter' === $block['attrs']['providerNameSlug'] ) {
1211
			return '';
1212
		}
1213
1214
		// @todo This fallback can be removed when WordPress 5.6 is the minimum supported version.
1215
		if ( 'core-embed/twitter' === $block['blockName'] ) {
1216
			return '';
1217
		}
1218
1219
		$url = '';
1220
		if ( 'block-attributes' === $block_def['content_location'] ) {
1221
			$url = $block['attrs'][ $block_def['content'][0] ];
1222
		}
1223
1224
		if ( 'jetpack/gif' === $block['blockName'] ) {
1225
			$url = str_replace( '/embed/', '/gifs/', $url );
1226
		}
1227
1228
		return $url;
1229
	}
1230
1231
	/**
1232
	 * There's a bunch of left-over cruft in the tweets array that we don't need to return. Removing
1233
	 * it helps keep the size of the data down.
1234
	 */
1235
	private static function clean_return_tweets() {
1236
		// Before we return, clean out unnecessary cruft from the return data.
1237
		$tweets = array_map(
1238
			function ( $tweet ) {
1239
				// Remove tweets that don't have anything saved in them. eg, if the last block is a
1240
				// header with no text, it'll force a new tweet, but we won't end up putting anything
1241
				// in that tweet.
1242
				if ( ! $tweet['changed'] ) {
1243
					return false;
1244
				}
1245
1246
				// Replace any URL placeholders that appear in the text.
1247
				$tweet['urls'] = array();
1248
				foreach ( self::$urls as $id => $url ) {
1249
					$count = 0;
1250
1251
					$tweet['text'] = str_replace( str_pad( "url-placeholder-$id", self::$characters_per_url, '-' ), $url, $tweet['text'], $count );
1252
1253
					// If we found a URL, keep track of it for the editor.
1254
					if ( $count > 0 ) {
1255
						$tweet['urls'][] = $url;
1256
					}
1257
				}
1258
1259
				// Remove any inline placeholders.
1260
				$tweet['text'] = str_replace( self::$inline_placeholder, '', $tweet['text'] );
1261
1262
				// Tidy up the whitespace.
1263
				$tweet['text'] = trim( $tweet['text'] );
1264
				$tweet['text'] = preg_replace( '/[ \t]+\n/', "\n", $tweet['text'] );
1265
1266
				// Remove internal flags.
1267
				unset( $tweet['changed'] );
1268
				unset( $tweet['finished'] );
1269
1270
				// Remove bulky block data.
1271
				if ( ! isset( $tweet['blocks'][0]['attributes'] ) && ! isset( $tweet['blocks'][0]['clientId'] ) ) {
1272
					$tweet['blocks'] = array();
1273
				} else {
1274
					// Remove the parts of the block data that the editor doesn't need.
1275
					$block_count = count( $tweet['blocks'] );
1276
					for ( $ii = 0; $ii < $block_count; $ii++ ) {
1277
						$keys = array_keys( $tweet['blocks'][ $ii ] );
1278
						foreach ( $keys as $key ) {
1279
							// The editor only needs these attributes, everything else will be unset.
1280
							if ( in_array( $key, array( 'attributes', 'clientId' ), true ) ) {
1281
								continue;
1282
							}
1283
1284
							unset( $tweet['blocks'][ $ii ][ $key ] );
1285
						}
1286
					}
1287
				}
1288
1289
				return $tweet;
1290
			},
1291
			self::$tweets
1292
		);
1293
1294
		// Clean any removed tweets out of the result.
1295
		return array_values( array_filter( $tweets, 'is_array' ) );
1296
	}
1297
1298
	/**
1299
	 * Given a list of tags and a HTML blob, this will extract the text content inside
1300
	 * each of the given tags.
1301
	 *
1302
	 * @param array  $tags An array of tag names.
1303
	 * @param string $html A blob of HTML.
1304
	 * @return array An array of the extract content. The keys in the array are the $tags,
1305
	 *               each value is an array. The value array is indexed in the same order as the tag
1306
	 *               appears in the HTML blob, including nested tags.
1307
	 */
1308
	private static function extract_tag_content_from_html( $tags, $html ) {
1309
		// Normalise <br>.
1310
		$html = preg_replace( '/<br\s*\/?>/', '<br>', $html );
1311
1312
		// If there were no tags passed, assume the entire text is required.
1313
		if ( empty( $tags ) ) {
1314
			$tags = array( 'content' );
1315
		}
1316
1317
		$values = array();
1318
1319
		$tokens = wp_html_split( $html );
1320
1321
		$validator = new Twitter_Validator();
1322
1323
		foreach ( $tags as $tag ) {
1324
			$values[ $tag ] = array();
1325
1326
			// Since tags can be nested, keeping track of the nesting level allows
1327
			// us to extract nested content into a flat array.
1328
			if ( 'content' === $tag ) {
1329
				// The special "content" tag means we should store the entire content,
1330
				// so assume the tag is open from the beginning.
1331
				$opened = 0;
1332
				$closed = -1;
1333
1334
				$values['content'][0] = '';
1335
			} else {
1336
				$opened = -1;
1337
				$closed = -1;
1338
			}
1339
1340
			// When we come across a URL, we need to keep track of it, so it can then be inserted
1341
			// in the right place.
1342
			$current_url = '';
1343
			foreach ( $tokens as $token ) {
1344
				if ( 0 === strlen( $token ) ) {
1345
					// Skip any empty tokens.
1346
					continue;
1347
				}
1348
1349
				// If we're currently storing content, check if it's a text-formatting
1350
				// tag that we should apply.
1351
				if ( $opened !== $closed ) {
1352
					// End of a paragraph, put in some newlines (as long as we're not extracting paragraphs).
1353
					if ( '</p>' === $token && 'p' !== $tag ) {
1354
						$values[ $tag ][ $opened ] .= "\n\n";
1355
					}
1356
1357
					// A line break gets one newline.
1358
					if ( '<br>' === $token ) {
1359
						$values[ $tag ][ $opened ] .= "\n";
1360
					}
1361
1362
					// A link has opened, grab the URL for inserting later.
1363
					if ( 0 === strpos( $token, '<a ' ) ) {
1364
						$href_values = self::extract_attr_content_from_html( 'a', 'href', $token );
1365
						if ( ! empty( $href_values[0] ) && $validator->isValidURL( $href_values[0] ) ) {
1366
							// Remember the URL.
1367
							$current_url = $href_values[0];
1368
						}
1369
					}
1370
1371
					// A link has closed, insert the URL from that link if we have one.
1372
					if ( '</a>' === $token && '' !== $current_url ) {
1373
						// Generate a unique-to-this-block placeholder which takes up the
1374
						// same number of characters as a URL does.
1375
						$values[ $tag ][ $opened ] .= ' (' . self::generate_url_placeholder( $current_url ) . ')';
1376
1377
						$current_url = '';
1378
					}
1379
1380
					// We don't return inline images, but they technically take up 1 character in the RichText.
1381
					if ( 0 === strpos( $token, '<img ' ) ) {
1382
						$values[ $tag ][ $opened ] .= self::$inline_placeholder;
1383
					}
1384
				}
1385
1386
				if ( "<$tag>" === $token || 0 === strpos( $token, "<$tag " ) ) {
1387
					// A tag has just been opened.
1388
					$opened++;
1389
					// Set an empty value now, so we're keeping track of empty tags.
1390
					if ( ! isset( $values[ $tag ][ $opened ] ) ) {
1391
						$values[ $tag ][ $opened ] = '';
1392
					}
1393
					continue;
1394
				}
1395
1396
				if ( "</$tag>" === $token ) {
1397
					// The tag has been closed.
1398
					$closed++;
1399
					continue;
1400
				}
1401
1402
				if ( '<' === $token[0] ) {
1403
					// We can skip any other tags.
1404
					continue;
1405
				}
1406
1407
				if ( $opened !== $closed ) {
1408
					// We're currently in a tag, with some content. Start by decoding any HTML entities.
1409
					$token = html_entity_decode( $token, ENT_QUOTES );
1410
1411
					// Find any URLs in this content, and replace them with a placeholder.
1412
					preg_match_all( Twitter_Regex::getValidUrlMatcher(), $token, $matches, PREG_SET_ORDER | PREG_OFFSET_CAPTURE );
1413
					$offset = 0;
1414
					foreach ( $matches as $match ) {
0 ignored issues
show
Bug introduced by
The expression $matches of type null|array<integer,array<integer,string>> is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
1415
						list( $url, $start ) = $match[2];
1416
1417
						$token = substr_replace( $token, self::generate_url_placeholder( $url ), $start + $offset, strlen( $url ) );
1418
1419
						$offset += self::$characters_per_url - strlen( $url );
1420
1421
						// If we're in a link with a URL set, there's no need to keep two copies of the same link.
1422
						if ( ! empty( $current_url ) ) {
1423
							$lower_url         = strtolower( $url );
1424
							$lower_current_url = strtolower( $current_url );
1425
1426
							if ( $lower_url === $lower_current_url ) {
1427
								$current_url = '';
1428
							}
1429
1430
							// Check that the link text isn't just a shortened version of the href value.
1431
							$trimmed_current_url = preg_replace( '|^https?://|', '', $lower_current_url );
1432
							if ( $lower_url === $trimmed_current_url || trim( $trimmed_current_url, '/' ) === $lower_url ) {
1433
								$current_url = '';
1434
							}
1435
						}
1436
					}
1437
1438
					// Append it to the right value.
1439
					$values[ $tag ][ $opened ] .= $token;
1440
				}
1441
			}
1442
		}
1443
1444
		return $values;
1445
	}
1446
1447
	/**
1448
	 * Extracts the attribute content from a tag.
1449
	 *
1450
	 * This method allows for the HTML to have multiple instances of the tag, and will return
1451
	 * an array containing the attribute value (or an empty string, if the tag doesn't have the
1452
	 * requested attribute) for each occurrence of the tag.
1453
	 *
1454
	 * @param string $tag          The tag we're looking for.
1455
	 * @param string $attr         The name of the attribute we're looking for.
1456
	 * @param string $html         The HTML we're searching through.
1457
	 * @param array  $attr_filters Optional. Filters tags based on whether or not they have attributes with given values.
1458
	 * @return array The array of attribute values found.
1459
	 */
1460
	private static function extract_attr_content_from_html( $tag, $attr, $html, $attr_filters = array() ) {
1461
		// Given our single tag and attribute, construct a KSES filter for it.
1462
		$kses_filter = array(
1463
			$tag => array(
1464
				$attr => array(),
1465
			),
1466
		);
1467
1468
		foreach ( $attr_filters as $filter_attr => $filter_value ) {
1469
			$kses_filter[ $tag ][ $filter_attr ] = array();
1470
		}
1471
1472
		// Remove all HTML except for the tag we're after. On that tag,
1473
		// remove all attributes except for the one we're after.
1474
		$stripped_html = wp_kses( $html, $kses_filter );
1475
1476
		$values = array();
1477
1478
		$tokens = wp_html_split( $stripped_html );
1479
		foreach ( $tokens as $token ) {
1480
			$found_value = '';
1481
1482
			if ( 0 === strlen( $token ) ) {
1483
				// Skip any empty tokens.
1484
				continue;
1485
			}
1486
1487
			if ( '<' !== $token[0] ) {
1488
				// We can skip any non-tag tokens.
1489
				continue;
1490
			}
1491
1492
			$token_attrs = wp_kses_attr_parse( $token );
1493
1494
			// Skip tags that KSES couldn't handle.
1495
			if ( false === $token_attrs ) {
1496
				continue;
1497
			}
1498
1499
			// Remove the tag open and close chunks.
1500
			$found_tag = array_shift( $token_attrs );
1501
			array_pop( $token_attrs );
1502
1503
			// We somehow got a tag that isn't the one we're after. Skip it.
1504
			if ( 0 !== strpos( $found_tag, "<$tag " ) ) {
1505
				continue;
1506
			}
1507
1508
			// We can only fail an attribute filter if one is set.
1509
			$passed_filter = count( $attr_filters ) === 0;
1510
1511
			foreach ( $token_attrs as $token_attr_string ) {
1512
				// The first "=" in the string will be between the attribute name/value.
1513
				list( $token_attr_name, $token_attr_value ) = explode( '=', $token_attr_string, 2 );
1514
1515
				$token_attr_name  = trim( $token_attr_name );
1516
				$token_attr_value = trim( $token_attr_value );
1517
1518
				// Remove a single set of quotes from around the value.
1519
				if ( '' !== $token_attr_value && in_array( $token_attr_value[0], array( '"', "'" ), true ) ) {
1520
					$token_attr_value = trim( $token_attr_value, $token_attr_value[0] );
1521
				}
1522
1523
				// If this is the attribute we're after, save the value for the end of the loop.
1524
				if ( $token_attr_name === $attr ) {
1525
					$found_value = $token_attr_value;
1526
				}
1527
1528
				if ( isset( $attr_filters[ $token_attr_name ] ) && $attr_filters[ $token_attr_name ] === $token_attr_value ) {
1529
					$passed_filter = true;
1530
				}
1531
			}
1532
1533
			if ( $passed_filter ) {
1534
				// We always want to append the found value, even if we didn't "find" a matching attribute.
1535
				// An empty string in the return value means that we found the tag, but the attribute was
1536
				// either empty, or not set.
1537
				$values[] = html_entity_decode( $found_value, ENT_QUOTES );
1538
			}
1539
		}
1540
1541
		return $values;
1542
	}
1543
1544
	/**
1545
	 * Generates a placeholder for URLs, using the appropriate number of characters to imitate how
1546
	 * Twitter counts the length of URLs in tweets.
1547
	 *
1548
	 * @param string $url The URL to generate a placeholder for.
1549
	 * @return string The placeholder.
1550
	 */
1551
	public static function generate_url_placeholder( $url ) {
1552
		self::$urls[] = $url;
1553
1554
		return str_pad( 'url-placeholder-' . ( count( self::$urls ) - 1 ), self::$characters_per_url, '-' );
1555
	}
1556
1557
	/**
1558
	 * Retrieves the Twitter card data for a list of URLs.
1559
	 *
1560
	 * @param array $urls The list of URLs to grab Twitter card data for.
1561
	 * @return array The Twitter card data.
1562
	 */
1563
	public static function generate_cards( $urls ) {
1564
		$requests = array_map(
1565
			function ( $url ) {
1566
				return array(
1567
					'url' => $url,
1568
				);
1569
			},
1570
			$urls
1571
		);
1572
1573
		$results = Requests::request_multiple( $requests );
1574
1575
		$card_data = array(
1576
			'creator'     => array(
1577
				'name' => 'twitter:creator',
1578
			),
1579
			'description' => array(
1580
				'name'     => 'twitter:description',
1581
				'property' => 'og:description',
1582
			),
1583
			'image'       => array(
1584
				'name'     => 'twitter:image',
1585
				'property' => 'og:image:secure',
1586
				'property' => 'og:image',
1587
			),
1588
			'title'       => array(
1589
				'name'     => 'twitter:text:title',
1590
				'property' => 'og:title',
1591
			),
1592
			'type'        => array(
1593
				'name' => 'twitter:card',
1594
			),
1595
		);
1596
1597
		$cards = array();
1598
		foreach ( $results as $result ) {
1599
			if ( count( $result->history ) > 0 ) {
1600
				$url = $result->history[0]->url;
1601
			} else {
1602
				$url = $result->url;
1603
			}
1604
1605
			if ( ! $result->success ) {
1606
				$cards[ $url ] = array(
1607
					'error' => 'invalid_url',
1608
				);
1609
				continue;
1610
			}
1611
1612
			$url_card_data = array();
1613
1614
			foreach ( $card_data as $key => $filters ) {
1615
				foreach ( $filters as $attribute => $value ) {
1616
					$found_data = self::extract_attr_content_from_html( 'meta', 'content', $result->body, array( $attribute => $value ) );
1617
					if ( count( $found_data ) > 0 && strlen( $found_data[0] ) > 0 ) {
1618
						$url_card_data[ $key ] = html_entity_decode( $found_data[0], ENT_QUOTES );
1619
						break;
1620
					}
1621
				}
1622
			}
1623
1624
			if ( count( $url_card_data ) > 0 ) {
1625
				$cards[ $url ] = $url_card_data;
1626
			} else {
1627
				$cards[ $url ] = array(
1628
					'error' => 'no_og_data',
1629
				);
1630
			}
1631
		}
1632
1633
		return $cards;
1634
	}
1635
1636
	/**
1637
	 * Get the WPCOM or self-hosted site ID.
1638
	 *
1639
	 * @return mixed
1640
	 */
1641 View Code Duplication
	public static function get_site_id() {
1642
		$is_wpcom = ( defined( 'IS_WPCOM' ) && IS_WPCOM );
1643
		$site_id  = $is_wpcom ? get_current_blog_id() : Jetpack_Options::get_option( 'id' );
1644
		if ( ! $site_id ) {
1645
			return new WP_Error(
1646
				'unavailable_site_id',
0 ignored issues
show
Unused Code introduced by
The call to WP_Error::__construct() has too many arguments starting with 'unavailable_site_id'.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
1647
				__( 'Sorry, something is wrong with your Jetpack connection.', 'jetpack' ),
1648
				403
1649
			);
1650
		}
1651
		return (int) $site_id;
1652
	}
1653
}
1654