Completed
Push — update/anchor-fm-add-podcast-p... ( 52f496...e64a3b )
by
unknown
251:07 queued 242:18
created

Jetpack_Tweetstorm_Helper::generate_cards()   C

Complexity

Conditions 9
Paths 10

Size

Total Lines 76

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 9
nc 10
nop 1
dl 0
loc 76
rs 6.968
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, or linebreaks.
411
			$sentences      = preg_split( '/(?|(?<!\.\.\.)(?<=[.?!]|\.\)|\.["\'])(\s+)(?=[\p{L}\'"\(])|(\n+))/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
			$space                  = empty( $current_tweet['text'] ) ? '' : ' ';
626
			$current_tweet['text'] .= $space . self::generate_url_placeholder( $block['embed'] );
627
		}
628
629
		self::save_current_tweet( $current_tweet, $block );
630
	}
631
632
	/**
633
	 * Given an array of blocks and optional editor information, this will extract them into
634
	 * the internal representation used during parsing.
635
	 *
636
	 * @param array $blocks An array of blocks and optional editor-related information.
637
	 * @return array An array of blocks, in our internal representation.
638
	 */
639
	private static function extract_blocks( $blocks ) {
640
		if ( empty( $blocks ) ) {
641
			return array();
642
		}
643
644
		$block_count = count( $blocks );
645
646
		for ( $ii = 0; $ii < $block_count; $ii++ ) {
647
			if ( ! self::get_block_definition( $blocks[ $ii ]['block']['blockName'] ) ) {
648
				unset( $blocks[ $ii ] );
649
				continue;
650
			}
651
652
			$blocks[ $ii ]['name']  = $blocks[ $ii ]['block']['blockName'];
653
			$blocks[ $ii ]['text']  = self::extract_text_from_block( $blocks[ $ii ]['block'] );
654
			$blocks[ $ii ]['media'] = self::extract_media_from_block( $blocks[ $ii ]['block'] );
655
			$blocks[ $ii ]['tweet'] = self::extract_tweet_from_block( $blocks[ $ii ]['block'] );
656
			$blocks[ $ii ]['embed'] = self::extract_embed_from_block( $blocks[ $ii ]['block'] );
657
		}
658
659
		return array_values( $blocks );
660
	}
661
662
	/**
663
	 * Creates a blank tweet, appends it to the tweets array, and returns the tweet.
664
	 *
665
	 * @return array The blank tweet.
666
	 */
667
	private static function start_new_tweet() {
668
		self::$tweets[] = array(
669
			// An array of blocks that make up this tweet.
670
			'blocks'   => array(),
671
			// If this tweet only contains part of a block, the boundary contains
672
			// information about where in the block the tweet ends.
673
			'boundary' => false,
674
			// The text content of the tweet.
675
			'text'     => '',
676
			// The media content of the tweet.
677
			'media'    => array(),
678
			// The quoted tweet in this tweet.
679
			'tweet'    => '',
680
			// Some blocks force a hard finish to the tweet, even if subsequent blocks
681
			// could technically be appended. This flag shows when a tweet is finished.
682
			'finished' => false,
683
			// Flag if the current tweet already has content in it.
684
			'changed'  => false,
685
		);
686
687
		return self::get_current_tweet();
688
	}
689
690
	/**
691
	 * Get the last tweet in the array.
692
	 *
693
	 * @return array The tweet.
694
	 */
695
	private static function get_current_tweet() {
696
		return end( self::$tweets );
697
	}
698
699
	/**
700
	 * Saves the passed tweet array as the last tweet, overwriting the former last tweet.
701
	 *
702
	 * This method adds some last minute checks: marking the tweet as "changed", as well
703
	 * as adding the $block to the tweet (if it was passed, and hasn't already been added).
704
	 *
705
	 * @param array $tweet       The tweet being stored.
706
	 * @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...
707
	 * @return array The saved tweet, after the last minute checks have been done.
708
	 */
709
	private static function save_current_tweet( $tweet, $block = null ) {
710
		$tweet['changed'] = true;
711
712
		if ( isset( $block ) ) {
713
			$block_def = self::get_block_definition( $block['name'] );
714
715
			// Check if this block type will be forcing a new tweet.
716
			if ( $block_def['force_finished'] ) {
717
				$tweet['finished'] = true;
718
			}
719
720
			// Check if this block is already recorded against this tweet.
721
			$last_block = end( $tweet['blocks'] );
722
			if ( isset( $block['clientId'] ) && ( false === $last_block || $last_block['clientId'] !== $block['clientId'] ) ) {
723
				$tweet['blocks'][] = $block;
724
			}
725
		}
726
727
		// Find the index of the last tweet in the array.
728
		end( self::$tweets );
729
		$tweet_index = key( self::$tweets );
730
731
		self::$tweets[ $tweet_index ] = $tweet;
732
733
		return $tweet;
734
	}
735
736
	/**
737
	 * Checks if the passed text is valid for a tweet or not.
738
	 *
739
	 * @param string $text                The text to check.
740
	 * @param int    $reserved_characters Optional. The number of characters to reduce the maximum tweet length by.
741
	 * @return bool Whether or not the text is valid.
742
	 */
743
	private static function is_valid_tweet( $text, $reserved_characters = 0 ) {
744
		return self::is_within_twitter_length( $text, 280 - $reserved_characters );
745
	}
746
747
	/**
748
	 * Checks if the passed text is valid for image alt text.
749
	 *
750
	 * @param string $text The text to check.
751
	 * @return bool Whether or not the text is valid.
752
	 */
