Completed
Push — add/private-site-mode ( 81d3a8...c37ff2 )
by
unknown
25:46 queued 11:45
created

Jetpack_Tweetstorm_Helper   F

Complexity

Total Complexity 204

Size/Duplication

Total Lines 1658
Duplicated Lines 3.38 %

Coupling/Cohesion

Components 1
Dependencies 4

Importance

Changes 0
Metric Value
dl 56
loc 1658
rs 0.8
c 0
b 0
f 0
wmc 204
lcom 1
cbo 4

27 Methods

Rating   Name   Duplication   Size   Complexity  
B gather() 0 40 8
B parse() 0 40 6
A get_block_definition() 0 7 2
F add_text_to_tweets() 13 179 25
C add_media_to_tweets() 15 59 11
A add_tweet_to_tweets() 0 17 3
A add_embed_to_tweets() 0 22 5
A extract_blocks() 0 22 4
A start_new_tweet() 0 22 1
A get_current_tweet() 0 3 1
B save_current_tweet() 0 26 6
A is_valid_tweet() 0 3 1
A is_valid_alt_text() 0 3 1
B is_within_twitter_length() 0 59 7
A is_ascii() 0 11 4
F get_boundary() 5 168 19
A utf_16_code_unit_length() 0 14 2
C extract_text_from_block() 5 64 11
B extract_media_from_block() 0 53 8
A extract_tweet_from_block() 3 7 3
B extract_embed_from_block() 3 23 6
C clean_return_tweets() 0 74 13
F extract_tag_content_from_html() 0 145 29
C extract_attr_content_from_html() 0 83 14
A generate_url_placeholder() 0 5 1
C generate_cards() 0 76 9
A get_site_id() 12 12 4

How to fix   Duplicated Code    Complexity   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

Complex Class

 Tip:   Before tackling complexity, make sure that you eliminate any duplication first. This often can reduce the size of classes significantly.

Complex classes like Jetpack_Tweetstorm_Helper often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use Jetpack_Tweetstorm_Helper, and based on these observations, apply Extract Interface, too.

1
<?php
2
/**
3
 * Tweetstorm block and API helper.
4
 *
5
 * @package automattic/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
		return null;
324
	}
325
326
	/**
327
	 * If the block has any text, process it, and add it to the tweet list.
328
	 *
329
	 * @param array $block The block to process.
330
	 */
