1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
require_once( AMP__ROOT__ . '/includes/embeds/class-amp-base-embed-handler.php' ); |
4
|
|
|
|
5
|
|
|
// Much of this class is borrowed from Jetpack embeds |
6
|
|
|
class AMP_Twitter_Embed_Handler extends AMP_Base_Embed_Handler { |
7
|
|
|
const URL_PATTERN = '#http(s|):\/\/twitter\.com(\/\#\!\/|\/)([a-zA-Z0-9_]{1,20})\/status(es)*\/(\d+)#i'; |
8
|
|
|
|
9
|
|
|
private static $script_slug = 'amp-twitter'; |
10
|
|
|
private static $script_src = 'https://cdn.ampproject.org/v0/amp-twitter-0.1.js'; |
11
|
|
|
|
12
|
|
|
public function register_embed() { |
13
|
|
|
add_shortcode( 'tweet', array( $this, 'shortcode' ) ); |
14
|
|
|
wp_embed_register_handler( 'amp-twitter', self::URL_PATTERN, array( $this, 'oembed' ), -1 ); |
15
|
|
|
} |
16
|
|
|
|
17
|
|
|
public function unregister_embed() { |
18
|
|
|
remove_shortcode( 'tweet' ); |
19
|
|
|
wp_embed_unregister_handler( 'amp-twitter', -1 ); |
20
|
|
|
} |
21
|
|
|
|
22
|
|
|
public function get_scripts() { |
23
|
|
|
if ( ! $this->did_convert_elements ) { |
24
|
|
|
return array(); |
25
|
|
|
} |
26
|
|
|
|
27
|
|
|
return array( self::$script_slug => self::$script_src ); |
28
|
|
|
} |
29
|
|
|
|
30
|
|
|
function shortcode( $attr ) { |
31
|
|
|
$attr = wp_parse_args( $attr, array( |
32
|
|
|
'tweet' => false, |
33
|
|
|
) ); |
34
|
|
|
|
35
|
|
View Code Duplication |
if ( empty( $attr['tweet'] ) && ! empty( $attr[0] ) ) { |
36
|
|
|
$attr['tweet'] = $attr[0]; |
37
|
|
|
} |
38
|
|
|
|
39
|
|
|
$id = false; |
40
|
|
|
if ( is_numeric( $attr['tweet'] ) ) { |
41
|
|
|
$id = $attr['tweet']; |
42
|
|
|
} else { |
43
|
|
|
preg_match( self::URL_PATTERN, $attr['tweet'], $matches ); |
44
|
|
View Code Duplication |
if ( isset( $matches[5] ) && is_numeric( $matches[5] ) ) { |
45
|
|
|
$id = $matches[5]; |
46
|
|
|
} |
47
|
|
|
|
48
|
|
|
if ( empty( $id ) ) { |
49
|
|
|
return ''; |
50
|
|
|
} |
51
|
|
|
} |
52
|
|
|
|
53
|
|
|
$this->did_convert_elements = true; |
54
|
|
|
|
55
|
|
|
return AMP_HTML_Utils::build_tag( |
56
|
|
|
'amp-twitter', |
57
|
|
|
array( |
58
|
|
|
'data-tweetid' => $id, |
59
|
|
|
'layout' => 'responsive', |
60
|
|
|
'width' => $this->args['width'], |
61
|
|
|
'height' => $this->args['height'], |
62
|
|
|
) |
63
|
|
|
); |
64
|
|
|
} |
65
|
|
|
|
66
|
|
|
function oembed( $matches, $attr, $url, $rawattr ) { |
67
|
|
|
$id = false; |
68
|
|
|
|
69
|
|
View Code Duplication |
if ( isset( $matches[5] ) && is_numeric( $matches[5] ) ) { |
70
|
|
|
$id = $matches[5]; |
71
|
|
|
} |
72
|
|
|
|
73
|
|
|
if ( ! $id ) { |
74
|
|
|
return ''; |
75
|
|
|
} |
76
|
|
|
|
77
|
|
|
return $this->shortcode( array( 'tweet' => $id ) ); |
78
|
|
|
} |
79
|
|
|
} |
80
|
|
|
|