753
	private static function is_valid_alt_text( $text ) {
754
		return self::is_within_twitter_length( $text, 1000 );
755
	}
756
757
	/**
758
	 * Check if a string is shorter than a given length, according to Twitter's rules for counting string length.
759
	 *
760
	 * @param string $text       The text to check.
761
	 * @param int    $max_length The number of characters long this string can be.
762
	 * @return bool Whether or not the string is no longer than the length limit.
763
	 */
764
	private static function is_within_twitter_length( $text, $max_length ) {
765
		// Replace all multiline separators with a \n, since that's the
766
		// character we actually want to count.
767
		$text = str_replace( self::$line_separator, "\n", $text );
768
769
		// Keep a running total of characters we've removed.
770
		$stripped_characters = 0;
771
772
		// Since we use '…' a lot, strip it out, so we can still use the ASCII checks.
773
		$ellipsis_count = 0;
774
		$text           = str_replace( '…', '', $text, $ellipsis_count );
775
776
		// The ellipsis glyph counts for two characters.
777
		$stripped_characters += $ellipsis_count * 2;
778
779
		// Try filtering out emoji first, since ASCII text + emoji is a relatively common case.
780
		if ( ! self::is_ascii( $text ) ) {
781
			// Initialise the emoji cache.
782
			if ( 0 === count( self::$emoji_list ) ) {
783
				self::$emoji_list = array_map( 'html_entity_decode', _wp_emoji_list( 'entities' ) );
784
			}
785
786
			$emoji_count = 0;
787
			$text        = str_replace( self::$emoji_list, '', $text, $emoji_count );
788
789
			// Emoji graphemes count as 2 characters each.
790
			$stripped_characters += $emoji_count * 2;
791
		}
792
793
		if ( self::is_ascii( $text ) ) {
794
			$stripped_characters += strlen( $text );
795
			if ( $stripped_characters <= $max_length ) {
796
				return true;
797
			}
798
799
			return false;
800
		}
801
802
		// Remove any glyphs that count as 1 character.
803
		// Source: https://github.com/twitter/twitter-text/blob/master/config/v3.json .
804
		// Note that the source ranges are in decimal, the regex ranges are converted to hex.
805
		$single_character_count = 0;
806
		$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 );
807
808
		$stripped_characters += $single_character_count;
809
810
		// Check if there's any text we haven't counted yet.
811
		// Any remaining glyphs count as 2 characters each.
812
		if ( 0 !== strlen( $text ) ) {
813
			// WP provides a compat version of mb_strlen(), no need to check if it exists.
814
			$stripped_characters += mb_strlen( $text, 'UTF-8' ) * 2;
815
		}
816
817
		if ( $stripped_characters <= $max_length ) {
818
			return true;
819
		}
820
821
		return false;
822
	}
823
824
	/**
825
	 * Checks if a string only contains ASCII characters.
826
	 *
827
	 * @param string $text The string to check.
828
	 * @return bool Whether or not the string is ASCII-only.
829
	 */
830
	private static function is_ascii( $text ) {
831
		if ( function_exists( 'mb_check_encoding' ) ) {
832
			if ( mb_check_encoding( $text, 'ASCII' ) ) {
833
				return true;
834
			}
835
		} elseif ( ! preg_match( '/[^\x00-\x7F]/', $text ) ) {
836
			return true;
837
		}
838
839
		return false;
840
	}
841
842
	/**
843
	 * A block will generate a certain amount of text to be inserted into a tweet. If that text is too
844
	 * long for a tweet, we already know where the text will be split when it's published as tweet, but
845
	 * we need to calculate where that corresponds to in the block edit UI.
846
	 *
847
	 * The tweet template for that block may add extra characters, extra characters are added for URL
848
	 * placeholders, and the block may contain multiple RichText areas (corresponding to attributes),
849
	 * so we need to keep track of both until the this function calculates which attribute area (in the
850
	 * block editor, the richTextIdentifier) that offset corresponds to, and how far into that attribute
851
	 * area it is.
852
	 *
853
	 * @param array   $block  The block being checked.
854
	 * @param integer $offset The position in the tweet text where it will be split.
855
	 * @return array|false `false` if the boundary can't be determined. Otherwise, returns the
856
	 *                     position in the block editor to insert the tweet boundary annotation.
857
	 */