331
	private static function add_text_to_tweets( $block ) {
332
		// This is a text block, is there any text?
333
		if ( 0 === strlen( $block['text'] ) ) {
334
			return;
335
		}
336
337
		$block_def = self::get_block_definition( $block['name'] );
338
339
		// Grab the most recent tweet, so we can append to that if we can.
340
		$current_tweet = self::get_current_tweet();
341
342
		// If the entire block can't be fit in this tweet, we need to start a new tweet.
343
		if ( $current_tweet['changed'] && ! self::is_valid_tweet( trim( $current_tweet['text'] ) . "\n\n{$block['text']}" ) ) {
344
			self::start_new_tweet();
345
		}
346
347
		// Multiline blocks prioritise splitting by line, but are otherwise identical to
348
		// normal text blocks. This means we can treat normal text blocks as being
349
		// "multiline", but with a single line.
350
		if ( 'multiline' === $block_def['type'] ) {
351
			$lines = explode( self::$line_separator, $block['text'] );
352
		} else {
353
			$lines = array( $block['text'] );
354
		}
355
		$line_total = count( $lines );
356
357
		// Keep track of how many characters from this block we've allocated to tweets.
358
		$current_character_count = 0;
359
360
		for ( $line_count = 0; $line_count < $line_total; $line_count++ ) {
361
			$line_text = $lines[ $line_count ];
362
363
			// Make sure we have the most recent tweet at the start of every loop.
364
			$current_tweet = self::get_current_tweet();
365
366
			if ( $current_tweet['changed'] ) {
367
				// When it's the first line, add an extra blank line to seperate
368
				// the tweet text from that of the previous block.
369
				$separator = "\n\n";
370
				if ( $line_count > 0 ) {
371
					$separator = "\n";
372
				}
373
374
				// Is this line short enough to append to the current tweet?
375
				if ( self::is_valid_tweet( trim( $current_tweet['text'] ) . "$separator$line_text" ) ) {
376
					// Don't trim the text yet, as we may need it for boundary calculations.
377
					$current_tweet['text'] = $current_tweet['text'] . "$separator$line_text";
378
379
					self::save_current_tweet( $current_tweet, $block );
380
					continue;
381
				}
382
383
				// This line is too long, and lines *must* be split to a new tweet if they don't fit
384
				// into the current tweet. If this isn't the first line, record where we split the block.
385 View Code Duplication
				if ( $line_count > 0 ) {
386
					// Increment by 1 to allow for the \n between lines to be counted by ::get_boundary().
387
					$current_character_count  += strlen( $current_tweet['text'] ) + 1;
388
					$current_tweet['boundary'] = self::get_boundary( $block, $current_character_count );
389
390
					self::save_current_tweet( $current_tweet );
391
				}
392
393
				// Start a new tweet.
394
				$current_tweet = self::start_new_tweet();
395
			}
396
397
			// Since we're now at the start of a new tweet, is this line short enough to be a tweet by itself?
398
			if ( self::is_valid_tweet( $line_text ) ) {
399
				$current_tweet['text'] = $line_text;
400
401
				self::save_current_tweet( $current_tweet, $block );
402
				continue;
403
			}
404
405
			// The line is too long for a single tweet, so split it by sentences, or linebreaks.
406
			$sentences      = preg_split( '/(?|(?<!\.\.\.)(?<=[.?!]|\.\)|\.["\'])(\s+)(?=[\p{L}\'"\(])|(\n+))/u', $line_text, -1, PREG_SPLIT_DELIM_CAPTURE );
407
			$sentence_total = count( $sentences );
408
409
			// preg_split() puts the blank space between sentences into a seperate entry in the result,
410
			// so we need to step through the result array by two, and append the blank space when needed.
411
			for ( $sentence_count = 0; $sentence_count < $sentence_total; $sentence_count += 2 ) {
412
				$current_sentence = $sentences[ $sentence_count ];
413
				if ( isset( $sentences[ $sentence_count + 1 ] ) ) {
414
					$current_sentence .= $sentences[ $sentence_count + 1 ];
415
				}
416
417
				// Make sure we have the most recent tweet.
418
				$current_tweet = self::get_current_tweet();
419
420
				// After the first sentence, we can try and append sentences to the previous sentence.
421
				if ( $current_tweet['changed'] && $sentence_count > 0 ) {
422
					// Is this sentence short enough for appending to the current tweet?
423
					if ( self::is_valid_tweet( $current_tweet['text'] . rtrim( $current_sentence ) ) ) {
424
						$current_tweet['text'] .= $current_sentence;
425
426
						self::save_current_tweet( $current_tweet, $block );
427
						continue;
428
					}
429
				}
430
431
				// Will this sentence fit in its own tweet?
432
				if ( self::is_valid_tweet( trim( $current_sentence ) ) ) {
433
					if ( $current_tweet['changed'] ) {
434
						// If we're already in the middle of a block, record the boundary
435
						// before creating a new tweet.
436 View Code Duplication
						if ( $line_count > 0 || $sentence_count > 0 ) {
437
							$current_character_count  += strlen( $current_tweet['text'] );
438
							$current_tweet['boundary'] = self::get_boundary( $block, $current_character_count );
439
440
							self::save_current_tweet( $current_tweet );
441
						}
442
443
						$current_tweet = self::start_new_tweet();
444
					}
445
					$current_tweet['text'] = $current_sentence;
446
447
					self::save_current_tweet( $current_tweet, $block );
448
					continue;
449
				}
450
451
				// This long sentence will start the next tweet that this block is going
452
				// to be turned into, so we need to record the boundary and start a new tweet.
453
				if ( $current_tweet['changed'] ) {
454
					$current_character_count  += strlen( $current_tweet['text'] );
455
					$current_tweet['boundary'] = self::get_boundary( $block, $current_character_count );
456
457
					self::save_current_tweet( $current_tweet );
458
459
					$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...
460
				}
461
462
				// Split the long sentence into words.
463
				$words      = preg_split( '/(\p{Z})/u', $current_sentence, -1, PREG_SPLIT_DELIM_CAPTURE );
464
				$word_total = count( $words );
465
				for ( $word_count = 0; $word_count < $word_total; $word_count += 2 ) {
466
					// Make sure we have the most recent tweet.
467
					$current_tweet = self::get_current_tweet();
468
469
					// If we're on a new tweet, we don't want to add a space at the start.
470
					if ( ! $current_tweet['changed'] ) {
471
						$current_tweet['text'] = $words[ $word_count ];
472
473
						self::save_current_tweet( $current_tweet, $block );
474
						continue;
475
					}
476
477
					// Can we add this word to the current tweet?
478
					if ( self::is_valid_tweet( "{$current_tweet['text']} {$words[ $word_count ]}…" ) ) {
479
						$space = isset( $words[ $word_count - 1 ] ) ? $words[ $word_count - 1 ] : ' ';
480
481
						$current_tweet['text'] .= $space . $words[ $word_count ];
482
483
						self::save_current_tweet( $current_tweet, $block );
484
						continue;
485
					}
486
487
					// Add one for the space character that we won't include in the tweet text.
488
					$current_character_count += strlen( $current_tweet['text'] ) + 1;
489
490
					// We're starting a new tweet with this word. Append ellipsis to
491
					// the current tweet, then move on.
492
					$current_tweet['text'] .= '…';
493
494
					$current_tweet['boundary'] = self::get_boundary( $block, $current_character_count );
495
					self::save_current_tweet( $current_tweet );
496
497
					$current_tweet = self::start_new_tweet();
498
499
					// If this is the second tweet created by the split sentence, it'll start
500
					// with ellipsis, which we don't want to count, but we do want to count the space
501
					// that was replaced by this ellipsis.
502
					$current_tweet['text']    = "…{$words[ $word_count ]}";
503
					$current_character_count -= strlen( '…' );
504
505
					self::save_current_tweet( $current_tweet, $block );
506
				}
507
			}
508
		}
509
	}
510
511
	/**
512
	 * Check if the block has any media to add, and add it.
513
	 *
514
	 * @param array $block  The block to process.
515
	 */
