Completed
Push — master ( f4af47...5230b3 )
by Gary
09:24
created

Jetpack_Tweetstorm_Helper::add_text_to_tweets()   F

Complexity

Conditions 25
Paths 53

Size

Total Lines 179

Duplication

Lines 13
Ratio 7.26 %

Importance

Changes 0
Metric Value
cc 25
nc 53
nop 1
dl 13
loc 179
rs 3.3333
c 0
b 0
f 0

How to fix   Long Method    Complexity   

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
13
/**
14
 * Class Jetpack_Tweetstorm_Helper
15
 *
16
 * @since 8.7.0
17
 */
18
class Jetpack_Tweetstorm_Helper {
19
	/**
20
	 * Blocks that can be converted to tweets.
21
	 *
22
	 * @var array {
23
	 *     The key for each element must match the registered block name.
24
	 *
25
	 *     @type string $type Required. The type of content this block produces. Can be one of 'break', 'embed', 'image',
26
	 *                        'multiline', 'text', or 'video'.
27
	 *     @type string $content_location Optional. Where the block content can be found. Can be 'html', if we need to parse
28
	 *                           it out of the block HTML text, 'html-attributes', if the we need to parse it out of HTML attributes
29
	 *                           in the block HTML, or 'block-attributes', if the content can be found in the block attributes.
30
	 *                           Note that these attributes need to be available when the serialised block is
31
	 *                           parsed using `parse_blocks()`. If it isn't set, it's assumed the block doesn't add
32
	 *                           any content to the Twitter thread.
33
	 *     @type array $content Optional. Defines what parts of the block content need to be extracted. Behaviour can vary based on
34
	 *                          `$content_location`, and `$type`:
35
	 *
36
	 *                              - When `$content_location` is 'html', a value of `array()` or `array( 'content' )` have the same meaning:
37
	 *                                The entire block HTML should be used. In both cases, 'content' will be the corresponding tag in `$template`.
38
	 *                              - When `$content_location` is 'html', it should be formatted as `array( 'container' => 'tag' )`,
39
	 *                                where 'container' is the name of the corresponding RichText container in the block editor, and is also the name
40
	 *                                of the corresponding tag in the $template string. 'tag' is the HTML tag within the block that corresponds to this
41
	 *                                container. When `$type` is 'multiline', there must only be one element in the array, and tag should be set to the HTML
42
	 *                                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'.)
43
	 *                              - When `$content_location` is 'html-attributes', the array should be formatted as `array( 'name' => array( 'tag', 'attribute') )`,
44
	 *                                where 'name' is the name of a particular value that different block types require, 'tag' is the name of the HTML tag where 'attribute'
45
	 *                                can be found, containing the value to use for 'name'. When `$type` is 'image', 'url' and 'alt' must be defined. When `$type` is 'video',
46
	 *                                'url' must be defined.
47
	 *                              - When `$content_location` is 'block-attributes', it must be an array of block attribute names. When `$type` is 'embed', there
48
	 *                                only be one element, corresponding to the URL for the embed.
49
	 *     @type string $template Required for 'text' and 'multiline' types, ignored for all other types. Describes how the block content will be formatted when tweeted.
50
	 *                            Tags should match the keys of `$content`, except for the special "{{content}}", which matches the entire HTML content of the block.
51
	 *                            For 'multiline' types, the template will be repeated for every line in the block.
52
	 *     @type boolean $force_new Required. Whether or not a new tweet should be started when this block is encountered.
53
	 *     @type boolean $force_finished Required. Whether or not a new tweet should be started after this block is finished.
54
	 * }
55
	 */
56
	private static $supported_blocks = array(
57
		'core/embed'     => array(
58
			'type'             => 'embed',
59
			'content_location' => 'block-attributes',
60
			'content'          => array( 'url' ),
61
			'force_new'        => false,
62
			'force_finished'   => true,
63
		),
64
		'core/gallery'   => array(
65
			'type'             => 'image',
66
			'content_location' => 'html-attributes',
67
			'content'          => array(
68
				'url' => array( 'img', 'src' ),
69
				'alt' => array( 'img', 'alt' ),
70
			),
71
			'force_new'        => false,
72
			'force_finished'   => true,
73
		),
74
		'core/heading'   => array(
75
			'type'             => 'text',
76
			'content_location' => 'html',
77
			'content'          => array(),
78
			'template'         => '{{content}}',
79
			'force_new'        => true,
80
			'force_finished'   => false,
81
		),
82
		'core/image'     => array(
83
			'type'             => 'image',
84
			'content_location' => 'html-attributes',
85
			'content'          => array(
86
				'url' => array( 'img', 'src' ),
87
				'alt' => array( 'img', 'alt' ),
88
			),
89
			'force_new'        => false,
90
			'force_finished'   => true,
91
		),
92
		'core/list'      => array(
93
			'type'             => 'multiline',
94
			'content_location' => 'html',
95
			// It looks a little weird to use the 'values' key for a single line,
96
			// but 'values' is the name of the RichText content area.
97
			'content'          => array(
98
				'values' => 'li',
99
			),
100
			'template'         => '- {{values}}',
101
			'force_new'        => false,
102
			'force_finished'   => false,
103
		),
104
		'core/paragraph' => array(
105
			'type'             => 'text',
106
			'content_location' => 'html',
107
			'content'          => array(),
108
			'template'         => '{{content}}',
109
			'force_new'        => false,
110
			'force_finished'   => false,
111
		),
112
		'core/quote'     => array(
113
			'type'             => 'text',
114
			'content_location' => 'html',
115
			// The quote content will always be inside <p> tags.
116
			'content'          => array(
117
				'value'    => 'p',
118
				'citation' => 'cite',
119
			),
120
			'template'         => '“{{value}}” – {{citation}}',
121
			'force_new'        => false,
122
			'force_finished'   => false,
123
		),
124
		'core/separator' => array(
125
			'type'           => 'break',
126
			'force_new'      => false,
127
			'force_finished' => true,
128
		),
129
		'core/spacer'    => array(
130
			'type'           => 'break',
131
			'force_new'      => false,
132
			'force_finished' => true,
133
		),
134
		'core/verse'     => array(
135
			'type'             => 'text',
136
			'content_location' => 'html',
137
			'content'          => array(),
138
			'template'         => '{{content}}',
139
			'force_new'        => false,
140
			'force_finished'   => false,
141
		),
142
		'core/video'     => array(
143
			'type'             => 'video',
144
			'content_location' => 'html-attributes',
145
			'content'          => array(
146
				'url' => array( 'video', 'src' ),
147
			),
148
			'force_new'        => false,
149
			'force_finished'   => true,
150
		),
151
		'jetpack/gif'    => array(
152
			'type'             => 'embed',
153
			'content_location' => 'block-attributes',
154
			'content'          => array( 'giphyUrl' ),
155
			'force_new'        => false,
156
			'force_finished'   => true,
157
		),
158
	);
159
160
	/**
161
	 * A cache of _wp_emoji_list( 'entities' ), after being run through html_entity_decode().
162
	 *
163
	 * Initialised in ::is_valid_tweet().
164
	 *
165
	 * @var array
166
	 */
167
	private static $emoji_list = array();
168
169
	/**
170
	 * Special line separator character, for multiline text.
171
	 *
172
	 * @var string
173
	 */
174
	private static $line_separator = "\xE2\x80\xA8";
175
176
	/**
177
	 * Special inline placeholder character, for inline tags that change content length in the RichText..
178
	 *
179
	 * @var string
180
	 */
181
	private static $inline_placeholder = "\xE2\x81\xA3";
182
183
	/**
184
	 * URLs always take up a fixed length from the text limit.
185
	 *
186
	 * @var int
187
	 */
188
	private static $characters_per_url = 24;
189
190
	/**
191
	 * Every media attachment takes up some space from the text limit.
192
	 *
193
	 * @var int
194
	 */
195
	private static $characters_per_media = 24;
196
197
	/**
198
	 * An array to store all the tweets in.
199
	 *
200
	 * @var array
201
	 */
202
	private static $tweets = array();
203
204
	/**
205
	 * While we're caching everything, we want to keep track of the URLs we're adding.
206
	 *
207
	 * @var array
208
	 */
209
	private static $urls = array();
210
211
	/**
212
	 * Gather the Tweetstorm.
213
	 *
214
	 * @param  string $url The tweet URL to gather from.
215
	 * @return mixed
216
	 */
217
	public static function gather( $url ) {
218
		if ( ( new Status() )->is_offline_mode() ) {
219
			return new WP_Error(
220
				'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...
221
				__( 'Tweet unrolling is not available in offline mode.', 'jetpack' )
222
			);
223
		}
224
225
		$site_id = self::get_site_id();
226
		if ( is_wp_error( $site_id ) ) {
227
			return $site_id;
228
		}
229
230
		if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) {
231
			if ( ! class_exists( 'WPCOM_Gather_Tweetstorm' ) ) {
232
				\jetpack_require_lib( 'gather-tweetstorm' );
233
			}
234
235
			return WPCOM_Gather_Tweetstorm::gather( $url );
236
		}
237
238
		$response = Client::wpcom_json_api_request_as_blog(
239
			sprintf( '/sites/%d/tweetstorm/gather?url=%s', $site_id, rawurlencode( $url ) ),
240
			2,
241
			array( 'headers' => array( 'content-type' => 'application/json' ) ),
242
			null,
243
			'wpcom'
244
		);
245
		if ( is_wp_error( $response ) ) {
246
			return $response;
247
		}
248
249
		$data = json_decode( wp_remote_retrieve_body( $response ) );
250
251
		if ( wp_remote_retrieve_response_code( $response ) >= 400 ) {
252
			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...
253
		}
254
255
		return $data;
256
	}
