Нема описа

class.json-api-links.php 9.9KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285
  1. <?php
  2. require_once dirname( __FILE__ ) . '/../class.json-api.php';
  3. class WPCOM_JSON_API_Links {
  4. private $api;
  5. private static $instance;
  6. private $closest_endpoint_cache_by_version = array();
  7. private $matches_by_version = array();
  8. private $cache_result = null;
  9. public static function getInstance() {
  10. if ( null === self::$instance ) {
  11. self::$instance = new self();
  12. }
  13. return self::$instance;
  14. }
  15. // protect these methods for singleton
  16. protected function __construct() {
  17. $this->api = WPCOM_JSON_API::init();
  18. }
  19. private function __clone() { }
  20. public function __wakeup() {
  21. die( "Please don't __wakeup WPCOM_JSON_API_Links" );
  22. }
  23. /**
  24. * Generate a URL to an endpoint
  25. *
  26. * Used to construct meta links in API responses
  27. *
  28. * @param mixed ...$args Optional arguments to be appended to URL
  29. * @return string Endpoint URL
  30. **/
  31. function get_link( ...$args ) {
  32. $format = array_shift( $args );
  33. $base = WPCOM_JSON_API__BASE;
  34. $path = array_pop( $args );
  35. if ( $path ) {
  36. $path = '/' . ltrim( $path, '/' );
  37. // tack the path onto the end of the format string
  38. // have to escape %'s in the path as %% because
  39. // we're about to pass it through sprintf and we don't
  40. // want it to see the % as a placeholder
  41. $format .= str_replace( '%', '%%', $path );
  42. }
  43. // Escape any % in args before using sprintf
  44. $escaped_args = array();
  45. foreach ( $args as $arg_key => $arg_value ) {
  46. $escaped_args[ $arg_key ] = str_replace( '%', '%%', $arg_value );
  47. }
  48. $relative_path = vsprintf( $format, $escaped_args );
  49. if ( ! wp_startswith( $relative_path, '.' ) ) {
  50. // Generic version. Match the requested version as best we can
  51. $api_version = $this->get_closest_version_of_endpoint( $format, $relative_path );
  52. $base = substr( $base, 0, - 1 ) . $api_version;
  53. }
  54. // escape any % in the relative path before running it through sprintf again
  55. $relative_path = str_replace( '%', '%%', $relative_path );
  56. // http, WPCOM_JSON_API__BASE, ... , path
  57. // %s , %s , $format, %s
  58. return esc_url_raw( sprintf( "https://%s$relative_path", $base ) );
  59. }
  60. function get_me_link( $path = '' ) {
  61. return $this->get_link( '/me', $path );
  62. }
  63. function get_taxonomy_link( $blog_id, $taxonomy_id, $taxonomy_type, $path = '' ) {
  64. switch ( $taxonomy_type ) {
  65. case 'category':
  66. return $this->get_link( '/sites/%d/categories/slug:%s', $blog_id, $taxonomy_id, $path );
  67. case 'post_tag':
  68. return $this->get_link( '/sites/%d/tags/slug:%s', $blog_id, $taxonomy_id, $path );
  69. default:
  70. return $this->get_link( '/sites/%d/taxonomies/%s/terms/slug:%s', $blog_id, $taxonomy_type, $taxonomy_id, $path );
  71. }
  72. }
  73. function get_media_link( $blog_id, $media_id, $path = '' ) {
  74. return $this->get_link( '/sites/%d/media/%d', $blog_id, $media_id, $path );
  75. }
  76. function get_site_link( $blog_id, $path = '' ) {
  77. return $this->get_link( '/sites/%d', $blog_id, $path );
  78. }
  79. function get_post_link( $blog_id, $post_id, $path = '' ) {
  80. return $this->get_link( '/sites/%d/posts/%d', $blog_id, $post_id, $path );
  81. }
  82. function get_comment_link( $blog_id, $comment_id, $path = '' ) {
  83. return $this->get_link( '/sites/%d/comments/%d', $blog_id, $comment_id, $path );
  84. }
  85. function get_publicize_connection_link( $blog_id, $publicize_connection_id, $path = '' ) {
  86. return $this->get_link( '.1/sites/%d/publicize-connections/%d', $blog_id, $publicize_connection_id, $path );
  87. }
  88. function get_publicize_connections_link( $keyring_token_id, $path = '' ) {
  89. return $this->get_link( '.1/me/publicize-connections/?keyring_connection_ID=%d', $keyring_token_id, $path );
  90. }
  91. function get_keyring_connection_link( $keyring_token_id, $path = '' ) {
  92. return $this->get_link( '.1/me/keyring-connections/%d', $keyring_token_id, $path );
  93. }
  94. function get_external_service_link( $external_service, $path = '' ) {
  95. return $this->get_link( '.1/meta/external-services/%s', $external_service, $path );
  96. }
  97. /**
  98. * Try to find the closest supported version of an endpoint to the current endpoint
  99. *
  100. * For example, if we were looking at the path /animals/panda:
  101. * - if the current endpoint is v1.3 and there is a v1.3 of /animals/%s available, we return 1.3
  102. * - if the current endpoint is v1.3 and there is no v1.3 of /animals/%s known, we fall back to the
  103. * maximum available version of /animals/%s, e.g. 1.1
  104. *
  105. * This method is used in get_link() to construct meta links for API responses.
  106. *
  107. * @param $template_path string The generic endpoint path, e.g. /sites/%s
  108. * @param $path string The current endpoint path, relative to the version, e.g. /sites/12345
  109. * @param $request_method string Request method used to access the endpoint path
  110. * @return string The current version, or otherwise the maximum version available
  111. */
  112. function get_closest_version_of_endpoint( $template_path, $path, $request_method = 'GET' ) {
  113. $closest_endpoint_cache_by_version = & $this->closest_endpoint_cache_by_version;
  114. $closest_endpoint_cache = & $closest_endpoint_cache_by_version[ $this->api->version ];
  115. if ( !$closest_endpoint_cache ) {
  116. $closest_endpoint_cache_by_version[ $this->api->version ] = array();
  117. $closest_endpoint_cache = & $closest_endpoint_cache_by_version[ $this->api->version ];
  118. }
  119. if ( ! isset( $closest_endpoint_cache[ $template_path ] ) ) {
  120. $closest_endpoint_cache[ $template_path ] = array();
  121. } elseif ( isset( $closest_endpoint_cache[ $template_path ][ $request_method ] ) ) {
  122. return $closest_endpoint_cache[ $template_path ][ $request_method ];
  123. }
  124. $path = untrailingslashit( $path );
  125. // /help is a special case - always use the current request version
  126. if ( wp_endswith( $path, '/help' ) ) {
  127. $closest_endpoint_cache[ $template_path ][ $request_method ] = $this->api->version;
  128. return $this->api->version;
  129. }
  130. $matches_by_version = & $this->matches_by_version;
  131. // try to match out of saved matches
  132. if ( ! isset( $matches_by_version[ $this->api->version ] ) ) {
  133. $matches_by_version[ $this->api->version ] = array();
  134. }
  135. foreach ( $matches_by_version[ $this->api->version ] as $match ) {
  136. $regex = $match->regex;
  137. if ( preg_match( "#^$regex\$#", $path ) ) {
  138. $closest_endpoint_cache[ $template_path ][ $request_method ] = $match->version;
  139. return $match->version;
  140. }
  141. }
  142. $endpoint_path_versions = $this->get_endpoint_path_versions();
  143. $last_path_segment = $this->get_last_segment_of_relative_path( $path );
  144. $max_version_found = null;
  145. foreach ( $endpoint_path_versions as $endpoint_last_path_segment => $endpoints ) {
  146. // Does the last part of the path match the path key? (e.g. 'posts')
  147. // If the last part contains a placeholder (e.g. %s), we want to carry on
  148. if ( $last_path_segment != $endpoint_last_path_segment && ! strstr( $endpoint_last_path_segment, '%' ) ) {
  149. continue;
  150. }
  151. foreach ( $endpoints as $endpoint ) {
  152. // Does the request method match?
  153. if ( ! in_array( $request_method, $endpoint['request_methods'] ) ) {
  154. continue;
  155. }
  156. $endpoint_path = untrailingslashit( $endpoint['path'] );
  157. $endpoint_path_regex = str_replace( array( '%s', '%d' ), array( '([^/?&]+)', '(\d+)' ), $endpoint_path );
  158. if ( ! preg_match( "#^$endpoint_path_regex\$#", $path ) ) {
  159. continue;
  160. }
  161. // Make sure the endpoint exists at the same version
  162. if ( version_compare( $this->api->version, $endpoint['min_version'], '>=') &&
  163. version_compare( $this->api->version, $endpoint['max_version'], '<=') ) {
  164. array_push(
  165. $matches_by_version[ $this->api->version ],
  166. (object) array( 'version' => $this->api->version, 'regex' => $endpoint_path_regex )
  167. );
  168. $closest_endpoint_cache[ $template_path ][ $request_method ] = $this->api->version;
  169. return $this->api->version;
  170. }
  171. // If the endpoint doesn't exist at the same version, record the max version we found
  172. if ( empty( $max_version_found ) || version_compare( $max_version_found['version'], $endpoint['max_version'], '<' ) ) {
  173. $max_version_found = array( 'version' => $endpoint['max_version'], 'regex' => $endpoint_path_regex );
  174. }
  175. }
  176. }
  177. // If the endpoint version is less than the requested endpoint version, return the max version found
  178. if ( ! empty( $max_version_found ) ) {
  179. array_push(
  180. $matches_by_version[ $this->api->version ],
  181. (object) $max_version_found
  182. );
  183. $closest_endpoint_cache[ $template_path ][ $request_method ] = $max_version_found['version'];
  184. return $max_version_found['version'];
  185. }
  186. // Otherwise, use the API version of the current request
  187. return $this->api->version;
  188. }
  189. /**
  190. * Get an array of endpoint paths with their associated versions
  191. *
  192. * @return array Array of endpoint paths, min_versions and max_versions, keyed by last segment of path
  193. **/
  194. protected function get_endpoint_path_versions() {
  195. if ( ! empty ( $this->cache_result ) ) {
  196. return $this->cache_result;
  197. }
  198. /*
  199. * Create a map of endpoints and their min/max versions keyed by the last segment of the path (e.g. 'posts')
  200. * This reduces the search space when finding endpoint matches in get_closest_version_of_endpoint()
  201. */
  202. $endpoint_path_versions = array();
  203. foreach ( $this->api->endpoints as $key => $endpoint_objects ) {
  204. // The key contains a serialized path, min_version and max_version
  205. list( $path, $min_version, $max_version ) = unserialize( $key );
  206. // Grab the last component of the relative path to use as the top-level key
  207. $last_path_segment = $this->get_last_segment_of_relative_path( $path );
  208. $endpoint_path_versions[ $last_path_segment ][] = array(
  209. 'path' => $path,
  210. 'min_version' => $min_version,
  211. 'max_version' => $max_version,
  212. 'request_methods' => array_keys( $endpoint_objects )
  213. );
  214. }
  215. $this->cache_result = $endpoint_path_versions;
  216. return $endpoint_path_versions;
  217. }
  218. /**
  219. * Grab the last segment of a relative path
  220. *
  221. * @param string $path Path
  222. * @return string Last path segment
  223. */
  224. protected function get_last_segment_of_relative_path( $path) {
  225. $path_parts = array_filter( explode( '/', $path ) );
  226. if ( empty( $path_parts ) ) {
  227. return null;
  228. }
  229. return end( $path_parts );
  230. }
  231. }