BitBucketApi.php 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272
  1. <?php
  2. namespace YahnisElsts\PluginUpdateChecker\v5p1\Vcs;
  3. use YahnisElsts\PluginUpdateChecker\v5p1\OAuthSignature;
  4. use YahnisElsts\PluginUpdateChecker\v5p1\Utils;
  5. if ( !class_exists(BitBucketApi::class, false) ):
  6. class BitBucketApi extends Api {
  7. /**
  8. * @var OAuthSignature
  9. */
  10. private $oauth = null;
  11. /**
  12. * @var string
  13. */
  14. private $username;
  15. /**
  16. * @var string
  17. */
  18. private $repository;
  19. public function __construct($repositoryUrl, $credentials = array()) {
  20. $path = wp_parse_url($repositoryUrl, PHP_URL_PATH);
  21. if ( preg_match('@^/?(?P<username>[^/]+?)/(?P<repository>[^/#?&]+?)/?$@', $path, $matches) ) {
  22. $this->username = $matches['username'];
  23. $this->repository = $matches['repository'];
  24. } else {
  25. throw new \InvalidArgumentException('Invalid BitBucket repository URL: "' . $repositoryUrl . '"');
  26. }
  27. parent::__construct($repositoryUrl, $credentials);
  28. }
  29. protected function getUpdateDetectionStrategies($configBranch) {
  30. $strategies = array(
  31. self::STRATEGY_STABLE_TAG => function () use ($configBranch) {
  32. return $this->getStableTag($configBranch);
  33. },
  34. );
  35. if ( ($configBranch === 'master' || $configBranch === 'main') ) {
  36. $strategies[self::STRATEGY_LATEST_TAG] = array($this, 'getLatestTag');
  37. }
  38. $strategies[self::STRATEGY_BRANCH] = function () use ($configBranch) {
  39. return $this->getBranch($configBranch);
  40. };
  41. return $strategies;
  42. }
  43. public function getBranch($branchName) {
  44. $branch = $this->api('/refs/branches/' . $branchName);
  45. if ( is_wp_error($branch) || empty($branch) ) {
  46. return null;
  47. }
  48. //The "/src/{stuff}/{path}" endpoint doesn't seem to handle branch names that contain slashes.
  49. //If we don't encode the slash, we get a 404. If we encode it as "%2F", we get a 401.
  50. //To avoid issues, if the branch name is not URL-safe, let's use the commit hash instead.
  51. $ref = $branch->name;
  52. if ((urlencode($ref) !== $ref) && isset($branch->target->hash)) {
  53. $ref = $branch->target->hash;
  54. }
  55. return new Reference(array(
  56. 'name' => $ref,
  57. 'updated' => $branch->target->date,
  58. 'downloadUrl' => $this->getDownloadUrl($branch->name),
  59. ));
  60. }
  61. /**
  62. * Get a specific tag.
  63. *
  64. * @param string $tagName
  65. * @return Reference|null
  66. */
  67. public function getTag($tagName) {
  68. $tag = $this->api('/refs/tags/' . $tagName);
  69. if ( is_wp_error($tag) || empty($tag) ) {
  70. return null;
  71. }
  72. return new Reference(array(
  73. 'name' => $tag->name,
  74. 'version' => ltrim($tag->name, 'v'),
  75. 'updated' => $tag->target->date,
  76. 'downloadUrl' => $this->getDownloadUrl($tag->name),
  77. ));
  78. }
  79. /**
  80. * Get the tag that looks like the highest version number.
  81. *
  82. * @return Reference|null
  83. */
  84. public function getLatestTag() {
  85. $tags = $this->api('/refs/tags?sort=-target.date');
  86. if ( !isset($tags, $tags->values) || !is_array($tags->values) ) {
  87. return null;
  88. }
  89. //Filter and sort the list of tags.
  90. $versionTags = $this->sortTagsByVersion($tags->values);
  91. //Return the first result.
  92. if ( !empty($versionTags) ) {
  93. $tag = $versionTags[0];
  94. return new Reference(array(
  95. 'name' => $tag->name,
  96. 'version' => ltrim($tag->name, 'v'),
  97. 'updated' => $tag->target->date,
  98. 'downloadUrl' => $this->getDownloadUrl($tag->name),
  99. ));
  100. }
  101. return null;
  102. }
  103. /**
  104. * Get the tag/ref specified by the "Stable tag" header in the readme.txt of a given branch.
  105. *
  106. * @param string $branch
  107. * @return null|Reference
  108. */
  109. protected function getStableTag($branch) {
  110. $remoteReadme = $this->getRemoteReadme($branch);
  111. if ( !empty($remoteReadme['stable_tag']) ) {
  112. $tag = $remoteReadme['stable_tag'];
  113. //You can explicitly opt out of using tags by setting "Stable tag" to
  114. //"trunk" or the name of the current branch.
  115. if ( ($tag === $branch) || ($tag === 'trunk') ) {
  116. return $this->getBranch($branch);
  117. }
  118. return $this->getTag($tag);
  119. }
  120. return null;
  121. }
  122. /**
  123. * @param string $ref
  124. * @return string
  125. */
  126. protected function getDownloadUrl($ref) {
  127. return sprintf(
  128. 'https://bitbucket.org/%s/%s/get/%s.zip',
  129. $this->username,
  130. $this->repository,
  131. $ref
  132. );
  133. }
  134. /**
  135. * Get the contents of a file from a specific branch or tag.
  136. *
  137. * @param string $path File name.
  138. * @param string $ref
  139. * @return null|string Either the contents of the file, or null if the file doesn't exist or there's an error.
  140. */
  141. public function getRemoteFile($path, $ref = 'master') {
  142. $response = $this->api('src/' . $ref . '/' . ltrim($path));
  143. if ( is_wp_error($response) || !is_string($response) ) {
  144. return null;
  145. }
  146. return $response;
  147. }
  148. /**
  149. * Get the timestamp of the latest commit that changed the specified branch or tag.
  150. *
  151. * @param string $ref Reference name (e.g. branch or tag).
  152. * @return string|null
  153. */
  154. public function getLatestCommitTime($ref) {
  155. $response = $this->api('commits/' . $ref);
  156. if ( isset($response->values, $response->values[0], $response->values[0]->date) ) {
  157. return $response->values[0]->date;
  158. }
  159. return null;
  160. }
  161. /**
  162. * Perform a BitBucket API 2.0 request.
  163. *
  164. * @param string $url
  165. * @param string $version
  166. * @return mixed|\WP_Error
  167. */
  168. public function api($url, $version = '2.0') {
  169. $url = ltrim($url, '/');
  170. $isSrcResource = Utils::startsWith($url, 'src/');
  171. $url = implode('/', array(
  172. 'https://api.bitbucket.org',
  173. $version,
  174. 'repositories',
  175. $this->username,
  176. $this->repository,
  177. $url
  178. ));
  179. $baseUrl = $url;
  180. if ( $this->oauth ) {
  181. $url = $this->oauth->sign($url,'GET');
  182. }
  183. $options = array('timeout' => wp_doing_cron() ? 10 : 3);
  184. if ( !empty($this->httpFilterName) ) {
  185. $options = apply_filters($this->httpFilterName, $options);
  186. }
  187. $response = wp_remote_get($url, $options);
  188. if ( is_wp_error($response) ) {
  189. do_action('puc_api_error', $response, null, $url, $this->slug);
  190. return $response;
  191. }
  192. $code = wp_remote_retrieve_response_code($response);
  193. $body = wp_remote_retrieve_body($response);
  194. if ( $code === 200 ) {
  195. if ( $isSrcResource ) {
  196. //Most responses are JSON-encoded, but src resources just
  197. //return raw file contents.
  198. $document = $body;
  199. } else {
  200. $document = json_decode($body);
  201. }
  202. return $document;
  203. }
  204. $error = new \WP_Error(
  205. 'puc-bitbucket-http-error',
  206. sprintf('BitBucket API error. Base URL: "%s", HTTP status code: %d.', $baseUrl, $code)
  207. );
  208. do_action('puc_api_error', $error, $response, $url, $this->slug);
  209. return $error;
  210. }
  211. /**
  212. * @param array $credentials
  213. */
  214. public function setAuthentication($credentials) {
  215. parent::setAuthentication($credentials);
  216. if ( !empty($credentials) && !empty($credentials['consumer_key']) ) {
  217. $this->oauth = new OAuthSignature(
  218. $credentials['consumer_key'],
  219. $credentials['consumer_secret']
  220. );
  221. } else {
  222. $this->oauth = null;
  223. }
  224. }
  225. public function signDownloadUrl($url) {
  226. //Add authentication data to download URLs. Since OAuth signatures incorporate
  227. //timestamps, we have to do this immediately before inserting the update. Otherwise,
  228. //authentication could fail due to a stale timestamp.
  229. if ( $this->oauth ) {
  230. $url = $this->oauth->sign($url);
  231. }
  232. return $url;
  233. }
  234. }
  235. endif;