257
258
	/**
259
	 * Parse blocks into an array of tweets.
260
	 *
261
	 * @param array $blocks {
262
	 *     An array of blocks, with optional editor-specific information, that need to be parsed into tweets.
263
	 *
264
	 *     @type array  $block      A single block, in the form produce by parse_blocks().
265
	 *     @type array  $attributes Optional. A list of block attributes and their values from the block editor.
266
	 *     @type string $clientId   Optional. The clientId of this block in the block editor.
267
	 * }
268
	 * @return array An array of tweets.
269
	 */
270
	public static function parse( $blocks ) {
271
		// Reset the tweets array.
272
		self::$tweets = array();
273
274
		$blocks = self::extract_blocks( $blocks );
275
276
		if ( empty( $blocks ) ) {
277
			return array();
278
		}
279
280
		// Initialise the tweets array with an empty tweet, so we don't need to check
281
		// if we're creating the first tweet while processing blocks.
282
		self::start_new_tweet();
283
284
		foreach ( $blocks as $block ) {
285
			$block_def = self::get_block_definition( $block['name'] );
286
287
			// Grab the most recent tweet.
288
			$current_tweet = self::get_current_tweet();
289
290
			// Break blocks have no content to add, so we can skip the rest of this loop.
291
			if ( 'break' === $block_def['type'] ) {
292
				self::save_current_tweet( $current_tweet, $block );
293
				continue;
294
			}
295
296
			// Check if we need to start a new tweet.
297
			if ( $current_tweet['finished'] || $block_def['force_new'] ) {
298
				self::start_new_tweet();
299
			}
300
301
			// Process the block.
302
			self::add_text_to_tweets( $block );
303
			self::add_media_to_tweets( $block );
304
			self::add_tweet_to_tweets( $block );
305
			self::add_embed_to_tweets( $block );
306
		}
307
308
		return self::clean_return_tweets();
309
	}
310
311
	/**
312
	 * If the passed block name is supported, return the block definition.
313
	 *
314
	 * @param string $block_name The registered block name.
315
	 * @return array|null The block definition, if it's supported.
316
	 */
317
	private static function get_block_definition( $block_name ) {
318
		if ( isset( self::$supported_blocks[ $block_name ] ) ) {
319
			return self::$supported_blocks[ $block_name ];
320
		}
321
322
		// @todo This is a fallback definition, it can be removed when WordPress 5.6 is the minimum supported version.
323
		if ( 0 === strpos( $block_name, 'core-embed/' ) ) {
324
			return self::$supported_blocks['core/embed'];
325
		}
326
327
		return null;
328
	}
329
330
	/**
331
	 * If the block has any text, process it, and add it to the tweet list.
332
	 *
333
	 * @param array $block The block to process.
334
	 */