858
	private static function get_boundary( $block, $offset ) {
859
		// If we don't have a clientId, there's no point in generating a boundary, since this
860
		// parse request doesn't have a way to map blocks back to editor UI.
861
		if ( ! isset( $block['clientId'] ) ) {
862
			return false;
863
		}
864
865
		$block_def = self::get_block_definition( $block['name'] );
866
867 View Code Duplication
		if ( isset( $block_def['content'] ) && count( $block_def['content'] ) > 0 ) {
868
			$tags = $block_def['content'];
869
		} else {
870
			$tags = array( 'content' );
871
		}
872
873
		$tag_content = self::extract_tag_content_from_html( $tags, $block['block']['innerHTML'] );
874
875
		// $tag_content is split up by tag first, then lines. We want to remap it to split it by lines
876
		// first, then tag.
877
		$lines = array();
878
		foreach ( $tag_content as $tag => $content ) {
879
			if ( 'content' === $tag ) {
880
				$attribute_name = 'content';
881
			} else {
882
				$attribute_name = array_search( $tag, $block_def['content'], true );
883
			}
884
885
			foreach ( $content as $id => $content_string ) {
886
				// Multiline blocks can have multiple lines, but other blocks will always only have 1.
887
				if ( 'multiline' === $block_def['type'] ) {
888
					$line_number = $id;
889
				} else {
890
					$line_number = 0;
891
				}
892
893
				if ( ! isset( $lines[ $line_number ] ) ) {
894
					$lines[ $line_number ] = array();
895
				}
896
897
				if ( ! isset( $lines[ $line_number ][ $attribute_name ] ) ) {
898
					// For multiline blocks, or the first time this attribute has been encountered
899
					// in single line blocks, assign the string to the line/attribute.
900
					$lines[ $line_number ][ $attribute_name ] = $content_string;
901
				} else {
902
					// For subsequent times this line/attribute is encountered (only in single line blocks),
903
					// append the string with a line break.
904
					$lines[ $line_number ][ $attribute_name ] .= "\n$content_string";
905
				}
906
			}
907
		}
908
909
		$line_count = count( $lines );
910
911
		$template_parts = preg_split( '/({{\w+}})/', $block_def['template'], -1, PREG_SPLIT_DELIM_CAPTURE );
912
913
		// Keep track of the total number of bytes we've processed from this block.
914
		$total_bytes_processed = 0;
915
916
		// Keep track of the number of characters that the processed data translates to in the editor.
917
		$characters_processed = 0;
918
919
		foreach ( $lines as $line_number => $line ) {
920
			// Add up the length of all the parts of this line.
921
			$line_byte_total = array_sum( array_map( 'strlen', $line ) );
922
923
			if ( $line_byte_total > 0 ) {
924
				// We have something to use in the template, so loop over each part of the template, and count it.
925
				foreach ( $template_parts as $template_part ) {
926
					$matches = array();
927
					if ( preg_match( '/{{(\w+)}}/', $template_part, $matches ) ) {
928
						$part_name = $matches[1];
929
930
						$line_part_data  = $line[ $part_name ];
931
						$line_part_bytes = strlen( $line_part_data );
932
933
						$cleaned_line_part_data = preg_replace( '/ \(url-placeholder-\d+-*\)/', '', $line_part_data );
934
935
						$cleaned_line_part_data = preg_replace_callback(
936
							'/url-placeholder-(\d+)-*/',
937
							function ( $matches ) {
938
								return self::$urls[ $matches[1] ];
939
							},
940
							$cleaned_line_part_data
941
						);
942
943
						if ( $total_bytes_processed + $line_part_bytes >= $offset ) {
944
							// We know that the offset is somewhere inside this part of the tweet, but we need to remove the length
945
							// of any URL placeholders that appear before the boundary, to be able to calculate the correct attribute offset.
946
947
							// $total_bytes_processed is the sum of everything we've processed so far, (including previous parts)
948
							// on this line. This makes it relatively easy to calculate the number of bytes into this part
949
							// that the boundary will occur.
950
							$line_part_byte_boundary = $offset - $total_bytes_processed;
951
952
							// Grab the data from this line part that appears before the boundary.
953
							$line_part_pre_boundary_data = substr( $line_part_data, 0, $line_part_byte_boundary );
954
955
							// Remove any URL placeholders, since these aren't shown in the editor.
956
							$line_part_pre_boundary_data = preg_replace( '/ \(url-placeholder-\d+-*\)/', '', $line_part_pre_boundary_data );
957
958
							$line_part_pre_boundary_data = preg_replace_callback(
959
								'/url-placeholder-(\d+)-*/',
960
								function ( $matches ) {
961
									return self::$urls[ $matches[1] ];
962
								},
963
								$line_part_pre_boundary_data
964
							);
965
966
							$boundary_start = self::utf_16_code_unit_length( $line_part_pre_boundary_data ) - 1;
967
968
							// Multiline blocks need to offset for the characters that are in the same content area,
969
							// but which were counted on previous lines.
970
							if ( 'multiline' === $block_def['type'] ) {
971
								$boundary_start += $characters_processed;
972
							}
973
974
							// Check if the boundary is happening on a line break or a space.
975
							if ( "\n" === $line_part_data[ $line_part_byte_boundary - 1 ] ) {
976
								$type = 'line-break';
977
978
								// A line break boundary can actually be multiple consecutive line breaks,
979
								// count them all up so we know how big the annotation needs to be.
980
								$matches = array();
981
								preg_match( '/\n+$/', substr( $line_part_data, 0, $line_part_byte_boundary ), $matches );
982
								$boundary_end    = $boundary_start + 1;
983
								$boundary_start -= strlen( $matches[0] ) - 1;
984
							} else {
985
								$type         = 'normal';
986
								$boundary_end = $boundary_start + 1;
987
							}
988
989
							return array(
990
								'start'     => $boundary_start,
991
								'end'       => $boundary_end,
992
								'container' => $part_name,
993
								'type'      => $type,
994
							);
995
						} else {
996
							$total_bytes_processed += $line_part_bytes;
997
							$characters_processed  += self::utf_16_code_unit_length( $cleaned_line_part_data );
998
							continue;
999
						}
1000
					} else {
1001
						$total_bytes_processed += strlen( $template_part );
1002
					}
1003
				}
1004
1005
				// Are we breaking at the end of this line?
1006
				if ( $total_bytes_processed + 1 === $offset && $line_count > 1 ) {
1007
					reset( $block_def['content'] );
1008
					$container = key( $block_def['content'] );
1009
					return array(
1010
						'line'      => $line_number,
1011
						'container' => $container,
1012
						'type'      => 'end-of-line',
1013
					);
1014
				}
1015
1016
				// The newline at the end of each line is 1 byte, but we don't need to count empty lines.
1017
				$total_bytes_processed++;
1018
			}
1019
1020
			// We do need to count empty lines in the editor, since they'll be displayed.
1021
			$characters_processed++;
1022
		}
1023
1024
		return false;
1025
	}
