Completed
Push — update/comments-module-amp-com... ( 974d49 )
by
unknown
06:48
created

class.jetpack-twitter-cards.php (4 issues)

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

1
<?php // phpcs:ignore WordPress.Files.FileName.InvalidClassFileName
2
/**
3
 * Jetpack Twitter Card handling.
4
 *
5
 * @package Jetpack.
6
 */
7
8
9
/**
10
 * Twitter Cards
11
 *
12
 * Hooks onto the Open Graph protocol and extends it by adding only the tags
13
 * we need for twitter cards.
14
 *
15
 * @see /wp-content/blog-plugins/open-graph.php
16
 * @see https://dev.twitter.com/cards/overview
17
 */
18
class Jetpack_Twitter_Cards {
19
20
	/**
21
	 * Adds Twitter Card tags.
22
	 *
23
	 * @param array $og_tags Existing OG tags.
24
	 *
25
	 * @return array OG tags inclusive of Twitter Card output.
26
	 */
27
	public static function twitter_cards_tags( $og_tags ) {
28
		global $post;
29
		$post_id = ( $post instanceof WP_Post ) ? $post->ID : null;
30
31
		/**
32
		 * Maximum alt text length.
33
		 *
34
		 * @see https://developer.twitter.com/en/docs/tweets/optimize-with-cards/overview/summary-card-with-large-image.html
35
		 */
36
		$alt_length = 420;
37
38
		if ( post_password_required() ) {
39
			return $og_tags;
40
		}
41
42
		/** This action is documented in class.jetpack.php */
43
		if ( apply_filters( 'jetpack_disable_twitter_cards', false ) ) {
44
			return $og_tags;
45
		}
46
47
		/*
48
		 * These tags apply to any page (home, archives, etc).
49
		 */
50
51
		// If we have information on the author/creator, then include that as well.
52
		if ( ! empty( $post ) && ! empty( $post->post_author ) ) {
53
			/** This action is documented in modules/sharedaddy/sharing-sources.php */
54
			$handle = apply_filters( 'jetpack_sharing_twitter_via', '', $post_id );
0 ignored issues
show
The call to apply_filters() has too many arguments starting with $post_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...
55
			if ( ! empty( $handle ) && ! self::is_default_site_tag( $handle ) ) {
56
				$og_tags['twitter:creator'] = self::sanitize_twitter_user( $handle );
57
			}
58
		}
59
60
		$site_tag = self::site_tag();
61
		/** This action is documented in modules/sharedaddy/sharing-sources.php */
62
		$site_tag = apply_filters( 'jetpack_sharing_twitter_via', $site_tag, ( is_singular() ? $post_id : null ) );
0 ignored issues
show
The call to apply_filters() has too many arguments starting with is_singular() ? $post_id : null.

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...
63
		/** This action is documented in modules/sharedaddy/sharing-sources.php */
64
		$site_tag = apply_filters( 'jetpack_twitter_cards_site_tag', $site_tag, $og_tags );
0 ignored issues
show
The call to apply_filters() has too many arguments starting with $og_tags.

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...
65
		if ( ! empty( $site_tag ) ) {
66
			$og_tags['twitter:site'] = self::sanitize_twitter_user( $site_tag );
67
		}
68
69
		if ( ! is_singular() || ! empty( $og_tags['twitter:card'] ) ) {
70
			/**
71
			 * Filter the default Twitter card image, used when no image can be found in a post.
72
			 *
73
			 * @module sharedaddy, publicize
74
			 *
75
			 * @since 5.9.0
76
			 *
77
			 * @param string $str Default image URL.
78
			 */
79
			$image = apply_filters( 'jetpack_twitter_cards_image_default', '' );
80
			if ( ! empty( $image ) ) {
81
				$og_tags['twitter:image'] = $image;
82
			}
83
84
			return $og_tags;
85
		}
86
87
		$the_title = get_the_title();
88
		if ( ! $the_title ) {
89
			$the_title = get_bloginfo( 'name' );
90
		}
91
		$og_tags['twitter:text:title'] = $the_title;
92
93
		/*
94
		 * The following tags only apply to single pages.
95
		 */
96
97
		$card_type = 'summary';
98
99
		// Try to give priority to featured images.
100
		if ( class_exists( 'Jetpack_PostImages' ) && ! empty( $post_id ) ) {
101
			$post_image = Jetpack_PostImages::get_image(
102
				$post_id,
103
				array(
104
					'width'  => 144,
105
					'height' => 144,
106
				)
107
			);
108
			if ( ! empty( $post_image ) && is_array( $post_image ) ) {
109
				// 4096 is the maximum size for an image per https://developer.twitter.com/en/docs/tweets/optimize-with-cards/overview/summary .
110
				if (
111
					isset( $post_image['src_width'], $post_image['src_height'] )
112
					&& (int) $post_image['src_width'] <= 4096
113
					&& (int) $post_image['src_height'] <= 4096
114
				) {
115
					// 300x157 is the minimum size for a summary_large_image per https://developer.twitter.com/en/docs/tweets/optimize-with-cards/overview/summary-card-with-large-image .
116
					if ( (int) $post_image['src_width'] >= 300 && (int) $post_image['src_height'] >= 157 ) {
117
						$card_type                = 'summary_large_image';
118
						$og_tags['twitter:image'] = esc_url( add_query_arg( 'w', 640, $post_image['src'] ) );
119
					} else {
120
						$og_tags['twitter:image'] = esc_url( add_query_arg( 'w', 144, $post_image['src'] ) );
121
					}
122
123
					// Add the alt tag if we have one.
124
					if ( ! empty( $post_image['alt_text'] ) ) {
125
						// Shorten it if it is too long.
126
						if ( strlen( $post_image['alt_text'] ) > $alt_length ) {
127
							$og_tags['twitter:image:alt'] = esc_attr( mb_substr( $post_image['alt_text'], 0, $alt_length ) . '…' );
128
						} else {
129
							$og_tags['twitter:image:alt'] = esc_attr( $post_image['alt_text'] );
130
						}
131
					}
132
				}
133
			}
134
		}
135
136
		// Only proceed with media analysis if a featured image has not superseded it already.
137
		if ( empty( $og_tags['twitter:image'] ) && empty( $og_tags['twitter:image:src'] ) ) {
138 View Code Duplication
			if ( ! class_exists( 'Jetpack_Media_Summary' ) && defined( 'IS_WPCOM' ) && IS_WPCOM ) {
139
				include WP_CONTENT_DIR . '/lib/class.wpcom-media-summary.php';
140
			}
141
142
			if ( ! class_exists( 'Jetpack_Media_Summary' ) ) {
143
				jetpack_require_lib( 'class.media-summary' );
144
			}
145
146
			// Test again, class should already be auto-loaded in Jetpack.
147
			// If not, skip extra media analysis and stick with a summary card.
148
			if ( class_exists( 'Jetpack_Media_Summary' ) && ! empty( $post_id ) ) {
149
				$extract = Jetpack_Media_Summary::get( $post_id );
150
151
				if ( 'gallery' === $extract['type'] ) {
152
					list( $og_tags, $card_type ) = self::twitter_cards_define_type_based_on_image_count( $og_tags, $extract );
153
				} elseif ( 'video' === $extract['type'] ) {
154
					// Leave as summary, but with large pict of poster frame (we know those comply to Twitter's size requirements).
155
					$card_type                = 'summary_large_image';
156
					$og_tags['twitter:image'] = esc_url( add_query_arg( 'w', 640, $extract['image'] ) );
157
				} else {
158
					list( $og_tags, $card_type ) = self::twitter_cards_define_type_based_on_image_count( $og_tags, $extract );
159
				}
160
			}
161
		}
162
163
		$og_tags['twitter:card'] = $card_type;
164
165
		// Make sure we have a description for Twitter, their validator isn't happy without some content (single space not valid).
166
		if ( ! isset( $og_tags['og:description'] ) || '' === trim( $og_tags['og:description'] ) || __( 'Visit the post for more.', 'jetpack' ) === $og_tags['og:description'] ) { // empty( trim( $og_tags['og:description'] ) ) isn't valid php.
167
			$has_creator = ( ! empty( $og_tags['twitter:creator'] ) && '@wordpressdotcom' !== $og_tags['twitter:creator'] ) ? true : false;
168
			if ( ! empty( $extract ) && 'video' === $extract['type'] ) { // use $extract['type'] since $card_type is 'summary' for video posts.
169
				/* translators: %s is the post author */
170
				$og_tags['twitter:description'] = ( $has_creator ) ? sprintf( __( 'Video post by %s.', 'jetpack' ), $og_tags['twitter:creator'] ) : __( 'Video post.', 'jetpack' );
171
			} else {
172
				/* translators: %s is the post author */
173
				$og_tags['twitter:description'] = ( $has_creator ) ? sprintf( __( 'Post by %s.', 'jetpack' ), $og_tags['twitter:creator'] ) : __( 'Visit the post for more.', 'jetpack' );
174
			}
175
		}
176
177
		if ( empty( $og_tags['twitter:image'] ) && empty( $og_tags['twitter:image:src'] ) ) {
178
			/** This action is documented in class.jetpack-twitter-cards.php */
179
			$image = apply_filters( 'jetpack_twitter_cards_image_default', '' );
180
			if ( ! empty( $image ) ) {
181
				$og_tags['twitter:image'] = $image;
182
			}
183
		}
184
185
		return $og_tags;
186
	}
187
188
	/**
189
	 * Sanitize the Twitter user by normalizing the @.
190
	 *
191
	 * @param string $str Twitter user value.
192
	 *
193
	 * @return string Twitter user value.
194
	 */
195
	public static function sanitize_twitter_user( $str ) {
196
		return '@' . preg_replace( '/^@/', '', $str );
197
	}
198
199
	/**
200
	 * Determines if a site tag is one of the default WP.com/Jetpack ones.
201
	 *
202
	 * @param string $site_tag Site tag.
203
	 *
204
	 * @return bool True if the default site tag is being used.
205
	 */
206
	public static function is_default_site_tag( $site_tag ) {
207
		return in_array( $site_tag, array( '@wordpressdotcom', '@jetpack', 'wordpressdotcom', 'jetpack' ), true );
208
	}
209
210
	/**
211
	 * Give priority to the creator tag if using the default site tag.
212
	 *
213
	 * @param string $site_tag Site tag.
214
	 * @param array  $og_tags OG tags.
215
	 *
216
	 * @return string Site tag.
217
	 */
218
	public static function prioritize_creator_over_default_site( $site_tag, $og_tags = array() ) {
219
		if ( ! empty( $og_tags['twitter:creator'] ) && self::is_default_site_tag( $site_tag ) ) {
220
			return $og_tags['twitter:creator'];
221
		}
222
		return $site_tag;
223
	}
224
225
	/**
226
	 * Define the Twitter Card type based on image count.
227
	 *
228
	 * @param array $og_tags Existing OG tags.
229
	 * @param array $extract Result of the Image Extractor class.
230
	 *
231
	 * @return array
232
	 */
233
	public static function twitter_cards_define_type_based_on_image_count( $og_tags, $extract ) {
234
		$card_type = 'summary';
235
		$img_count = $extract['count']['image'];
236
237
		if ( empty( $img_count ) ) {
238
239
			// No images, use Blavatar as a thumbnail for the summary type.
240
			if ( function_exists( 'blavatar_domain' ) ) {
241
				$blavatar_domain = blavatar_domain( site_url() );
242
				if ( blavatar_exists( $blavatar_domain ) ) {
243
					$og_tags['twitter:image'] = blavatar_url( $blavatar_domain, 'img', 240 );
244
				}
245
			}
246
247
			// Second fall back, Site Logo.
248
			if ( empty( $og_tags['twitter:image'] ) && ( function_exists( 'jetpack_has_site_logo' ) && jetpack_has_site_logo() ) ) {
249
				$og_tags['twitter:image'] = jetpack_get_site_logo( 'url' );
250
			}
251
252
			// Third fall back, Site Icon.
253
			if ( empty( $og_tags['twitter:image'] ) && has_site_icon() ) {
254
				$og_tags['twitter:image'] = get_site_icon_url( '240' );
255
			}
256
257
			// Not falling back on Gravatar, because there's no way to know if we end up with an auto-generated one.
258
259
		} elseif ( $img_count && ( 'image' === $extract['type'] || 'gallery' === $extract['type'] ) ) {
260
			// Test for $extract['type'] to limit to image and gallery, so we don't send a potential fallback image like a Gravatar as a photo post.
261
			$card_type                = 'summary_large_image';
262
			$og_tags['twitter:image'] = esc_url( add_query_arg( 'w', 1400, ( empty( $extract['images'] ) ) ? $extract['image'] : $extract['images'][0]['url'] ) );
263
		}
264
265
		return array( $og_tags, $card_type );
266
	}
267
268
	/**
269
	 * Updates the Twitter Card output.
270
	 *
271
	 * @param string $og_tag A single OG tag.
272
	 *
273
	 * @return string Result of the OG tag.
274
	 */
275
	public static function twitter_cards_output( $og_tag ) {
276
		return ( false !== strpos( $og_tag, 'twitter:' ) ) ? preg_replace( '/property="([^"]+)"/', 'name="\1"', $og_tag ) : $og_tag;
277
	}
278
279
	/**
280
	 * Adds settings section and field.
281
	 */
282
	public static function settings_init() {
283
		add_settings_section( 'jetpack-twitter-cards-settings', 'Twitter Cards', '__return_false', 'sharing' );
284
		add_settings_field(
285
			'jetpack-twitter-cards-site-tag',
286
			__( 'Twitter Site Tag', 'jetpack' ),
287
			array( __CLASS__, 'settings_field' ),
288
			'sharing',
289
			'jetpack-twitter-cards-settings',
290
			array(
291
				'label_for' => 'jetpack-twitter-cards-site-tag',
292
			)
293
		);
294
	}
295
296
	/**
297
	 * Add global sharing options.
298
	 */
299
	public static function sharing_global_options() {
300
		do_settings_fields( 'sharing', 'jetpack-twitter-cards-settings' );
301
	}
302
303
	/**
304
	 * Get the Twitter Via tag.
305
	 *
306
	 * @return string Twitter via tag.
307
	 */
308
	public static function site_tag() {
309
		$site_tag = ( defined( 'IS_WPCOM' ) && IS_WPCOM ) ?
310
			trim( get_option( 'twitter_via' ) ) :
311
			Jetpack_Options::get_option_and_ensure_autoload( 'jetpack-twitter-cards-site-tag', '' );
312
		if ( empty( $site_tag ) ) {
313
			/** This action is documented in modules/sharedaddy/sharing-sources.php */
314
			return apply_filters( 'jetpack_sharing_twitter_via', '', null );
0 ignored issues
show
The call to apply_filters() has too many arguments starting with null.

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...
315
		}
316
		return $site_tag;
317
	}
318
319
	/**
320
	 * Output the settings field.
321
	 */
322
	public static function settings_field() {
323
		wp_nonce_field( 'jetpack-twitter-cards-settings', 'jetpack_twitter_cards_nonce', false );
324
		?>
325
		<input type="text" id="jetpack-twitter-cards-site-tag" class="regular-text" name="jetpack-twitter-cards-site-tag" value="<?php echo esc_attr( get_option( 'jetpack-twitter-cards-site-tag' ) ); ?>" />
326
		<p class="description" style="width: auto;"><?php esc_html_e( 'The Twitter username of the owner of this site\'s domain.', 'jetpack' ); ?></p>
327
		<?php
328
	}
329
330
	/**
331
	 * Validate the settings submission.
332
	 */
333
	public static function settings_validate() {
334
		if ( wp_verify_nonce( $_POST['jetpack_twitter_cards_nonce'], 'jetpack-twitter-cards-settings' ) ) {
335
			update_option( 'jetpack-twitter-cards-site-tag', trim( ltrim( wp_strip_all_tags( $_POST['jetpack-twitter-cards-site-tag'] ), '@' ) ) );
336
		}
337
	}
338
339
	/**
340
	 * Initiates the class.
341
	 */
342
	public static function init() {
343
		add_filter( 'jetpack_open_graph_tags', array( __CLASS__, 'twitter_cards_tags' ) );
344
		add_filter( 'jetpack_open_graph_output', array( __CLASS__, 'twitter_cards_output' ) );
345
		add_filter( 'jetpack_twitter_cards_site_tag', array( __CLASS__, 'site_tag' ), -99 );
346
		add_filter( 'jetpack_twitter_cards_site_tag', array( __CLASS__, 'prioritize_creator_over_default_site' ), 99, 2 );
347
		add_action( 'admin_init', array( __CLASS__, 'settings_init' ) );
348
		add_action( 'sharing_global_options', array( __CLASS__, 'sharing_global_options' ) );
349
		add_action( 'sharing_admin_update', array( __CLASS__, 'settings_validate' ) );
350
	}
351
}
352
353
Jetpack_Twitter_Cards::init();
354