Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
62.39% covered (warning)
62.39%
287 / 460
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
73.33% covered (warning)
73.33%
99 / 135
0.00% covered (danger)
0.00%
0 / 1
155.68
jetpack_og_get_image
95.74% covered (success)
95.74%
45 / 47
0.00% covered (danger)
0.00%
0 / 1
18
jetpack_og_get_fallback_social_image
81.25% covered (warning)
81.25%
13 / 16
0.00% covered (danger)
0.00%
0 / 1
7.32
jetpack_og_get_site_image
84.62% covered (warning)
84.62%
44 / 52
0.00% covered (danger)
0.00%
0 / 1
20.31
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
95.12% covered (success)
95.12%
39 / 41
0.00% covered (danger)
0.00%
0 / 1
18
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    if ( ! post_password_required() ) {
272        $image_info       = jetpack_og_get_image( $image_width, $image_height );
273        $tags['og:image'] = $image_info['src'];
274
275        if ( ! empty( $image_info['width'] ) ) {
276            $tags['og:image:width'] = (int) $image_info['width'];
277        }
278        if ( ! empty( $image_info['height'] ) ) {
279            $tags['og:image:height'] = (int) $image_info['height'];
280        }
281        // If we have an image, add the alt text even if it's empty.
282        if ( ! empty( $image_info['src'] ) && isset( $image_info['alt_text'] ) ) {
283            $tags['og:image:alt'] = esc_attr( $image_info['alt_text'] );
284        }
285    }
286
287    // Facebook whines if you give it an empty title.
288    if ( empty( $tags['og:title'] ) ) {
289        $tags['og:title'] = __( '(no title)', 'jetpack' );
290    }
291
292    // Shorten the description if it's too long.
293    if ( isset( $tags['og:description'] ) ) {
294        $tags['og:description'] = strlen( $tags['og:description'] ) > $description_length ? mb_substr( $tags['og:description'], 0, $description_length ) . '…' : $tags['og:description'];
295    }
296
297    // Try to add OG locale tag if the WP->FB data mapping exists.
298    if ( defined( 'JETPACK__GLOTPRESS_LOCALES_PATH' ) && file_exists( JETPACK__GLOTPRESS_LOCALES_PATH ) ) {
299        require_once JETPACK__GLOTPRESS_LOCALES_PATH;
300        $_locale = get_locale();
301
302        // We have to account for w.org vs WP.com locale divergence.
303        if ( defined( 'IS_WPCOM' ) && IS_WPCOM ) {
304            $gp_locale = GP_Locales::by_field( 'slug', $_locale );
305        } else {
306            $gp_locale = GP_Locales::by_field( 'wp_locale', $_locale );
307        }
308    }
309
310    if ( isset( $gp_locale->facebook_locale ) && ! empty( $gp_locale->facebook_locale ) ) {
311        $tags['og:locale'] = $gp_locale->facebook_locale;
312    }
313
314    /**
315     * Allow the addition of additional Open Graph Meta tags, or modify the existing tags.
316     *
317     * @module sharedaddy, publicize
318     *
319     * @since 2.0.0
320     *
321     * @param array $tags Array of Open Graph Meta tags.
322     * @param array $args Array of image size parameters.
323     */
324    $tags = apply_filters( 'jetpack_open_graph_tags', $tags, compact( 'image_width', 'image_height' ) );
325
326    // secure_urls need to go right after each og:image to work properly so we will abstract them here.
327    $tags['og:image:secure_url'] = ( empty( $tags['og:image:secure_url'] ) ) ? '' : $tags['og:image:secure_url'];
328    $secure                      = $tags['og:image:secure_url'];
329    unset( $tags['og:image:secure_url'] );
330    $secure_image_num = 0;
331
332    $allowed_empty_tags = array(
333        'og:image:alt',
334    );
335
336    foreach ( (array) $tags as $tag_property => $tag_content ) {
337        // to accommodate multiple images.
338        $tag_content = (array) $tag_content;
339        $tag_content = array_unique( array_filter( $tag_content, 'is_scalar' ) );
340
341        foreach ( $tag_content as $tag_content_single ) {
342            if ( empty( $tag_content_single ) && ! in_array( $tag_property, $allowed_empty_tags, true ) ) {
343                continue; // Only allow certain empty tags.
344            }
345
346            switch ( $tag_property ) {
347                case 'og:url':
348                case 'og:image':
349                case 'og:image:url':
350                case 'og:image:secure_url':
351                case 'og:audio':
352                case 'og:audio:url':
353                case 'og:audio:secure_url':
354                case 'og:video':
355                case 'og:video:url':
356                case 'og:video:secure_url':
357                    $og_tag = sprintf( '<meta property="%s" content="%s" />', esc_attr( $tag_property ), esc_url( $tag_content_single ) );
358                    break;
359                default:
360                    $og_tag = sprintf( '<meta property="%s" content="%s" />', esc_attr( $tag_property ), esc_attr( $tag_content_single ) );
361            }
362            /**
363             * Filter the HTML Output of each Open Graph Meta tag.
364             *
365             * @module sharedaddy, publicize
366             *
367             * @since 2.0.0
368             *
369             * @param string $og_tag HTML HTML Output of each Open Graph Meta tag.
370             */
371            $og_output .= apply_filters( 'jetpack_open_graph_output', $og_tag );
372            $og_output .= "\n";
373
374            if ( 'og:image' === $tag_property ) {
375                if ( is_array( $secure ) && ! empty( $secure[ $secure_image_num ] ) ) {
376                    $og_tag = sprintf( '<meta property="og:image:secure_url" content="%s" />', esc_url( $secure[ $secure_image_num ] ) );
377                    /** This filter is documented in functions.opengraph.php */
378                    $og_output .= apply_filters( 'jetpack_open_graph_output', $og_tag );
379                    $og_output .= "\n";
380                } elseif ( ! is_array( $secure ) && ! empty( $secure ) ) {
381                    $og_tag = sprintf( '<meta property="og:image:secure_url" content="%s" />', esc_url( $secure ) );
382                    /** This filter is documented in functions.opengraph.php */
383                    $og_output .= apply_filters( 'jetpack_open_graph_output', $og_tag );
384                    $og_output .= "\n";
385                }
386                ++$secure_image_num;
387            }
388        }
389    }
390
391    if ( ! $is_amp_response ) { // Because AMP optimizes the order or the nodes in the head.
392        $og_output .= "\n<!-- End Jetpack Open Graph Tags -->";
393    }
394    $og_output .= "\n";
395    // This is trusted output or added by a filter.
396    echo $og_output; // phpcs:ignore WordPress.Security.EscapeOutput.OutputNotEscaped
397}
398
399/**
400 * Returns an image used in social shares.
401 *
402 * @since 2.0.0
403 *
404 * @param int  $width Minimum width for the image. Default is 200 based on Facebook's requirement.
405 * @param int  $height Minimum height for the image. Default is 200 based on Facebook's requirement.
406 * @param null $deprecated Deprecated.
407 *
408 * @return array The source ('src'), 'width', and 'height' of the image.
409 */
410function jetpack_og_get_image( $width = 200, $height = 200, $deprecated = null ) {
411    if ( ! empty( $deprecated ) ) {
412        _deprecated_argument( __FUNCTION__, 'jetpack-6.6.0' );
413    }
414    $image = array();
415
416    if ( is_singular() && ! is_home() ) {
417        // Grab obvious image if post is an attachment page for an image.
418        if ( is_attachment( get_the_ID() ) && str_starts_with( get_post_mime_type(), 'image' ) ) {
419            $image['src']      = wp_get_attachment_url( get_the_ID() );
420            $image['alt_text'] = Images::get_alt_text( get_the_ID() );
421        }
422
423        // Attempt to find something good for this post using our generalized PostImages code.
424        if ( empty( $image ) ) {
425            $image_args = array(
426                'width'  => $width,
427                'height' => $height,
428            );
429            // Every source but the featured image is parsed out of the body.
430            if ( \Automattic\Jetpack\SEO\Content_Gate::is_gated( get_post( get_the_ID() ) ) ) {
431                $image_args += array(
432                    'from_slideshow'  => false,
433                    'from_gallery'    => false,
434                    'from_attachment' => false,
435                    'from_blocks'     => false,
436                    'from_html'       => false,
437                );
438            }
439            $post_image = Images::get_image( get_the_ID(), $image_args );
440            if ( ! empty( $post_image ) && is_array( $post_image ) ) {
441                $image['src'] = $post_image['src'];
442                if ( isset( $post_image['src_width'] ) && isset( $post_image['src_height'] ) ) {
443                    $image['width']  = $post_image['src_width'];
444                    $image['height'] = $post_image['src_height'];
445                }
446                if ( ! empty( $post_image['alt_text'] ) ) {
447                    $image['alt_text'] = $post_image['alt_text'];
448                }
449            }
450        }
451    } elseif ( is_author() ) {
452        $author = get_queried_object();
453        if ( $author instanceof \WP_User ) {
454            $image['src']          = get_avatar_url(
455                $author->user_email,
456                array(
457                    'size' => $width,
458                )
459            );
460                $image['alt_text'] = $author->display_name;
461        }
462    }
463
464    /*
465     * Generate a fallback social image,
466     * dynamically generated based on the site name,
467     * a representative image of the site,
468     * and a custom template used by our Social Image Generator.
469     */
470    if ( empty( $image ) ) {
471        $site_image = jetpack_og_get_fallback_social_image( $width, $height );
472        if ( ! empty( $site_image ) ) {
473            $image['src']    = $site_image['src'];
474            $image['width']  = $site_image['width'];
475            $image['height'] = $site_image['height'];
476        }
477    }
478
479    // If we didn't get an explicit alt tag from the image, set a default.
480    if ( empty( $image['alt_text'] ) ) {
481        /**
482         * Filter the default Open Graph image alt text, used when the Open Graph image from the post does not have an alt text.
483         *
484         * @since 10.4
485         *
486         * @param string $str Default Open Graph image alt text.
487         */
488        $image['alt_text'] = apply_filters( 'jetpack_open_graph_image_default_alt_text', '' );
489    }
490
491    return $image;
492}
493
494/**
495 * Get a fallback social image for the site.
496 *
497 * @since 14.9
498 *
499 * @param int $width The width of the image.
500 * @param int $height The height of the image.
501 *
502 * @return array The source ('src'), 'width', 'height', and source type of the image.
503 */
504function jetpack_og_get_fallback_social_image( $width, $height ) {
505    // Default template.
506    $template = 'edge';
507
508    // Let's get the site's representative image.
509    $site_image = jetpack_og_get_site_image( $width, $height );
510
511    /**
512     * Define your own site's representative image,
513     * to override any fallback image found by looking through site's logo, site icon, and blavatar.
514     * This will allow you to overwrite the default fallback image generated dynamically.
515     *
516     * @since 15.0
517     *
518     * @param array $site_image Your own site's representative image.
519     * @param array $site_image The site's representative image picked by Jetpack. {
520     *     @type string $src    The source of the image.
521     *     @type int    $width  The width of the image.
522     *     @type int    $height The height of the image.
523     *     @type string $type   The type of the image.
524     * }
525     */
526    $custom_site_image = apply_filters( 'jetpack_og_default_site_image', array(), $site_image );
527    if ( ! empty( $custom_site_image['src'] ) ) {
528        return $custom_site_image;
529    }
530
531    if ( empty( $site_image['src'] ) ) {
532        // When using the default blank image, use a different template in Social Image Generator.
533        $template          = 'highway';
534        $site_image['src'] = jetpack_og_get_site_fallback_blank_image();
535    }
536
537    // Return the site image if we are in offline mode instead of attempting to generate a dynamic one.
538    if ( ( new Status() )->is_offline_mode() ) {
539        return $site_image;
540    }
541
542    /*
543     * Only attempt to generate a dynamic fallback image
544     * if we have a healthy connection to WPCOM.
545     * and if the site has the right plan.
546     */
547    if (
548        ( ( new Host() )->is_wpcom_simple()
549        || ( new Connection_Manager() )->is_connected()
550        )
551        && Current_Plan::supports( 'social-image-generator' )
552    ) {
553        /**
554         * Allow filtering the template to use with Social Image Generator.
555         * Available templates: highway, dois, fullscreen, edge.
556         *
557         * @since 14.9
558         *
559         * @param string $template The template to use.
560         */
561        $template = apply_filters( 'jetpack_og_fallback_social_image_template', $template );
562
563        // Let's generate the image.
564        $site_image = jetpack_og_generate_fallback_social_image( $site_image, $template );
565    }
566
567    return $site_image;
568}
569
570/**
571 * Get the site's representative image.
572 *
573 * @since 14.9
574 *
575 * @param int $width The width of the image.
576 * @param int $height The height of the image.
577 *
578 * @return array The source ('src'), 'width', 'height', and source type of the image.
579 */
580function jetpack_og_get_site_image( $width, $height ) {
581    // First fall back, blavatar.
582    if ( function_exists( 'blavatar_domain' ) ) {
583        $blavatar_domain = blavatar_domain( site_url() );
584        if ( blavatar_exists( $blavatar_domain ) ) {
585            return array(
586                'src'    => blavatar_url( $blavatar_domain, 'img', $width, false, true ),
587                'width'  => $width,
588                'height' => $height,
589                'type'   => 'blavatar',
590            );
591        }
592    }
593
594    // Second fall back, Site Logo.
595    if (
596        function_exists( 'jetpack_has_site_logo' )
597        && jetpack_has_site_logo()
598    ) {
599        $image_id = jetpack_get_site_logo( 'id' );
600        $logo     = wp_get_attachment_image_src( $image_id, 'full' );
601        if (
602            isset( $logo[0] ) && isset( $logo[1] ) && isset( $logo[2] )
603            && ( _jetpack_og_get_image_validate_size( $logo[1], $logo[2], $width, $height ) )
604        ) {
605            return array(
606                'src'    => $logo[0],
607                'width'  => $logo[1],
608                'height' => $logo[2],
609                'type'   => 'site_logo',
610            );
611        }
612    }
613
614    // Third fall back, Core's site logo.
615    if ( has_custom_logo() ) {
616        $custom_logo_id = get_theme_mod( 'custom_logo' );
617        $sl_details     = wp_get_attachment_image_src(
618            $custom_logo_id,
619            'full'
620        );
621        if (
622            isset( $sl_details[0] ) && isset( $sl_details[1] ) && isset( $sl_details[2] )
623            && ( _jetpack_og_get_image_validate_size( $sl_details[1], $sl_details[2], $width, $height ) )
624        ) {
625            return array(
626                'src'      => $sl_details[0],
627                'width'    => $sl_details[1],
628                'height'   => $sl_details[2],
629                'alt_text' => Images::get_alt_text( $custom_logo_id ),
630            );
631        }
632    }
633
634    // Fourth fall back, Core Site Icon, if valid in size.
635    if ( has_site_icon() ) {
636        $image_id = get_option( 'site_icon' );
637        $icon     = wp_get_attachment_image_src( $image_id, 'full' );
638        if (
639            isset( $icon[0] ) && isset( $icon[1] ) && isset( $icon[2] )
640            && ( _jetpack_og_get_image_validate_size( $icon[1], $icon[2], $width, $height ) )
641        ) {
642            return array(
643                'src'    => $icon[0],
644                'width'  => $icon[1],
645                'height' => $icon[2],
646                'type'   => 'site_icon',
647            );
648        }
649    }
650
651    return array(
652        'src'    => '',
653        'width'  => $width,
654        'height' => $height,
655        'type'   => 'blank',
656    );
657}
658
659/**
660 * Get the site's fallback image.
661 *
662 * @since 14.9
663 *
664 * @return string
665 */
666function jetpack_og_get_site_fallback_blank_image() {
667    /**
668     * Filter the default Open Graph Image tag, used when no Image can be found in a post.
669     *
670     * @since 3.0.0
671     *
672     * @param string $str Default Image URL.
673     */
674    return apply_filters( 'jetpack_open_graph_image_default', 'https://s0.wp.com/i/blank.jpg' );
675}
676
677/**
678 * Get available templates for Social Image Generator.
679 *
680 * @since 14.9
681 *
682 * @return array The available templates.
683 */
684function jetpack_og_get_available_templates() {
685    if ( ! class_exists( '\Automattic\Jetpack\Publicize\Social_Image_Generator\Templates' ) ) {
686        return array();
687    }
688
689    return \Automattic\Jetpack\Publicize\Social_Image_Generator\Templates::TEMPLATES;
690}
691
692/**
693 * Get a social image token from Social Image Generator.
694 *
695 * @since 14.9
696 *
697 * @param string $site_title The site title.
698 * @param string $image_url The image URL.
699 * @param string $template The template to use.
700 *
701 * @return string|WP_Error The social image token, or a WP_Error if the token could not be generated.
702 */
703function jetpack_og_get_social_image_token( $site_title, $image_url, $template ) {
704    // Let's check if we have a cached token.
705    $cache_key      = wp_hash( $site_title . $image_url . $template );
706    $transient_name = 'jetpack_og_social_image_token_' . $cache_key;
707    $cached_token   = get_transient( $transient_name );
708
709    if ( ! empty( $cached_token ) ) {
710        return $cached_token;
711    }
712
713    /**
714     * Filter the social image token for testing purposes.
715     *
716     * @since 14.9
717     *
718     * @param string|WP_Error|null $token The token to return, or null to use default behavior.
719     */
720    $token = apply_filters( 'jetpack_og_get_social_image_token', null );
721    if ( null !== $token ) {
722        return $token;
723    }
724
725    if ( ! function_exists( '\Automattic\Jetpack\Publicize\Social_Image_Generator\fetch_token' ) ) {
726        return new WP_Error( 'jetpack_og_get_social_image_token_error', __( 'Social Image Generator is not available.', 'jetpack' ) );
727    }
728
729    $token = \Automattic\Jetpack\Publicize\Social_Image_Generator\fetch_token( $site_title, $image_url, $template );
730
731    /*
732     * We want to cache 2 types of responses:
733     * - Successful responses with a token.
734     * - WP_Error responses that denote a WordPress.com connection issue.
735     */
736    if (
737        ! is_wp_error( $token )
738        || (
739            is_wp_error( $token )
740            && 'invalid_user_permission_publicize' === $token->get_error_code()
741        )
742    ) {
743        set_transient( $transient_name, $token, DAY_IN_SECONDS );
744    }
745
746    return $token;
747}
748
749/**
750 * Generate and create a fallback social image.
751 *
752 * @since 14.9
753 *
754 * @param array  $representative_image The representative image of the site.
755 * @param string $template The template to use.
756 *
757 * @return array The source ('src'), 'width', and 'height' of the image.
758 */
759function jetpack_og_generate_fallback_social_image( $representative_image, $template ) {
760    $site_title     = get_bloginfo( 'name' );
761    $fallback_image = array(
762        'src'    => $representative_image['src'],
763        'width'  => $representative_image['width'],
764        'height' => $representative_image['height'],
765    );
766
767    // Ensure that we use a valid template.
768    if (
769        ! in_array(
770            $template,
771            jetpack_og_get_available_templates(),
772            true
773        )
774    ) {
775        $template = 'edge';
776    }
777
778    // Let's generate the token matching the image..
779    $token = jetpack_og_get_social_image_token( $site_title, $representative_image['src'], $template );
780
781    if ( is_wp_error( $token ) ) {
782        return $fallback_image;
783    }
784
785    // Build the image URL and return it.
786    return array(
787        'src'    => sprintf(
788            'https://s0.wp.com/_si/?t=%s',
789            $token
790        ),
791        'width'  => 1200,
792        'height' => 630,
793    );
794}
795
796/**
797 * Validate the width and height against required width and height
798 *
799 * @param int $width      Width of the image.
800 * @param int $height     Height of the image.
801 * @param int $req_width  Required width to pass validation.
802 * @param int $req_height Required height to pass validation.
803 *
804 * @return bool - True if the image passed the required size validation
805 */
806function _jetpack_og_get_image_validate_size( $width, $height, $req_width, $req_height ) {
807    if ( ! $width || ! $height ) {
808        return false;
809    }
810
811    $valid_width         = ( $width >= $req_width );
812    $valid_height        = ( $height >= $req_height );
813    $is_image_acceptable = $valid_width && $valid_height;
814
815    return $is_image_acceptable;
816}
817
818/**
819 * Gets a gravatar URL of the specified size.
820 *
821 * @param string $email E-mail address to get gravatar for.
822 * @param int    $width Size of returned gravatar.
823 * @return array|bool|mixed|string
824 */
825function jetpack_og_get_image_gravatar( $email, $width ) {
826    return get_avatar_url(
827        $email,
828        array(
829            'size' => $width,
830        )
831    );
832}
833
834/**
835 * Clean up text meant to be used as Description Open Graph tag.
836 *
837 * There should be:
838 * - no links
839 * - no shortcodes
840 * - no html tags or their contents
841 * - no content within wp:query blocks
842 * - not too many words.
843 *
844 * @param string       $description Text coming from WordPress (autogenerated or manually generated by author).
845 * @param WP_Post|null $data        Information about our post.
846 *
847 * @return string $description Cleaned up description string.
848 */
849function jetpack_og_get_description( $description = '', $data = null ) {
850    // Remove content within wp:query blocks.
851    $description = jetpack_og_remove_query_blocks( $description );
852
853    // Remove tags such as <style or <script.
854    $description = wp_strip_all_tags( $description );
855
856    /*
857     * Clean up any plain text entities left into formatted entities.
858     * Intentionally not using a filter to prevent pollution.
859     * @see https://github.com/Automattic/jetpack/pull/2899#issuecomment-151957382
860     */
861    $description = wp_kses(
862        trim(
863            convert_chars(
864                wptexturize( $description )
865            )
866        ),
867        array()
868    );
869
870    // Remove shortcodes.
871    $description = strip_shortcodes( $description );
872
873    // Remove links.
874    $description = preg_replace(
875        '@https?://[\S]+@',
876        '',
877        $description
878    );
879
880    /*
881     * Limit things to a small text blurb.
882     * There isn't a hard limit set by Facebook, so let's rely on WP's own limit.
883     * (55 words or the localized equivalent).
884     * This limit can be customized with the wp_trim_words filter.
885     */
886    $description = wp_trim_words( $description );
887
888    // Let's set a default if we have no text by now.
889    if ( empty( $description ) ) {
890        /**
891         * Filter the fallback `og:description` used when no excerpt information is provided.
892         *
893         * @module sharedaddy, publicize
894         *
895         * @since 3.9.0
896         *
897         * @param string $var  Fallback og:description. Default is translated `Visit the post for more'.
898         * @param object $data Post object for the current post.
899         */
900        $description = apply_filters(
901            'jetpack_open_graph_fallback_description',
902            __( 'Visit the post for more.', 'jetpack' ),
903            $data
904        );
905    }
906
907    return $description;
908}
909
910/**
911 * Remove content within wp:query blocks from the description.
912 *
913 * @since 14.9
914 *
915 * @param string $description The description text that may contain block markup.
916 * @return string The description with wp:query blocks removed.
917 */
918function jetpack_og_remove_query_blocks( $description ) {
919    // Handle non-string input
920    if ( ! is_string( $description ) ) {
921        return '';
922    }
923
924    $output         = '';
925    $offset         = 0;
926    $depth          = 0;
927    $in_query_block = false;
928
929    $scanner = Block_Scanner::create( $description );
930    if ( ! $scanner ) {
931        return $description;
932    }
933
934    while ( $scanner->next_delimiter() ) {
935        $span     = $scanner->get_span();
936        $match_at = $span->start;
937        $length   = $span->length;
938
939        // Check if this is a query block.
940        if ( $scanner->is_block_type( 'query' ) ) {
941            switch ( $scanner->get_delimiter_type() ) {
942                case Block_Scanner::OPENER:
943                    if ( ! $in_query_block ) {
944                        // Copy content before the query block.
945                        $output        .= substr( $description, $offset, $match_at - $offset );
946                        $in_query_block = true;
947                    }
948                    ++$depth;
949                    break;
950
951                case Block_Scanner::CLOSER:
952                    --$depth;
953                    if ( $in_query_block && $depth === 0 ) {
954                        // We've exited the query block, continue from after it.
955                        $in_query_block = false;
956                        $offset         = $match_at + $length;
957
958                        // Remove extra newline if present
959                        if (
960                            str_starts_with( substr( $description, $offset ), "\n" )
961                            && str_ends_with( $output, "\n" )
962                        ) {
963                            ++$offset;
964                        }
965                    }
966                    break;
967
968                case Block_Scanner::VOID:
969                    // Void query blocks should be removed entirely.
970                    if ( ! $in_query_block ) {
971                        $output .= substr( $description, $offset, $match_at - $offset );
972                        $offset  = $match_at + $length;
973                        // Remove extra newline if present
974                        if (
975                            str_starts_with( substr( $description, $offset ), "\n" )
976                            && str_ends_with( $output, "\n" )
977                        ) {
978                            ++$offset;
979                        }
980                    }
981                    break;
982            }
983        } elseif ( ! $in_query_block ) {
984            // Not a query block, copy content including the delimiter if we're not inside a query block.
985            $output .= substr( $description, $offset, $match_at - $offset + $length );
986            $offset  = $match_at + $length;
987        }
988    }
989
990    // Add any remaining content after the last delimiter.
991    if ( ! $in_query_block ) {
992        $output .= substr( $description, $offset );
993    }
994
995    return $output;
996}
997
998/**
999 * Display a Fediverse actor Open Graph tag when the post author has a Mastodon connection.
1000 *
1001 * @see https://blog.joinmastodon.org/2024/07/highlighting-journalism-on-mastodon/
1002 *
1003 * @since 13.8
1004 *
1005 * @param array $tags Current tags.
1006 *
1007 * @return array
1008 */
1009function jetpack_add_fediverse_creator_open_graph_tag( $tags ) {
1010    /*
1011     * Let's not do this on WordPress.com Simple for now,
1012     * because of its performance impact.
1013     * See p1723574138779019/1723572983.803009-slack-C01U2KGS2PQ
1014     */
1015    if ( ( new Host() )->is_wpcom_simple() ) {
1016        return $tags;
1017    }
1018
1019    // Let's not add any tags when the ActivityPub plugin already adds its own.
1020    $is_activitypub_opengraph_integration_active = get_option( 'activitypub_use_opengraph' );
1021    if ( $is_activitypub_opengraph_integration_active ) {
1022        return $tags;
1023    }
1024
1025    // We pull the Mastodon connection data from Publicize.
1026    if ( ! function_exists( 'publicize_init' ) ) {
1027        return $tags;
1028    }
1029    $publicize = publicize_init();
1030
1031    global $post;
1032    if (
1033        ! is_singular()
1034        || ! $post instanceof WP_Post
1035        || ! isset( $post->ID )
1036        || empty( $post->post_author )
1037    ) {
1038        return $tags;
1039    }
1040
1041    $post_mastodon_connections = array();
1042
1043    // Loop through active connections.
1044    foreach ( (array) $publicize->get_services( 'connected' ) as $service_name => $connections ) {
1045        if ( 'mastodon' !== $service_name ) {
1046            continue;
1047        }
1048
1049        // services can have multiple connections. Store them all in our array.
1050        foreach ( $connections as $connection ) {
1051            $connection_id   = $publicize->get_connection_id( $connection );
1052            $connection_meta = $publicize->get_connection_meta( $connection );
1053
1054            $connection_data    = $connection_meta['connection_data'] ?? array();
1055            $mastodon_handle    = $connection_meta['external_display'] ?? '';
1056            $connection_user_id = $connection_data['user_id'] ?? 0;
1057
1058            if ( empty( $mastodon_handle ) ) {
1059                continue;
1060            }
1061
1062            // Did we skip this connection for this post?
1063            if ( get_post_meta( $post->ID, $publicize->POST_SKIP_PUBLICIZE . $connection_id, true ) ) { // phpcs:ignore WordPress.NamingConventions.ValidVariableName.UsedPropertyNotSnakeCase
1064                continue;
1065            }
1066
1067            $post_mastodon_connections[] = array(
1068                'user_id'       => (int) $connection_user_id,
1069                'connection_id' => (int) $connection_id,
1070                'handle'        => $mastodon_handle,
1071                'global'        => 0 === (int) $connection_user_id,
1072            );
1073        }
1074    }
1075
1076    // If we have no Mastodon connections, skip.
1077    if ( empty( $post_mastodon_connections ) ) {
1078        return $tags;
1079    }
1080
1081    /*
1082     * Select a single Mastodon connection to use.
1083     * It should be either the first connection belonging to the post author,
1084     * or the first global connection.
1085     */
1086    foreach ( $post_mastodon_connections as $mastodon_connection ) {
1087        if ( (int) $post->post_author === $mastodon_connection['user_id'] ) {
1088            $tags['fediverse:creator'] = esc_attr( $mastodon_connection['handle'] );
1089            break;
1090        }
1091
1092        if ( $mastodon_connection['global'] ) {
1093            $tags['fediverse:creator'] = esc_attr( $mastodon_connection['handle'] );
1094            break;
1095        }
1096    }
1097
1098    return $tags;
1099}
1100
1101/**
1102 * Update the markup for the Open Graph tag to match the expected output for Mastodon
1103 * (name instead of property).
1104 *
1105 * @since 13.8
1106 *
1107 * @param string $og_tag A single OG tag.
1108 *
1109 * @return string Result of the OG tag.
1110 */
1111function jetpack_filter_fediverse_cards_output( $og_tag ) {
1112    return ( str_contains( $og_tag, 'fediverse:' ) ) ? preg_replace( '/property="([^"]+)"/', 'name="\1"', $og_tag ) : $og_tag;
1113}