1026
1027
	/**
1028
	 * JavaScript uses UTF-16 for encoding strings, which means we need to provide UTF-16
1029
	 * based offsets for the block editor to render tweet boundaries in the correct location.
1030
	 *
1031
	 * UTF-16 is a variable-width character encoding: every code unit is 2 bytes, a single character
1032
	 * can be one or two code units long. Fortunately for us, JavaScript's String.charAt() is based
1033
	 * on the older UCS-2 character encoding, which only counts single code units. PHP's strlen()
1034
	 * counts a code unit as being 2 characters, so once a string is converted to UTF-16, we have
1035
	 * a fast way to determine how long it is in UTF-16 code units.
1036
	 *
1037
	 * @param string $text The natively encoded string to get the length of.
1038
	 * @return int The length of the string in UTF-16 code units. Returns -1 if the length could not
1039
	 *             be calculated.
1040
	 */
1041
	private static function utf_16_code_unit_length( $text ) {
1042
		// If mb_convert_encoding() exists, we can use that for conversion.
1043
		if ( function_exists( 'mb_convert_encoding' ) ) {
1044
			// UTF-16 can add an additional code unit to the start of the string, called the
1045
			// Byte Order Mark (BOM), which indicates whether the string is encoding as
1046
			// big-endian, or little-endian. Since we don't want to count code unit, and the endianness
1047
			// doesn't matter for our purposes, using PHP's UTF-16BE encoding uses big-endian
1048
			// encoding, and ensures the BOM *won't* be prepended to the string to the string.
1049
			return strlen( mb_convert_encoding( $text, 'UTF-16BE' ) ) / 2;
1050
		}
1051
1052
		// If we can't convert this string, return a result that will avoid an incorrect annotation being added.
1053
		return -1;
1054
	}
1055
1056
	/**
1057
	 * Extracts the tweetable text from a block.
1058
	 *
1059
	 * @param array $block A single block, as generated by parse_block().
1060
	 * @return string The tweetable text from the block, in the correct template form.
1061
	 */
1062
	private static function extract_text_from_block( $block ) {
1063
		// If the block doesn't have an innerHTMl, we're not going to get any text.
1064
		if ( empty( $block['innerHTML'] ) ) {
1065
			return '';
1066
		}
1067
1068
		$block_def = self::get_block_definition( $block['blockName'] );
1069
1070
		// We currently only support extracting text from HTML text nodes.
1071
		if ( ! isset( $block_def['content_location'] ) || 'html' !== $block_def['content_location'] ) {
1072
			return '';
1073
		}
1074
1075
		// Find out which tags we need to extract content from.
1076 View Code Duplication
		if ( isset( $block_def['content'] ) && count( $block_def['content'] ) > 0 ) {
1077
			$tags = $block_def['content'];
1078
		} else {
1079
			$tags = array( 'content' );
1080
		}
1081
1082
		$tag_values = self::extract_tag_content_from_html( $tags, $block['innerHTML'] );
1083
1084
		// We can treat single line blocks as "multiline", with only one line in them.
1085
		$lines = array();
1086
		foreach ( $tag_values as $tag => $values ) {
1087
			// For single-line blocks, we need to squash all the values for this tag into a single value.
1088
			if ( 'multiline' !== $block_def['type'] ) {
1089
				$values = array( implode( "\n", $values ) );
1090
			}
1091
1092
			// Handle the special "content" tag.
1093
			if ( 'content' === $tag ) {
1094
				$placeholder = 'content';
1095
			} else {
1096
				$placeholder = array_search( $tag, $block_def['content'], true );
1097
			}
1098
1099
			// Loop over each instance of this value, appling that value to the corresponding line template.
1100
			foreach ( $values as $line_number => $value ) {
1101
				if ( ! isset( $lines[ $line_number ] ) ) {
1102
					$lines[ $line_number ] = $block_def['template'];
1103
				}
1104
1105
				$lines[ $line_number ] = str_replace( '{{' . $placeholder . '}}', $value, $lines[ $line_number ] );
1106
			}
1107
		}
1108
1109
		// Remove any lines that didn't apply any content.
1110
		$empty_template = preg_replace( '/{{.*?}}/', '', $block_def['template'] );
1111
		$lines          = array_filter(
1112
			$lines,
1113
			function ( $line ) use ( $empty_template ) {
1114
				return $line !== $empty_template;
1115
			}
1116
		);
1117
1118
		// Join the lines together into a single string.
1119
		$text = implode( self::$line_separator, $lines );
1120
1121
		// Trim off any trailing whitespace that we no longer need.
1122
		$text = preg_replace( '/(\s|' . self::$line_separator . ')+$/u', '', $text );
1123
1124
		return $text;
1125
	}
1126
1127
	/**
1128
	 * Extracts the tweetable media from a block.
1129
	 *
1130
	 * @param array $block A single block, as generated by parse_block().
1131
	 * @return array {
1132
	 *     An array of media.
1133
	 *
1134
	 *     @type string url The URL of the media.
1135
	 *     @type string alt The alt text of the media.
1136
	 * }
1137
	 */