516
	private static function add_media_to_tweets( $block ) {
517
		// There's some media to attach!
518
		$media_count = count( $block['media'] );
519
		if ( 0 === $media_count ) {
520
			return;
521
		}
522
523
		$current_tweet = self::get_current_tweet();
524
525
		// We can only attach media to the previous tweet if the previous tweet
526
		// doesn't already have media.
527
		if ( count( $current_tweet['media'] ) > 0 ) {
528
			$current_tweet = self::start_new_tweet();
529
		}
530
531
		// Would adding this media make the text of the previous tweet too long?
532
		if ( ! self::is_valid_tweet( $current_tweet['text'], $media_count * self::$characters_per_media ) ) {
533
			$current_tweet = self::start_new_tweet();
534
		}
535
536
		$media = array_values(
537
			array_filter(
538
				$block['media'],
539 View Code Duplication
				function ( $single ) {
540
					// Only images and videos can be uploaded.
541
					if ( 0 === strpos( $single['type'], 'image/' ) || 0 === strpos( $single['type'], 'video/' ) ) {
542
						return true;
543
					}
544
545
					return false;
546
				}
547
			)
548
		);
549
550
		if ( count( $media ) > 0 ) {
551
			if ( 0 === strpos( $media[0]['type'], 'video/' ) || 'image/gif' === $media[0]['type'] ) {
552
				// We can only attach a single video or GIF.
553
				$current_tweet['media'] = array_slice( $media, 0, 1 );
554
			} else {
555
				// Since a GIF or video isn't the first element, we can remove all of them from the array.
556
				$filtered_media = array_values(
557
					array_filter(
558
						$media,
559 View Code Duplication
						function ( $single ) {
560
							if ( 0 === strpos( $single['type'], 'video/' ) || 'image/gif' === $single['type'] ) {
561
								return false;
562
							}
563
564
							return true;
565
						}
566
					)
567
				);
568
				// We can only add the first four images found to the tweet.
569
				$current_tweet['media'] = array_slice( $filtered_media, 0, 4 );
570
			}
571
572
			self::save_current_tweet( $current_tweet, $block );
573
		}
574
	}
575
576
	/**
577
	 * Check if the block has a tweet that we can attach to the current tweet as a quote, and add it.
578
	 *
579
	 * @param array $block  The block to process.
580
	 */
581
	private static function add_tweet_to_tweets( $block ) {
582
		if ( 0 === strlen( $block['tweet'] ) ) {
583
			return;
584
		}
585
586
		$current_tweet = self::get_current_tweet();
587
588
		// We can only attach a tweet to the previous tweet if the previous tweet
589
		// doesn't already have a tweet quoted.
590
		if ( strlen( $current_tweet['tweet'] ) > 0 ) {
591
			$current_tweet = self::start_new_tweet();
592
		}
593
594
		$current_tweet['tweet'] = $block['tweet'];
595
596
		self::save_current_tweet( $current_tweet, $block );
597
	}
598
599
	/**
600
	 * Check if the block has an embed URL that we can append to the current tweet text.
601
	 *
602
	 * @param array $block  The block to process.
603
	 */
604
	private static function add_embed_to_tweets( $block ) {
605
		if ( 0 === strlen( $block['embed'] ) ) {
606
			return;
607
		}
608
609
		$current_tweet = self::get_current_tweet();
610
611
		$reserved_characters  = count( $current_tweet['media'] ) * self::$characters_per_media;
612
		$reserved_characters += 1 + self::$characters_per_url;
613
614
		// We can only attach an embed to the previous tweet if it doesn't already
615
		// have any URLs in it. Also, we can't attach it if it'll make the tweet too long.
616
		if ( preg_match( '/url-placeholder-\d+-*/', $current_tweet['text'] ) || ! self::is_valid_tweet( $current_tweet['text'], $reserved_characters ) ) {
617
			$current_tweet         = self::start_new_tweet();
618
			$current_tweet['text'] = self::generate_url_placeholder( $block['embed'] );
619
		} else {
620
			$space                  = empty( $current_tweet['text'] ) ? '' : ' ';
621
			$current_tweet['text'] .= $space . 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
							// Check if the boundary is happening on a line break or a space.
970
							if ( "\n" === $line_part_data[ $line_part_byte_boundary - 1 ] ) {
971
								$type = 'line-break';
972
973
								// A line break boundary can actually be multiple consecutive line breaks,
974
								// count them all up so we know how big the annotation needs to be.
975
								$matches = array();
976
								preg_match( '/\n+$/', substr( $line_part_data, 0, $line_part_byte_boundary ), $matches );
977
								$boundary_end    = $boundary_start + 1;
978
								$boundary_start -= strlen( $matches[0] ) - 1;
979
							} else {
980
								$type         = 'normal';
981
								$boundary_end = $boundary_start + 1;
982
							}
983
984
							return array(
985
								'start'     => $boundary_start,
986
								'end'       => $boundary_end,
987
								'container' => $part_name,
988
								'type'      => $type,
989
							);
990
						} else {
991
							$total_bytes_processed += $line_part_bytes;
992
							$characters_processed  += self::utf_16_code_unit_length( $cleaned_line_part_data );
993
							continue;
994
						}
995
					} else {
996
						$total_bytes_processed += strlen( $template_part );
997
					}
998
				}
999
1000
				// Are we breaking at the end of this line?
1001
				if ( $total_bytes_processed + 1 === $offset && $line_count > 1 ) {
1002
					reset( $block_def['content'] );
1003
					$container = key( $block_def['content'] );
1004
					return array(
1005
						'line'      => $line_number,
1006
						'container' => $container,
1007
						'type'      => 'end-of-line',
1008
					);
1009
				}
1010
1011
				// The newline at the end of each line is 1 byte, but we don't need to count empty lines.
