| 1 |
<?php |
| 2 |
namespace Activitypub; |
| 3 |
|
| 4 |
/** |
| 5 |
* ActivityPub WebFinger Class |
| 6 |
* |
| 7 |
* @author Matthias Pfefferle |
| 8 |
* |
| 9 |
* @see https://webfinger.net/ |
| 10 |
*/ |
| 11 |
class Webfinger { |
| 12 |
/** |
| 13 |
* Returns a users WebFinger "resource" |
| 14 |
* |
| 15 |
* @param int $user_id |
| 16 |
* |
| 17 |
* @return string The user-resource |
| 18 |
*/ |
| 19 |
public static function get_user_resource( $user_id ) { |
| 20 |
// use WebFinger plugin if installed |
| 21 |
if ( \function_exists( '\get_webfinger_resource' ) ) { |
| 22 |
return \get_webfinger_resource( $user_id, false ); |
| 23 |
} |
| 24 |
|
| 25 |
$user = \get_user_by( 'id', $user_id ); |
| 26 |
|
| 27 |
return $user->user_login . '@' . \wp_parse_url( \home_url(), \PHP_URL_HOST ); |
| 28 |
} |
| 29 |
|
| 30 |
public static function resolve( $account ) { |
| 31 |
if ( ! preg_match( '/^@?[^@]+@((?:[a-z0-9-]+\.)+[a-z]+)$/i', $account, $m ) ) { |
| 32 |
return null; |
| 33 |
} |
| 34 |
$url = \add_query_arg( 'resource', 'acct:' . ltrim( $account, '@' ), 'https://' . $m[1] . '/.well-known/webfinger' ); |
| 35 |
if ( ! \wp_http_validate_url( $url ) ) { |
| 36 |
return new \WP_Error( 'invalid_webfinger_url', null, $url ); |
| 37 |
} |
| 38 |
|
| 39 |
// try to access author URL |
| 40 |
$response = \wp_remote_get( |
| 41 |
$url, |
| 42 |
array( |
| 43 |
'headers' => array( 'Accept' => 'application/activity+json' ), |
| 44 |
'redirection' => 0, |
| 45 |
) |
| 46 |
); |
| 47 |
|
| 48 |
if ( \is_wp_error( $response ) ) { |
| 49 |
return new \WP_Error( 'webfinger_url_not_accessible', null, $url ); |
| 50 |
} |
| 51 |
|
| 52 |
$response_code = \wp_remote_retrieve_response_code( $response ); |
| 53 |
|
| 54 |
$body = \wp_remote_retrieve_body( $response ); |
| 55 |
$body = \json_decode( $body, true ); |
| 56 |
|
| 57 |
if ( ! isset( $body['links'] ) ) { |
| 58 |
return new \WP_Error( 'webfinger_url_invalid_response', null, $url ); |
| 59 |
} |
| 60 |
|
| 61 |
foreach ( $body['links'] as $link ) { |
| 62 |
if ( 'self' === $link['rel'] && 'application/activity+json' === $link['type'] ) { |
| 63 |
return $link['href']; |
| 64 |
} |
| 65 |
} |
| 66 |
|
| 67 |
return new \WP_Error( 'webfinger_url_no_activity_pub', null, $body ); |
| 68 |
} |
| 69 |
} |
| 70 |
|