1138
	private static function extract_media_from_block( $block ) {
1139
		$block_def = self::get_block_definition( $block['blockName'] );
1140
1141
		$media = array();
1142
1143
		if ( 'image' === $block_def['type'] ) {
1144
			$url = self::extract_attr_content_from_html(
1145
				$block_def['content']['url'][0],
1146
				$block_def['content']['url'][1],
1147
				$block['innerHTML']
1148
			);
1149
			$alt = self::extract_attr_content_from_html(
1150
				$block_def['content']['alt'][0],
1151
				$block_def['content']['alt'][1],
1152
				$block['innerHTML']
1153
			);
1154
1155
			$img_count = count( $url );
1156
1157
			for ( $ii = 0; $ii < $img_count; $ii++ ) {
1158
				$filedata = wp_check_filetype( basename( wp_parse_url( $url[ $ii ], PHP_URL_PATH ) ) );
1159
1160
				$media[] = array(
1161
					'url'  => $url[ $ii ],
1162
					'alt'  => self::is_valid_alt_text( $alt[ $ii ] ) ? $alt[ $ii ] : '',
1163
					'type' => $filedata['type'],
1164
				);
1165
			}
1166
		} elseif ( 'video' === $block_def['type'] ) {
1167
			// Handle VideoPress videos.
1168
			if ( isset( $block['attrs']['src'] ) && 0 === strpos( $block['attrs']['src'], 'https://videos.files.wordpress.com/' ) ) {
1169
				$url = array( $block['attrs']['src'] );
1170
			} else {
1171
				$url = self::extract_attr_content_from_html(
1172
					$block_def['content']['url'][0],
1173
					$block_def['content']['url'][1],
1174
					$block['innerHTML']
1175
				);
1176
			}
1177
1178
			// We can only ever use the first video found, no need to go through all of them.
1179
			if ( count( $url ) > 0 ) {
1180
				$filedata = wp_check_filetype( basename( wp_parse_url( $url[0], PHP_URL_PATH ) ) );
1181
1182
				$media[] = array(
1183
					'url'  => $url[0],
1184
					'type' => $filedata['type'],
1185
				);
1186
			}
1187
		}
1188
1189
		return $media;
1190
	}
1191
1192
	/**
1193
	 * Extracts the tweet URL from a Twitter embed block.
1194
	 *
1195
	 * @param array $block A single block, as generated by parse_block().
1196
	 * @return string The tweet URL. Empty string if there is none available.
1197
	 */
1198
	private static function extract_tweet_from_block( $block ) {
1199 View Code Duplication
		if ( 'core/embed' === $block['blockName'] && 'twitter' === $block['attrs']['providerNameSlug'] ) {
1200
			return $block['attrs']['url'];
1201
		}
1202
1203
		// @todo This fallback can be removed when WordPress 5.6 is the minimum supported version.
1204
		if ( 'core-embed/twitter' === $block['blockName'] ) {
1205
			return $block['attrs']['url'];
1206
		}
1207
1208
		return '';
1209
	}
1210
1211
	/**
1212
	 * Extracts URL from an embed block.
1213
	 *
1214
	 * @param array $block A single block, as generated by parse_block().
1215
	 * @return string The URL. Empty string if there is none available.
1216
	 */
1217
	private static function extract_embed_from_block( $block ) {
1218
		$block_def = self::get_block_definition( $block['blockName'] );
1219
1220
		if ( 'embed' !== $block_def['type'] ) {
1221
			return '';
1222
		}
1223
1224
		// Twitter embeds are handled in ::extract_tweet_from_block().
1225 View Code Duplication
		if ( 'core/embed' === $block['blockName'] && 'twitter' === $block['attrs']['providerNameSlug'] ) {
1226
			return '';
1227
		}
1228
1229
		// @todo This fallback can be removed when WordPress 5.6 is the minimum supported version.
1230
		if ( 'core-embed/twitter' === $block['blockName'] ) {
1231
			return '';
1232
		}
1233
1234
		$url = '';
1235
		if ( 'block-attributes' === $block_def['content_location'] ) {
1236
			$url = $block['attrs'][ $block_def['content'][0] ];
1237
		}
1238
1239
		if ( 'jetpack/gif' === $block['blockName'] ) {
1240
			$url = str_replace( '/embed/', '/gifs/', $url );
1241
		}
1242
1243
		return $url;
1244
	}
1245
1246
	/**
1247
	 * There's a bunch of left-over cruft in the tweets array that we don't need to return. Removing
1248
	 * it helps keep the size of the data down.
1249
	 */