1012
				$total_bytes_processed++;
1013
			}
1014
1015
			// We do need to count empty lines in the editor, since they'll be displayed.
1016
			$characters_processed++;
1017
		}
1018
1019
		return false;
1020
	}
1021
1022
	/**
1023
	 * JavaScript uses UTF-16 for encoding strings, which means we need to provide UTF-16
1024
	 * based offsets for the block editor to render tweet boundaries in the correct location.
1025
	 *
1026
	 * UTF-16 is a variable-width character encoding: every code unit is 2 bytes, a single character
1027
	 * can be one or two code units long. Fortunately for us, JavaScript's String.charAt() is based
1028
	 * on the older UCS-2 character encoding, which only counts single code units. PHP's strlen()
1029
	 * counts a code unit as being 2 characters, so once a string is converted to UTF-16, we have
1030
	 * a fast way to determine how long it is in UTF-16 code units.
1031
	 *
1032
	 * @param string $text The natively encoded string to get the length of.
1033
	 * @return int The length of the string in UTF-16 code units. Returns -1 if the length could not
1034
	 *             be calculated.
1035
	 */
1036
	private static function utf_16_code_unit_length( $text ) {
1037
		// If mb_convert_encoding() exists, we can use that for conversion.
1038
		if ( function_exists( 'mb_convert_encoding' ) ) {
1039
			// UTF-16 can add an additional code unit to the start of the string, called the
1040
			// Byte Order Mark (BOM), which indicates whether the string is encoding as
1041
			// big-endian, or little-endian. Since we don't want to count code unit, and the endianness
1042
			// doesn't matter for our purposes, using PHP's UTF-16BE encoding uses big-endian
1043
			// encoding, and ensures the BOM *won't* be prepended to the string to the string.
1044
			return strlen( mb_convert_encoding( $text, 'UTF-16BE' ) ) / 2;
1045
		}
1046
1047
		// If we can't convert this string, return a result that will avoid an incorrect annotation being added.
1048
		return -1;
1049
	}
1050
1051
	/**
1052
	 * Extracts the tweetable text from a block.
1053
	 *
1054
	 * @param array $block A single block, as generated by parse_block().
1055
	 * @return string The tweetable text from the block, in the correct template form.
1056
	 */
1057
	private static function extract_text_from_block( $block ) {
1058
		// If the block doesn't have an innerHTMl, we're not going to get any text.
1059
		if ( empty( $block['innerHTML'] ) ) {
1060
			return '';
1061
		}
1062
1063
		$block_def = self::get_block_definition( $block['blockName'] );
1064
1065
		// We currently only support extracting text from HTML text nodes.
1066
		if ( ! isset( $block_def['content_location'] ) || 'html' !== $block_def['content_location'] ) {
1067
			return '';
1068
		}
1069
1070
		// Find out which tags we need to extract content from.
1071 View Code Duplication
		if ( isset( $block_def['content'] ) && count( $block_def['content'] ) > 0 ) {
1072
			$tags = $block_def['content'];
1073
		} else {
1074
			$tags = array( 'content' );
1075
		}
1076
1077
		$tag_values = self::extract_tag_content_from_html( $tags, $block['innerHTML'] );
1078
1079
		// We can treat single line blocks as "multiline", with only one line in them.
1080
		$lines = array();
1081
		foreach ( $tag_values as $tag => $values ) {
1082
			// For single-line blocks, we need to squash all the values for this tag into a single value.
1083
			if ( 'multiline' !== $block_def['type'] ) {
1084
				$values = array( implode( "\n", $values ) );
1085
			}
1086
1087
			// Handle the special "content" tag.
1088
			if ( 'content' === $tag ) {
1089
				$placeholder = 'content';
1090
			} else {
1091
				$placeholder = array_search( $tag, $block_def['content'], true );
1092
			}
1093
1094
			// Loop over each instance of this value, appling that value to the corresponding line template.
1095
			foreach ( $values as $line_number => $value ) {
1096
				if ( ! isset( $lines[ $line_number ] ) ) {
1097
					$lines[ $line_number ] = $block_def['template'];
1098
				}
1099
1100
				$lines[ $line_number ] = str_replace( '{{' . $placeholder . '}}', $value, $lines[ $line_number ] );
1101
			}
1102
		}
1103
1104
		// Remove any lines that didn't apply any content.
1105
		$empty_template = preg_replace( '/{{.*?}}/', '', $block_def['template'] );
1106
		$lines          = array_filter(
1107
			$lines,
1108
			function ( $line ) use ( $empty_template ) {
1109
				return $line !== $empty_template;
1110
			}
1111
		);
1112
1113
		// Join the lines together into a single string.
1114
		$text = implode( self::$line_separator, $lines );
1115
1116
		// Trim off any trailing whitespace that we no longer need.
1117
		$text = preg_replace( '/(\s|' . self::$line_separator . ')+$/u', '', $text );
1118
1119
		return $text;
1120
	}
1121
1122
	/**
1123
	 * Extracts the tweetable media from a block.
1124
	 *
1125
	 * @param array $block A single block, as generated by parse_block().
1126
	 * @return array {
1127
	 *     An array of media.
1128
	 *
1129
	 *     @type string url The URL of the media.
1130
	 *     @type string alt The alt text of the media.
1131
	 * }
1132
	 */
