PageRenderTime 28ms CodeModel.GetById 27ms RepoModel.GetById 0ms app.codeStats 0ms

/includes/lib/Braintree/lib/Braintree/Http.php

https://github.com/strangerstudios/paid-memberships-pro
PHP | 273 lines | 244 code | 25 blank | 4 comment | 52 complexity | b96151720f66b6f20fa661ad7ee16326 MD5 | raw file
  1. <?php
  2. namespace Braintree;
  3. use finfo;
  4. /**
  5. * Braintree HTTP Client
  6. * processes Http requests using curl
  7. */
  8. class Http
  9. {
  10. protected $_config;
  11. private $_useClientCredentials = false;
  12. public function __construct($config)
  13. {
  14. $this->_config = $config;
  15. }
  16. public function delete($path, $params = null)
  17. {
  18. $response = $this->_doRequest('DELETE', $path, $this->_buildXml($params));
  19. $responseCode = $response['status'];
  20. if ($responseCode === 200 || $responseCode === 204) {
  21. return true;
  22. } else if ($responseCode === 422) {
  23. return Xml::buildArrayFromXml($response['body']);
  24. } else {
  25. Util::throwStatusCodeException($response['status']);
  26. }
  27. }
  28. public function get($path)
  29. {
  30. $response = $this->_doRequest('GET', $path);
  31. if ($response['status'] === 200) {
  32. return Xml::buildArrayFromXml($response['body']);
  33. } else {
  34. Util::throwStatusCodeException($response['status']);
  35. }
  36. }
  37. public function post($path, $params = null)
  38. {
  39. $response = $this->_doRequest('POST', $path, $this->_buildXml($params));
  40. $responseCode = $response['status'];
  41. if ($responseCode === 200 || $responseCode === 201 || $responseCode === 422 || $responseCode == 400) {
  42. return Xml::buildArrayFromXml($response['body']);
  43. } else {
  44. Util::throwStatusCodeException($responseCode);
  45. }
  46. }
  47. public function postMultipart($path, $params, $file)
  48. {
  49. $headers = [
  50. 'User-Agent: Braintree PHP Library ' . Version::get(),
  51. 'X-ApiVersion: ' . Configuration::API_VERSION
  52. ];
  53. $response = $this->_doRequest('POST', $path, $params, $file, $headers);
  54. $responseCode = $response['status'];
  55. if ($responseCode === 200 || $responseCode === 201 || $responseCode === 422 || $responseCode == 400) {
  56. return Xml::buildArrayFromXml($response['body']);
  57. } else {
  58. Util::throwStatusCodeException($responseCode);
  59. }
  60. }
  61. public function put($path, $params = null)
  62. {
  63. $response = $this->_doRequest('PUT', $path, $this->_buildXml($params));
  64. $responseCode = $response['status'];
  65. if ($responseCode === 200 || $responseCode === 201 || $responseCode === 422 || $responseCode == 400) {
  66. return Xml::buildArrayFromXml($response['body']);
  67. } else {
  68. Util::throwStatusCodeException($responseCode);
  69. }
  70. }
  71. private function _buildXml($params)
  72. {
  73. return empty($params) ? null : Xml::buildXmlFromArray($params);
  74. }
  75. private function _getHeaders()
  76. {
  77. return [
  78. 'Accept: application/xml',
  79. ];
  80. }
  81. private function _getAuthorization()
  82. {
  83. if ($this->_useClientCredentials) {
  84. return [
  85. 'user' => $this->_config->getClientId(),
  86. 'password' => $this->_config->getClientSecret(),
  87. ];
  88. } else if ($this->_config->isAccessToken()) {
  89. return [
  90. 'token' => $this->_config->getAccessToken(),
  91. ];
  92. } else {
  93. return [
  94. 'user' => $this->_config->getPublicKey(),
  95. 'password' => $this->_config->getPrivateKey(),
  96. ];
  97. }
  98. }
  99. public function useClientCredentials()
  100. {
  101. $this->_useClientCredentials = true;
  102. }
  103. private function _doRequest($httpVerb, $path, $requestBody = null, $file = null, $headers = null)
  104. {
  105. return $this->_doUrlRequest($httpVerb, $this->_config->baseUrl() . $path, $requestBody, $file, $headers);
  106. }
  107. public function _doUrlRequest($httpVerb, $url, $requestBody = null, $file = null, $customHeaders = null)
  108. {
  109. $curl = curl_init();
  110. curl_setopt($curl, CURLOPT_TIMEOUT, $this->_config->timeout());
  111. curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $httpVerb);
  112. curl_setopt($curl, CURLOPT_URL, $url);
  113. if ($this->_config->acceptGzipEncoding()) {
  114. curl_setopt($curl, CURLOPT_ENCODING, 'gzip');
  115. }
  116. if ($this->_config->sslVersion()) {
  117. curl_setopt($curl, CURLOPT_SSLVERSION, $this->_config->sslVersion());
  118. }
  119. $headers = [];
  120. if ($customHeaders) {
  121. $headers = $customHeaders;
  122. } else {
  123. $headers = $this->_getHeaders($curl);
  124. $headers[] = 'User-Agent: Braintree PHP Library ' . Version::get();
  125. $headers[] = 'X-ApiVersion: ' . Configuration::API_VERSION;
  126. $headers[] = 'Content-Type: application/xml';
  127. }
  128. $authorization = $this->_getAuthorization();
  129. if (isset($authorization['user'])) {
  130. curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
  131. curl_setopt($curl, CURLOPT_USERPWD, $authorization['user'] . ':' . $authorization['password']);
  132. } else if (isset($authorization['token'])) {
  133. $headers[] = 'Authorization: Bearer ' . $authorization['token'];
  134. }
  135. if ($this->_config->sslOn()) {
  136. curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, true);
  137. curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 2);
  138. curl_setopt($curl, CURLOPT_CAINFO, $this->getCaFile());
  139. }
  140. if (!empty($file)) {
  141. $boundary = "---------------------" . md5(mt_rand() . microtime());
  142. $headers[] = "Content-Type: multipart/form-data; boundary={$boundary}";
  143. $this->prepareMultipart($curl, $requestBody, $file, $boundary);
  144. } else if (!empty($requestBody)) {
  145. curl_setopt($curl, CURLOPT_POSTFIELDS, $requestBody);
  146. }
  147. if ($this->_config->isUsingProxy()) {
  148. $proxyHost = $this->_config->getProxyHost();
  149. $proxyPort = $this->_config->getProxyPort();
  150. $proxyType = $this->_config->getProxyType();
  151. $proxyUser = $this->_config->getProxyUser();
  152. $proxyPwd= $this->_config->getProxyPassword();
  153. curl_setopt($curl, CURLOPT_PROXY, $proxyHost . ':' . $proxyPort);
  154. if (!empty($proxyType)) {
  155. curl_setopt($curl, CURLOPT_PROXYTYPE, $proxyType);
  156. }
  157. if ($this->_config->isAuthenticatedProxy()) {
  158. curl_setopt($curl, CURLOPT_PROXYUSERPWD, $proxyUser . ':' . $proxyPwd);
  159. }
  160. }
  161. curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
  162. curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
  163. $response = curl_exec($curl);
  164. $httpStatus = curl_getinfo($curl, CURLINFO_HTTP_CODE);
  165. $error_code = curl_errno($curl);
  166. $error = curl_error($curl);
  167. if ($error_code == 28 && $httpStatus == 0) {
  168. throw new Exception\Timeout();
  169. }
  170. curl_close($curl);
  171. if ($this->_config->sslOn()) {
  172. if ($httpStatus == 0) {
  173. throw new Exception\SSLCertificate($error, $error_code);
  174. }
  175. } else if ($error_code) {
  176. throw new Exception\Connection($error, $error_code);
  177. }
  178. return ['status' => $httpStatus, 'body' => $response];
  179. }
  180. function prepareMultipart($ch, $requestBody, $file, $boundary) {
  181. $disallow = ["\0", "\"", "\r", "\n"];
  182. $fileInfo = new finfo(FILEINFO_MIME_TYPE);
  183. $filePath = stream_get_meta_data($file)['uri'];
  184. $data = file_get_contents($filePath);
  185. $mimeType = $fileInfo->buffer($data);
  186. // build normal parameters
  187. foreach ($requestBody as $k => $v) {
  188. $k = str_replace($disallow, "_", $k);
  189. $body[] = implode("\r\n", [
  190. "Content-Disposition: form-data; name=\"{$k}\"",
  191. "",
  192. filter_var($v),
  193. ]);
  194. }
  195. // build file parameter
  196. $splitFilePath = explode(DIRECTORY_SEPARATOR, $filePath);
  197. $filePath = end($splitFilePath);
  198. $filePath = str_replace($disallow, "_", $filePath);
  199. $body[] = implode("\r\n", [
  200. "Content-Disposition: form-data; name=\"file\"; filename=\"{$filePath}\"",
  201. "Content-Type: {$mimeType}",
  202. "",
  203. $data,
  204. ]);
  205. // add boundary for each parameters
  206. array_walk($body, function (&$part) use ($boundary) {
  207. $part = "--{$boundary}\r\n{$part}";
  208. });
  209. // add final boundary
  210. $body[] = "--{$boundary}--";
  211. $body[] = "";
  212. // set options
  213. return curl_setopt_array($ch, [
  214. CURLOPT_POST => true,
  215. CURLOPT_POSTFIELDS => implode("\r\n", $body)
  216. ]);
  217. }
  218. private function getCaFile()
  219. {
  220. static $memo;
  221. if ($memo === null) {
  222. $caFile = $this->_config->caFile();
  223. if (substr($caFile, 0, 7) !== 'phar://') {
  224. return $caFile;
  225. }
  226. $extractedCaFile = sys_get_temp_dir() . '/api_braintreegateway_com.ca.crt';
  227. if (!file_exists($extractedCaFile) || sha1_file($extractedCaFile) != sha1_file($caFile)) {
  228. if (!copy($caFile, $extractedCaFile)) {
  229. throw new Exception\SSLCaFileNotFound();
  230. }
  231. }
  232. $memo = $extractedCaFile;
  233. }
  234. return $memo;
  235. }
  236. }
  237. class_alias('Braintree\Http', 'Braintree_Http');