PageRenderTime 45ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 0ms

/LiveSigns/src/aliuly/livesigns/TwitterAPIExchange.php

https://gitlab.com/Skull3x/pocketmine-plugins
PHP | 376 lines | 195 code | 54 blank | 127 comment | 21 complexity | 6a30d549a96ffe877cb5751c32ad9b4c MD5 | raw file
  1. <?php
  2. namespace aliuly\livesigns;
  3. /**
  4. * Twitter-API-PHP : Simple PHP wrapper for the v1.1 API
  5. *
  6. * PHP version 5.3.10
  7. *
  8. * @category Awesomeness
  9. * @package Twitter-API-PHP
  10. * @author James Mallison <me@j7mbo.co.uk>
  11. * @license MIT License
  12. * @link http://github.com/j7mbo/twitter-api-php
  13. */
  14. class TwitterAPIExchange
  15. {
  16. /**
  17. * @var string
  18. */
  19. private $oauth_access_token;
  20. /**
  21. * @var string
  22. */
  23. private $oauth_access_token_secret;
  24. /**
  25. * @var string
  26. */
  27. private $consumer_key;
  28. /**
  29. * @var string
  30. */
  31. private $consumer_secret;
  32. /**
  33. * @var array
  34. */
  35. private $postfields;
  36. /**
  37. * @var string
  38. */
  39. private $getfield;
  40. /**
  41. * @var mixed
  42. */
  43. protected $oauth;
  44. /**
  45. * @var string
  46. */
  47. public $url;
  48. /**
  49. * @var string
  50. */
  51. public $requestMethod;
  52. /**
  53. * Create the API access object. Requires an array of settings::
  54. * oauth access token, oauth access token secret, consumer key, consumer secret
  55. * These are all available by creating your own application on dev.twitter.com
  56. * Requires the cURL library
  57. *
  58. * @throws \Exception When cURL isn't installed or incorrect settings parameters are provided
  59. *
  60. * @param array $settings
  61. */
  62. public function __construct(array $settings)
  63. {
  64. if (!in_array('curl', get_loaded_extensions()))
  65. {
  66. throw new Exception('You need to install cURL, see: http://curl.haxx.se/docs/install.html');
  67. }
  68. if (!isset($settings['oauth_access_token'])
  69. || !isset($settings['oauth_access_token_secret'])
  70. || !isset($settings['consumer_key'])
  71. || !isset($settings['consumer_secret']))
  72. {
  73. throw new Exception('Make sure you are passing in the correct parameters');
  74. }
  75. $this->oauth_access_token = $settings['oauth_access_token'];
  76. $this->oauth_access_token_secret = $settings['oauth_access_token_secret'];
  77. $this->consumer_key = $settings['consumer_key'];
  78. $this->consumer_secret = $settings['consumer_secret'];
  79. }
  80. /**
  81. * Set postfields array, example: array('screen_name' => 'J7mbo')
  82. *
  83. * @param array $array Array of parameters to send to API
  84. *
  85. * @throws \Exception When you are trying to set both get and post fields
  86. *
  87. * @return TwitterAPIExchange Instance of self for method chaining
  88. */
  89. public function setPostfields(array $array)
  90. {
  91. if (!is_null($this->getGetfield()))
  92. {
  93. throw new Exception('You can only choose get OR post fields.');
  94. }
  95. if (isset($array['status']) && substr($array['status'], 0, 1) === '@')
  96. {
  97. $array['status'] = sprintf("\0%s", $array['status']);
  98. }
  99. $this->postfields = $array;
  100. // rebuild oAuth
  101. if (isset($this->oauth['oauth_signature'])) {
  102. $this->buildOauth($this->url, $this->requestMethod);
  103. }
  104. return $this;
  105. }
  106. /**
  107. * Set getfield string, example: '?screen_name=J7mbo'
  108. *
  109. * @param string $string Get key and value pairs as string
  110. *
  111. * @throws \Exception
  112. *
  113. * @return \TwitterAPIExchange Instance of self for method chaining
  114. */
  115. public function setGetfield($string)
  116. {
  117. if (!is_null($this->getPostfields()))
  118. {
  119. throw new Exception('You can only choose get OR post fields.');
  120. }
  121. $getfields = preg_replace('/^\?/', '', explode('&', $string));
  122. $params = array();
  123. foreach ($getfields as $field)
  124. {
  125. if ($field !== '')
  126. {
  127. list($key, $value) = explode('=', $field);
  128. $params[$key] = $value;
  129. }
  130. }
  131. $this->getfield = '?' . http_build_query($params);
  132. return $this;
  133. }
  134. /**
  135. * Get getfield string (simple getter)
  136. *
  137. * @return string $this->getfields
  138. */
  139. public function getGetfield()
  140. {
  141. return $this->getfield;
  142. }
  143. /**
  144. * Get postfields array (simple getter)
  145. *
  146. * @return array $this->postfields
  147. */
  148. public function getPostfields()
  149. {
  150. return $this->postfields;
  151. }
  152. /**
  153. * Build the Oauth object using params set in construct and additionals
  154. * passed to this method. For v1.1, see: https://dev.twitter.com/docs/api/1.1
  155. *
  156. * @param string $url The API url to use. Example: https://api.twitter.com/1.1/search/tweets.json
  157. * @param string $requestMethod Either POST or GET
  158. *
  159. * @throws \Exception
  160. *
  161. * @return \TwitterAPIExchange Instance of self for method chaining
  162. */
  163. public function buildOauth($url, $requestMethod)
  164. {
  165. if (!in_array(strtolower($requestMethod), array('post', 'get')))
  166. {
  167. throw new Exception('Request method must be either POST or GET');
  168. }
  169. $consumer_key = $this->consumer_key;
  170. $consumer_secret = $this->consumer_secret;
  171. $oauth_access_token = $this->oauth_access_token;
  172. $oauth_access_token_secret = $this->oauth_access_token_secret;
  173. $oauth = array(
  174. 'oauth_consumer_key' => $consumer_key,
  175. 'oauth_nonce' => time(),
  176. 'oauth_signature_method' => 'HMAC-SHA1',
  177. 'oauth_token' => $oauth_access_token,
  178. 'oauth_timestamp' => time(),
  179. 'oauth_version' => '1.0'
  180. );
  181. $getfield = $this->getGetfield();
  182. if (!is_null($getfield))
  183. {
  184. $getfields = str_replace('?', '', explode('&', $getfield));
  185. foreach ($getfields as $g)
  186. {
  187. $split = explode('=', $g);
  188. /** In case a null is passed through **/
  189. if (isset($split[1]))
  190. {
  191. $oauth[$split[0]] = urldecode($split[1]);
  192. }
  193. }
  194. }
  195. $postfields = $this->getPostfields();
  196. if (!is_null($postfields)) {
  197. foreach ($postfields as $key => $value) {
  198. $oauth[$key] = $value;
  199. }
  200. }
  201. $base_info = $this->buildBaseString($url, $requestMethod, $oauth);
  202. $composite_key = rawurlencode($consumer_secret) . '&' . rawurlencode($oauth_access_token_secret);
  203. $oauth_signature = base64_encode(hash_hmac('sha1', $base_info, $composite_key, true));
  204. $oauth['oauth_signature'] = $oauth_signature;
  205. $this->url = $url;
  206. $this->requestMethod = $requestMethod;
  207. $this->oauth = $oauth;
  208. return $this;
  209. }
  210. /**
  211. * Perform the actual data retrieval from the API
  212. *
  213. * @param boolean $return If true, returns data. This is left in for backward compatibility reasons
  214. * @param array $curlOptions Additional Curl options for this request
  215. *
  216. * @throws \Exception
  217. *
  218. * @return string json If $return param is true, returns json data.
  219. */
  220. public function performRequest($return = true, $curlOptions = array())
  221. {
  222. if (!is_bool($return))
  223. {
  224. throw new Exception('performRequest parameter must be true or false');
  225. }
  226. $header = array($this->buildAuthorizationHeader($this->oauth), 'Expect:');
  227. $getfield = $this->getGetfield();
  228. $postfields = $this->getPostfields();
  229. $options = array(
  230. CURLOPT_HTTPHEADER => $header,
  231. CURLOPT_HEADER => false,
  232. CURLOPT_URL => $this->url,
  233. CURLOPT_RETURNTRANSFER => true,
  234. CURLOPT_TIMEOUT => 10,
  235. ) + $curlOptions;
  236. if (!is_null($postfields))
  237. {
  238. $options[CURLOPT_POSTFIELDS] = http_build_query($postfields);
  239. }
  240. else
  241. {
  242. if ($getfield !== '')
  243. {
  244. $options[CURLOPT_URL] .= $getfield;
  245. }
  246. }
  247. $feed = curl_init();
  248. curl_setopt_array($feed, $options);
  249. $json = curl_exec($feed);
  250. if (($error = curl_error($feed)) !== '')
  251. {
  252. curl_close($feed);
  253. throw new \Exception($error);
  254. }
  255. curl_close($feed);
  256. return $json;
  257. }
  258. /**
  259. * Private method to generate the base string used by cURL
  260. *
  261. * @param string $baseURI
  262. * @param string $method
  263. * @param array $params
  264. *
  265. * @return string Built base string
  266. */
  267. private function buildBaseString($baseURI, $method, $params)
  268. {
  269. $return = array();
  270. ksort($params);
  271. foreach($params as $key => $value)
  272. {
  273. $return[] = rawurlencode($key) . '=' . rawurlencode($value);
  274. }
  275. return $method . "&" . rawurlencode($baseURI) . '&' . rawurlencode(implode('&', $return));
  276. }
  277. /**
  278. * Private method to generate authorization header used by cURL
  279. *
  280. * @param array $oauth Array of oauth data generated by buildOauth()
  281. *
  282. * @return string $return Header used by cURL for request
  283. */
  284. private function buildAuthorizationHeader(array $oauth)
  285. {
  286. $return = 'Authorization: OAuth ';
  287. $values = array();
  288. foreach($oauth as $key => $value)
  289. {
  290. if (in_array($key, array('oauth_consumer_key', 'oauth_nonce', 'oauth_signature',
  291. 'oauth_signature_method', 'oauth_timestamp', 'oauth_token', 'oauth_version'))) {
  292. $values[] = "$key=\"" . rawurlencode($value) . "\"";
  293. }
  294. }
  295. $return .= implode(', ', $values);
  296. return $return;
  297. }
  298. /**
  299. * Helper method to perform our request
  300. *
  301. * @param string $url
  302. * @param string $method
  303. * @param string $data
  304. * @param array $curlOptions
  305. *
  306. * @throws \Exception
  307. *
  308. * @return string The json response from the server
  309. */
  310. public function request($url, $method = 'get', $data = null, $curlOptions = array())
  311. {
  312. if (strtolower($method) === 'get')
  313. {
  314. $this->setGetfield($data);
  315. }
  316. else
  317. {
  318. $this->setPostfields($data);
  319. }
  320. return $this->buildOauth($url, $method)->performRequest(true, $curlOptions);
  321. }
  322. }