1133
	private static function extract_media_from_block( $block ) {
1134
		$block_def = self::get_block_definition( $block['blockName'] );
1135
1136
		$media = array();
1137
1138
		if ( 'image' === $block_def['type'] ) {
1139
			$url = self::extract_attr_content_from_html(
1140
				$block_def['content']['url'][0],
1141
				$block_def['content']['url'][1],
1142
				$block['innerHTML']
1143
			);
1144
			$alt = self::extract_attr_content_from_html(
1145
				$block_def['content']['alt'][0],
1146
				$block_def['content']['alt'][1],
1147
				$block['innerHTML']
1148
			);
1149
1150
			$img_count = count( $url );
1151
1152
			for ( $ii = 0; $ii < $img_count; $ii++ ) {
1153
				$filedata = wp_check_filetype( basename( wp_parse_url( $url[ $ii ], PHP_URL_PATH ) ) );
1154
1155
				$media[] = array(
1156
					'url'  => $url[ $ii ],
1157
					'alt'  => self::is_valid_alt_text( $alt[ $ii ] ) ? $alt[ $ii ] : '',
1158
					'type' => $filedata['type'],
1159
				);
1160
			}
1161
		} elseif ( 'video' === $block_def['type'] ) {
1162
			// Handle VideoPress videos.
1163
			if ( isset( $block['attrs']['src'] ) && 0 === strpos( $block['attrs']['src'], 'https://videos.files.wordpress.com/' ) ) {
1164
				$url = array( $block['attrs']['src'] );
1165
			} else {
1166
				$url = self::extract_attr_content_from_html(
1167
					$block_def['content']['url'][0],
1168
					$block_def['content']['url'][1],
1169
					$block['innerHTML']
1170
				);
1171
			}
1172
1173
			// We can only ever use the first video found, no need to go through all of them.
1174
			if ( count( $url ) > 0 ) {
1175
				$filedata = wp_check_filetype( basename( wp_parse_url( $url[0], PHP_URL_PATH ) ) );
1176
1177
				$media[] = array(
1178
					'url'  => $url[0],
1179
					'type' => $filedata['type'],
1180
				);
1181
			}
1182
		}
1183
1184
		return $media;
1185
	}
1186
1187
	/**
1188
	 * Extracts the tweet URL from a Twitter embed block.
1189
	 *
1190
	 * @param array $block A single block, as generated by parse_block().
1191
	 * @return string The tweet URL. Empty string if there is none available.
1192
	 */
1193
	private static function extract_tweet_from_block( $block ) {
1194 View Code Duplication
		if ( 'core/embed' === $block['blockName'] && 'twitter' === $block['attrs']['providerNameSlug'] ) {
1195
			return $block['attrs']['url'];
1196
		}
1197
1198
		return '';
1199
	}
1200
1201
	/**
1202
	 * Extracts URL from an embed block.
1203
	 *
1204
	 * @param array $block A single block, as generated by parse_block().
1205
	 * @return string The URL. Empty string if there is none available.
1206
	 */
1207
	private static function extract_embed_from_block( $block ) {
1208
		$block_def = self::get_block_definition( $block['blockName'] );
1209
1210
		if ( 'embed' !== $block_def['type'] ) {
1211
			return '';
1212
		}
1213
1214
		// Twitter embeds are handled in ::extract_tweet_from_block().
1215 View Code Duplication
		if ( 'core/embed' === $block['blockName'] && 'twitter' === $block['attrs']['providerNameSlug'] ) {
1216
			return '';
1217
		}
1218
1219
		$url = '';
1220
		if ( 'block-attributes' === $block_def['content_location'] ) {
1221
			$url = $block['attrs'][ $block_def['content'][0] ];
1222
		}
1223
1224
		if ( 'jetpack/gif' === $block['blockName'] ) {
1225
			$url = str_replace( '/embed/', '/gifs/', $url );
1226
		}
1227
1228
		return $url;
1229
	}
1230
1231
	/**
1232
	 * There's a bunch of left-over cruft in the tweets array that we don't need to return. Removing
1233
	 * it helps keep the size of the data down.
1234
	 */
