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