335
	private static function add_text_to_tweets( $block ) {
336
		// This is a text block, is there any text?
337
		if ( 0 === strlen( $block['text'] ) ) {
338
			return;
339
		}
340
341
		$block_def = self::get_block_definition( $block['name'] );
342
343
		// Grab the most recent tweet, so we can append to that if we can.
344
		$current_tweet = self::get_current_tweet();
345
346
		// If the entire block can't be fit in this tweet, we need to start a new tweet.
347
		if ( $current_tweet['changed'] && ! self::is_valid_tweet( trim( $current_tweet['text'] ) . "\n\n{$block['text']}" ) ) {
348
			self::start_new_tweet();
349
		}
350
351
		// Multiline blocks prioritise splitting by line, but are otherwise identical to
352
		// normal text blocks. This means we can treat normal text blocks as being
353
		// "multiline", but with a single line.
354
		if ( 'multiline' === $block_def['type'] ) {
355
			$lines = explode( self::$line_separator, $block['text'] );
356
		} else {
357
			$lines = array( $block['text'] );
358
		}
359
		$line_total = count( $lines );
360
361
		// Keep track of how many characters from this block we've allocated to tweets.
362
		$current_character_count = 0;
363
364
		for ( $line_count = 0; $line_count < $line_total; $line_count++ ) {
365
			$line_text = $lines[ $line_count ];
366
367
			// Make sure we have the most recent tweet at the start of every loop.
368
			$current_tweet = self::get_current_tweet();
369
370
			if ( $current_tweet['changed'] ) {
371
				// When it's the first line, add an extra blank line to seperate
372
				// the tweet text from that of the previous block.
373
				$separator = "\n\n";
374
				if ( $line_count > 0 ) {
375
					$separator = "\n";
376
				}
377
378
				// Is this line short enough to append to the current tweet?
379
				if ( self::is_valid_tweet( trim( $current_tweet['text'] ) . "$separator$line_text" ) ) {
380
					// Don't trim the text yet, as we may need it for boundary calculations.
381
					$current_tweet['text'] = $current_tweet['text'] . "$separator$line_text";
382
383
					self::save_current_tweet( $current_tweet, $block );
384
					continue;
385
				}
386
387
				// This line is too long, and lines *must* be split to a new tweet if they don't fit
388
				// into the current tweet. If this isn't the first line, record where we split the block.
389 View Code Duplication
				if ( $line_count > 0 ) {
390
					// Increment by 1 to allow for the \n between lines to be counted by ::get_boundary().
391
					$current_character_count  += strlen( $current_tweet['text'] ) + 1;
392
					$current_tweet['boundary'] = self::get_boundary( $block, $current_character_count );
393
394
					self::save_current_tweet( $current_tweet );
395
				}
396
397
				// Start a new tweet.
398
				$current_tweet = self::start_new_tweet();
399
			}
400
401
			// Since we're now at the start of a new tweet, is this line short enough to be a tweet by itself?
402
			if ( self::is_valid_tweet( $line_text ) ) {
403
				$current_tweet['text'] = $line_text;
404
405
				self::save_current_tweet( $current_tweet, $block );
406
				continue;
407
			}
408
409
			// The line is too long for a single tweet, so split it by sentences.
410
			$sentences      = preg_split( '/(?<!\.\.\.)(?<=[.?!]|\.\)|\.["\'])(\s+)(?=[\p{L}\'"\(])/u', $line_text, -1, PREG_SPLIT_DELIM_CAPTURE );
411
			$sentence_total = count( $sentences );
412
413
			// preg_split() puts the blank space between sentences into a seperate entry in the result,
414
			// so we need to step through the result array by two, and append the blank space when needed.
415
			for ( $sentence_count = 0; $sentence_count < $sentence_total; $sentence_count += 2 ) {
416
				$current_sentence = $sentences[ $sentence_count ];
417
				if ( isset( $sentences[ $sentence_count + 1 ] ) ) {
418
					$current_sentence .= $sentences[ $sentence_count + 1 ];
419
				}
420
421
				// Make sure we have the most recent tweet.
422
				$current_tweet = self::get_current_tweet();
423
424
				// After the first sentence, we can try and append sentences to the previous sentence.
425
				if ( $current_tweet['changed'] && $sentence_count > 0 ) {
426
					// Is this sentence short enough for appending to the current tweet?
427
					if ( self::is_valid_tweet( $current_tweet['text'] . rtrim( $current_sentence ) ) ) {
428
						$current_tweet['text'] .= $current_sentence;
429
430
						self::save_current_tweet( $current_tweet, $block );
431
						continue;
432
					}
433
				}
434
435
				// Will this sentence fit in its own tweet?
436
				if ( self::is_valid_tweet( trim( $current_sentence ) ) ) {
437
					if ( $current_tweet['changed'] ) {
438
						// If we're already in the middle of a block, record the boundary
439
						// before creating a new tweet.
440 View Code Duplication
						if ( $line_count > 0 || $sentence_count > 0 ) {
441
							$current_character_count  += strlen( $current_tweet['text'] );
442
							$current_tweet['boundary'] = self::get_boundary( $block, $current_character_count );
443
444
							self::save_current_tweet( $current_tweet );
445
						}
446
447
						$current_tweet = self::start_new_tweet();
448
					}
449
					$current_tweet['text'] = $current_sentence;
450
451
					self::save_current_tweet( $current_tweet, $block );
452
					continue;
453
				}
454
455
				// This long sentence will start the next tweet that this block is going
456
				// to be turned into, so we need to record the boundary and start a new tweet.
457
				if ( $current_tweet['changed'] ) {
458
					$current_character_count  += strlen( $current_tweet['text'] );
459
					$current_tweet['boundary'] = self::get_boundary( $block, $current_character_count );
460
461
					self::save_current_tweet( $current_tweet );
462
463
					$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...
464
				}
465
466
				// Split the long sentence into words.
467
				$words      = preg_split( '/(\p{Z})/u', $current_sentence, -1, PREG_SPLIT_DELIM_CAPTURE );
468
				$word_total = count( $words );
469
				for ( $word_count = 0; $word_count < $word_total; $word_count += 2 ) {
470
					// Make sure we have the most recent tweet.
471
					$current_tweet = self::get_current_tweet();
472
473
					// If we're on a new tweet, we don't want to add a space at the start.
474
					if ( ! $current_tweet['changed'] ) {
475
						$current_tweet['text'] = $words[ $word_count ];
476
477
						self::save_current_tweet( $current_tweet, $block );
478
						continue;
479
					}
480
481
					// Can we add this word to the current tweet?
482
					if ( self::is_valid_tweet( "{$current_tweet['text']} {$words[ $word_count ]}…" ) ) {
483
						$space = isset( $words[ $word_count - 1 ] ) ? $words[ $word_count - 1 ] : ' ';
484
485
						$current_tweet['text'] .= $space . $words[ $word_count ];
486
487
						self::save_current_tweet( $current_tweet, $block );
488
						continue;
489
					}
490
491
					// Add one for the space character that we won't include in the tweet text.
492
					$current_character_count += strlen( $current_tweet['text'] ) + 1;
493
494
					// We're starting a new tweet with this word. Append ellipsis to
495
					// the current tweet, then move on.
496
					$current_tweet['text'] .= '…';
497
498
					$current_tweet['boundary'] = self::get_boundary( $block, $current_character_count );
499
					self::save_current_tweet( $current_tweet );
500
501
					$current_tweet = self::start_new_tweet();
502
503
					// If this is the second tweet created by the split sentence, it'll start
504
					// with ellipsis, which we don't want to count, but we do want to count the space
505
					// that was replaced by this ellipsis.
506
					$current_tweet['text']    = "…{$words[ $word_count ]}";
507
					$current_character_count -= strlen( '…' );
508
509
					self::save_current_tweet( $current_tweet, $block );
510
				}
511
			}
512
		}
513
	}
514
515
	/**
516
	 * Check if the block has any media to add, and add it.
517
	 *
518
	 * @param array $block  The block to process.
519
	 */
520
	private static function add_media_to_tweets( $block ) {
521
		// There's some media to attach!
522
		$media_count = count( $block['media'] );
523
		if ( 0 === $media_count ) {
524
			return;
525
		}
526
527
		$current_tweet = self::get_current_tweet();
528
529
		// We can only attach media to the previous tweet if the previous tweet
530
		// doesn't already have media.
531
		if ( count( $current_tweet['media'] ) > 0 ) {
532
			$current_tweet = self::start_new_tweet();
533
		}
534
535
		// Would adding this media make the text of the previous tweet too long?
536
		if ( ! self::is_valid_tweet( $current_tweet['text'], $media_count * self::$characters_per_media ) ) {
537
			$current_tweet = self::start_new_tweet();
538
		}
539
540
		$media = array_values(
541
			array_filter(
542
				$block['media'],
543 View Code Duplication
				function ( $single ) {
544
					// Only images and videos can be uploaded.
545
					if ( 0 === strpos( $single['type'], 'image/' ) || 0 === strpos( $single['type'], 'video/' ) ) {
546
						return true;
547
					}
548
549
					return false;
550
				}
551
			)
552
		);
553
554
		if ( count( $media ) > 0 ) {
555
			if ( 0 === strpos( $media[0]['type'], 'video/' ) || 'image/gif' === $media[0]['type'] ) {
556
				// We can only attach a single video or GIF.
557
				$current_tweet['media'] = array_slice( $media, 0, 1 );
558
			} else {
559
				// Since a GIF or video isn't the first element, we can remove all of them from the array.
560
				$filtered_media = array_values(
561
					array_filter(
562
						$media,
563 View Code Duplication
						function ( $single ) {
564
							if ( 0 === strpos( $single['type'], 'video/' ) || 'image/gif' === $single['type'] ) {
565
								return false;
566
							}
567
568
							return true;
569
						}
570
					)
571
				);
572
				// We can only add the first four images found to the tweet.
573
				$current_tweet['media'] = array_slice( $filtered_media, 0, 4 );
574
			}
575
576
			self::save_current_tweet( $current_tweet, $block );
577
		}
578
	}
579
580
	/**
581
	 * Check if the block has a tweet that we can attach to the current tweet as a quote, and add it.
582
	 *
583
	 * @param array $block  The block to process.
584
	 */
585
	private static function add_tweet_to_tweets( $block ) {
586
		if ( 0 === strlen( $block['tweet'] ) ) {
587
			return;
588
		}
589
590
		$current_tweet = self::get_current_tweet();
591
592
		// We can only attach a tweet to the previous tweet if the previous tweet
593
		// doesn't already have a tweet quoted.
594
		if ( strlen( $current_tweet['tweet'] ) > 0 ) {
595
			$current_tweet = self::start_new_tweet();
596
		}
597
598
		$current_tweet['tweet'] = $block['tweet'];
599
600
		self::save_current_tweet( $current_tweet, $block );
601
	}
602
603
	/**
604
	 * Check if the block has an embed URL that we can append to the current tweet text.
605
	 *
606
	 * @param array $block  The block to process.
607
	 */
608
	private static function add_embed_to_tweets( $block ) {
609
		if ( 0 === strlen( $block['embed'] ) ) {
610
			return;
611
		}
612
613
		$current_tweet = self::get_current_tweet();
614
615
		// We can only attach an embed to the previous tweet if it doesn't already
616
		// have any URLs in it.
617
		if ( preg_match( '/url-placeholder-\d+-*/', $current_tweet['text'] ) ) {
618
			$current_tweet         = self::start_new_tweet();
619
			$current_tweet['text'] = self::generate_url_placeholder( $block['embed'] );
620
		} else {
621
			$current_tweet['text'] .= ' ' . self::generate_url_placeholder( $block['embed'] );
622
		}
623
624
		self::save_current_tweet( $current_tweet, $block );
625
	}