1235
	private static function clean_return_tweets() {
1236
		// Before we return, clean out unnecessary cruft from the return data.
1237
		$tweets = array_map(
1238
			function ( $tweet ) {
1239
				// Remove tweets that don't have anything saved in them. eg, if the last block is a
1240
				// header with no text, it'll force a new tweet, but we won't end up putting anything
1241
				// in that tweet.
1242
				if ( ! $tweet['changed'] ) {
1243
					return false;
1244
				}
1245
1246
				// Replace any URL placeholders that appear in the text.
1247
				$tweet['urls'] = array();
1248
				foreach ( self::$urls as $id => $url ) {
1249
					$count = 0;
1250
1251
					$tweet['text'] = str_replace( str_pad( "url-placeholder-$id", self::$characters_per_url, '-' ), $url, $tweet['text'], $count );
1252
1253
					// If we found a URL, keep track of it for the editor.
1254
					if ( $count > 0 ) {
1255
						$tweet['urls'][] = $url;
1256
					}
1257
				}
1258
1259
				// Remove any inline placeholders.
1260
				$tweet['text'] = str_replace( self::$inline_placeholder, '', $tweet['text'] );
1261
1262
				// If the tweet text consists only of whitespace, we can remove all of it.
1263
				if ( preg_match( '/^\s*$/u', $tweet['text'] ) ) {
1264
					$tweet['text'] = '';
1265
				}
1266
1267
				// Remove trailing whitespace from every line.
1268
				$tweet['text'] = preg_replace( '/\p{Z}+$/um', '', $tweet['text'] );
1269
1270
				// Remove all trailing whitespace (including line breaks) from the end of the text.
1271
				$tweet['text'] = rtrim( $tweet['text'] );
1272
1273
				// Remove internal flags.
1274
				unset( $tweet['changed'] );
1275
				unset( $tweet['finished'] );
1276
1277
				// Remove bulky block data.
1278
				if ( ! isset( $tweet['blocks'][0]['attributes'] ) && ! isset( $tweet['blocks'][0]['clientId'] ) ) {
1279
					$tweet['blocks'] = array();
1280
				} else {
1281
					// Remove the parts of the block data that the editor doesn't need.
1282
					$block_count = count( $tweet['blocks'] );
1283
					for ( $ii = 0; $ii < $block_count; $ii++ ) {
1284
						$keys = array_keys( $tweet['blocks'][ $ii ] );
1285
						foreach ( $keys as $key ) {
1286
							// The editor only needs these attributes, everything else will be unset.
1287
							if ( in_array( $key, array( 'attributes', 'clientId' ), true ) ) {
1288
								continue;
1289
							}
1290
1291
							unset( $tweet['blocks'][ $ii ][ $key ] );
1292
						}
1293
					}
1294
				}
1295
1296
				// Once we've finished cleaning up, check if there's anything left to be tweeted.
1297
				if ( empty( $tweet['text'] ) && empty( $tweet['media'] ) && empty( $tweet['tweet'] ) ) {
1298
					return false;
1299
				}
1300
1301
				return $tweet;
1302
			},
1303
			self::$tweets
1304
		);
1305
1306
		// Clean any removed tweets out of the result.
1307
		return array_values( array_filter( $tweets, 'is_array' ) );
1308
	}
1309
1310
	/**
1311
	 * Given a list of tags and a HTML blob, this will extract the text content inside
1312
	 * each of the given tags.
1313
	 *
1314
	 * @param array  $tags An array of tag names.
1315
	 * @param string $html A blob of HTML.
1316
	 * @return array An array of the extract content. The keys in the array are the $tags,
1317
	 *               each value is an array. The value array is indexed in the same order as the tag
1318
	 *               appears in the HTML blob, including nested tags.
1319
	 */
1320
	private static function extract_tag_content_from_html( $tags, $html ) {
1321
		// Serialised blocks will sometimes wrap the innerHTML in newlines, but those newlines
1322
		// are removed when innerHTML is parsed into an attribute. Remove them so we're working
1323
		// with the same information.
1324
		if ( "\n" === $html[0] && "\n" === $html[ strlen( $html ) - 1 ] ) {
1325
			$html = substr( $html, 1, strlen( $html ) - 2 );
1326
		}
1327
1328
		// Normalise <br>.
1329
		$html = preg_replace( '/<br\s*\/?>/', '<br>', $html );
1330
1331
		// If there were no tags passed, assume the entire text is required.
1332
		if ( empty( $tags ) ) {
1333
			$tags = array( 'content' );
1334
		}
1335
1336
		$values = array();
1337
1338
		$tokens = wp_html_split( $html );
1339
1340
		$validator = new Twitter_Validator();
1341
1342
		foreach ( $tags as $tag ) {
1343
			$values[ $tag ] = array();
1344
1345
			// Since tags can be nested, keeping track of the nesting level allows
1346
			// us to extract nested content into a flat array.
1347
			if ( 'content' === $tag ) {
1348
				// The special "content" tag means we should store the entire content,
1349
				// so assume the tag is open from the beginning.
1350
				$opened = 0;
1351
				$closed = -1;
1352
1353
				$values['content'][0] = '';
1354
			} else {
1355
				$opened = -1;
1356
				$closed = -1;
1357
			}
1358
1359
			// When we come across a URL, we need to keep track of it, so it can then be inserted
1360
			// in the right place.
1361
			$current_url = '';
1362
			foreach ( $tokens as $token ) {
1363
				if ( 0 === strlen( $token ) ) {
1364
					// Skip any empty tokens.
1365
					continue;
1366
				}
1367
1368
				// If we're currently storing content, check if it's a text-formatting
1369
				// tag that we should apply.
1370
				if ( $opened !== $closed ) {
1371
					// End of a paragraph, put in some newlines (as long as we're not extracting paragraphs).
1372
					if ( '</p>' === $token && 'p' !== $tag ) {
1373
						$values[ $tag ][ $opened ] .= "\n\n";
1374
					}
1375
1376
					// A line break gets one newline.
1377
					if ( '<br>' === $token ) {
1378
						$values[ $tag ][ $opened ] .= "\n";
1379
					}
1380
1381
					// A link has opened, grab the URL for inserting later.
1382
					if ( 0 === strpos( $token, '<a ' ) ) {
1383
						$href_values = self::extract_attr_content_from_html( 'a', 'href', $token );
1384
						if ( ! empty( $href_values[0] ) && $validator->isValidURL( $href_values[0] ) ) {
1385
							// Remember the URL.
1386
							$current_url = $href_values[0];
1387
						}
1388
					}
1389
1390
					// A link has closed, insert the URL from that link if we have one.
1391
					if ( '</a>' === $token && '' !== $current_url ) {
1392
						// Generate a unique-to-this-block placeholder which takes up the
1393
						// same number of characters as a URL does.
1394
						$values[ $tag ][ $opened ] .= ' (' . self::generate_url_placeholder( $current_url ) . ')';
1395
1396
						$current_url = '';
1397
					}
1398
1399
					// We don't return inline images, but they technically take up 1 character in the RichText.
1400
					if ( 0 === strpos( $token, '<img ' ) ) {
1401
						$values[ $tag ][ $opened ] .= self::$inline_placeholder;
1402
					}
1403
				}
1404
1405
				if ( "<$tag>" === $token || 0 === strpos( $token, "<$tag " ) ) {
1406
					// A tag has just been opened.
1407
					$opened++;
1408
					// Set an empty value now, so we're keeping track of empty tags.
1409
					if ( ! isset( $values[ $tag ][ $opened ] ) ) {
1410
						$values[ $tag ][ $opened ] = '';
1411
					}
1412
					continue;
1413
				}
1414
1415
				if ( "</$tag>" === $token ) {
1416
					// The tag has been closed.
1417
					$closed++;
1418
					continue;
1419
				}
1420
1421
				if ( '<' === $token[0] ) {
1422
					// We can skip any other tags.
1423
					continue;
1424
				}
1425
1426
				if ( $opened !== $closed ) {
1427
					// We're currently in a tag, with some content. Start by decoding any HTML entities.
1428
					$token = html_entity_decode( $token, ENT_QUOTES );
1429
1430
					// Find any URLs in this content, and replace them with a placeholder.
1431
					preg_match_all( Twitter_Regex::getValidUrlMatcher(), $token, $matches, PREG_SET_ORDER | PREG_OFFSET_CAPTURE );
1432
					$offset = 0;
1433
					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...
1434
						list( $url, $start ) = $match[2];
1435
1436
						$token = substr_replace( $token, self::generate_url_placeholder( $url ), $start + $offset, strlen( $url ) );
1437
1438
						$offset += self::$characters_per_url - strlen( $url );
1439
1440
						// If we're in a link with a URL set, there's no need to keep two copies of the same link.
1441
						if ( ! empty( $current_url ) ) {
1442
							$lower_url         = strtolower( $url );
1443
							$lower_current_url = strtolower( $current_url );
1444
1445
							if ( $lower_url === $lower_current_url ) {
1446
								$current_url = '';
1447
							}
1448
1449
							// Check that the link text isn't just a shortened version of the href value.
1450
							$trimmed_current_url = preg_replace( '|^https?://|', '', $lower_current_url );
1451
							if ( $lower_url === $trimmed_current_url || trim( $trimmed_current_url, '/' ) === $lower_url ) {
1452
								$current_url = '';
1453
							}
1454
						}
1455
					}
1456
1457
					// Append it to the right value.
1458
					$values[ $tag ][ $opened ] .= $token;
1459
				}
1460
			}
1461
		}
