class.json-api-links.php 9.9 KB

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