1250
	private static function clean_return_tweets() {
1251
		// Before we return, clean out unnecessary cruft from the return data.
1252
		$tweets = array_map(
1253
			function ( $tweet ) {
1254
				// Remove tweets that don't have anything saved in them. eg, if the last block is a
1255
				// header with no text, it'll force a new tweet, but we won't end up putting anything
1256
				// in that tweet.
1257
				if ( ! $tweet['changed'] ) {
1258
					return false;
1259
				}
1260
1261
				// Replace any URL placeholders that appear in the text.
1262
				$tweet['urls'] = array();
1263
				foreach ( self::$urls as $id => $url ) {
1264
					$count = 0;
1265
1266
					$tweet['text'] = str_replace( str_pad( "url-placeholder-$id", self::$characters_per_url, '-' ), $url, $tweet['text'], $count );
1267
1268
					// If we found a URL, keep track of it for the editor.
1269
					if ( $count > 0 ) {
1270
						$tweet['urls'][] = $url;
1271
					}
1272
				}
1273
1274
				// Remove any inline placeholders.
1275
				$tweet['text'] = str_replace( self::$inline_placeholder, '', $tweet['text'] );
1276
1277
				// If the tweet text consists only of whitespace, we can remove all of it.
1278
				if ( preg_match( '/^\s*$/u', $tweet['text'] ) ) {
1279
					$tweet['text'] = '';
1280
				}
1281
1282
				// Remove trailing whitespace from every line.
1283
				$tweet['text'] = preg_replace( '/\p{Z}+$/um', '', $tweet['text'] );
1284
1285
				// Remove all trailing whitespace (including line breaks) from the end of the text.
1286
				$tweet['text'] = rtrim( $tweet['text'] );
1287
1288
				// Remove internal flags.
1289
				unset( $tweet['changed'] );
1290
				unset( $tweet['finished'] );
1291
1292
				// Remove bulky block data.
1293
				if ( ! isset( $tweet['blocks'][0]['attributes'] ) && ! isset( $tweet['blocks'][0]['clientId'] ) ) {
1294
					$tweet['blocks'] = array();
1295
				} else {
1296
					// Remove the parts of the block data that the editor doesn't need.
1297
					$block_count = count( $tweet['blocks'] );
1298
					for ( $ii = 0; $ii < $block_count; $ii++ ) {
1299
						$keys = array_keys( $tweet['blocks'][ $ii ] );
1300
						foreach ( $keys as $key ) {
1301
							// The editor only needs these attributes, everything else will be unset.
1302
							if ( in_array( $key, array( 'attributes', 'clientId' ), true ) ) {
1303
								continue;
1304
							}
1305
1306
							unset( $tweet['blocks'][ $ii ][ $key ] );
1307
						}
1308
					}
1309
				}
1310
1311
				// Once we've finished cleaning up, check if there's anything left to be tweeted.
1312
				if ( empty( $tweet['text'] ) && empty( $tweet['media'] ) && empty( $tweet['tweet'] ) ) {
1313
					return false;
1314
				}
1315
1316
				return $tweet;
1317
			},
1318
			self::$tweets
1319
		);
1320
1321
		// Clean any removed tweets out of the result.
1322
		return array_values( array_filter( $tweets, 'is_array' ) );
1323
	}
1324
1325
	/**
1326
	 * Given a list of tags and a HTML blob, this will extract the text content inside
1327
	 * each of the given tags.
1328
	 *
1329
	 * @param array  $tags An array of tag names.
1330
	 * @param string $html A blob of HTML.
1331
	 * @return array An array of the extract content. The keys in the array are the $tags,
1332
	 *               each value is an array. The value array is indexed in the same order as the tag
1333
	 *               appears in the HTML blob, including nested tags.
1334
	 */
