Code Coverage |
||||||||||
Lines |
Functions and Methods |
Classes and Traits |
||||||||
| Total | |
92.86% |
13 / 14 |
|
100.00% |
2 / 2 |
CRAP | n/a |
0 / 0 |
|
| wpcom_wpme_base62_decode | |
100.00% |
5 / 5 |
|
100.00% |
1 / 1 |
2 | |||
| wpcom_wpme_oembed_request_post_id | |
100.00% |
8 / 8 |
|
100.00% |
1 / 1 |
6 | |||
| 1 | <?php |
| 2 | /** |
| 3 | * Lets the site's oEmbed endpoint resolve its own wp.me shortlinks. |
| 4 | * |
| 5 | * Embedding a wp.me shortlink goes through oEmbed discovery, which asks the |
| 6 | * site's endpoint about the wp.me URL itself. Core can't map it to a post. |
| 7 | * |
| 8 | * @package automattic/jetpack-mu-wpcom |
| 9 | */ |
| 10 | |
| 11 | /** |
| 12 | * Decodes a base62 string, as used by wp.me shortlinks. |
| 13 | * |
| 14 | * @param string $str Base62 string. |
| 15 | * @return int The decoded number. |
| 16 | */ |
| 17 | function wpcom_wpme_base62_decode( $str ) { |
| 18 | $digits = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; |
| 19 | $num = 0; |
| 20 | foreach ( str_split( $str ) as $char ) { |
| 21 | $num = $num * 62 + strpos( $digits, $char ); |
| 22 | } |
| 23 | return $num; |
| 24 | } |
| 25 | |
| 26 | /** |
| 27 | * Maps a wp.me shortlink of the current site to the post it points to. |
| 28 | * |
| 29 | * @param int $post_id The post ID resolved by core. |
| 30 | * @param string $url The requested URL. |
| 31 | * @return int The post ID. |
| 32 | */ |
| 33 | function wpcom_wpme_oembed_request_post_id( $post_id, $url ) { |
| 34 | // Capped at 10 characters so the decoded IDs fit in an int. |
| 35 | if ( $post_id || ! preg_match( '#^(?i:https?://wp\.me)/([pPas])([0-9a-zA-Z]{1,10})-([0-9a-zA-Z]{1,10})$#', (string) $url, $matches ) ) { |
| 36 | return $post_id; |
| 37 | } |
| 38 | |
| 39 | if ( wpcom_wpme_base62_decode( $matches[2] ) !== get_wpcom_blog_id() ) { |
| 40 | return $post_id; |
| 41 | } |
| 42 | |
| 43 | if ( 's' === $matches[1] ) { |
| 44 | $post = get_page_by_path( $matches[3], OBJECT, 'post' ); |
| 45 | return $post ? $post->ID : $post_id; |
| 46 | } |
| 47 | |
| 48 | return wpcom_wpme_base62_decode( $matches[3] ); |
| 49 | } |
| 50 | add_filter( 'oembed_request_post_id', 'wpcom_wpme_oembed_request_post_id', 10, 2 ); |