626
627
	/**
628
	 * Given an array of blocks and optional editor information, this will extract them into
629
	 * the internal representation used during parsing.
630
	 *
631
	 * @param array $blocks An array of blocks and optional editor-related information.
632
	 * @return array An array of blocks, in our internal representation.
633
	 */
634
	private static function extract_blocks( $blocks ) {
635
		if ( empty( $blocks ) ) {
636
			return array();
637
		}
638
639
		$block_count = count( $blocks );
640
641
		for ( $ii = 0; $ii < $block_count; $ii++ ) {
642
			if ( ! self::get_block_definition( $blocks[ $ii ]['block']['blockName'] ) ) {
643
				unset( $blocks[ $ii ] );
644
				continue;
645
			}
646
647
			$blocks[ $ii ]['name']  = $blocks[ $ii ]['block']['blockName'];
648
			$blocks[ $ii ]['text']  = self::extract_text_from_block( $blocks[ $ii ]['block'] );
649
			$blocks[ $ii ]['media'] = self::extract_media_from_block( $blocks[ $ii ]['block'] );
650
			$blocks[ $ii ]['tweet'] = self::extract_tweet_from_block( $blocks[ $ii ]['block'] );
651
			$blocks[ $ii ]['embed'] = self::extract_embed_from_block( $blocks[ $ii ]['block'] );
652
		}
653
654
		return array_values( $blocks );
655
	}
656
657
	/**
658
	 * Creates a blank tweet, appends it to the tweets array, and returns the tweet.
659
	 *
660
	 * @return array The blank tweet.
661
	 */
662
	private static function start_new_tweet() {
663
		self::$tweets[] = array(
664
			// An array of blocks that make up this tweet.
665
			'blocks'   => array(),
666
			// If this tweet only contains part of a block, the boundary contains
667
			// information about where in the block the tweet ends.
668
			'boundary' => false,
669
			// The text content of the tweet.
670
			'text'     => '',
671
			// The media content of the tweet.
672
			'media'    => array(),
673
			// The quoted tweet in this tweet.
674
			'tweet'    => '',
675
			// Some blocks force a hard finish to the tweet, even if subsequent blocks
676
			// could technically be appended. This flag shows when a tweet is finished.
677
			'finished' => false,
678
			// Flag if the current tweet already has content in it.
679
			'changed'  => false,
680
		);
681
682
		return self::get_current_tweet();
683
	}
684
685
	/**
686
	 * Get the last tweet in the array.
687
	 *
688
	 * @return array The tweet.
689
	 */
690
	private static function get_current_tweet() {
691
		return end( self::$tweets );
692
	}
693
694
	/**
695
	 * Saves the passed tweet array as the last tweet, overwriting the former last tweet.
696
	 *
697
	 * This method adds some last minute checks: marking the tweet as "changed", as well
698
	 * as adding the $block to the tweet (if it was passed, and hasn't already been added).
699
	 *
700
	 * @param array $tweet       The tweet being stored.
701
	 * @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...
702
	 * @return array The saved tweet, after the last minute checks have been done.
703
	 */
704
	private static function save_current_tweet( $tweet, $block = null ) {
705
		$tweet['changed'] = true;
706
707
		if ( isset( $block ) ) {
708
			$block_def = self::get_block_definition( $block['name'] );
709
710
			// Check if this block type will be forcing a new tweet.
711
			if ( $block_def['force_finished'] ) {
712
				$tweet['finished'] = true;
713
			}
714
715
			// Check if this block is already recorded against this tweet.
716
			$last_block = end( $tweet['blocks'] );
717
			if ( isset( $block['clientId'] ) && ( false === $last_block || $last_block['clientId'] !== $block['clientId'] ) ) {
718
				$tweet['blocks'][] = $block;
719
			}
720
		}
721
722
		// Find the index of the last tweet in the array.
723
		end( self::$tweets );
724
		$tweet_index = key( self::$tweets );
725
726
		self::$tweets[ $tweet_index ] = $tweet;
727
728
		return $tweet;
729
	}
730
731
	/**
732
	 * Checks if the passed text is valid for a tweet or not.
733
	 *
734
	 * @param string $text                The text to check.
735
	 * @param int    $reserved_characters Optional. The number of characters to reduce the maximum tweet length by.
736
	 * @return bool Whether or not the text is valid.
737
	 */
738
	private static function is_valid_tweet( $text, $reserved_characters = 0 ) {
739
		return self::is_within_twitter_length( $text, 280 - $reserved_characters );
740
	}
741
742
	/**
743
	 * Checks if the passed text is valid for image alt text.
744
	 *
745
	 * @param string $text The text to check.
746
	 * @return bool Whether or not the text is valid.
747
	 */
748
	private static function is_valid_alt_text( $text ) {
749
		return self::is_within_twitter_length( $text, 1000 );
750
	}
751
752
	/**
753
	 * Check if a string is shorter than a given length, according to Twitter's rules for counting string length.
754
	 *
755
	 * @param string $text       The text to check.
756
	 * @param int    $max_length The number of characters long this string can be.
757
	 * @return bool Whether or not the string is no longer than the length limit.
758
	 */
759
	private static function is_within_twitter_length( $text, $max_length ) {
760
		// Replace all multiline separators with a \n, since that's the
761
		// character we actually want to count.
762
		$text = str_replace( self::$line_separator, "\n", $text );
763
764
		// Keep a running total of characters we've removed.
765
		$stripped_characters = 0;
766
767
		// Since we use '…' a lot, strip it out, so we can still use the ASCII checks.
768
		$ellipsis_count = 0;
769
		$text           = str_replace( '…', '', $text, $ellipsis_count );
770
771
		// The ellipsis glyph counts for two characters.
772
		$stripped_characters += $ellipsis_count * 2;
773
774
		// Try filtering out emoji first, since ASCII text + emoji is a relatively common case.
775
		if ( ! self::is_ascii( $text ) ) {
776
			// Initialise the emoji cache.
777
			if ( 0 === count( self::$emoji_list ) ) {
778
				self::$emoji_list = array_map( 'html_entity_decode', _wp_emoji_list( 'entities' ) );
779
			}
780
781
			$emoji_count = 0;
782
			$text        = str_replace( self::$emoji_list, '', $text, $emoji_count );
783
784
			// Emoji graphemes count as 2 characters each.
785
			$stripped_characters += $emoji_count * 2;
786
		}
787
788
		if ( self::is_ascii( $text ) ) {
789
			$stripped_characters += strlen( $text );
790
			if ( $stripped_characters <= $max_length ) {
791
				return true;
792
			}
793
794
			return false;
795
		}
796
797
		// Remove any glyphs that count as 1 character.
798
		// Source: https://github.com/twitter/twitter-text/blob/master/config/v3.json .
799
		// Note that the source ranges are in decimal, the regex ranges are converted to hex.
800
		$single_character_count = 0;
801
		$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 );
802
803
		$stripped_characters += $single_character_count;
804
805
		// Check if there's any text we haven't counted yet.
806
		// Any remaining glyphs count as 2 characters each.
807
		if ( 0 !== strlen( $text ) ) {
808
			// WP provides a compat version of mb_strlen(), no need to check if it exists.
809
			$stripped_characters += mb_strlen( $text, 'UTF-8' ) * 2;
810
		}
811
812
		if ( $stripped_characters <= $max_length ) {
813
			return true;
814
		}
815
816
		return false;
817
	}
818
819
	/**
820
	 * Checks if a string only contains ASCII characters.
821
	 *
822
	 * @param string $text The string to check.
823
	 * @return bool Whether or not the string is ASCII-only.
824
	 */
825
	private static function is_ascii( $text ) {
826
		if ( function_exists( 'mb_check_encoding' ) ) {
827
			if ( mb_check_encoding( $text, 'ASCII' ) ) {
828
				return true;
829
			}
830
		} elseif ( ! preg_match( '/[^\x00-\x7F]/', $text ) ) {
831
			return true;
832
		}
833
834
		return false;
835
	}