1335
	private static function extract_tag_content_from_html( $tags, $html ) {
1336
		// Serialised blocks will sometimes wrap the innerHTML in newlines, but those newlines
1337
		// are removed when innerHTML is parsed into an attribute. Remove them so we're working
1338
		// with the same information.
1339
		if ( "\n" === $html[0] && "\n" === $html[ strlen( $html ) - 1 ] ) {
1340
			$html = substr( $html, 1, strlen( $html ) - 2 );
1341
		}
1342
1343
		// Normalise <br>.
1344
		$html = preg_replace( '/<br\s*\/?>/', '<br>', $html );
1345
1346
		// If there were no tags passed, assume the entire text is required.
1347
		if ( empty( $tags ) ) {
1348
			$tags = array( 'content' );
1349
		}
1350
1351
		$values = array();
1352
1353
		$tokens = wp_html_split( $html );
1354
1355
		$validator = new Twitter_Validator();
1356
1357
		foreach ( $tags as $tag ) {
1358
			$values[ $tag ] = array();
1359
1360
			// Since tags can be nested, keeping track of the nesting level allows
1361
			// us to extract nested content into a flat array.
1362
			if ( 'content' === $tag ) {
1363
				// The special "content" tag means we should store the entire content,
1364
				// so assume the tag is open from the beginning.
1365
				$opened = 0;
1366
				$closed = -1;
1367
1368
				$values['content'][0] = '';
1369
			} else {
1370
				$opened = -1;
1371
				$closed = -1;
1372
			}
1373
1374
			// When we come across a URL, we need to keep track of it, so it can then be inserted
1375
			// in the right place.
1376
			$current_url = '';
1377
			foreach ( $tokens as $token ) {
1378
				if ( 0 === strlen( $token ) ) {
1379
					// Skip any empty tokens.
1380
					continue;
1381
				}
1382
1383
				// If we're currently storing content, check if it's a text-formatting
1384
				// tag that we should apply.
1385
				if ( $opened !== $closed ) {
1386
					// End of a paragraph, put in some newlines (as long as we're not extracting paragraphs).
1387
					if ( '</p>' === $token && 'p' !== $tag ) {
1388
						$values[ $tag ][ $opened ] .= "\n\n";
1389
					}
1390
1391
					// A line break gets one newline.
1392
					if ( '<br>' === $token ) {
1393
						$values[ $tag ][ $opened ] .= "\n";
1394
					}
1395
1396
					// A link has opened, grab the URL for inserting later.
1397
					if ( 0 === strpos( $token, '<a ' ) ) {
1398
						$href_values = self::extract_attr_content_from_html( 'a', 'href', $token );
1399
						if ( ! empty( $href_values[0] ) && $validator->isValidURL( $href_values[0] ) ) {
1400
							// Remember the URL.
1401
							$current_url = $href_values[0];
1402
						}
1403
					}
1404
1405
					// A link has closed, insert the URL from that link if we have one.
1406
					if ( '</a>' === $token && '' !== $current_url ) {
1407
						// Generate a unique-to-this-block placeholder which takes up the
1408
						// same number of characters as a URL does.
1409
						$values[ $tag ][ $opened ] .= ' (' . self::generate_url_placeholder( $current_url ) . ')';
1410
1411
						$current_url = '';
1412
					}
1413
1414
					// We don't return inline images, but they technically take up 1 character in the RichText.
1415
					if ( 0 === strpos( $token, '<img ' ) ) {
1416
						$values[ $tag ][ $opened ] .= self::$inline_placeholder;
1417
					}
1418
				}
1419
1420
				if ( "<$tag>" === $token || 0 === strpos( $token, "<$tag " ) ) {
1421
					// A tag has just been opened.
1422
					$opened++;
1423
					// Set an empty value now, so we're keeping track of empty tags.
1424
					if ( ! isset( $values[ $tag ][ $opened ] ) ) {
1425
						$values[ $tag ][ $opened ] = '';
1426
					}
1427
					continue;
1428
				}
1429
1430
				if ( "</$tag>" === $token ) {
1431
					// The tag has been closed.
1432
					$closed++;
1433
					continue;
1434
				}
1435
1436
				if ( '<' === $token[0] ) {
1437
					// We can skip any other tags.
1438
					continue;
1439
				}
1440
1441
				if ( $opened !== $closed ) {
1442
					// We're currently in a tag, with some content. Start by decoding any HTML entities.
1443
					$token = html_entity_decode( $token, ENT_QUOTES );
1444
1445
					// Find any URLs in this content, and replace them with a placeholder.
1446
					preg_match_all( Twitter_Regex::getValidUrlMatcher(), $token, $matches, PREG_SET_ORDER | PREG_OFFSET_CAPTURE );
1447
					$offset = 0;
1448
					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...
1449
						list( $url, $start ) = $match[2];
1450
1451
						$token = substr_replace( $token, self::generate_url_placeholder( $url ), $start + $offset, strlen( $url ) );
1452
1453
						$offset += self::$characters_per_url - strlen( $url );
1454
1455
						// If we're in a link with a URL set, there's no need to keep two copies of the same link.
1456
						if ( ! empty( $current_url ) ) {
1457
							$lower_url         = strtolower( $url );
1458
							$lower_current_url = strtolower( $current_url );
1459
1460
							if ( $lower_url === $lower_current_url ) {
1461
								$current_url = '';
1462
							}
1463
1464
							// Check that the link text isn't just a shortened version of the href value.
1465
							$trimmed_current_url = preg_replace( '|^https?://|', '', $lower_current_url );
1466
							if ( $lower_url === $trimmed_current_url || trim( $trimmed_current_url, '/' ) === $lower_url ) {
1467
								$current_url = '';
1468
							}
1469
						}
1470
					}
1471
1472
					// Append it to the right value.
1473
					$values[ $tag ][ $opened ] .= $token;
1474
				}
1475
			}
1476
		}
1477
1478
		return $values;
1479
	}
1480
1481
	/**
1482
	 * Extracts the attribute content from a tag.
1483
	 *
1484
	 * This method allows for the HTML to have multiple instances of the tag, and will return
1485
	 * an array containing the attribute value (or an empty string, if the tag doesn't have the
1486
	 * requested attribute) for each occurrence of the tag.
1487
	 *
1488
	 * @param string $tag          The tag we're looking for.
1489
	 * @param string $attr         The name of the attribute we're looking for.
1490
	 * @param string $html         The HTML we're searching through.
1491
	 * @param array  $attr_filters Optional. Filters tags based on whether or not they have attributes with given values.
1492
	 * @return array The array of attribute values found.
1493
	 */
1494
	private static function extract_attr_content_from_html( $tag, $attr, $html, $attr_filters = array() ) {
1495
		// Given our single tag and attribute, construct a KSES filter for it.
1496
		$kses_filter = array(
1497
			$tag => array(
1498
				$attr => array(),
1499
			),
1500
		);
1501
1502
		foreach ( $attr_filters as $filter_attr => $filter_value ) {
1503
			$kses_filter[ $tag ][ $filter_attr ] = array();
1504
		}
1505
1506
		// Remove all HTML except for the tag we're after. On that tag,
1507
		// remove all attributes except for the one we're after.
1508
		$stripped_html = wp_kses( $html, $kses_filter );
1509
1510
		$values = array();
1511
1512
		$tokens = wp_html_split( $stripped_html );
1513
		foreach ( $tokens as $token ) {
1514
			$found_value = '';
1515
1516
			if ( 0 === strlen( $token ) ) {
1517
				// Skip any empty tokens.
1518
				continue;
1519
			}
1520
1521
			if ( '<' !== $token[0] ) {
1522
				// We can skip any non-tag tokens.
1523
				continue;
1524
			}
1525
1526
			$token_attrs = wp_kses_attr_parse( $token );
1527
1528
			// Skip tags that KSES couldn't handle.
1529
			if ( false === $token_attrs ) {
1530
				continue;
1531
			}
1532
1533
			// Remove the tag open and close chunks.
1534
			$found_tag = array_shift( $token_attrs );
1535
			array_pop( $token_attrs );
1536
1537
			// We somehow got a tag that isn't the one we're after. Skip it.
1538
			if ( 0 !== strpos( $found_tag, "<$tag " ) ) {
1539
				continue;
1540
			}
1541
1542
			// We can only fail an attribute filter if one is set.
1543
			$passed_filter = count( $attr_filters ) === 0;
1544
1545
			foreach ( $token_attrs as $token_attr_string ) {
1546
				// The first "=" in the string will be between the attribute name/value.
1547
				list( $token_attr_name, $token_attr_value ) = explode( '=', $token_attr_string, 2 );
1548
1549
				$token_attr_name  = trim( $token_attr_name );
1550
				$token_attr_value = trim( $token_attr_value );
1551
1552
				// Remove a single set of quotes from around the value.
1553
				if ( '' !== $token_attr_value && in_array( $token_attr_value[0], array( '"', "'" ), true ) ) {
1554
					$token_attr_value = trim( $token_attr_value, $token_attr_value[0] );
1555
				}
1556
1557
				// If this is the attribute we're after, save the value for the end of the loop.
1558
				if ( $token_attr_name === $attr ) {
1559
					$found_value = $token_attr_value;
1560
				}
1561
1562
				if ( isset( $attr_filters[ $token_attr_name ] ) && $attr_filters[ $token_attr_name ] === $token_attr_value ) {
1563
					$passed_filter = true;
1564
				}
1565
			}
1566
1567
			if ( $passed_filter ) {
1568
				// We always want to append the found value, even if we didn't "find" a matching attribute.
1569
				// An empty string in the return value means that we found the tag, but the attribute was
1570
				// either empty, or not set.
1571
				$values[] = html_entity_decode( $found_value, ENT_QUOTES );
1572
			}
1573
		}
1574
1575
		return $values;
1576
	}
