PluginProbe
Jetpack – WP Security, Backup, Speed, & Growth / 14.9
Jetpack – WP Security, Backup, Speed, & Growth v14.9
16.2-beta 12.0.3 12.1.3 12.2.3 12.3.2 12.4.2 12.5.2 12.6.4 12.7.3 12.8.3 12.9.5 13.0.2 13.1.5 13.2.4 13.3.3 13.4.5 13.5.2 13.6.2 13.7.2 13.8.3 13.9.2 14.0.1 14.1.1 14.2.2 14.3.1 All 501 releases
jetpack / functions.opengraph.php

functions.opengraph.php in Jetpack – WP Security, Backup, Speed, & Growth 14.9, at functions.opengraph.php

971 lines 29.5 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php // phpcs:ignore WordPress.Files.FileName.NotHyphenatedLowercase
2 /**
3 * Open Graph Tags
4 *
5 * Add Open Graph tags so that Facebook (and any other service that supports them)
6 * can crawl the site better and we provide a better sharing experience.
7 *
8 * @link https://ogp.me/
9 * @link https://developers.facebook.com/docs/opengraph/
10 *
11 * @package automattic/jetpack
12 */
13
14 use Automattic\Block_Scanner;
15 use Automattic\Jetpack\Status\Host;
16
17 add_action( 'wp_head', 'jetpack_og_tags' );
18 add_action( 'web_stories_story_head', 'jetpack_og_tags' );
19
20 // Add a Fediverse Open Graph Tag when an author has connected their Mastodon account.
21 add_filter( 'jetpack_open_graph_tags', 'jetpack_add_fediverse_creator_open_graph_tag', 10, 1 );
22 add_filter( 'jetpack_open_graph_output', 'jetpack_filter_fediverse_cards_output', 10, 1 );
23
24 /**
25 * Outputs Open Graph tags generated by Jetpack.
26 */
27 function jetpack_og_tags() {
28 global $post;
29 $data = $post; // so that we don't accidentally explode the global.
30
31 $is_amp_response = ( class_exists( 'Jetpack_AMP_Support' ) && Jetpack_AMP_Support::is_amp_request() );
32
33 // Disable the widont filter on WP.com to avoid stray &nbsps.
34 $disable_widont = remove_filter( 'the_title', 'widont' );
35
36 $og_output = "\n";
37 if ( ! $is_amp_response ) { // Because AMP optimizes the order or the nodes in the head.
38 $og_output .= "<!-- Jetpack Open Graph Tags -->\n";
39 }
40 $tags = array();
41
42 /**
43 * Filter the minimum width of the images used in Jetpack Open Graph Meta Tags.
44 *
45 * @module sharedaddy, publicize
46 *
47 * @since 2.0.0
48 *
49 * @param int 200 Minimum image width used in Jetpack Open Graph Meta Tags.
50 */
51 $image_width = absint( apply_filters( 'jetpack_open_graph_image_width', 200 ) );
52 /**
53 * Filter the minimum height of the images used in Jetpack Open Graph Meta Tags.
54 *
55 * @module sharedaddy, publicize
56 *
57 * @since 2.0.0
58 *
59 * @param int 200 Minimum image height used in Jetpack Open Graph Meta Tags.
60 */
61 $image_height = absint( apply_filters( 'jetpack_open_graph_image_height', 200 ) );
62 $description_length = 197;
63
64 if ( is_home() || is_front_page() ) {
65 $site_type = Jetpack_Options::get_option_and_ensure_autoload( 'open_graph_protocol_site_type', '' );
66 $tags['og:type'] = ! empty( $site_type ) ? $site_type : 'website';
67 $tags['og:title'] = get_bloginfo( 'name' );
68 $tags['og:description'] = get_bloginfo( 'description' );
69
70 $front_page_id = get_option( 'page_for_posts' );
71 if ( 'page' === get_option( 'show_on_front' ) && $front_page_id && is_home() ) {
72 $tags['og:url'] = get_permalink( $front_page_id );
73 } else {
74 $tags['og:url'] = home_url( '/' );
75 }
76
77 // Associate a blog's root path with one or more Facebook accounts.
78 $facebook_admins = Jetpack_Options::get_option_and_ensure_autoload( 'facebook_admins', array() );
79 if ( ! empty( $facebook_admins ) ) {
80 $tags['fb:admins'] = $facebook_admins;
81 }
82 } elseif ( is_author() ) {
83 $tags['og:type'] = 'profile';
84
85 $author = get_queried_object();
86
87 if ( is_a( $author, 'WP_User' ) ) {
88 $tags['og:title'] = $author->display_name;
89 if ( ! empty( $author->user_url ) ) {
90 $tags['og:url'] = $author->user_url;
91 } else {
92 $tags['og:url'] = get_author_posts_url( $author->ID );
93 }
94 $tags['og:description'] = $author->description;
95 $tags['profile:first_name'] = get_the_author_meta( 'first_name', $author->ID );
96 $tags['profile:last_name'] = get_the_author_meta( 'last_name', $author->ID );
97 }
98 } elseif ( is_archive() ) {
99 $tags['og:type'] = 'website';
100 $tags['og:title'] = wp_get_document_title();
101
102 $archive = get_queried_object();
103 if ( $archive instanceof WP_Term ) {
104 $tags['og:url'] = get_term_link( $archive->term_id, $archive->taxonomy );
105 $tags['og:description'] = $archive->description;
106 } elseif ( ! empty( $archive ) && is_post_type_archive() ) {
107 $tags['og:url'] = get_post_type_archive_link( $archive->name );
108 $tags['og:description'] = $archive->description;
109 }
110 } elseif ( is_singular() && is_a( $data, 'WP_Post' ) ) {
111 $tags['og:type'] = 'article';
112 if ( empty( $data->post_title ) ) {
113 $tags['og:title'] = ' ';
114 } else {
115 /** This filter is documented in core/src/wp-includes/post-template.php */
116 $tags['og:title'] = wp_kses( apply_filters( 'the_title', $data->post_title, $data->ID ), array() );
117 }
118
119 $tags['og:url'] = get_permalink( $data->ID );
120 if ( ! post_password_required() ) {
121 /*
122 * If the post author set an excerpt, use that.
123 * Otherwise, pick the post content that comes before the More tag if there is one.
124 * Do not use the post content if it contains premium content.
125 */
126 if ( ! empty( $data->post_excerpt ) ) {
127 $tags['og:description'] = jetpack_og_get_description( $data->post_excerpt );
128 } elseif ( ! has_block( 'premium-content/container', $data->post_content ) ) {
129 $excerpt = explode( '<!--more-->', $data->post_content )[0];
130 $tags['og:description'] = jetpack_og_get_description( $excerpt );
131 }
132 }
133
134 $tags['article:published_time'] = gmdate( 'c', strtotime( $data->post_date_gmt ) );
135 $tags['article:modified_time'] = gmdate( 'c', strtotime( $data->post_modified_gmt ) );
136 if ( post_type_supports( get_post_type( $data ), 'author' ) && isset( $data->post_author ) ) {
137 $publicize_facebook_user = get_post_meta( $data->ID, '_publicize_facebook_user', true );
138 if ( ! empty( $publicize_facebook_user ) ) {
139 $tags['article:author'] = esc_url( $publicize_facebook_user );
140 }
141 }
142 } elseif ( is_search() ) {
143 if ( '' !== get_query_var( 's', '' ) ) {
144 $tags['og:title'] = wp_get_document_title();
145 }
146 }
147 /**
148 * Allow plugins to inject additional template-specific Open Graph tags.
149 *
150 * @module sharedaddy, publicize
151 *
152 * @since 3.0.0
153 *
154 * @param array $tags Array of Open Graph Meta tags.
155 * @param array $args Array of image size parameters.
156 */
157 $tags = apply_filters( 'jetpack_open_graph_base_tags', $tags, compact( 'image_width', 'image_height' ) );
158
159 // Re-enable widont if we had disabled it.
160 if ( $disable_widont ) {
161 add_filter( 'the_title', 'widont' );
162 }
163
164 /**
165 * Do not return any Open Graph Meta tags if we don't have any info about a post.
166 *
167 * @module sharedaddy, publicize
168 *
169 * @since 3.0.0
170 *
171 * @param bool true Do not return any Open Graph Meta tags if we don't have any info about a post.
172 */
173 if ( empty( $tags ) && apply_filters( 'jetpack_open_graph_return_if_empty', true ) ) {
174 return;
175 }
176
177 $tags['og:site_name'] = get_bloginfo( 'name' );
178
179 // Get image info and build tags.
180 if ( ! post_password_required() ) {
181 $image_info = jetpack_og_get_image( $image_width, $image_height );
182 $tags['og:image'] = $image_info['src'];
183
184 if ( ! empty( $image_info['width'] ) ) {
185 $tags['og:image:width'] = (int) $image_info['width'];
186 }
187 if ( ! empty( $image_info['height'] ) ) {
188 $tags['og:image:height'] = (int) $image_info['height'];
189 }
190 // If we have an image, add the alt text even if it's empty.
191 if ( ! empty( $image_info['src'] ) && isset( $image_info['alt_text'] ) ) {
192 $tags['og:image:alt'] = esc_attr( $image_info['alt_text'] );
193 }
194 }
195
196 // Facebook whines if you give it an empty title.
197 if ( empty( $tags['og:title'] ) ) {
198 $tags['og:title'] = __( '(no title)', 'jetpack' );
199 }
200
201 // Shorten the description if it's too long.
202 if ( isset( $tags['og:description'] ) ) {
203 $tags['og:description'] = strlen( $tags['og:description'] ) > $description_length ? mb_substr( $tags['og:description'], 0, $description_length ) . '' : $tags['og:description'];
204 }
205
206 // Try to add OG locale tag if the WP->FB data mapping exists.
207 if ( defined( 'JETPACK__GLOTPRESS_LOCALES_PATH' ) && file_exists( JETPACK__GLOTPRESS_LOCALES_PATH ) ) {
208 require_once JETPACK__GLOTPRESS_LOCALES_PATH;
209 $_locale = get_locale();
210
211 // We have to account for w.org vs WP.com locale divergence.
212 if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) {
213 $gp_locale = GP_Locales::by_field( 'slug', $_locale );
214 } else {
215 $gp_locale = GP_Locales::by_field( 'wp_locale', $_locale );
216 }
217 }
218
219 if ( isset( $gp_locale->facebook_locale ) && ! empty( $gp_locale->facebook_locale ) ) {
220 $tags['og:locale'] = $gp_locale->facebook_locale;
221 }
222
223 /**
224 * Allow the addition of additional Open Graph Meta tags, or modify the existing tags.
225 *
226 * @module sharedaddy, publicize
227 *
228 * @since 2.0.0
229 *
230 * @param array $tags Array of Open Graph Meta tags.
231 * @param array $args Array of image size parameters.
232 */
233 $tags = apply_filters( 'jetpack_open_graph_tags', $tags, compact( 'image_width', 'image_height' ) );
234
235 // secure_urls need to go right after each og:image to work properly so we will abstract them here.
236 $tags['og:image:secure_url'] = ( empty( $tags['og:image:secure_url'] ) ) ? '' : $tags['og:image:secure_url'];
237 $secure = $tags['og:image:secure_url'];
238 unset( $tags['og:image:secure_url'] );
239 $secure_image_num = 0;
240
241 $allowed_empty_tags = array(
242 'og:image:alt',
243 );
244
245 foreach ( (array) $tags as $tag_property => $tag_content ) {
246 // to accommodate multiple images.
247 $tag_content = (array) $tag_content;
248 $tag_content = array_unique( array_filter( $tag_content, 'is_scalar' ) );
249
250 foreach ( $tag_content as $tag_content_single ) {
251 if ( empty( $tag_content_single ) && ! in_array( $tag_property, $allowed_empty_tags, true ) ) {
252 continue; // Only allow certain empty tags.
253 }
254
255 switch ( $tag_property ) {
256 case 'og:url':
257 case 'og:image':
258 case 'og:image:url':
259 case 'og:image:secure_url':
260 case 'og:audio':
261 case 'og:audio:url':
262 case 'og:audio:secure_url':
263 case 'og:video':
264 case 'og:video:url':
265 case 'og:video:secure_url':
266 $og_tag = sprintf( '<meta property="%s" content="%s" />', esc_attr( $tag_property ), esc_url( $tag_content_single ) );
267 break;
268 default:
269 $og_tag = sprintf( '<meta property="%s" content="%s" />', esc_attr( $tag_property ), esc_attr( $tag_content_single ) );
270 }
271 /**
272 * Filter the HTML Output of each Open Graph Meta tag.
273 *
274 * @module sharedaddy, publicize
275 *
276 * @since 2.0.0
277 *
278 * @param string $og_tag HTML HTML Output of each Open Graph Meta tag.
279 */
280 $og_output .= apply_filters( 'jetpack_open_graph_output', $og_tag );
281 $og_output .= "\n";
282
283 if ( 'og:image' === $tag_property ) {
284 if ( is_array( $secure ) && ! empty( $secure[ $secure_image_num ] ) ) {
285 $og_tag = sprintf( '<meta property="og:image:secure_url" content="%s" />', esc_url( $secure[ $secure_image_num ] ) );
286 /** This filter is documented in functions.opengraph.php */
287 $og_output .= apply_filters( 'jetpack_open_graph_output', $og_tag );
288 $og_output .= "\n";
289 } elseif ( ! is_array( $secure ) && ! empty( $secure ) ) {
290 $og_tag = sprintf( '<meta property="og:image:secure_url" content="%s" />', esc_url( $secure ) );
291 /** This filter is documented in functions.opengraph.php */
292 $og_output .= apply_filters( 'jetpack_open_graph_output', $og_tag );
293 $og_output .= "\n";
294 }
295 ++$secure_image_num;
296 }
297 }
298 }
299
300 if ( ! $is_amp_response ) { // Because AMP optimizes the order or the nodes in the head.
301 $og_output .= "\n<!-- End Jetpack Open Graph Tags -->";
302 }
303 $og_output .= "\n";
304 // This is trusted output or added by a filter.
305 echo $og_output; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
306 }
307
308 /**
309 * Returns an image used in social shares.
310 *
311 * @since 2.0.0
312 *
313 * @param int $width Minimum width for the image. Default is 200 based on Facebook's requirement.
314 * @param int $height Minimum height for the image. Default is 200 based on Facebook's requirement.
315 * @param null $deprecated Deprecated.
316 *
317 * @return array The source ('src'), 'width', and 'height' of the image.
318 */
319 function jetpack_og_get_image( $width = 200, $height = 200, $deprecated = null ) {
320 if ( ! empty( $deprecated ) ) {
321 _deprecated_argument( __FUNCTION__, 'jetpack-6.6.0' );
322 }
323 $image = array();
324
325 if ( is_singular() && ! is_home() ) {
326 // Grab obvious image if post is an attachment page for an image.
327 if ( is_attachment( get_the_ID() ) && str_starts_with( get_post_mime_type(), 'image' ) ) {
328 $image['src'] = wp_get_attachment_url( get_the_ID() );
329 $image['alt_text'] = Jetpack_PostImages::get_alt_text( get_the_ID() );
330 }
331
332 // Attempt to find something good for this post using our generalized PostImages code.
333 if ( empty( $image ) && class_exists( 'Jetpack_PostImages' ) ) {
334 $post_image = Jetpack_PostImages::get_image(
335 get_the_ID(),
336 array(
337 'width' => $width,
338 'height' => $height,
339 )
340 );
341 if ( ! empty( $post_image ) && is_array( $post_image ) ) {
342 $image['src'] = $post_image['src'];
343 if ( isset( $post_image['src_width'] ) && isset( $post_image['src_height'] ) ) {
344 $image['width'] = $post_image['src_width'];
345 $image['height'] = $post_image['src_height'];
346 }
347 if ( ! empty( $post_image['alt_text'] ) ) {
348 $image['alt_text'] = $post_image['alt_text'];
349 }
350 }
351 }
352 } elseif ( is_author() ) {
353 $author = get_queried_object();
354 if ( is_a( $author, 'WP_User' ) ) {
355 $image['src'] = get_avatar_url(
356 $author->user_email,
357 array(
358 'size' => $width,
359 )
360 );
361 $image['alt_text'] = $author->display_name;
362 }
363 }
364
365 /*
366 * Generate a fallback social image,
367 * dynamically generated based on the site name,
368 * a representative image of the site,
369 * and a custom template used by our Social Image Generator.
370 */
371 if ( empty( $image ) ) {
372 $site_image = jetpack_og_get_fallback_social_image( $width, $height );
373 if ( ! empty( $site_image ) ) {
374 $image['src'] = $site_image['src'];
375 $image['width'] = $site_image['width'];
376 $image['height'] = $site_image['height'];
377 }
378 }
379
380 // If we didn't get an explicit alt tag from the image, set a default.
381 if ( empty( $image['alt_text'] ) ) {
382 /**
383 * Filter the default Open Graph image alt text, used when the Open Graph image from the post does not have an alt text.
384 *
385 * @since 10.4
386 *
387 * @param string $str Default Open Graph image alt text.
388 */
389 $image['alt_text'] = apply_filters( 'jetpack_open_graph_image_default_alt_text', '' );
390 }
391
392 return $image;
393 }
394
395 /**
396 * Get a fallback social image for the site.
397 *
398 * @since 14.9
399 *
400 * @param int $width The width of the image.
401 * @param int $height The height of the image.
402 *
403 * @return array The source ('src'), 'width', 'height', and source type of the image.
404 */
405 function jetpack_og_get_fallback_social_image( $width, $height ) {
406 // Default template.
407 $template = 'edge';
408
409 // Let's get the site's representative image.
410 $site_image = jetpack_og_get_site_image( $width, $height );
411 if ( empty( $site_image['src'] ) ) {
412 // When using the default blank image, use a different template in Social Image Generator.
413 $template = 'highway';
414 $site_image['src'] = jetpack_og_get_site_fallback_blank_image();
415 }
416
417 /**
418 * Allow filtering the template to use with Social Image Generator.
419 * Available templates: highway, dois, fullscreen, edge.
420 *
421 * @since 14.9
422 *
423 * @param string $template The template to use.
424 */
425 $template = apply_filters( 'jetpack_og_fallback_social_image_template', $template );
426
427 // Let's generate the image.
428 $image = jetpack_og_generate_fallback_social_image( $site_image, $template );
429
430 // Final fallback if everything else fails, the blank image.
431 if ( empty( $image['src'] ) ) {
432 return array(
433 'src' => jetpack_og_get_site_fallback_blank_image(),
434 'width' => $width,
435 'height' => $height,
436 );
437 }
438
439 return $image;
440 }
441
442 /**
443 * Get the site's representative image.
444 *
445 * @since 14.9
446 *
447 * @param int $width The width of the image.
448 * @param int $height The height of the image.
449 *
450 * @return array The source ('src'), 'width', 'height', and source type of the image.
451 */
452 function jetpack_og_get_site_image( $width, $height ) {
453 // First fall back, blavatar.
454 if ( function_exists( 'blavatar_domain' ) ) {
455 $blavatar_domain = blavatar_domain( site_url() );
456 if ( blavatar_exists( $blavatar_domain ) ) {
457 return array(
458 'src' => blavatar_url( $blavatar_domain, 'img', $width, false, true ),
459 'width' => $width,
460 'height' => $height,
461 'type' => 'blavatar',
462 );
463 }
464 }
465
466 // Second fall back, Site Logo.
467 if (
468 function_exists( 'jetpack_has_site_logo' )
469 && jetpack_has_site_logo()
470 ) {
471 $image_id = jetpack_get_site_logo( 'id' );
472 $logo = wp_get_attachment_image_src( $image_id, 'full' );
473 if (
474 isset( $logo[0] ) && isset( $logo[1] ) && isset( $logo[2] )
475 && ( _jetpack_og_get_image_validate_size( $logo[1], $logo[2], $width, $height ) )
476 ) {
477 return array(
478 'src' => $logo[0],
479 'width' => $logo[1],
480 'height' => $logo[2],
481 'type' => 'site_logo',
482 );
483 }
484 }
485
486 // Third fall back, Core's site logo.
487 if ( has_custom_logo() ) {
488 $custom_logo_id = get_theme_mod( 'custom_logo' );
489 $sl_details = wp_get_attachment_image_src(
490 $custom_logo_id,
491 'full'
492 );
493 if (
494 isset( $sl_details[0] ) && isset( $sl_details[1] ) && isset( $sl_details[2] )
495 && ( _jetpack_og_get_image_validate_size( $sl_details[1], $sl_details[2], $width, $height ) )
496 ) {
497 return array(
498 'src' => $sl_details[0],
499 'width' => $sl_details[1],
500 'height' => $sl_details[2],
501 'alt_text' => Jetpack_PostImages::get_alt_text( $custom_logo_id ),
502 );
503 }
504 }
505
506 // Fourth fall back, Core Site Icon, if valid in size.
507 if ( has_site_icon() ) {
508 $image_id = get_option( 'site_icon' );
509 $icon = wp_get_attachment_image_src( $image_id, 'full' );
510 if (
511 isset( $icon[0] ) && isset( $icon[1] ) && isset( $icon[2] )
512 && ( _jetpack_og_get_image_validate_size( $icon[1], $icon[2], $width, $height ) )
513 ) {
514 return array(
515 'src' => $icon[0],
516 'width' => $icon[1],
517 'height' => $icon[2],
518 'type' => 'site_icon',
519 );
520 }
521 }
522
523 return array(
524 'src' => '',
525 'width' => $width,
526 'height' => $height,
527 'type' => 'blank',
528 );
529 }
530
531 /**
532 * Get the site's fallback image.
533 *
534 * @since 14.9
535 *
536 * @return string
537 */
538 function jetpack_og_get_site_fallback_blank_image() {
539 /**
540 * Filter the default Open Graph Image tag, used when no Image can be found in a post.
541 *
542 * @since 3.0.0
543 *
544 * @param string $str Default Image URL.
545 */
546 return apply_filters( 'jetpack_open_graph_image_default', 'https://s0.wp.com/i/blank.jpg' );
547 }
548
549 /**
550 * Get available templates for Social Image Generator.
551 *
552 * @since 14.9
553 *
554 * @return array The available templates.
555 */
556 function jetpack_og_get_available_templates() {
557 if ( ! class_exists( '\Automattic\Jetpack\Publicize\Social_Image_Generator\Templates' ) ) {
558 return array();
559 }
560
561 return \Automattic\Jetpack\Publicize\Social_Image_Generator\Templates::TEMPLATES;
562 }
563
564 /**
565 * Get a social image token from Social Image Generator.
566 *
567 * @since 14.9
568 *
569 * @param string $site_title The site title.
570 * @param string $image_url The image URL.
571 * @param string $template The template to use.
572 *
573 * @return string|WP_Error The social image token, or a WP_Error if the token could not be generated.
574 */
575 function jetpack_og_get_social_image_token( $site_title, $image_url, $template ) {
576 // Let's check if we have a cached token.
577 $cache_key = wp_hash( $site_title . $image_url . $template );
578 $transient_name = 'jetpack_og_social_image_token_' . $cache_key;
579 $cached_token = get_transient( $transient_name );
580
581 if ( ! empty( $cached_token ) ) {
582 return $cached_token;
583 }
584
585 /**
586 * Filter the social image token for testing purposes.
587 *
588 * @since 14.9
589 *
590 * @param string|WP_Error|null $token The token to return, or null to use default behavior.
591 */
592 $token = apply_filters( 'jetpack_og_get_social_image_token', null );
593 if ( null !== $token ) {
594 return $token;
595 }
596
597 if ( ! function_exists( '\Automattic\Jetpack\Publicize\Social_Image_Generator\fetch_token' ) ) {
598 return new WP_Error( 'jetpack_og_get_social_image_token_error', __( 'Social Image Generator is not available.', 'jetpack' ) );
599 }
600
601 $token = \Automattic\Jetpack\Publicize\Social_Image_Generator\fetch_token( $site_title, $image_url, $template );
602
603 // If we have a token, cache it for a day.
604 if ( ! is_wp_error( $token ) ) {
605 set_transient( $transient_name, $token, DAY_IN_SECONDS );
606 }
607
608 return $token;
609 }
610
611 /**
612 * Generate and create a fallback social image.
613 *
614 * @since 14.9
615 *
616 * @param array $representative_image The representative image of the site.
617 * @param string $template The template to use.
618 *
619 * @return array The source ('src'), 'width', and 'height' of the image.
620 */
621 function jetpack_og_generate_fallback_social_image( $representative_image, $template ) {
622 $site_title = get_bloginfo( 'name' );
623 $fallback_image = array(
624 'src' => $representative_image['src'],
625 'width' => $representative_image['width'],
626 'height' => $representative_image['height'],
627 );
628
629 // Ensure that we use a valid template.
630 if (
631 ! in_array(
632 $template,
633 jetpack_og_get_available_templates(),
634 true
635 )
636 ) {
637 $template = 'edge';
638 }
639
640 // Let's generate the token matching the image..
641 $token = jetpack_og_get_social_image_token( $site_title, $representative_image['src'], $template );
642
643 if ( is_wp_error( $token ) ) {
644 return $fallback_image;
645 }
646
647 // Build the image URL and return it.
648 return array(
649 'src' => sprintf(
650 'https://s0.wp.com/_si/?t=%s',
651 $token
652 ),
653 'width' => 1200,
654 'height' => 630,
655 );
656 }
657
658 /**
659 * Validate the width and height against required width and height
660 *
661 * @param int $width Width of the image.
662 * @param int $height Height of the image.
663 * @param int $req_width Required width to pass validation.
664 * @param int $req_height Required height to pass validation.
665 *
666 * @return bool - True if the image passed the required size validation
667 */
668 function _jetpack_og_get_image_validate_size( $width, $height, $req_width, $req_height ) {
669 if ( ! $width || ! $height ) {
670 return false;
671 }
672
673 $valid_width = ( $width >= $req_width );
674 $valid_height = ( $height >= $req_height );
675 $is_image_acceptable = $valid_width && $valid_height;
676
677 return $is_image_acceptable;
678 }
679
680 /**
681 * Gets a gravatar URL of the specified size.
682 *
683 * @param string $email E-mail address to get gravatar for.
684 * @param int $width Size of returned gravatar.
685 * @return array|bool|mixed|string
686 */
687 function jetpack_og_get_image_gravatar( $email, $width ) {
688 return get_avatar_url(
689 $email,
690 array(
691 'size' => $width,
692 )
693 );
694 }
695
696 /**
697 * Clean up text meant to be used as Description Open Graph tag.
698 *
699 * There should be:
700 * - no links
701 * - no shortcodes
702 * - no html tags or their contents
703 * - no content within wp:query blocks
704 * - not too many words.
705 *
706 * @param string $description Text coming from WordPress (autogenerated or manually generated by author).
707 * @param WP_Post|null $data Information about our post.
708 *
709 * @return string $description Cleaned up description string.
710 */
711 function jetpack_og_get_description( $description = '', $data = null ) {
712 // Remove content within wp:query blocks.
713 $description = jetpack_og_remove_query_blocks( $description );
714
715 // Remove tags such as <style or <script.
716 $description = wp_strip_all_tags( $description );
717
718 /*
719 * Clean up any plain text entities left into formatted entities.
720 * Intentionally not using a filter to prevent pollution.
721 * @see https://github.com/Automattic/jetpack/pull/2899#issuecomment-151957382
722 */
723 $description = wp_kses(
724 trim(
725 convert_chars(
726 wptexturize( $description )
727 )
728 ),
729 array()
730 );
731
732 // Remove shortcodes.
733 $description = strip_shortcodes( $description );
734
735 // Remove links.
736 $description = preg_replace(
737 '@https?://[\S]+@',
738 '',
739 $description
740 );
741
742 /*
743 * Limit things to a small text blurb.
744 * There isn't a hard limit set by Facebook, so let's rely on WP's own limit.
745 * (55 words or the localized equivalent).
746 * This limit can be customized with the wp_trim_words filter.
747 */
748 $description = wp_trim_words( $description );
749
750 // Let's set a default if we have no text by now.
751 if ( empty( $description ) ) {
752 /**
753 * Filter the fallback `og:description` used when no excerpt information is provided.
754 *
755 * @module sharedaddy, publicize
756 *
757 * @since 3.9.0
758 *
759 * @param string $var Fallback og:description. Default is translated `Visit the post for more'.
760 * @param object $data Post object for the current post.
761 */
762 $description = apply_filters(
763 'jetpack_open_graph_fallback_description',
764 __( 'Visit the post for more.', 'jetpack' ),
765 $data
766 );
767 }
768
769 return $description;
770 }
771
772 /**
773 * Remove content within wp:query blocks from the description.
774 *
775 * @since 14.9
776 *
777 * @param string $description The description text that may contain block markup.
778 * @return string The description with wp:query blocks removed.
779 */
780 function jetpack_og_remove_query_blocks( $description ) {
781 $output = '';
782 $offset = 0;
783 $depth = 0;
784 $in_query_block = false;
785
786 $scanner = Block_Scanner::create( $description );
787 if ( ! $scanner ) {
788 return $description;
789 }
790
791 while ( $scanner->next_delimiter() ) {
792 $span = $scanner->get_span();
793 $match_at = $span->start;
794 $length = $span->length;
795
796 // Check if this is a query block.
797 if ( $scanner->is_block_type( 'query' ) ) {
798 switch ( $scanner->get_delimiter_type() ) {
799 case Block_Scanner::OPENER:
800 if ( ! $in_query_block ) {
801 // Copy content before the query block.
802 $output .= substr( $description, $offset, $match_at - $offset );
803 $in_query_block = true;
804 }
805 ++$depth;
806 break;
807
808 case Block_Scanner::CLOSER:
809 --$depth;
810 if ( $in_query_block && $depth === 0 ) {
811 // We've exited the query block, continue from after it.
812 $in_query_block = false;
813 $offset = $match_at + $length;
814
815 // Remove extra newline if present
816 if (
817 str_starts_with( substr( $description, $offset ), "\n" )
818 && str_ends_with( $output, "\n" )
819 ) {
820 ++$offset;
821 }
822 }
823 break;
824
825 case Block_Scanner::VOID:
826 // Void query blocks should be removed entirely.
827 if ( ! $in_query_block ) {
828 $output .= substr( $description, $offset, $match_at - $offset );
829 $offset = $match_at + $length;
830 // Remove extra newline if present
831 if (
832 str_starts_with( substr( $description, $offset ), "\n" )
833 && str_ends_with( $output, "\n" )
834 ) {
835 ++$offset;
836 }
837 }
838 break;
839 }
840 } elseif ( ! $in_query_block ) {
841 // Not a query block, copy content including the delimiter if we're not inside a query block.
842 $output .= substr( $description, $offset, $match_at - $offset + $length );
843 $offset = $match_at + $length;
844 }
845 }
846
847 // Add any remaining content after the last delimiter.
848 if ( ! $in_query_block ) {
849 $output .= substr( $description, $offset );
850 }
851
852 return $output;
853 }
854
855 /**
856 * Display a Fediverse actor Open Graph tag when the post author has a Mastodon connection.
857 *
858 * @see https://blog.joinmastodon.org/2024/07/highlighting-journalism-on-mastodon/
859 *
860 * @since 13.8
861 *
862 * @param array $tags Current tags.
863 *
864 * @return array
865 */
866 function jetpack_add_fediverse_creator_open_graph_tag( $tags ) {
867 /*
868 * Let's not do this on WordPress.com Simple for now,
869 * because of its performance impact.
870 * See p1723574138779019/1723572983.803009-slack-C01U2KGS2PQ
871 */
872 if ( ( new Host() )->is_wpcom_simple() ) {
873 return $tags;
874 }
875
876 // Let's not add any tags when the ActivityPub plugin already adds its own.
877 $is_activitypub_opengraph_integration_active = get_option( 'activitypub_use_opengraph' );
878 if ( $is_activitypub_opengraph_integration_active ) {
879 return $tags;
880 }
881
882 // We pull the Mastodon connection data from Publicize.
883 if ( ! function_exists( 'publicize_init' ) ) {
884 return $tags;
885 }
886 $publicize = publicize_init();
887
888 global $post;
889 if (
890 ! is_singular()
891 || ! $post instanceof WP_Post
892 || ! isset( $post->ID )
893 || empty( $post->post_author )
894 ) {
895 return $tags;
896 }
897
898 $post_mastodon_connections = array();
899
900 // Loop through active connections.
901 foreach ( (array) $publicize->get_services( 'connected' ) as $service_name => $connections ) {
902 if ( 'mastodon' !== $service_name ) {
903 continue;
904 }
905
906 // services can have multiple connections. Store them all in our array.
907 foreach ( $connections as $connection ) {
908 $connection_id = $publicize->get_connection_id( $connection );
909 $connection_meta = $publicize->get_connection_meta( $connection );
910
911 $connection_data = $connection_meta['connection_data'] ?? array();
912 $mastodon_handle = $connection_meta['external_display'] ?? '';
913 $connection_user_id = $connection_data['user_id'] ?? 0;
914
915 if ( empty( $mastodon_handle ) ) {
916 continue;
917 }
918
919 // Did we skip this connection for this post?
920 if ( get_post_meta( $post->ID, $publicize->POST_SKIP_PUBLICIZE . $connection_id, true ) ) { // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase
921 continue;
922 }
923
924 $post_mastodon_connections[] = array(
925 'user_id' => (int) $connection_user_id,
926 'connection_id' => (int) $connection_id,
927 'handle' => $mastodon_handle,
928 'global' => 0 === (int) $connection_user_id,
929 );
930 }
931 }
932
933 // If we have no Mastodon connections, skip.
934 if ( empty( $post_mastodon_connections ) ) {
935 return $tags;
936 }
937
938 /*
939 * Select a single Mastodon connection to use.
940 * It should be either the first connection belonging to the post author,
941 * or the first global connection.
942 */
943 foreach ( $post_mastodon_connections as $mastodon_connection ) {
944 if ( (int) $post->post_author === $mastodon_connection['user_id'] ) {
945 $tags['fediverse:creator'] = esc_attr( $mastodon_connection['handle'] );
946 break;
947 }
948
949 if ( $mastodon_connection['global'] ) {
950 $tags['fediverse:creator'] = esc_attr( $mastodon_connection['handle'] );
951 break;
952 }
953 }
954
955 return $tags;
956 }
957
958 /**
959 * Update the markup for the Open Graph tag to match the expected output for Mastodon
960 * (name instead of property).
961 *
962 * @since 13.8
963 *
964 * @param string $og_tag A single OG tag.
965 *
966 * @return string Result of the OG tag.
967 */
968 function jetpack_filter_fediverse_cards_output( $og_tag ) {
969 return ( str_contains( $og_tag, 'fediverse:' ) ) ? preg_replace( '/property="([^"]+)"/', 'name="\1"', $og_tag ) : $og_tag;
970 }
971