836
837
	/**
838
	 * A block will generate a certain amount of text to be inserted into a tweet. If that text is too
839
	 * long for a tweet, we already know where the text will be split when it's published as tweet, but
840
	 * we need to calculate where that corresponds to in the block edit UI.
841
	 *
842
	 * The tweet template for that block may add extra characters, extra characters are added for URL
843
	 * placeholders, and the block may contain multiple RichText areas (corresponding to attributes),
844
	 * so we need to keep track of both until the this function calculates which attribute area (in the
845
	 * block editor, the richTextIdentifier) that offset corresponds to, and how far into that attribute
846
	 * area it is.
847
	 *
848
	 * @param array   $block  The block being checked.
849
	 * @param integer $offset The position in the tweet text where it will be split.
850
	 * @return array|false `false` if the boundary can't be determined. Otherwise, returns the
851
	 *                     position in the block editor to insert the tweet boundary annotation.
852
	 */
853
	private static function get_boundary( $block, $offset ) {
854
		// If we don't have a clientId, there's no point in generating a boundary, since this
855
		// parse request doesn't have a way to map blocks back to editor UI.
856
		if ( ! isset( $block['clientId'] ) ) {
857
			return false;
858
		}
859
860
		$block_def = self::get_block_definition( $block['name'] );
861
862 View Code Duplication
		if ( isset( $block_def['content'] ) && count( $block_def['content'] ) > 0 ) {
863
			$tags = $block_def['content'];
864
		} else {
865
			$tags = array( 'content' );
866
		}
867
868
		$tag_content = self::extract_tag_content_from_html( $tags, $block['block']['innerHTML'] );
869
870
		// $tag_content is split up by tag first, then lines. We want to remap it to split it by lines
871
		// first, then tag.
872
		$lines = array();
873
		foreach ( $tag_content as $tag => $content ) {
874
			if ( 'content' === $tag ) {
875
				$attribute_name = 'content';
876
			} else {
877
				$attribute_name = array_search( $tag, $block_def['content'], true );
878
			}
879
880
			foreach ( $content as $id => $content_string ) {
881
				// Multiline blocks can have multiple lines, but other blocks will always only have 1.
882
				if ( 'multiline' === $block_def['type'] ) {
883
					$line_number = $id;
884
				} else {
885
					$line_number = 0;
886
				}
887
888
				if ( ! isset( $lines[ $line_number ] ) ) {
889
					$lines[ $line_number ] = array();
890
				}
891
892
				if ( ! isset( $lines[ $line_number ][ $attribute_name ] ) ) {
893
					// For multiline blocks, or the first time this attribute has been encountered
894
					// in single line blocks, assign the string to the line/attribute.
895
					$lines[ $line_number ][ $attribute_name ] = $content_string;
896
				} else {
897
					// For subsequent times this line/attribute is encountered (only in single line blocks),
898
					// append the string with a line break.
899
					$lines[ $line_number ][ $attribute_name ] .= "\n$content_string";
900
				}
901
			}
902
		}
903
904
		$line_count = count( $lines );
905
906
		$template_parts = preg_split( '/({{\w+}})/', $block_def['template'], -1, PREG_SPLIT_DELIM_CAPTURE );
907
908
		// Keep track of the total number of bytes we've processed from this block.
909
		$total_bytes_processed = 0;
910
911
		// Keep track of the number of characters that the processed data translates to in the editor.
912
		$characters_processed = 0;
913
914
		foreach ( $lines as $line_number => $line ) {
915
			// Add up the length of all the parts of this line.
916
			$line_byte_total = array_sum( array_map( 'strlen', $line ) );
917
918
			if ( $line_byte_total > 0 ) {
919
				// We have something to use in the template, so loop over each part of the template, and count it.
920
				foreach ( $template_parts as $template_part ) {
921
					$matches = array();
922
					if ( preg_match( '/{{(\w+)}}/', $template_part, $matches ) ) {
923
						$part_name = $matches[1];
924
925
						$line_part_data  = $line[ $part_name ];
926
						$line_part_bytes = strlen( $line_part_data );
927
928
						$cleaned_line_part_data = preg_replace( '/ \(url-placeholder-\d+-*\)/', '', $line_part_data );
929
930
						$cleaned_line_part_data = preg_replace_callback(
931
							'/url-placeholder-(\d+)-*/',
932
							function ( $matches ) {
933
								return self::$urls[ $matches[1] ];
934
							},
935
							$cleaned_line_part_data
936
						);
937
938
						if ( $total_bytes_processed + $line_part_bytes >= $offset ) {
939
							// We know that the offset is somewhere inside this part of the tweet, but we need to remove the length
940
							// of any URL placeholders that appear before the boundary, to be able to calculate the correct attribute offset.
941
942
							// $total_bytes_processed is the sum of everything we've processed so far, (including previous parts)
943
							// on this line. This makes it relatively easy to calculate the number of bytes into this part
944
							// that the boundary will occur.
945
							$line_part_byte_boundary = $offset - $total_bytes_processed;
946
947
							// Grab the data from this line part that appears before the boundary.
948
							$line_part_pre_boundary_data = substr( $line_part_data, 0, $line_part_byte_boundary );
949
950
							// Remove any URL placeholders, since these aren't shown in the editor.
951
							$line_part_pre_boundary_data = preg_replace( '/ \(url-placeholder-\d+-*\)/', '', $line_part_pre_boundary_data );
952
953
							$line_part_pre_boundary_data = preg_replace_callback(
954
								'/url-placeholder-(\d+)-*/',
955
								function ( $matches ) {
956
									return self::$urls[ $matches[1] ];
957
								},
958
								$line_part_pre_boundary_data
959
							);
960
961
							$boundary_start = self::utf_16_code_unit_length( $line_part_pre_boundary_data ) - 1;
962
963
							// Multiline blocks need to offset for the characters that are in the same content area,
964
							// but which were counted on previous lines.
965
							if ( 'multiline' === $block_def['type'] ) {
966
								$boundary_start += $characters_processed;
967
							}
968
969
							return array(
970
								'start'     => $boundary_start,
971
								'end'       => $boundary_start + 1,
972
								'container' => $part_name,
973
								'type'      => 'normal',
974
							);
975
						} else {
976
							$total_bytes_processed += $line_part_bytes;
977
							$characters_processed  += self::utf_16_code_unit_length( $cleaned_line_part_data );
978
							continue;
979
						}
980
					} else {
981
						$total_bytes_processed += strlen( $template_part );
982
					}
983
				}
984
985
				// Are we breaking at the end of this line?
986
				if ( $total_bytes_processed + 1 === $offset && $line_count > 1 ) {
987
					reset( $block_def['content'] );
988
					$container = key( $block_def['content'] );
989
					return array(
990
						'line'      => $line_number,
991
						'container' => $container,
992
						'type'      => 'end-of-line',
993
					);
994
				}
995
996
				// The newline at the end of each line is 1 byte, but we don't need to count empty lines.
997
				$total_bytes_processed++;
998
			}
999
1000
			// We do need to count empty lines in the editor, since they'll be displayed.
1001
			$characters_processed++;
1002
		}
1003
1004
		return false;
1005
	}
1006
1007
	/**
1008
	 * JavaScript uses UTF-16 for encoding strings, which means we need to provide UTF-16
1009
	 * based offsets for the block editor to render tweet boundaries in the correct location.
1010
	 *
1011
	 * UTF-16 is a variable-width character encoding: every code unit is 2 bytes, a single character
1012
	 * can be one or two code units long. Fortunately for us, JavaScript's String.charAt() is based
1013
	 * on the older UCS-2 character encoding, which only counts single code units. PHP's strlen()
1014
	 * counts a code unit as being 2 characters, so once a string is converted to UTF-16, we have
1015
	 * a fast way to determine how long it is in UTF-16 code units.
1016
	 *
1017
	 * @param string $text The natively encoded string to get the length of.
1018
	 * @return int The length of the string in UTF-16 code units. Returns -1 if the length could not
1019
	 *             be calculated.
1020
	 */