1577
1578
	/**
1579
	 * Generates a placeholder for URLs, using the appropriate number of characters to imitate how
1580
	 * Twitter counts the length of URLs in tweets.
1581
	 *
1582
	 * @param string $url The URL to generate a placeholder for.
1583
	 * @return string The placeholder.
1584
	 */
1585
	public static function generate_url_placeholder( $url ) {
1586
		self::$urls[] = $url;
1587
1588
		return str_pad( 'url-placeholder-' . ( count( self::$urls ) - 1 ), self::$characters_per_url, '-' );
1589
	}
1590
1591
	/**
1592
	 * Retrieves the Twitter card data for a list of URLs.
1593
	 *
1594
	 * @param array $urls The list of URLs to grab Twitter card data for.
1595
	 * @return array The Twitter card data.
1596
	 */
1597
	public static function generate_cards( $urls ) {
1598
		$validator = new Twitter_Validator();
1599
1600
		$requests = array_map(
1601
			function ( $url ) use ( $validator ) {
1602
				if ( $validator->isValidURL( $url ) ) {
1603
					return array(
1604
						'url' => $url,
1605
					);
1606
				}
1607
1608
				return false;
1609
			},
1610
			$urls
1611
		);
1612
1613
		$requests = array_filter( $requests );
1614
1615
		$results = Requests::request_multiple( $requests );
1616
1617
		$card_data = array(
1618
			'creator'     => array(
1619
				'name' => 'twitter:creator',
1620
			),
1621
			'description' => array(
1622
				'name'     => 'twitter:description',
1623
				'property' => 'og:description',
1624
			),
1625
			'image'       => array(
1626
				'name'     => 'twitter:image',
1627
				'property' => 'og:image:secure',
1628
				'property' => 'og:image',
1629
			),
1630
			'title'       => array(
1631
				'name'     => 'twitter:text:title',
1632
				'property' => 'og:title',
1633
			),
1634
			'type'        => array(
1635
				'name' => 'twitter:card',
1636
			),
1637
		);
1638
1639
		$cards = array();
1640
		foreach ( $results as $id => $result ) {
1641
			$url = $requests[ $id ]['url'];
1642
1643
			if ( ! $result->success ) {
1644
				$cards[ $url ] = array(
1645
					'error' => 'invalid_url',
1646
				);
1647
				continue;
1648
			}
1649
1650
			$url_card_data = array();
1651
1652
			foreach ( $card_data as $key => $filters ) {
1653
				foreach ( $filters as $attribute => $value ) {
1654
					$found_data = self::extract_attr_content_from_html( 'meta', 'content', $result->body, array( $attribute => $value ) );
1655
					if ( count( $found_data ) > 0 && strlen( $found_data[0] ) > 0 ) {
1656
						$url_card_data[ $key ] = html_entity_decode( $found_data[0], ENT_QUOTES );
1657
						break;
1658
					}
1659
				}
1660
			}
1661
1662
			if ( count( $url_card_data ) > 0 ) {
1663
				$cards[ $url ] = $url_card_data;
1664
			} else {
1665
				$cards[ $url ] = array(
1666
					'error' => 'no_og_data',
1667
				);
1668
			}
1669
		}
1670
1671
		return $cards;
1672
	}
1673
1674
	/**
1675
	 * Get the WPCOM or self-hosted site ID.
1676
	 *
1677
	 * @return mixed
1678
	 */
1679 View Code Duplication
	public static function get_site_id() {
1680
		$is_wpcom = ( defined( 'IS_WPCOM' ) && IS_WPCOM );
1681
		$site_id  = $is_wpcom ? get_current_blog_id() : Jetpack_Options::get_option( 'id' );
1682
		if ( ! $site_id ) {
1683
			return new WP_Error(
1684
				'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...
1685
				__( 'Sorry, something is wrong with your Jetpack connection.', 'jetpack' ),
1686
				403
1687
			);
1688
		}
1689
		return (int) $site_id;
1690
	}
1691
}
1692