GitLabApi.php 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309
  1. <?php
  2. if ( !class_exists('Puc_v4p11_Vcs_GitLabApi', false) ):
  3. class Puc_v4p11_Vcs_GitLabApi extends Puc_v4p11_Vcs_Api {
  4. /**
  5. * @var string GitLab username.
  6. */
  7. protected $userName;
  8. /**
  9. * @var string GitLab server host.
  10. */
  11. protected $repositoryHost;
  12. /**
  13. * @var string Protocol used by this GitLab server: "http" or "https".
  14. */
  15. protected $repositoryProtocol = 'https';
  16. /**
  17. * @var string GitLab repository name.
  18. */
  19. protected $repositoryName;
  20. /**
  21. * @var string GitLab authentication token. Optional.
  22. */
  23. protected $accessToken;
  24. public function __construct($repositoryUrl, $accessToken = null, $subgroup = null) {
  25. //Parse the repository host to support custom hosts.
  26. $port = parse_url($repositoryUrl, PHP_URL_PORT);
  27. if ( !empty($port) ) {
  28. $port = ':' . $port;
  29. }
  30. $this->repositoryHost = parse_url($repositoryUrl, PHP_URL_HOST) . $port;
  31. if ( $this->repositoryHost !== 'gitlab.com' ) {
  32. $this->repositoryProtocol = parse_url($repositoryUrl, PHP_URL_SCHEME);
  33. }
  34. //Find the repository information
  35. $path = parse_url($repositoryUrl, PHP_URL_PATH);
  36. if ( preg_match('@^/?(?P<username>[^/]+?)/(?P<repository>[^/#?&]+?)/?$@', $path, $matches) ) {
  37. $this->userName = $matches['username'];
  38. $this->repositoryName = $matches['repository'];
  39. } elseif ( ($this->repositoryHost === 'gitlab.com') ) {
  40. //This is probably a repository in a subgroup, e.g. "/organization/category/repo".
  41. $parts = explode('/', trim($path, '/'));
  42. if ( count($parts) < 3 ) {
  43. throw new InvalidArgumentException('Invalid GitLab.com repository URL: "' . $repositoryUrl . '"');
  44. }
  45. $lastPart = array_pop($parts);
  46. $this->userName = implode('/', $parts);
  47. $this->repositoryName = $lastPart;
  48. } else {
  49. //There could be subgroups in the URL: gitlab.domain.com/group/subgroup/subgroup2/repository
  50. if ( $subgroup !== null ) {
  51. $path = str_replace(trailingslashit($subgroup), '', $path);
  52. }
  53. //This is not a traditional url, it could be gitlab is in a deeper subdirectory.
  54. //Get the path segments.
  55. $segments = explode('/', untrailingslashit(ltrim($path, '/')));
  56. //We need at least /user-name/repository-name/
  57. if ( count($segments) < 2 ) {
  58. throw new InvalidArgumentException('Invalid GitLab repository URL: "' . $repositoryUrl . '"');
  59. }
  60. //Get the username and repository name.
  61. $usernameRepo = array_splice($segments, -2, 2);
  62. $this->userName = $usernameRepo[0];
  63. $this->repositoryName = $usernameRepo[1];
  64. //Append the remaining segments to the host if there are segments left.
  65. if ( count($segments) > 0 ) {
  66. $this->repositoryHost = trailingslashit($this->repositoryHost) . implode('/', $segments);
  67. }
  68. //Add subgroups to username.
  69. if ( $subgroup !== null ) {
  70. $this->userName = $usernameRepo[0] . '/' . untrailingslashit($subgroup);
  71. }
  72. }
  73. parent::__construct($repositoryUrl, $accessToken);
  74. }
  75. /**
  76. * Get the latest release from GitLab.
  77. *
  78. * @return Puc_v4p11_Vcs_Reference|null
  79. */
  80. public function getLatestRelease() {
  81. return $this->getLatestTag();
  82. }
  83. /**
  84. * Get the tag that looks like the highest version number.
  85. *
  86. * @return Puc_v4p11_Vcs_Reference|null
  87. */
  88. public function getLatestTag() {
  89. $tags = $this->api('/:id/repository/tags');
  90. if ( is_wp_error($tags) || empty($tags) || !is_array($tags) ) {
  91. return null;
  92. }
  93. $versionTags = $this->sortTagsByVersion($tags);
  94. if ( empty($versionTags) ) {
  95. return null;
  96. }
  97. $tag = $versionTags[0];
  98. return new Puc_v4p11_Vcs_Reference(array(
  99. 'name' => $tag->name,
  100. 'version' => ltrim($tag->name, 'v'),
  101. 'downloadUrl' => $this->buildArchiveDownloadUrl($tag->name),
  102. 'apiResponse' => $tag,
  103. ));
  104. }
  105. /**
  106. * Get a branch by name.
  107. *
  108. * @param string $branchName
  109. * @return null|Puc_v4p11_Vcs_Reference
  110. */
  111. public function getBranch($branchName) {
  112. $branch = $this->api('/:id/repository/branches/' . $branchName);
  113. if ( is_wp_error($branch) || empty($branch) ) {
  114. return null;
  115. }
  116. $reference = new Puc_v4p11_Vcs_Reference(array(
  117. 'name' => $branch->name,
  118. 'downloadUrl' => $this->buildArchiveDownloadUrl($branch->name),
  119. 'apiResponse' => $branch,
  120. ));
  121. if ( isset($branch->commit, $branch->commit->committed_date) ) {
  122. $reference->updated = $branch->commit->committed_date;
  123. }
  124. return $reference;
  125. }
  126. /**
  127. * Get the timestamp of the latest commit that changed the specified branch or tag.
  128. *
  129. * @param string $ref Reference name (e.g. branch or tag).
  130. * @return string|null
  131. */
  132. public function getLatestCommitTime($ref) {
  133. $commits = $this->api('/:id/repository/commits/', array('ref_name' => $ref));
  134. if ( is_wp_error($commits) || !is_array($commits) || !isset($commits[0]) ) {
  135. return null;
  136. }
  137. return $commits[0]->committed_date;
  138. }
  139. /**
  140. * Perform a GitLab API request.
  141. *
  142. * @param string $url
  143. * @param array $queryParams
  144. * @return mixed|WP_Error
  145. */
  146. protected function api($url, $queryParams = array()) {
  147. $baseUrl = $url;
  148. $url = $this->buildApiUrl($url, $queryParams);
  149. $options = array('timeout' => 10);
  150. if ( !empty($this->httpFilterName) ) {
  151. $options = apply_filters($this->httpFilterName, $options);
  152. }
  153. $response = wp_remote_get($url, $options);
  154. if ( is_wp_error($response) ) {
  155. do_action('puc_api_error', $response, null, $url, $this->slug);
  156. return $response;
  157. }
  158. $code = wp_remote_retrieve_response_code($response);
  159. $body = wp_remote_retrieve_body($response);
  160. if ( $code === 200 ) {
  161. return json_decode($body);
  162. }
  163. $error = new WP_Error(
  164. 'puc-gitlab-http-error',
  165. sprintf('GitLab API error. URL: "%s", HTTP status code: %d.', $baseUrl, $code)
  166. );
  167. do_action('puc_api_error', $error, $response, $url, $this->slug);
  168. return $error;
  169. }
  170. /**
  171. * Build a fully qualified URL for an API request.
  172. *
  173. * @param string $url
  174. * @param array $queryParams
  175. * @return string
  176. */
  177. protected function buildApiUrl($url, $queryParams) {
  178. $variables = array(
  179. 'user' => $this->userName,
  180. 'repo' => $this->repositoryName,
  181. 'id' => $this->userName . '/' . $this->repositoryName,
  182. );
  183. foreach ($variables as $name => $value) {
  184. $url = str_replace("/:{$name}", '/' . urlencode($value), $url);
  185. }
  186. $url = substr($url, 1);
  187. $url = sprintf('%1$s://%2$s/api/v4/projects/%3$s', $this->repositoryProtocol, $this->repositoryHost, $url);
  188. if ( !empty($this->accessToken) ) {
  189. $queryParams['private_token'] = $this->accessToken;
  190. }
  191. if ( !empty($queryParams) ) {
  192. $url = add_query_arg($queryParams, $url);
  193. }
  194. return $url;
  195. }
  196. /**
  197. * Get the contents of a file from a specific branch or tag.
  198. *
  199. * @param string $path File name.
  200. * @param string $ref
  201. * @return null|string Either the contents of the file, or null if the file doesn't exist or there's an error.
  202. */
  203. public function getRemoteFile($path, $ref = 'master') {
  204. $response = $this->api('/:id/repository/files/' . $path, array('ref' => $ref));
  205. if ( is_wp_error($response) || !isset($response->content) || $response->encoding !== 'base64' ) {
  206. return null;
  207. }
  208. return base64_decode($response->content);
  209. }
  210. /**
  211. * Generate a URL to download a ZIP archive of the specified branch/tag/etc.
  212. *
  213. * @param string $ref
  214. * @return string
  215. */
  216. public function buildArchiveDownloadUrl($ref = 'master') {
  217. $url = sprintf(
  218. '%1$s://%2$s/api/v4/projects/%3$s/repository/archive.zip',
  219. $this->repositoryProtocol,
  220. $this->repositoryHost,
  221. urlencode($this->userName . '/' . $this->repositoryName)
  222. );
  223. $url = add_query_arg('sha', urlencode($ref), $url);
  224. if ( !empty($this->accessToken) ) {
  225. $url = add_query_arg('private_token', $this->accessToken, $url);
  226. }
  227. return $url;
  228. }
  229. /**
  230. * Get a specific tag.
  231. *
  232. * @param string $tagName
  233. * @return void
  234. */
  235. public function getTag($tagName) {
  236. throw new LogicException('The ' . __METHOD__ . ' method is not implemented and should not be used.');
  237. }
  238. /**
  239. * Figure out which reference (i.e tag or branch) contains the latest version.
  240. *
  241. * @param string $configBranch Start looking in this branch.
  242. * @return null|Puc_v4p11_Vcs_Reference
  243. */
  244. public function chooseReference($configBranch) {
  245. $updateSource = null;
  246. // GitLab doesn't handle releases the same as GitHub so just use the latest tag
  247. if ( $configBranch === 'master' ) {
  248. $updateSource = $this->getLatestTag();
  249. }
  250. if ( empty($updateSource) ) {
  251. $updateSource = $this->getBranch($configBranch);
  252. }
  253. return $updateSource;
  254. }
  255. public function setAuthentication($credentials) {
  256. parent::setAuthentication($credentials);
  257. $this->accessToken = is_string($credentials) ? $credentials : null;
  258. }
  259. }
  260. endif;