Nessuna descrizione

twitter-client.php 9.2KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325
  1. <?php
  2. use NSL\Persistent\Persistent;
  3. require_once NSL_PATH . '/includes/auth.php';
  4. class NextendSocialProviderTwitterClient extends NextendSocialAuth {
  5. const VERSION = '1.0';
  6. const SIGNATURE_METHOD = 'HMAC-SHA1';
  7. private $endpoint = 'https://api.twitter.com/';
  8. protected $consumer_key = '';
  9. protected $consumer_secret = '';
  10. protected $redirect_uri = '';
  11. public function __construct($providerID, $consumer_key, $consumer_secret) {
  12. parent::__construct($providerID);
  13. $this->consumer_key = $consumer_key;
  14. $this->consumer_secret = $consumer_secret;
  15. }
  16. public function getTestUrl() {
  17. return $this->endpoint;
  18. }
  19. /**
  20. * @param string $redirect_uri
  21. */
  22. public function setRedirectUri($redirect_uri) {
  23. $this->redirect_uri = $redirect_uri;
  24. }
  25. public function deleteLoginPersistentData() {
  26. Persistent::delete($this->providerID . '_request_token');
  27. }
  28. /**
  29. * @return string
  30. * @throws Exception
  31. */
  32. public function createAuthUrl() {
  33. $response = $this->oauthRequest($this->endpoint . 'oauth/request_token', 'POST', array(), array(
  34. 'oauth_callback' => $this->redirect_uri
  35. ));
  36. $oauthTokenData = $this->extract_params($response);
  37. Persistent::set($this->providerID . '_request_token', maybe_serialize($oauthTokenData));
  38. return $this->endpoint . 'oauth/authenticate?oauth_token=' . $oauthTokenData['oauth_token'] /*. '&force_login=1'*/ ;
  39. }
  40. /**
  41. * @throws Exception
  42. */
  43. public function checkError() {
  44. if (isset($_GET['denied'])) {
  45. throw new Exception('Authentication cancelled');
  46. }
  47. }
  48. public function hasAuthenticateData() {
  49. return isset($_REQUEST['oauth_token']) && isset($_REQUEST['oauth_verifier']);
  50. }
  51. /**
  52. * @return false|string
  53. * @throws Exception
  54. */
  55. public function authenticate() {
  56. $requestToken = maybe_unserialize(Persistent::get($this->providerID . '_request_token'));
  57. $response = $this->oauthRequest($this->endpoint . 'oauth/access_token', 'POST', array(), array(
  58. 'oauth_verifier' => $_GET['oauth_verifier']
  59. ), array(
  60. 'token' => $requestToken['oauth_token'],
  61. 'secret' => $requestToken['oauth_token_secret']
  62. ));
  63. $accessTokenData = $this->extract_params($response);
  64. $access_token_data = wp_json_encode(array(
  65. 'oauth_token' => $accessTokenData['oauth_token'],
  66. 'oauth_token_secret' => $accessTokenData['oauth_token_secret'],
  67. 'user_id' => $accessTokenData['user_id'],
  68. 'screen_name' => $accessTokenData['screen_name']
  69. ));
  70. $this->setAccessTokenData($access_token_data);
  71. return $access_token_data;
  72. }
  73. /**
  74. * @param $path
  75. * @param array $data
  76. *
  77. * @return array|mixed|object
  78. * @throws Exception
  79. */
  80. public function get($path, $data = array(), $endpoint = false) {
  81. if (!$endpoint) {
  82. $endpoint = $this->endpoint;
  83. }
  84. $response = $this->oauthRequest($endpoint . '1.1/' . $path . '.json', 'GET', $data + array(
  85. 'user_id' => $this->access_token_data['user_id']
  86. ), array(), array(
  87. 'token' => $this->access_token_data['oauth_token'],
  88. 'secret' => $this->access_token_data['oauth_token_secret']
  89. ));
  90. return json_decode($response, true);
  91. }
  92. /**
  93. * @param $url
  94. * @param $method
  95. * @param array $_requestData
  96. * @param array $_oauthData
  97. * @param array $context
  98. *
  99. * @return string
  100. * @throws Exception
  101. */
  102. private function oauthRequest($url, $method, $_requestData = array(), $_oauthData = array(), $context = array()) {
  103. $method = strtoupper($method);
  104. uksort($_requestData, 'strcmp');
  105. $headers = array();
  106. $headers['Authorization'] = $this->getAuthorizationHeader($url, $method, $_requestData, $_oauthData, $context);
  107. $http_args = array(
  108. 'timeout' => 15,
  109. 'user-agent' => 'WordPress',
  110. 'headers' => $headers,
  111. 'body' => $_requestData
  112. );
  113. if ($method == 'POST') {
  114. $request = wp_remote_post($url, $http_args);
  115. } else {
  116. $request = wp_remote_get($url, $http_args);
  117. }
  118. if (is_wp_error($request)) {
  119. throw new Exception($request->get_error_message());
  120. } else if (wp_remote_retrieve_response_code($request) !== 200) {
  121. $this->errorFromResponse(json_decode(wp_remote_retrieve_body($request), true));
  122. throw new Exception(sprintf(__('Unexpected response: %s', 'nextend-facebook-connect'), wp_remote_retrieve_body($request)));
  123. }
  124. return wp_remote_retrieve_body($request);
  125. }
  126. private function getAuthorizationHeader($url, $method, $_requestData = array(), $_oauthData = array(), $context = array()) {
  127. $oauthParams = $this->getOauth1Params($context);
  128. foreach ($_oauthData as $k => $v) {
  129. $oauthParams[$this->safe_encode($k)] = $this->safe_encode($v);
  130. }
  131. $params = array_merge($oauthParams, $_requestData);
  132. unset($params['oauth_signature']);
  133. uksort($params, 'strcmp');
  134. $prepared_pairs_with_oauth = array();
  135. foreach ($params as $k => $v) {
  136. $prepared_pairs_with_oauth[] = "{$k}={$v}";
  137. }
  138. $paramsForSignature = implode('&', $this->safe_encode(array(
  139. $method,
  140. $url,
  141. implode('&', $prepared_pairs_with_oauth)
  142. )));
  143. $left = $this->safe_encode($this->consumer_secret);
  144. $right = $this->safe_encode($this->secret($context));
  145. $signing_key = $left . '&' . $right;
  146. $oauthParams['oauth_signature'] = $this->safe_encode(base64_encode(hash_hmac('sha1', $paramsForSignature, $signing_key, true)));
  147. uksort($oauthParams, 'strcmp');
  148. $encoded_quoted_pairs = array();
  149. foreach ($oauthParams as $k => $v) {
  150. $encoded_quoted_pairs[] = "{$k}=\"{$v}\"";
  151. }
  152. return 'OAuth ' . implode(', ', $encoded_quoted_pairs);
  153. }
  154. /**
  155. * @param $response
  156. *
  157. * @throws Exception
  158. */
  159. private function errorFromResponse($response) {
  160. if (isset($response['errors']) && is_array($response['errors'])) {
  161. throw new Exception($response['errors'][0]['message']);
  162. }
  163. }
  164. private function safe_encode($data) {
  165. if (is_array($data)) {
  166. return array_map(array(
  167. $this,
  168. 'safe_encode'
  169. ), $data);
  170. } else if (is_scalar($data)) {
  171. return str_ireplace(array(
  172. '+',
  173. '%7E'
  174. ), array(
  175. ' ',
  176. '~'
  177. ), rawurlencode($data));
  178. } else {
  179. return '';
  180. }
  181. }
  182. private function safe_decode($data) {
  183. if (is_array($data)) {
  184. return array_map(array(
  185. $this,
  186. 'safe_decode'
  187. ), $data);
  188. } else if (is_scalar($data)) {
  189. return rawurldecode($data);
  190. } else {
  191. return '';
  192. }
  193. }
  194. private function extract_params($body) {
  195. $kvs = explode('&', $body);
  196. $decoded = array();
  197. foreach ($kvs as $kv) {
  198. $kv = explode('=', $kv, 2);
  199. $kv[0] = $this->safe_decode($kv[0]);
  200. $kv[1] = $this->safe_decode($kv[1]);
  201. $decoded[$kv[0]] = $kv[1];
  202. }
  203. return $decoded;
  204. }
  205. private function nonce($length = 12, $include_time = true) {
  206. $prefix = $include_time ? microtime() : '';
  207. return md5(substr($prefix . uniqid(), 0, $length));
  208. }
  209. private function timestamp() {
  210. $time = time();
  211. return (string)$time;
  212. }
  213. private function getOauth1Params($data) {
  214. $defaults = array(
  215. 'oauth_nonce' => $this->nonce(),
  216. 'oauth_timestamp' => $this->timestamp(),
  217. 'oauth_version' => self::VERSION,
  218. 'oauth_consumer_key' => $this->consumer_key,
  219. 'oauth_signature_method' => self::SIGNATURE_METHOD,
  220. );
  221. // include the user token if it exists
  222. if ($oauth_token = $this->token($data)) {
  223. $defaults['oauth_token'] = $oauth_token;
  224. }
  225. $encoded = array();
  226. foreach ($defaults as $k => $v) {
  227. $encoded[$this->safe_encode($k)] = $this->safe_encode($v);
  228. }
  229. return $encoded;
  230. }
  231. private function token($context) {
  232. if (isset($context['token']) && !empty($context['token'])) {
  233. return $context['token'];
  234. } else if (isset($context['user_token'])) {
  235. return $context['user_token'];
  236. }
  237. return '';
  238. }
  239. private function secret($context) {
  240. if (isset($context['secret']) && !empty($context['secret'])) {
  241. return $context['secret'];
  242. } else if (isset($context['user_secret'])) {
  243. return $context['user_secret'];
  244. }
  245. return '';
  246. }
  247. }