1462
1463
		return $values;
1464
	}
1465
1466
	/**
1467
	 * Extracts the attribute content from a tag.
1468
	 *
1469
	 * This method allows for the HTML to have multiple instances of the tag, and will return
1470
	 * an array containing the attribute value (or an empty string, if the tag doesn't have the
1471
	 * requested attribute) for each occurrence of the tag.
1472
	 *
1473
	 * @param string $tag          The tag we're looking for.
1474
	 * @param string $attr         The name of the attribute we're looking for.
1475
	 * @param string $html         The HTML we're searching through.
1476
	 * @param array  $attr_filters Optional. Filters tags based on whether or not they have attributes with given values.
1477
	 * @return array The array of attribute values found.
1478
	 */
1479
	private static function extract_attr_content_from_html( $tag, $attr, $html, $attr_filters = array() ) {
1480
		// Given our single tag and attribute, construct a KSES filter for it.
1481
		$kses_filter = array(
1482
			$tag => array(
1483
				$attr => array(),
1484
			),
1485
		);
1486
1487
		foreach ( $attr_filters as $filter_attr => $filter_value ) {
1488
			$kses_filter[ $tag ][ $filter_attr ] = array();
1489
		}
1490
1491
		// Remove all HTML except for the tag we're after. On that tag,
1492
		// remove all attributes except for the one we're after.
1493
		$stripped_html = wp_kses( $html, $kses_filter );
1494
1495
		$values = array();
1496
1497
		$tokens = wp_html_split( $stripped_html );
1498
		foreach ( $tokens as $token ) {
1499
			$found_value = '';
1500
1501
			if ( 0 === strlen( $token ) ) {
1502
				// Skip any empty tokens.
1503
				continue;
1504
			}
1505
1506
			if ( '<' !== $token[0] ) {
1507
				// We can skip any non-tag tokens.
1508
				continue;
1509
			}
1510
1511
			$token_attrs = wp_kses_attr_parse( $token );
1512
1513
			// Skip tags that KSES couldn't handle.
1514
			if ( false === $token_attrs ) {
1515
				continue;
1516
			}
1517
1518
			// Remove the tag open and close chunks.
1519
			$found_tag = array_shift( $token_attrs );
1520
			array_pop( $token_attrs );
1521
1522
			// We somehow got a tag that isn't the one we're after. Skip it.
1523
			if ( 0 !== strpos( $found_tag, "<$tag " ) ) {
1524
				continue;
1525
			}
1526
1527
			// We can only fail an attribute filter if one is set.
1528
			$passed_filter = count( $attr_filters ) === 0;
1529
1530
			foreach ( $token_attrs as $token_attr_string ) {
1531
				// The first "=" in the string will be between the attribute name/value.
1532
				list( $token_attr_name, $token_attr_value ) = explode( '=', $token_attr_string, 2 );
1533
1534
				$token_attr_name  = trim( $token_attr_name );
1535
				$token_attr_value = trim( $token_attr_value );
1536
1537
				// Remove a single set of quotes from around the value.
1538
				if ( '' !== $token_attr_value && in_array( $token_attr_value[0], array( '"', "'" ), true ) ) {
1539
					$token_attr_value = trim( $token_attr_value, $token_attr_value[0] );
1540
				}
1541
1542
				// If this is the attribute we're after, save the value for the end of the loop.
1543
				if ( $token_attr_name === $attr ) {
1544
					$found_value = $token_attr_value;
1545
				}
1546
1547
				if ( isset( $attr_filters[ $token_attr_name ] ) && $attr_filters[ $token_attr_name ] === $token_attr_value ) {
1548
					$passed_filter = true;
1549
				}
1550
			}
1551
1552
			if ( $passed_filter ) {
1553
				// We always want to append the found value, even if we didn't "find" a matching attribute.
1554
				// An empty string in the return value means that we found the tag, but the attribute was
1555
				// either empty, or not set.
1556
				$values[] = html_entity_decode( $found_value, ENT_QUOTES );
1557
			}
1558
		}
1559
1560
		return $values;
1561
	}