1021
	private static function utf_16_code_unit_length( $text ) {
1022
		// If mb_convert_encoding() exists, we can use that for conversion.
1023
		if ( function_exists( 'mb_convert_encoding' ) ) {
1024
			// UTF-16 can add an additional code unit to the start of the string, called the
1025
			// Byte Order Mark (BOM), which indicates whether the string is encoding as
1026
			// big-endian, or little-endian. Since we don't want to count code unit, and the endianness
1027
			// doesn't matter for our purposes, using PHP's UTF-16BE encoding uses big-endian
1028
			// encoding, and ensures the BOM *won't* be prepended to the string to the string.
1029
			return strlen( mb_convert_encoding( $text, 'UTF-16BE' ) ) / 2;
1030
		}
1031
1032
		// If we can't convert this string, return a result that will avoid an incorrect annotation being added.
1033
		return -1;
1034
	}
1035
1036
	/**
1037
	 * Extracts the tweetable text from a block.
1038
	 *
1039
	 * @param array $block A single block, as generated by parse_block().
1040
	 * @return string The tweetable text from the block, in the correct template form.
1041
	 */
1042
	private static function extract_text_from_block( $block ) {
1043
		// If the block doesn't have an innerHTMl, we're not going to get any text.
1044
		if ( empty( $block['innerHTML'] ) ) {
1045
			return '';
1046
		}
1047
1048
		$block_def = self::get_block_definition( $block['blockName'] );
1049
1050
		// We currently only support extracting text from HTML text nodes.
1051
		if ( ! isset( $block_def['content_location'] ) || 'html' !== $block_def['content_location'] ) {
1052
			return '';
1053
		}
1054
1055
		// Find out which tags we need to extract content from.
1056 View Code Duplication
		if ( isset( $block_def['content'] ) && count( $block_def['content'] ) > 0 ) {
1057
			$tags = $block_def['content'];
1058
		} else {
1059
			$tags = array( 'content' );
1060
		}
1061
1062
		$tag_values = self::extract_tag_content_from_html( $tags, $block['innerHTML'] );
1063
1064
		// We can treat single line blocks as "multiline", with only one line in them.
1065
		$lines = array();
1066
		foreach ( $tag_values as $tag => $values ) {
1067
			// For single-line blocks, we need to squash all the values for this tag into a single value.
1068
			if ( 'multiline' !== $block_def['type'] ) {
1069
				$values = array( trim( implode( "\n", $values ) ) );
1070
			}
1071
1072
			// Handle the special "content" tag.
1073
			if ( 'content' === $tag ) {
1074
				$placeholder = 'content';
1075
			} else {
1076
				$placeholder = array_search( $tag, $block_def['content'], true );
1077
			}
1078
1079
			// Loop over each instance of this value, appling that value to the corresponding line template.
1080
			foreach ( $values as $line_number => $value ) {
1081
				if ( ! isset( $lines[ $line_number ] ) ) {
1082
					$lines[ $line_number ] = $block_def['template'];
1083
				}
1084
1085
				$lines[ $line_number ] = str_replace( '{{' . $placeholder . '}}', $value, $lines[ $line_number ] );
1086
			}
1087
		}
1088
1089
		// Remove any lines that didn't apply any content.
1090
		$empty_template = preg_replace( '/{{.*?}}/', '', $block_def['template'] );
1091
		$lines          = array_filter(
1092
			$lines,
1093
			function ( $line ) use ( $empty_template ) {
1094
				return $line !== $empty_template;
1095
			}
1096
		);
1097
1098
		// Join the lines together into a single string.
1099
		$text = implode( self::$line_separator, $lines );
1100
1101
		// Trim off any extra whitespace that we no longer need.
1102
		$text = trim( $text );
1103
		$text = preg_replace( '/(' . self::$line_separator . ')+$/', '', $text );
1104
1105
		return $text;
1106
	}
1107
1108
	/**
1109
	 * Extracts the tweetable media from a block.
1110
	 *
1111
	 * @param array $block A single block, as generated by parse_block().
1112
	 * @return array {
1113
	 *     An array of media.
1114
	 *
1115
	 *     @type string url The URL of the media.
1116
	 *     @type string alt The alt text of the media.
1117
	 * }
1118
	 */
1119
	private static function extract_media_from_block( $block ) {
1120
		$block_def = self::get_block_definition( $block['blockName'] );
1121
1122
		$media = array();
1123
1124
		if ( 'image' === $block_def['type'] ) {
1125
			$url = self::extract_attr_content_from_html(
1126
				$block_def['content']['url'][0],
1127
				$block_def['content']['url'][1],
1128
				$block['innerHTML']
1129
			);
1130
			$alt = self::extract_attr_content_from_html(
1131
				$block_def['content']['alt'][0],
1132
				$block_def['content']['alt'][1],
1133
				$block['innerHTML']
1134
			);
1135
1136
			$img_count = count( $url );
1137
1138
			for ( $ii = 0; $ii < $img_count; $ii++ ) {
1139
				$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...
1140
1141
				$media[] = array(
1142
					'url'  => $url[ $ii ],
1143
					'alt'  => self::is_valid_alt_text( $alt[ $ii ] ) ? $alt[ $ii ] : '',
1144
					'type' => $filedata['type'],
1145
				);
1146
			}
1147
		} elseif ( 'video' === $block_def['type'] ) {
1148
			// Handle VideoPress videos.
1149
			if ( isset( $block['attrs']['src'] ) && 0 === strpos( $block['attrs']['src'], 'https://videos.files.wordpress.com/' ) ) {
1150
				$url = array( $block['attrs']['src'] );
1151
			} else {
1152
				$url = self::extract_attr_content_from_html(
1153
					$block_def['content']['url'][0],
1154
					$block_def['content']['url'][1],
1155
					$block['innerHTML']
1156
				);
1157
			}
1158
1159
			// We can only ever use the first video found, no need to go through all of them.
1160
			if ( count( $url ) > 0 ) {
1161
				$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...
1162
1163
				$media[] = array(
1164
					'url'  => $url[0],
1165
					'type' => $filedata['type'],
1166
				);
1167
			}
1168
		}
1169
1170
		return $media;
1171
	}
1172
1173
	/**
1174
	 * Extracts the tweet URL from a Twitter embed block.
1175
	 *
1176
	 * @param array $block A single block, as generated by parse_block().
1177
	 * @return string The tweet URL. Empty string if there is none available.
1178
	 */
1179
	private static function extract_tweet_from_block( $block ) {
1180 View Code Duplication
		if ( 'core/embed' === $block['blockName'] && 'twitter' === $block['attrs']['providerNameSlug'] ) {
1181
			return $block['attrs']['url'];
1182
		}
1183
1184
		// @todo This fallback can be removed when WordPress 5.6 is the minimum supported version.
1185
		if ( 'core-embed/twitter' === $block['blockName'] ) {
1186
			return $block['attrs']['url'];
1187
		}
1188
1189
		return '';
1190
	}
1191
1192
	/**
1193
	 * Extracts URL from an embed block.
1194
	 *
1195
	 * @param array $block A single block, as generated by parse_block().
1196
	 * @return string The URL. Empty string if there is none available.
1197
	 */
1198
	private static function extract_embed_from_block( $block ) {
1199
		$block_def = self::get_block_definition( $block['blockName'] );
1200
1201
		if ( 'embed' !== $block_def['type'] ) {
1202
			return '';
1203
		}
1204
1205
		// Twitter embeds are handled in ::extract_tweet_from_block().
1206 View Code Duplication
		if ( 'core/embed' === $block['blockName'] && 'twitter' === $block['attrs']['providerNameSlug'] ) {
1207
			return '';
1208
		}
1209
1210
		// @todo This fallback can be removed when WordPress 5.6 is the minimum supported version.
1211
		if ( 'core-embed/twitter' === $block['blockName'] ) {
1212
			return '';
1213
		}
1214
1215
		$url = '';
1216
		if ( 'block-attributes' === $block_def['content_location'] ) {
1217
			$url = $block['attrs'][ $block_def['content'][0] ];
1218
		}
1219
1220
		if ( 'jetpack/gif' === $block['blockName'] ) {
1221
			$url = str_replace( '/embed/', '/gifs/', $url );
1222
		}
1223
1224
		return $url;
1225
	}
