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