BitBucketApi.php 7.0 KB

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