1226
1227
	/**
1228
	 * There's a bunch of left-over cruft in the tweets array that we don't need to return. Removing
1229
	 * it helps keep the size of the data down.
1230
	 */
1231
	private static function clean_return_tweets() {
1232
		// Before we return, clean out unnecessary cruft from the return data.
1233
		$tweets = array_map(
1234
			function ( $tweet ) {
1235
				// Remove tweets that don't have anything saved in them. eg, if the last block is a
1236
				// header with no text, it'll force a new tweet, but we won't end up putting anything
1237
				// in that tweet.
1238
				if ( ! $tweet['changed'] ) {
1239
					return false;
1240
				}
1241
1242
				// Replace any URL placeholders that appear in the text.
1243
				$tweet['urls'] = array();
1244
				foreach ( self::$urls as $id => $url ) {
1245
					$count = 0;
1246
1247
					$tweet['text'] = str_replace( str_pad( "url-placeholder-$id", self::$characters_per_url, '-' ), $url, $tweet['text'], $count );
1248
1249
					// If we found a URL, keep track of it for the editor.
1250
					if ( $count > 0 ) {
1251
						$tweet['urls'][] = $url;
1252
					}
1253
				}
1254
1255
				// Remove any inline placeholders.
1256
				$tweet['text'] = str_replace( self::$inline_placeholder, '', $tweet['text'] );
1257
1258
				// Tidy up the whitespace.
1259
				$tweet['text'] = trim( $tweet['text'] );
1260
				$tweet['text'] = preg_replace( '/[ \t]+\n/', "\n", $tweet['text'] );
1261
1262
				// Remove internal flags.
1263
				unset( $tweet['changed'] );
1264
				unset( $tweet['finished'] );
1265
1266
				// Remove bulky block data.
1267
				if ( ! isset( $tweet['blocks'][0]['attributes'] ) && ! isset( $tweet['blocks'][0]['clientId'] ) ) {
1268
					$tweet['blocks'] = array();
1269
				} else {
1270
					// Remove the parts of the block data that the editor doesn't need.
1271
					$block_count = count( $tweet['blocks'] );
1272
					for ( $ii = 0; $ii < $block_count; $ii++ ) {
1273
						$keys = array_keys( $tweet['blocks'][ $ii ] );
1274
						foreach ( $keys as $key ) {
1275
							// The editor only needs these attributes, everything else will be unset.
1276
							if ( in_array( $key, array( 'attributes', 'clientId' ), true ) ) {
1277
								continue;
1278
							}
1279
1280
							unset( $tweet['blocks'][ $ii ][ $key ] );
1281
						}
1282
					}
1283
				}
1284
1285
				return $tweet;
1286
			},
1287
			self::$tweets
1288
		);
1289
1290
		// Clean any removed tweets out of the result.
1291
		return array_values( array_filter( $tweets, 'is_array' ) );
1292
	}
1293
1294
	/**
1295
	 * Given a list of tags and a HTML blob, this will extract the text content inside
1296
	 * each of the given tags.
1297
	 *
1298
	 * @param array  $tags An array of tag names.
1299
	 * @param string $html A blob of HTML.
1300
	 * @return array An array of the extract content. The keys in the array are the $tags,
1301
	 *               each value is an array. The value array is indexed in the same order as the tag
1302
	 *               appears in the HTML blob, including nested tags.
1303
	 */
1304
	private static function extract_tag_content_from_html( $tags, $html ) {
1305
		// Normalise <br>.
1306
		$html = preg_replace( '/<br\s*\/?>/', '<br>', $html );
1307
1308
		// If there were no tags passed, assume the entire text is required.
1309
		if ( empty( $tags ) ) {
1310
			$tags = array( 'content' );
1311
		}
1312
1313
		$values = array();
1314
1315
		$tokens = wp_html_split( $html );
1316
1317
		foreach ( $tags as $tag ) {
1318
			$values[ $tag ] = array();
1319
1320
			// Since tags can be nested, keeping track of the nesting level allows
1321
			// us to extract nested content into a flat array.
1322
			if ( 'content' === $tag ) {
1323
				// The special "content" tag means we should store the entire content,
1324
				// so assume the tag is open from the beginning.
1325
				$opened = 0;
1326
				$closed = -1;
1327
1328
				$values['content'][0] = '';
1329
			} else {
1330
				$opened = -1;
1331
				$closed = -1;
1332
			}
1333
1334
			// When we come across a URL, we need to keep track of it, so it can then be inserted
1335
			// in the right place.
1336
			$current_url = '';
1337
			foreach ( $tokens as $token ) {
1338
				if ( 0 === strlen( $token ) ) {
1339
					// Skip any empty tokens.
1340
					continue;
1341
				}
1342
1343
				// If we're currently storing content, check if it's a text-formatting
1344
				// tag that we should apply.
1345
				if ( $opened !== $closed ) {
1346
					// End of a paragraph, put in some newlines (as long as we're not extracting paragraphs).
1347
					if ( '</p>' === $token && 'p' !== $tag ) {
1348
						$values[ $tag ][ $opened ] .= "\n\n";
1349
					}
1350
1351
					// A line break gets one newline.
1352
					if ( '<br>' === $token ) {
1353
						$values[ $tag ][ $opened ] .= "\n";
1354
					}
1355
1356
					// A link has opened, grab the URL for inserting later.
1357
					if ( 0 === strpos( $token, '<a ' ) ) {
1358
						$href_values = self::extract_attr_content_from_html( 'a', 'href', $token );
1359
						if ( ! empty( $href_values[0] ) ) {
1360
							// Remember the URL.
1361
							$current_url = $href_values[0];
1362
						}
1363
					}
1364
1365
					// A link has closed, insert the URL from that link if we have one.
1366
					if ( '</a>' === $token && '' !== $current_url ) {
1367
						// Generate a unique-to-this-block placeholder which takes up the
1368
						// same number of characters as a URL does.
1369
						$values[ $tag ][ $opened ] .= ' (' . self::generate_url_placeholder( $current_url ) . ')';
1370
1371
						$current_url = '';
1372
					}
1373
1374
					// We don't return inline images, but they technically take up 1 character in the RichText.
1375
					if ( 0 === strpos( $token, '<img ' ) ) {
1376
						$values[ $tag ][ $opened ] .= self::$inline_placeholder;
1377
					}
1378
				}
1379
1380
				if ( "<$tag>" === $token || 0 === strpos( $token, "<$tag " ) ) {
1381
					// A tag has just been opened.
1382
					$opened++;
1383
					// Set an empty value now, so we're keeping track of empty tags.
1384
					if ( ! isset( $values[ $tag ][ $opened ] ) ) {
1385
						$values[ $tag ][ $opened ] = '';
1386
					}
1387
					continue;
1388
				}
1389
1390
				if ( "</$tag>" === $token ) {
1391
					// The tag has been closed.
1392
					$closed++;
1393
					continue;
1394
				}
1395
1396
				if ( '<' === $token[0] ) {
1397
					// We can skip any other tags.
1398
					continue;
1399
				}
1400
1401
				if ( $opened !== $closed ) {
1402
					// We're currently in a tag, with some content. Start by decoding any HTML entities.
1403
					$token = html_entity_decode( $token, ENT_QUOTES );
1404
1405
					// Find any URLs in this content, and replace them with a placeholder.
1406
					preg_match_all( Twitter_Regex::getValidUrlMatcher(), $token, $matches, PREG_SET_ORDER | PREG_OFFSET_CAPTURE );
1407
					$offset = 0;
1408
					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...
1409
						list( $url, $start ) = $match[2];
1410
1411
						$token = substr_replace( $token, self::generate_url_placeholder( $url ), $start + $offset, strlen( $url ) );
1412
1413
						$offset += self::$characters_per_url - strlen( $url );
1414
1415
						// If we're in a link with a URL set, there's no need to keep two copies of the same link.
1416
						if ( $url === $current_url ) {
1417
							$current_url = '';
1418
						}
1419
					}
1420
1421
					// Append it to the right value.
1422
					$values[ $tag ][ $opened ] .= $token;
1423
				}
1424
			}
1425
		}
