Client.php 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237
  1. <?php
  2. namespace Gogs\Lib\Curl {
  3. /**
  4. * A trait used for every class referencing the api-url and token.
  5. *
  6. * @author Joachim M. Giaever (joachim[]giaever.org)
  7. * @package curl
  8. * @version 0.1.1
  9. */
  10. trait Client {
  11. private static $log = array();
  12. protected $url;
  13. protected $token;
  14. protected $user_agent = "Gogs PHP Api Curl\\Client/0.1 (compatible; LINUX)";
  15. protected $timeout = 30;
  16. protected $max_redirects = 4;
  17. /**
  18. * array_2_params takes an array and converts it into a
  19. * query string (e.g param=val&param2=val2).
  20. *
  21. * @param array $params parameters to pass
  22. * @return string
  23. */
  24. private function array_2_params(array $params) {
  25. return join("&", array_map(function($k, $v) {
  26. return sprintf("%s=%s", $k, rawurlencode(is_bool($v) ? ($v ? "true" : "false") : $v ));
  27. }, array_keys($params), $params));
  28. }
  29. /**
  30. * array_2_json takes an array and converts it into a
  31. * json-string (e.g {'name': 'This'}) which is typically
  32. * used in a request body.
  33. *
  34. * @param array $params paramters to pass
  35. * @return string
  36. */
  37. private function array_2_json(array $params) {
  38. return count($params) == 0 ? null : json_encode($params);
  39. }
  40. /**
  41. * Initializes a curl request of different kinds, depending
  42. * on the specified method. This can be
  43. *
  44. * DELETE, PATCH, POST or GET. An unidentified value will
  45. * become a GET-request.
  46. *
  47. * @param string $method either DELETE, PATCH, POST, GET
  48. * @param string &$req variable to store request body in
  49. * @param string $scope scope within the API (e.g /user/repos)
  50. * @param array $params parameters to pass
  51. * @param bool $ret return transfer
  52. * @return int the status code
  53. */
  54. protected function method(string $method, string &$req, string $scope, array $params, bool $ret) {
  55. $c = curl_init();
  56. if (!$c) {
  57. return false;
  58. }
  59. $headers = array(
  60. sprintf("Authorization: token %s", $this->token),
  61. );
  62. $url = sprintf("%s%s", $this->url, $scope);
  63. self::$log[] = sprintf(
  64. "%s:[%s] %s, %s, %s",
  65. date("y-m-d H:i:s"),
  66. $method,
  67. $url,
  68. !empty($p = $this->array_2_json($params)) ? $p : "none",
  69. get_class($this)
  70. );
  71. if (in_array($method, array("DELETE", "PATCH", "POST"))) {
  72. $json = $this->array_2_json($params);
  73. curl_setopt($c, CURLOPT_CUSTOMREQUEST, $method);
  74. curl_setopt($c, CURLOPT_POSTFIELDS, $json);
  75. array_unshift($headers, "Content-Type: application/json");
  76. array_push($headers, "Content-Length: " . strlen($json));
  77. } else {
  78. $url .= "?" . $this->array_2_params($params);
  79. }
  80. curl_setopt($c, CURLOPT_USERAGENT, $this->user_agent);
  81. curl_setopt($c, CURLOPT_URL, $url);
  82. curl_setopt($c, CURLOPT_HTTPHEADER, $headers);
  83. curl_setopt($c, CURLOPT_RETURNTRANSFER, $ret);
  84. curl_setopt($c, CURLOPT_TIMEOUT, $this->timeout);
  85. curl_setopt($c, CURLOPT_MAXREDIRS, $this->max_redirects);
  86. curl_setopt($c, CURLOPT_FOLLOWLOCATION, true);
  87. $req = curl_exec($c);
  88. $status_code = curl_getinfo($c, CURLINFO_HTTP_CODE);
  89. curl_close($c);
  90. array_push(
  91. self::$log,
  92. sprintf(
  93. "%s:[%s] %s, %d, %s",
  94. date("y-m-d H:i:s"),
  95. $method,
  96. $url,
  97. $status_code,
  98. substr($req, 0, 100) . (strlen($req) > 100 ? "..." : ".")
  99. )
  100. );
  101. return $status_code;
  102. }
  103. /**
  104. * Checks if the user is authorized for the scope. Shouldn't
  105. * be used frequently. One test for one scope should be enough,
  106. * but if you know for sure thats you're programming with the
  107. * use of an authorized user you should leave this and just
  108. * handle the NotAuthorizedExeption whenever thrown.
  109. *
  110. * @param $scope the scope, a relative uri.
  111. * @throws Not AuthorizedException if server responde with a 401
  112. * @return bool
  113. */
  114. protected function authorized(string $scope = "") {
  115. $ret = "";
  116. if (in_array(($code = $this->method("GET", $ret, $scope, array(), false)),
  117. array(400, 401, 402, 403)
  118. )) {
  119. throw new NotAuthorizedException("Not authorized", 401);
  120. }
  121. return true;
  122. }
  123. /**
  124. * Post method.
  125. *
  126. * @param string $scope the scope, a relative uri.
  127. * @param array $params the parameters to post.
  128. * @throws NotAuthorizedException on 401, 403
  129. * @throws HTTPUnexpectedResponse when not 200,201,401,403
  130. * @return string the request content.
  131. */
  132. private function post(string $scope = "", array $params = array()) {
  133. $req = "";
  134. $code = $this->method("POST", $req, $scope, $params, true);
  135. switch ($code) {
  136. case 200:
  137. case 201:
  138. return $req;
  139. case 400:
  140. case 401:
  141. case 403:
  142. throw new Exception\NotAuthorizedException($req, $code);
  143. default:
  144. throw new Exception\HTTPUnexpectedResponse($req, $code);
  145. }
  146. }
  147. /**
  148. * Delete method.
  149. *
  150. * @param string $scope the scope, a relative uri.
  151. * @throws NotAuthorizedException on 401, 403
  152. * @throws HTTPUnexpectedResponse when not 200,204,401,403
  153. * @return string the request content.
  154. */
  155. private function delete(string $scope = "") {
  156. $req = "";
  157. $code = $this->method("DELETE", $req, $scope, array(), true);
  158. switch ($code) {
  159. case 200:
  160. case 204:
  161. return true;
  162. case 401:
  163. case 403:
  164. throw new Exception\NotAuthorizedException($req, $code);
  165. default:
  166. throw new Exception\HTTPUnexpectedResponse($req, $code);
  167. }
  168. }
  169. /**
  170. * GET method.
  171. *
  172. * @param string $scope the scope, a relative uri.
  173. * @param array $params the parameters to post.
  174. * @throws NotAuthorizedException on 401, 403
  175. * @throws HTTPUnexpectedResponse when not 200,401,403
  176. * @return string the request content.
  177. */
  178. private function get($scope = "", $params = array()) {
  179. $req = "";
  180. $code = $this->method("GET", $req, $scope, $params, true);
  181. switch ($code) {
  182. case 200:
  183. return $req;
  184. case 401:
  185. case 403:
  186. throw new Exception\NotAuthorizedException($req, $code);
  187. default:
  188. throw new Exception\HTTPUnexpectedResponse($req, $code);
  189. }
  190. }
  191. /**
  192. * Returns log entries for the client.
  193. *
  194. * @return array
  195. */
  196. public static function get_log() {
  197. if (empty(self::$log))
  198. return self::$log;
  199. return array_merge(self::$log, array("\n"));
  200. }
  201. }
  202. }
  203. ?>