1562
1563
	/**
1564
	 * Generates a placeholder for URLs, using the appropriate number of characters to imitate how
1565
	 * Twitter counts the length of URLs in tweets.
1566
	 *
1567
	 * @param string $url The URL to generate a placeholder for.
1568
	 * @return string The placeholder.
1569
	 */
1570
	public static function generate_url_placeholder( $url ) {
1571
		self::$urls[] = $url;
1572
1573
		return str_pad( 'url-placeholder-' . ( count( self::$urls ) - 1 ), self::$characters_per_url, '-' );
1574
	}
1575
1576
	/**
1577
	 * Retrieves the Twitter card data for a list of URLs.
1578
	 *
1579
	 * @param array $urls The list of URLs to grab Twitter card data for.
1580
	 * @return array The Twitter card data.
1581
	 */
1582
	public static function generate_cards( $urls ) {
1583
		$validator = new Twitter_Validator();
1584
1585
		$requests = array_map(
1586
			function ( $url ) use ( $validator ) {
1587
				if ( $validator->isValidURL( $url ) ) {
1588
					return array(
1589
						'url' => $url,
1590
					);
1591
				}
1592
1593
				return false;
1594
			},
1595
			$urls
1596
		);
1597
1598
		$requests = array_filter( $requests );
1599
1600
		$results = Requests::request_multiple( $requests );
1601
1602
		$card_data = array(
1603
			'creator'     => array(
1604
				'name' => 'twitter:creator',
1605
			),
1606
			'description' => array(
1607
				'name'     => 'twitter:description',
1608
				'property' => 'og:description',
1609
			),
1610
			'image'       => array(
1611
				'name'     => 'twitter:image',
1612
				'property' => 'og:image:secure',
1613
				'property' => 'og:image',
1614
			),
1615
			'title'       => array(
1616
				'name'     => 'twitter:text:title',
1617
				'property' => 'og:title',
1618
			),
1619
			'type'        => array(
1620
				'name' => 'twitter:card',
1621
			),
1622
		);
1623
1624
		$cards = array();
1625
		foreach ( $results as $id => $result ) {
1626
			$url = $requests[ $id ]['url'];
1627
1628
			if ( ! $result->success ) {
1629
				$cards[ $url ] = array(
1630
					'error' => 'invalid_url',
1631
				);
1632
				continue;
1633
			}
1634
1635
			$url_card_data = array();
1636
1637
			foreach ( $card_data as $key => $filters ) {
1638
				foreach ( $filters as $attribute => $value ) {
1639
					$found_data = self::extract_attr_content_from_html( 'meta', 'content', $result->body, array( $attribute => $value ) );
1640
					if ( count( $found_data ) > 0 && strlen( $found_data[0] ) > 0 ) {
1641
						$url_card_data[ $key ] = html_entity_decode( $found_data[0], ENT_QUOTES );
1642
						break;
1643
					}
1644
				}
1645
			}
1646
1647
			if ( count( $url_card_data ) > 0 ) {
1648
				$cards[ $url ] = $url_card_data;
1649
			} else {
1650
				$cards[ $url ] = array(
1651
					'error' => 'no_og_data',
1652
				);
1653
			}
1654
		}
1655
1656
		return $cards;
1657
	}
1658
1659
	/**
1660
	 * Get the WPCOM or self-hosted site ID.
1661
	 *
1662
	 * @return mixed
1663
	 */
1664 View Code Duplication
	public static function get_site_id() {
1665
		$is_wpcom = ( defined( 'IS_WPCOM' ) && IS_WPCOM );
1666
		$site_id  = $is_wpcom ? get_current_blog_id() : Jetpack_Options::get_option( 'id' );
1667
		if ( ! $site_id ) {
1668
			return new WP_Error(
1669
				'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...
1670
				__( 'Sorry, something is wrong with your Jetpack connection.', 'jetpack' ),
1671
				403
1672
			);
1673
		}
1674
		return (int) $site_id;
1675
	}
1676
}
1677