1426
1427
		return $values;
1428
	}
1429
1430
	/**
1431
	 * Extracts the attribute content from a tag.
1432
	 *
1433
	 * This method allows for the HTML to have multiple instances of the tag, and will return
1434
	 * an array containing the attribute value (or an empty string, if the tag doesn't have the
1435
	 * requested attribute) for each occurrence of the tag.
1436
	 *
1437
	 * @param string $tag          The tag we're looking for.
1438
	 * @param string $attr         The name of the attribute we're looking for.
1439
	 * @param string $html         The HTML we're searching through.
1440
	 * @param array  $attr_filters Optional. Filters tags based on whether or not they have attributes with given values.
1441
	 * @return array The array of attribute values found.
1442
	 */
1443
	private static function extract_attr_content_from_html( $tag, $attr, $html, $attr_filters = array() ) {
1444
		// Given our single tag and attribute, construct a KSES filter for it.
1445
		$kses_filter = array(
1446
			$tag => array(
1447
				$attr => array(),
1448
			),
1449
		);
1450
1451
		foreach ( $attr_filters as $filter_attr => $filter_value ) {
1452
			$kses_filter[ $tag ][ $filter_attr ] = array();
1453
		}
1454
1455
		// Remove all HTML except for the tag we're after. On that tag,
1456
		// remove all attributes except for the one we're after.
1457
		$stripped_html = wp_kses( $html, $kses_filter );
1458
1459
		$values = array();
1460
1461
		$tokens = wp_html_split( $stripped_html );
1462
		foreach ( $tokens as $token ) {
1463
			$found_value = '';
1464
1465
			if ( 0 === strlen( $token ) ) {
1466
				// Skip any empty tokens.
1467
				continue;
1468
			}
1469
1470
			if ( '<' !== $token[0] ) {
1471
				// We can skip any non-tag tokens.
1472
				continue;
1473
			}
1474
1475
			$token_attrs = wp_kses_attr_parse( $token );
1476
1477
			// Skip tags that KSES couldn't handle.
1478
			if ( false === $token_attrs ) {
1479
				continue;
1480
			}
1481
1482
			// Remove the tag open and close chunks.
1483
			$found_tag = array_shift( $token_attrs );
1484
			array_pop( $token_attrs );
1485
1486
			// We somehow got a tag that isn't the one we're after. Skip it.
1487
			if ( 0 !== strpos( $found_tag, "<$tag " ) ) {
1488
				continue;
1489
			}
1490
1491
			// We can only fail an attribute filter if one is set.
1492
			$passed_filter = count( $attr_filters ) === 0;
1493
1494
			foreach ( $token_attrs as $token_attr_string ) {
1495
				// The first "=" in the string will be between the attribute name/value.
1496
				list( $token_attr_name, $token_attr_value ) = explode( '=', $token_attr_string, 2 );
1497
1498
				$token_attr_name  = trim( $token_attr_name );
1499
				$token_attr_value = trim( $token_attr_value );
1500
1501
				// Remove a single set of quotes from around the value.
1502
				if ( '' !== $token_attr_value && in_array( $token_attr_value[0], array( '"', "'" ), true ) ) {
1503
					$token_attr_value = trim( $token_attr_value, $token_attr_value[0] );
1504
				}
1505
1506
				// If this is the attribute we're after, save the value for the end of the loop.
1507
				if ( $token_attr_name === $attr ) {
1508
					$found_value = $token_attr_value;
1509
				}
1510
1511
				if ( isset( $attr_filters[ $token_attr_name ] ) && $attr_filters[ $token_attr_name ] === $token_attr_value ) {
1512
					$passed_filter = true;
1513
				}
1514
			}
1515
1516
			if ( $passed_filter ) {
1517
				// We always want to append the found value, even if we didn't "find" a matching attribute.
1518
				// An empty string in the return value means that we found the tag, but the attribute was
1519
				// either empty, or not set.
1520
				$values[] = html_entity_decode( $found_value, ENT_QUOTES );
1521
			}
1522
		}
1523
1524
		return $values;
1525
	}
1526
1527
	/**
1528
	 * Generates a placeholder for URLs, using the appropriate number of characters to imitate how
1529
	 * Twitter counts the length of URLs in tweets.
1530
	 *
1531
	 * @param string $url The URL to generate a placeholder for.
1532
	 * @return string The placeholder.
1533
	 */
1534
	public static function generate_url_placeholder( $url ) {
1535
		self::$urls[] = $url;
1536
1537
		return str_pad( 'url-placeholder-' . ( count( self::$urls ) - 1 ), self::$characters_per_url, '-' );
1538
	}
1539
1540
	/**
1541
	 * Retrieves the Twitter card data for a list of URLs.
1542
	 *
1543
	 * @param array $urls The list of URLs to grab Twitter card data for.
1544
	 * @return array The Twitter card data.
1545
	 */
1546
	public static function generate_cards( $urls ) {
1547
		$requests = array_map(
1548
			function ( $url ) {
1549
				return array(
1550
					'url' => $url,
1551
				);
1552
			},
1553
			$urls
1554
		);
1555
1556
		$results = Requests::request_multiple( $requests );
1557
1558
		$card_data = array(
1559
			'creator'     => array(
1560
				'name' => 'twitter:creator',
1561
			),
1562
			'description' => array(
1563
				'name'     => 'twitter:description',
1564
				'property' => 'og:description',
1565
			),
1566
			'image'       => array(
1567
				'name'     => 'twitter:image',
1568
				'property' => 'og:image:secure',
1569
				'property' => 'og:image',
1570
			),
1571
			'title'       => array(
1572
				'name'     => 'twitter:text:title',
1573
				'property' => 'og:title',
1574
			),
1575
			'type'        => array(
1576
				'name' => 'twitter:card',
1577
			),
1578
		);
1579
1580
		$cards = array();
1581
		foreach ( $results as $result ) {
1582
			if ( count( $result->history ) > 0 ) {
1583
				$url = $result->history[0]->url;
1584
			} else {
1585
				$url = $result->url;
1586
			}
1587
1588
			if ( ! $result->success ) {
1589
				$cards[ $url ] = array(
1590
					'error' => 'invalid_url',
1591
				);
1592
				continue;
1593
			}
1594
1595
			$url_card_data = array();
1596
1597
			foreach ( $card_data as $key => $filters ) {
1598
				foreach ( $filters as $attribute => $value ) {
1599
					$found_data = self::extract_attr_content_from_html( 'meta', 'content', $result->body, array( $attribute => $value ) );
1600
					if ( count( $found_data ) > 0 && strlen( $found_data[0] ) > 0 ) {
1601
						$url_card_data[ $key ] = html_entity_decode( $found_data[0], ENT_QUOTES );
1602
						break;
1603
					}
1604
				}
1605
			}
1606
1607
			if ( count( $url_card_data ) > 0 ) {
1608
				$cards[ $url ] = $url_card_data;
1609
			} else {
1610
				$cards[ $url ] = array(
1611
					'error' => 'no_og_data',
1612
				);
1613
			}
1614
		}
1615
1616
		return $cards;
1617
	}
1618
1619
	/**
1620
	 * Get the WPCOM or self-hosted site ID.
1621
	 *
1622
	 * @return mixed
1623
	 */
1624 View Code Duplication
	public static function get_site_id() {
1625
		$is_wpcom = ( defined( 'IS_WPCOM' ) && IS_WPCOM );
1626
		$site_id  = $is_wpcom ? get_current_blog_id() : Jetpack_Options::get_option( 'id' );
1627
		if ( ! $site_id ) {
1628
			return new WP_Error(
1629
				'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...
1630
				__( 'Sorry, something is wrong with your Jetpack connection.', 'jetpack' ),
1631
				403
1632
			);
1633
		}
1634
		return (int) $site_id;
1635
	}
1636
}
1637